xref: /optee_os/core/arch/arm/kernel/thread.c (revision c96bced4504bd39ff8ccc57a21d29fa97aff4506)
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2016, Linaro Limited
4  * Copyright (c) 2014, STMicroelectronics International N.V.
5  */
6 
7 #include <platform_config.h>
8 
9 #include <arm.h>
10 #include <assert.h>
11 #include <io.h>
12 #include <keep.h>
13 #include <kernel/asan.h>
14 #include <kernel/lockdep.h>
15 #include <kernel/misc.h>
16 #include <kernel/msg_param.h>
17 #include <kernel/panic.h>
18 #include <kernel/spinlock.h>
19 #include <kernel/tee_ta_manager.h>
20 #include <kernel/thread_defs.h>
21 #include <kernel/thread.h>
22 #include <kernel/virtualization.h>
23 #include <mm/core_memprot.h>
24 #include <mm/mobj.h>
25 #include <mm/tee_mm.h>
26 #include <mm/tee_mmu.h>
27 #include <mm/tee_pager.h>
28 #include <optee_msg.h>
29 #include <optee_rpc_cmd.h>
30 #include <smccc.h>
31 #include <sm/optee_smc.h>
32 #include <sm/sm.h>
33 #include <tee/tee_cryp_utl.h>
34 #include <tee/tee_fs_rpc.h>
35 #include <trace.h>
36 #include <util.h>
37 
38 #include "thread_private.h"
39 
40 #ifdef CFG_WITH_ARM_TRUSTED_FW
41 #define STACK_TMP_OFFS		0
42 #else
43 #define STACK_TMP_OFFS		SM_STACK_TMP_RESERVE_SIZE
44 #endif
45 
46 
47 #ifdef ARM32
48 #ifdef CFG_CORE_SANITIZE_KADDRESS
49 #define STACK_TMP_SIZE		(3072 + STACK_TMP_OFFS)
50 #else
51 #define STACK_TMP_SIZE		(2048 + STACK_TMP_OFFS)
52 #endif
53 #define STACK_THREAD_SIZE	8192
54 
55 #ifdef CFG_CORE_SANITIZE_KADDRESS
56 #define STACK_ABT_SIZE		3072
57 #else
58 #define STACK_ABT_SIZE		2048
59 #endif
60 
61 #endif /*ARM32*/
62 
63 #ifdef ARM64
64 #define STACK_TMP_SIZE		(2048 + STACK_TMP_OFFS)
65 #define STACK_THREAD_SIZE	8192
66 
67 #if TRACE_LEVEL > 0
68 #define STACK_ABT_SIZE		3072
69 #else
70 #define STACK_ABT_SIZE		1024
71 #endif
72 #endif /*ARM64*/
73 
74 struct thread_ctx threads[CFG_NUM_THREADS];
75 
76 struct thread_core_local thread_core_local[CFG_TEE_CORE_NB_CORE] __nex_bss;
77 
78 #ifdef CFG_WITH_STACK_CANARIES
79 #ifdef ARM32
80 #define STACK_CANARY_SIZE	(4 * sizeof(uint32_t))
81 #endif
82 #ifdef ARM64
83 #define STACK_CANARY_SIZE	(8 * sizeof(uint32_t))
84 #endif
85 #define START_CANARY_VALUE	0xdededede
86 #define END_CANARY_VALUE	0xabababab
87 #define GET_START_CANARY(name, stack_num) name[stack_num][0]
88 #define GET_END_CANARY(name, stack_num) \
89 	name[stack_num][sizeof(name[stack_num]) / sizeof(uint32_t) - 1]
90 #else
91 #define STACK_CANARY_SIZE	0
92 #endif
93 
94 #define DECLARE_STACK(name, num_stacks, stack_size, linkage) \
95 linkage uint32_t name[num_stacks] \
96 		[ROUNDUP(stack_size + STACK_CANARY_SIZE, STACK_ALIGNMENT) / \
97 		sizeof(uint32_t)] \
98 		__attribute__((section(".nozi_stack." # name), \
99 			       aligned(STACK_ALIGNMENT)))
100 
101 #define STACK_SIZE(stack) (sizeof(stack) - STACK_CANARY_SIZE / 2)
102 
103 #define GET_STACK(stack) \
104 	((vaddr_t)(stack) + STACK_SIZE(stack))
105 
106 DECLARE_STACK(stack_tmp, CFG_TEE_CORE_NB_CORE, STACK_TMP_SIZE, static);
107 DECLARE_STACK(stack_abt, CFG_TEE_CORE_NB_CORE, STACK_ABT_SIZE, static);
108 #ifndef CFG_WITH_PAGER
109 DECLARE_STACK(stack_thread, CFG_NUM_THREADS, STACK_THREAD_SIZE, static);
110 #endif
111 
112 const void *stack_tmp_export = (uint8_t *)stack_tmp + sizeof(stack_tmp[0]) -
113 			       (STACK_TMP_OFFS + STACK_CANARY_SIZE / 2);
114 const uint32_t stack_tmp_stride = sizeof(stack_tmp[0]);
115 
116 /*
117  * These stack setup info are required by secondary boot cores before they
118  * each locally enable the pager (the mmu). Hence kept in pager sections.
119  */
120 KEEP_PAGER(stack_tmp_export);
121 KEEP_PAGER(stack_tmp_stride);
122 
123 thread_smc_handler_t thread_std_smc_handler_ptr __nex_bss;
124 static thread_smc_handler_t thread_fast_smc_handler_ptr __nex_bss;
125 thread_nintr_handler_t thread_nintr_handler_ptr __nex_bss;
126 thread_pm_handler_t thread_cpu_on_handler_ptr __nex_bss;
127 thread_pm_handler_t thread_cpu_off_handler_ptr __nex_bss;
128 thread_pm_handler_t thread_cpu_suspend_handler_ptr __nex_bss;
129 thread_pm_handler_t thread_cpu_resume_handler_ptr __nex_bss;
130 thread_pm_handler_t thread_system_off_handler_ptr __nex_bss;
131 thread_pm_handler_t thread_system_reset_handler_ptr __nex_bss;
132 
133 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
134 static vaddr_t thread_user_kcode_va __nex_bss;
135 long thread_user_kcode_offset __nex_bss;
136 static size_t thread_user_kcode_size __nex_bss;
137 #endif
138 
139 #if defined(CFG_CORE_UNMAP_CORE_AT_EL0) && \
140 	defined(CFG_CORE_WORKAROUND_SPECTRE_BP_SEC) && defined(ARM64)
141 long thread_user_kdata_sp_offset __nex_bss;
142 static uint8_t thread_user_kdata_page[
143 	ROUNDUP(sizeof(thread_core_local), SMALL_PAGE_SIZE)]
144 	__aligned(SMALL_PAGE_SIZE)
145 #ifndef CFG_VIRTUALIZATION
146 	__section(".nozi.kdata_page");
147 #else
148 	__section(".nex_nozi.kdata_page");
149 #endif
150 #endif
151 
152 static unsigned int thread_global_lock __nex_bss = SPINLOCK_UNLOCK;
153 static bool thread_prealloc_rpc_cache;
154 
155 static unsigned int thread_rpc_pnum;
156 
157 static void init_canaries(void)
158 {
159 #ifdef CFG_WITH_STACK_CANARIES
160 	size_t n;
161 #define INIT_CANARY(name)						\
162 	for (n = 0; n < ARRAY_SIZE(name); n++) {			\
163 		uint32_t *start_canary = &GET_START_CANARY(name, n);	\
164 		uint32_t *end_canary = &GET_END_CANARY(name, n);	\
165 									\
166 		*start_canary = START_CANARY_VALUE;			\
167 		*end_canary = END_CANARY_VALUE;				\
168 		DMSG("#Stack canaries for %s[%zu] with top at %p",	\
169 			#name, n, (void *)(end_canary - 1));		\
170 		DMSG("watch *%p", (void *)end_canary);			\
171 	}
172 
173 	INIT_CANARY(stack_tmp);
174 	INIT_CANARY(stack_abt);
175 #if !defined(CFG_WITH_PAGER) && !defined(CFG_VIRTUALIZATION)
176 	INIT_CANARY(stack_thread);
177 #endif
178 #endif/*CFG_WITH_STACK_CANARIES*/
179 }
180 
181 #define CANARY_DIED(stack, loc, n) \
182 	do { \
183 		EMSG_RAW("Dead canary at %s of '%s[%zu]'", #loc, #stack, n); \
184 		panic(); \
185 	} while (0)
186 
187 void thread_check_canaries(void)
188 {
189 #ifdef CFG_WITH_STACK_CANARIES
190 	size_t n;
191 
192 	for (n = 0; n < ARRAY_SIZE(stack_tmp); n++) {
193 		if (GET_START_CANARY(stack_tmp, n) != START_CANARY_VALUE)
194 			CANARY_DIED(stack_tmp, start, n);
195 		if (GET_END_CANARY(stack_tmp, n) != END_CANARY_VALUE)
196 			CANARY_DIED(stack_tmp, end, n);
197 	}
198 
199 	for (n = 0; n < ARRAY_SIZE(stack_abt); n++) {
200 		if (GET_START_CANARY(stack_abt, n) != START_CANARY_VALUE)
201 			CANARY_DIED(stack_abt, start, n);
202 		if (GET_END_CANARY(stack_abt, n) != END_CANARY_VALUE)
203 			CANARY_DIED(stack_abt, end, n);
204 
205 	}
206 #if !defined(CFG_WITH_PAGER) && !defined(CFG_VIRTUALIZATION)
207 	for (n = 0; n < ARRAY_SIZE(stack_thread); n++) {
208 		if (GET_START_CANARY(stack_thread, n) != START_CANARY_VALUE)
209 			CANARY_DIED(stack_thread, start, n);
210 		if (GET_END_CANARY(stack_thread, n) != END_CANARY_VALUE)
211 			CANARY_DIED(stack_thread, end, n);
212 	}
213 #endif
214 #endif/*CFG_WITH_STACK_CANARIES*/
215 }
216 
217 static void lock_global(void)
218 {
219 	cpu_spin_lock(&thread_global_lock);
220 }
221 
222 static void unlock_global(void)
223 {
224 	cpu_spin_unlock(&thread_global_lock);
225 }
226 
227 #ifdef ARM32
228 uint32_t thread_get_exceptions(void)
229 {
230 	uint32_t cpsr = read_cpsr();
231 
232 	return (cpsr >> CPSR_F_SHIFT) & THREAD_EXCP_ALL;
233 }
234 
235 void thread_set_exceptions(uint32_t exceptions)
236 {
237 	uint32_t cpsr = read_cpsr();
238 
239 	/* Foreign interrupts must not be unmasked while holding a spinlock */
240 	if (!(exceptions & THREAD_EXCP_FOREIGN_INTR))
241 		assert_have_no_spinlock();
242 
243 	cpsr &= ~(THREAD_EXCP_ALL << CPSR_F_SHIFT);
244 	cpsr |= ((exceptions & THREAD_EXCP_ALL) << CPSR_F_SHIFT);
245 	write_cpsr(cpsr);
246 }
247 #endif /*ARM32*/
248 
249 #ifdef ARM64
250 uint32_t thread_get_exceptions(void)
251 {
252 	uint32_t daif = read_daif();
253 
254 	return (daif >> DAIF_F_SHIFT) & THREAD_EXCP_ALL;
255 }
256 
257 void thread_set_exceptions(uint32_t exceptions)
258 {
259 	uint32_t daif = read_daif();
260 
261 	/* Foreign interrupts must not be unmasked while holding a spinlock */
262 	if (!(exceptions & THREAD_EXCP_FOREIGN_INTR))
263 		assert_have_no_spinlock();
264 
265 	daif &= ~(THREAD_EXCP_ALL << DAIF_F_SHIFT);
266 	daif |= ((exceptions & THREAD_EXCP_ALL) << DAIF_F_SHIFT);
267 	write_daif(daif);
268 }
269 #endif /*ARM64*/
270 
271 uint32_t thread_mask_exceptions(uint32_t exceptions)
272 {
273 	uint32_t state = thread_get_exceptions();
274 
275 	thread_set_exceptions(state | (exceptions & THREAD_EXCP_ALL));
276 	return state;
277 }
278 
279 void thread_unmask_exceptions(uint32_t state)
280 {
281 	thread_set_exceptions(state & THREAD_EXCP_ALL);
282 }
283 
284 
285 struct thread_core_local *thread_get_core_local(void)
286 {
287 	uint32_t cpu_id = get_core_pos();
288 
289 	/*
290 	 * Foreign interrupts must be disabled before playing with core_local
291 	 * since we otherwise may be rescheduled to a different core in the
292 	 * middle of this function.
293 	 */
294 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
295 
296 	assert(cpu_id < CFG_TEE_CORE_NB_CORE);
297 	return &thread_core_local[cpu_id];
298 }
299 
300 static void thread_lazy_save_ns_vfp(void)
301 {
302 #ifdef CFG_WITH_VFP
303 	struct thread_ctx *thr = threads + thread_get_id();
304 
305 	thr->vfp_state.ns_saved = false;
306 	vfp_lazy_save_state_init(&thr->vfp_state.ns);
307 #endif /*CFG_WITH_VFP*/
308 }
309 
310 static void thread_lazy_restore_ns_vfp(void)
311 {
312 #ifdef CFG_WITH_VFP
313 	struct thread_ctx *thr = threads + thread_get_id();
314 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
315 
316 	assert(!thr->vfp_state.sec_lazy_saved && !thr->vfp_state.sec_saved);
317 
318 	if (tuv && tuv->lazy_saved && !tuv->saved) {
319 		vfp_lazy_save_state_final(&tuv->vfp, false /*!force_save*/);
320 		tuv->saved = true;
321 	}
322 
323 	vfp_lazy_restore_state(&thr->vfp_state.ns, thr->vfp_state.ns_saved);
324 	thr->vfp_state.ns_saved = false;
325 #endif /*CFG_WITH_VFP*/
326 }
327 
328 #ifdef ARM32
329 static void init_regs(struct thread_ctx *thread,
330 		struct thread_smc_args *args)
331 {
332 	thread->regs.pc = (uint32_t)thread_std_smc_entry;
333 
334 	/*
335 	 * Stdcalls starts in SVC mode with masked foreign interrupts, masked
336 	 * Asynchronous abort and unmasked native interrupts.
337 	 */
338 	thread->regs.cpsr = read_cpsr() & ARM32_CPSR_E;
339 	thread->regs.cpsr |= CPSR_MODE_SVC | CPSR_A |
340 			(THREAD_EXCP_FOREIGN_INTR << ARM32_CPSR_F_SHIFT);
341 	/* Enable thumb mode if it's a thumb instruction */
342 	if (thread->regs.pc & 1)
343 		thread->regs.cpsr |= CPSR_T;
344 	/* Reinitialize stack pointer */
345 	thread->regs.svc_sp = thread->stack_va_end;
346 
347 	/*
348 	 * Copy arguments into context. This will make the
349 	 * arguments appear in r0-r7 when thread is started.
350 	 */
351 	thread->regs.r0 = args->a0;
352 	thread->regs.r1 = args->a1;
353 	thread->regs.r2 = args->a2;
354 	thread->regs.r3 = args->a3;
355 	thread->regs.r4 = args->a4;
356 	thread->regs.r5 = args->a5;
357 	thread->regs.r6 = args->a6;
358 	thread->regs.r7 = args->a7;
359 }
360 #endif /*ARM32*/
361 
362 #ifdef ARM64
363 static void init_regs(struct thread_ctx *thread,
364 		struct thread_smc_args *args)
365 {
366 	thread->regs.pc = (uint64_t)thread_std_smc_entry;
367 
368 	/*
369 	 * Stdcalls starts in SVC mode with masked foreign interrupts, masked
370 	 * Asynchronous abort and unmasked native interrupts.
371 	 */
372 	thread->regs.cpsr = SPSR_64(SPSR_64_MODE_EL1, SPSR_64_MODE_SP_EL0,
373 				THREAD_EXCP_FOREIGN_INTR | DAIFBIT_ABT);
374 	/* Reinitialize stack pointer */
375 	thread->regs.sp = thread->stack_va_end;
376 
377 	/*
378 	 * Copy arguments into context. This will make the
379 	 * arguments appear in x0-x7 when thread is started.
380 	 */
381 	thread->regs.x[0] = args->a0;
382 	thread->regs.x[1] = args->a1;
383 	thread->regs.x[2] = args->a2;
384 	thread->regs.x[3] = args->a3;
385 	thread->regs.x[4] = args->a4;
386 	thread->regs.x[5] = args->a5;
387 	thread->regs.x[6] = args->a6;
388 	thread->regs.x[7] = args->a7;
389 
390 	/* Set up frame pointer as per the Aarch64 AAPCS */
391 	thread->regs.x[29] = 0;
392 }
393 #endif /*ARM64*/
394 
395 void thread_init_boot_thread(void)
396 {
397 	struct thread_core_local *l = thread_get_core_local();
398 
399 	thread_init_threads();
400 
401 	l->curr_thread = 0;
402 	threads[0].state = THREAD_STATE_ACTIVE;
403 }
404 
405 void thread_clr_boot_thread(void)
406 {
407 	struct thread_core_local *l = thread_get_core_local();
408 
409 	assert(l->curr_thread >= 0 && l->curr_thread < CFG_NUM_THREADS);
410 	assert(threads[l->curr_thread].state == THREAD_STATE_ACTIVE);
411 	threads[l->curr_thread].state = THREAD_STATE_FREE;
412 	l->curr_thread = -1;
413 }
414 
415 static void thread_alloc_and_run(struct thread_smc_args *args)
416 {
417 	size_t n;
418 	struct thread_core_local *l = thread_get_core_local();
419 	bool found_thread = false;
420 
421 	assert(l->curr_thread == -1);
422 
423 	lock_global();
424 
425 	for (n = 0; n < CFG_NUM_THREADS; n++) {
426 		if (threads[n].state == THREAD_STATE_FREE) {
427 			threads[n].state = THREAD_STATE_ACTIVE;
428 			found_thread = true;
429 			break;
430 		}
431 	}
432 
433 	unlock_global();
434 
435 	if (!found_thread) {
436 		args->a0 = OPTEE_SMC_RETURN_ETHREAD_LIMIT;
437 		return;
438 	}
439 
440 	l->curr_thread = n;
441 
442 	threads[n].flags = 0;
443 	init_regs(threads + n, args);
444 
445 	/* Save Hypervisor Client ID */
446 	threads[n].hyp_clnt_id = args->a7;
447 
448 	thread_lazy_save_ns_vfp();
449 	thread_resume(&threads[n].regs);
450 }
451 
452 #ifdef ARM32
453 static void copy_a0_to_a5(struct thread_ctx_regs *regs,
454 		struct thread_smc_args *args)
455 {
456 	/*
457 	 * Update returned values from RPC, values will appear in
458 	 * r0-r3 when thread is resumed.
459 	 */
460 	regs->r0 = args->a0;
461 	regs->r1 = args->a1;
462 	regs->r2 = args->a2;
463 	regs->r3 = args->a3;
464 	regs->r4 = args->a4;
465 	regs->r5 = args->a5;
466 }
467 #endif /*ARM32*/
468 
469 #ifdef ARM64
470 static void copy_a0_to_a5(struct thread_ctx_regs *regs,
471 		struct thread_smc_args *args)
472 {
473 	/*
474 	 * Update returned values from RPC, values will appear in
475 	 * x0-x3 when thread is resumed.
476 	 */
477 	regs->x[0] = args->a0;
478 	regs->x[1] = args->a1;
479 	regs->x[2] = args->a2;
480 	regs->x[3] = args->a3;
481 	regs->x[4] = args->a4;
482 	regs->x[5] = args->a5;
483 }
484 #endif /*ARM64*/
485 
486 #ifdef ARM32
487 static bool is_from_user(uint32_t cpsr)
488 {
489 	return (cpsr & ARM32_CPSR_MODE_MASK) == ARM32_CPSR_MODE_USR;
490 }
491 #endif
492 
493 #ifdef ARM64
494 static bool is_from_user(uint32_t cpsr)
495 {
496 	if (cpsr & (SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT))
497 		return true;
498 	if (((cpsr >> SPSR_64_MODE_EL_SHIFT) & SPSR_64_MODE_EL_MASK) ==
499 	     SPSR_64_MODE_EL0)
500 		return true;
501 	return false;
502 }
503 #endif
504 
505 static bool is_user_mode(struct thread_ctx_regs *regs)
506 {
507 	return is_from_user((uint32_t)regs->cpsr);
508 }
509 
510 static void thread_resume_from_rpc(struct thread_smc_args *args)
511 {
512 	size_t n = args->a3; /* thread id */
513 	struct thread_core_local *l = thread_get_core_local();
514 	uint32_t rv = 0;
515 
516 	assert(l->curr_thread == -1);
517 
518 	lock_global();
519 
520 	if (n < CFG_NUM_THREADS &&
521 	    threads[n].state == THREAD_STATE_SUSPENDED &&
522 	    args->a7 == threads[n].hyp_clnt_id)
523 		threads[n].state = THREAD_STATE_ACTIVE;
524 	else
525 		rv = OPTEE_SMC_RETURN_ERESUME;
526 
527 	unlock_global();
528 
529 	if (rv) {
530 		args->a0 = rv;
531 		return;
532 	}
533 
534 	l->curr_thread = n;
535 
536 	if (threads[n].have_user_map)
537 		core_mmu_set_user_map(&threads[n].user_map);
538 
539 	if (is_user_mode(&threads[n].regs))
540 		tee_ta_update_session_utime_resume();
541 
542 	/*
543 	 * Return from RPC to request service of a foreign interrupt must not
544 	 * get parameters from non-secure world.
545 	 */
546 	if (threads[n].flags & THREAD_FLAGS_COPY_ARGS_ON_RETURN) {
547 		copy_a0_to_a5(&threads[n].regs, args);
548 		threads[n].flags &= ~THREAD_FLAGS_COPY_ARGS_ON_RETURN;
549 	}
550 
551 	thread_lazy_save_ns_vfp();
552 	thread_resume(&threads[n].regs);
553 }
554 
555 void thread_handle_fast_smc(struct thread_smc_args *args)
556 {
557 	thread_check_canaries();
558 
559 #ifdef CFG_VIRTUALIZATION
560 	if (!virt_set_guest(args->a7)) {
561 		args->a0 = OPTEE_SMC_RETURN_ENOTAVAIL;
562 		goto out;
563 	}
564 #endif
565 
566 	thread_fast_smc_handler_ptr(args);
567 
568 #ifdef CFG_VIRTUALIZATION
569 	virt_unset_guest();
570 #endif
571 	/* Fast handlers must not unmask any exceptions */
572 out:
573 	__maybe_unused;
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 #ifdef CFG_VIRTUALIZATION
582 	if (!virt_set_guest(args->a7)) {
583 		args->a0 = OPTEE_SMC_RETURN_ENOTAVAIL;
584 		return;
585 	}
586 #endif
587 
588 	if (args->a0 == OPTEE_SMC_CALL_RETURN_FROM_RPC)
589 		thread_resume_from_rpc(args);
590 	else
591 		thread_alloc_and_run(args);
592 
593 #ifdef CFG_VIRTUALIZATION
594 	virt_unset_guest();
595 #endif
596 
597 }
598 
599 /**
600  * Free physical memory previously allocated with thread_rpc_alloc_arg()
601  *
602  * @cookie:	cookie received when allocating the buffer
603  */
604 static void thread_rpc_free_arg(uint64_t cookie)
605 {
606 	if (cookie) {
607 		uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = {
608 			OPTEE_SMC_RETURN_RPC_FREE
609 		};
610 
611 		reg_pair_from_64(cookie, rpc_args + 1, rpc_args + 2);
612 		thread_rpc(rpc_args);
613 	}
614 }
615 
616 /*
617  * Helper routine for the assembly function thread_std_smc_entry()
618  *
619  * Note: this function is weak just to make it possible to exclude it from
620  * the unpaged area.
621  */
622 void __weak __thread_std_smc_entry(struct thread_smc_args *args)
623 {
624 #ifdef CFG_VIRTUALIZATION
625 	virt_on_stdcall();
626 #endif
627 	thread_std_smc_handler_ptr(args);
628 
629 	if (args->a0 == OPTEE_SMC_RETURN_OK) {
630 		struct thread_ctx *thr = threads + thread_get_id();
631 
632 		tee_fs_rpc_cache_clear(&thr->tsd);
633 		if (!thread_prealloc_rpc_cache) {
634 			thread_rpc_free_arg(mobj_get_cookie(thr->rpc_mobj));
635 			mobj_free(thr->rpc_mobj);
636 			thr->rpc_arg = 0;
637 			thr->rpc_mobj = NULL;
638 		}
639 	}
640 }
641 
642 void *thread_get_tmp_sp(void)
643 {
644 	struct thread_core_local *l = thread_get_core_local();
645 
646 	return (void *)l->tmp_stack_va_end;
647 }
648 
649 #ifdef ARM64
650 vaddr_t thread_get_saved_thread_sp(void)
651 {
652 	struct thread_core_local *l = thread_get_core_local();
653 	int ct = l->curr_thread;
654 
655 	assert(ct != -1);
656 	return threads[ct].kern_sp;
657 }
658 #endif /*ARM64*/
659 
660 vaddr_t thread_stack_start(void)
661 {
662 	struct thread_ctx *thr;
663 	int ct = thread_get_id_may_fail();
664 
665 	if (ct == -1)
666 		return 0;
667 
668 	thr = threads + ct;
669 	return thr->stack_va_end - STACK_THREAD_SIZE;
670 }
671 
672 size_t thread_stack_size(void)
673 {
674 	return STACK_THREAD_SIZE;
675 }
676 
677 bool thread_is_from_abort_mode(void)
678 {
679 	struct thread_core_local *l = thread_get_core_local();
680 
681 	return (l->flags >> THREAD_CLF_SAVED_SHIFT) & THREAD_CLF_ABORT;
682 }
683 
684 #ifdef ARM32
685 bool thread_is_in_normal_mode(void)
686 {
687 	return (read_cpsr() & ARM32_CPSR_MODE_MASK) == ARM32_CPSR_MODE_SVC;
688 }
689 #endif
690 
691 #ifdef ARM64
692 bool thread_is_in_normal_mode(void)
693 {
694 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
695 	struct thread_core_local *l = thread_get_core_local();
696 	bool ret;
697 
698 	/* If any bit in l->flags is set we're handling some exception. */
699 	ret = !l->flags;
700 	thread_unmask_exceptions(exceptions);
701 
702 	return ret;
703 }
704 #endif
705 
706 void thread_state_free(void)
707 {
708 	struct thread_core_local *l = thread_get_core_local();
709 	int ct = l->curr_thread;
710 
711 	assert(ct != -1);
712 
713 	thread_lazy_restore_ns_vfp();
714 	tee_pager_release_phys(
715 		(void *)(threads[ct].stack_va_end - STACK_THREAD_SIZE),
716 		STACK_THREAD_SIZE);
717 
718 	lock_global();
719 
720 	assert(threads[ct].state == THREAD_STATE_ACTIVE);
721 	threads[ct].state = THREAD_STATE_FREE;
722 	threads[ct].flags = 0;
723 	l->curr_thread = -1;
724 
725 #ifdef CFG_VIRTUALIZATION
726 	virt_unset_guest();
727 #endif
728 	unlock_global();
729 }
730 
731 #ifdef CFG_WITH_PAGER
732 static void release_unused_kernel_stack(struct thread_ctx *thr,
733 					uint32_t cpsr __maybe_unused)
734 {
735 #ifdef ARM64
736 	/*
737 	 * If we're from user mode then thr->regs.sp is the saved user
738 	 * stack pointer and thr->kern_sp holds the last kernel stack
739 	 * pointer. But if we're from kernel mode then thr->kern_sp isn't
740 	 * up to date so we need to read from thr->regs.sp instead.
741 	 */
742 	vaddr_t sp = is_from_user(cpsr) ?  thr->kern_sp : thr->regs.sp;
743 #else
744 	vaddr_t sp = thr->regs.svc_sp;
745 #endif
746 	vaddr_t base = thr->stack_va_end - STACK_THREAD_SIZE;
747 	size_t len = sp - base;
748 
749 	tee_pager_release_phys((void *)base, len);
750 }
751 #else
752 static void release_unused_kernel_stack(struct thread_ctx *thr __unused,
753 					uint32_t cpsr __unused)
754 {
755 }
756 #endif
757 
758 int thread_state_suspend(uint32_t flags, uint32_t cpsr, vaddr_t pc)
759 {
760 	struct thread_core_local *l = thread_get_core_local();
761 	int ct = l->curr_thread;
762 
763 	assert(ct != -1);
764 
765 	thread_check_canaries();
766 
767 	release_unused_kernel_stack(threads + ct, cpsr);
768 
769 	if (is_from_user(cpsr)) {
770 		thread_user_save_vfp();
771 		tee_ta_update_session_utime_suspend();
772 		tee_ta_gprof_sample_pc(pc);
773 	}
774 	thread_lazy_restore_ns_vfp();
775 
776 	lock_global();
777 
778 	assert(threads[ct].state == THREAD_STATE_ACTIVE);
779 	threads[ct].flags |= flags;
780 	threads[ct].regs.cpsr = cpsr;
781 	threads[ct].regs.pc = pc;
782 	threads[ct].state = THREAD_STATE_SUSPENDED;
783 
784 	threads[ct].have_user_map = core_mmu_user_mapping_is_active();
785 	if (threads[ct].have_user_map) {
786 		core_mmu_get_user_map(&threads[ct].user_map);
787 		core_mmu_set_user_map(NULL);
788 	}
789 
790 	l->curr_thread = -1;
791 
792 #ifdef CFG_VIRTUALIZATION
793 	virt_unset_guest();
794 #endif
795 
796 	unlock_global();
797 
798 	return ct;
799 }
800 
801 #ifdef ARM32
802 static void set_tmp_stack(struct thread_core_local *l, vaddr_t sp)
803 {
804 	l->tmp_stack_va_end = sp;
805 	thread_set_irq_sp(sp);
806 	thread_set_fiq_sp(sp);
807 }
808 
809 static void set_abt_stack(struct thread_core_local *l, vaddr_t sp)
810 {
811 	l->abt_stack_va_end = sp;
812 	thread_set_abt_sp((vaddr_t)l);
813 	thread_set_und_sp((vaddr_t)l);
814 }
815 #endif /*ARM32*/
816 
817 #ifdef ARM64
818 static void set_tmp_stack(struct thread_core_local *l, vaddr_t sp)
819 {
820 	/*
821 	 * We're already using the tmp stack when this function is called
822 	 * so there's no need to assign it to any stack pointer. However,
823 	 * we'll need to restore it at different times so store it here.
824 	 */
825 	l->tmp_stack_va_end = sp;
826 }
827 
828 static void set_abt_stack(struct thread_core_local *l, vaddr_t sp)
829 {
830 	l->abt_stack_va_end = sp;
831 }
832 #endif /*ARM64*/
833 
834 bool thread_init_stack(uint32_t thread_id, vaddr_t sp)
835 {
836 	if (thread_id >= CFG_NUM_THREADS)
837 		return false;
838 	threads[thread_id].stack_va_end = sp;
839 	return true;
840 }
841 
842 int thread_get_id_may_fail(void)
843 {
844 	/*
845 	 * thread_get_core_local() requires foreign interrupts to be disabled
846 	 */
847 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
848 	struct thread_core_local *l = thread_get_core_local();
849 	int ct = l->curr_thread;
850 
851 	thread_unmask_exceptions(exceptions);
852 	return ct;
853 }
854 
855 int thread_get_id(void)
856 {
857 	int ct = thread_get_id_may_fail();
858 
859 	assert(ct >= 0 && ct < CFG_NUM_THREADS);
860 	return ct;
861 }
862 
863 static void init_handlers(const struct thread_handlers *handlers)
864 {
865 	thread_std_smc_handler_ptr = handlers->std_smc;
866 	thread_fast_smc_handler_ptr = handlers->fast_smc;
867 	thread_nintr_handler_ptr = handlers->nintr;
868 	thread_cpu_on_handler_ptr = handlers->cpu_on;
869 	thread_cpu_off_handler_ptr = handlers->cpu_off;
870 	thread_cpu_suspend_handler_ptr = handlers->cpu_suspend;
871 	thread_cpu_resume_handler_ptr = handlers->cpu_resume;
872 	thread_system_off_handler_ptr = handlers->system_off;
873 	thread_system_reset_handler_ptr = handlers->system_reset;
874 }
875 
876 #ifdef CFG_WITH_PAGER
877 static void init_thread_stacks(void)
878 {
879 	size_t n = 0;
880 
881 	/*
882 	 * Allocate virtual memory for thread stacks.
883 	 */
884 	for (n = 0; n < CFG_NUM_THREADS; n++) {
885 		tee_mm_entry_t *mm = NULL;
886 		vaddr_t sp = 0;
887 		size_t num_pages = 0;
888 		struct fobj *fobj = NULL;
889 
890 		/* Find vmem for thread stack and its protection gap */
891 		mm = tee_mm_alloc(&tee_mm_vcore,
892 				  SMALL_PAGE_SIZE + STACK_THREAD_SIZE);
893 		assert(mm);
894 
895 		/* Claim eventual physical page */
896 		tee_pager_add_pages(tee_mm_get_smem(mm), tee_mm_get_size(mm),
897 				    true);
898 
899 		num_pages = tee_mm_get_bytes(mm) / SMALL_PAGE_SIZE - 1;
900 		fobj = fobj_locked_paged_alloc(num_pages);
901 
902 		/* Add the area to the pager */
903 		tee_pager_add_core_area(tee_mm_get_smem(mm) + SMALL_PAGE_SIZE,
904 					PAGER_AREA_TYPE_LOCK, fobj);
905 		fobj_put(fobj);
906 
907 		/* init effective stack */
908 		sp = tee_mm_get_smem(mm) + tee_mm_get_bytes(mm);
909 		asan_tag_access((void *)tee_mm_get_smem(mm), (void *)sp);
910 		if (!thread_init_stack(n, sp))
911 			panic("init stack failed");
912 	}
913 }
914 #else
915 static void init_thread_stacks(void)
916 {
917 	size_t n;
918 
919 	/* Assign the thread stacks */
920 	for (n = 0; n < CFG_NUM_THREADS; n++) {
921 		if (!thread_init_stack(n, GET_STACK(stack_thread[n])))
922 			panic("thread_init_stack failed");
923 	}
924 }
925 #endif /*CFG_WITH_PAGER*/
926 
927 static void init_user_kcode(void)
928 {
929 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
930 	vaddr_t v = (vaddr_t)thread_excp_vect;
931 	vaddr_t ve = (vaddr_t)thread_excp_vect_end;
932 
933 	thread_user_kcode_va = ROUNDDOWN(v, CORE_MMU_USER_CODE_SIZE);
934 	ve = ROUNDUP(ve, CORE_MMU_USER_CODE_SIZE);
935 	thread_user_kcode_size = ve - thread_user_kcode_va;
936 
937 	core_mmu_get_user_va_range(&v, NULL);
938 	thread_user_kcode_offset = thread_user_kcode_va - v;
939 
940 #if defined(CFG_CORE_WORKAROUND_SPECTRE_BP_SEC) && defined(ARM64)
941 	/*
942 	 * When transitioning to EL0 subtract SP with this much to point to
943 	 * this special kdata page instead. SP is restored by add this much
944 	 * while transitioning back to EL1.
945 	 */
946 	v += thread_user_kcode_size;
947 	thread_user_kdata_sp_offset = (vaddr_t)thread_core_local - v;
948 #endif
949 #endif /*CFG_CORE_UNMAP_CORE_AT_EL0*/
950 }
951 
952 void thread_init_threads(void)
953 {
954 	size_t n;
955 
956 	init_thread_stacks();
957 	pgt_init();
958 
959 	mutex_lockdep_init();
960 
961 	for (n = 0; n < CFG_NUM_THREADS; n++) {
962 		TAILQ_INIT(&threads[n].tsd.sess_stack);
963 		SLIST_INIT(&threads[n].tsd.pgt_cache);
964 	}
965 
966 	for (n = 0; n < CFG_TEE_CORE_NB_CORE; n++)
967 		thread_core_local[n].curr_thread = -1;
968 }
969 
970 void thread_init_primary(const struct thread_handlers *handlers)
971 {
972 	init_handlers(handlers);
973 
974 	/* Initialize canaries around the stacks */
975 	init_canaries();
976 
977 	init_user_kcode();
978 }
979 
980 static void init_sec_mon(size_t pos __maybe_unused)
981 {
982 #if !defined(CFG_WITH_ARM_TRUSTED_FW)
983 	/* Initialize secure monitor */
984 	sm_init(GET_STACK(stack_tmp[pos]));
985 #endif
986 }
987 
988 static uint32_t __maybe_unused get_midr_implementer(uint32_t midr)
989 {
990 	return (midr >> MIDR_IMPLEMENTER_SHIFT) & MIDR_IMPLEMENTER_MASK;
991 }
992 
993 static uint32_t __maybe_unused get_midr_primary_part(uint32_t midr)
994 {
995 	return (midr >> MIDR_PRIMARY_PART_NUM_SHIFT) &
996 	       MIDR_PRIMARY_PART_NUM_MASK;
997 }
998 
999 #ifdef ARM64
1000 static bool probe_workaround_available(void)
1001 {
1002 	int32_t r;
1003 
1004 	r = thread_smc(SMCCC_VERSION, 0, 0, 0);
1005 	if (r < 0)
1006 		return false;
1007 	if (r < 0x10001)	/* compare with version 1.1 */
1008 		return false;
1009 
1010 	/* Version >= 1.1, so SMCCC_ARCH_FEATURES is available */
1011 	r = thread_smc(SMCCC_ARCH_FEATURES, SMCCC_ARCH_WORKAROUND_1, 0, 0);
1012 	return r >= 0;
1013 }
1014 
1015 static vaddr_t __maybe_unused select_vector(vaddr_t a)
1016 {
1017 	if (probe_workaround_available()) {
1018 		DMSG("SMCCC_ARCH_WORKAROUND_1 (%#08" PRIx32 ") available",
1019 		     SMCCC_ARCH_WORKAROUND_1);
1020 		DMSG("SMC Workaround for CVE-2017-5715 used");
1021 		return a;
1022 	}
1023 
1024 	DMSG("SMCCC_ARCH_WORKAROUND_1 (%#08" PRIx32 ") unavailable",
1025 	     SMCCC_ARCH_WORKAROUND_1);
1026 	DMSG("SMC Workaround for CVE-2017-5715 not needed (if ARM-TF is up to date)");
1027 	return (vaddr_t)thread_excp_vect;
1028 }
1029 #else
1030 static vaddr_t __maybe_unused select_vector(vaddr_t a)
1031 {
1032 	return a;
1033 }
1034 #endif
1035 
1036 static vaddr_t get_excp_vect(void)
1037 {
1038 #ifdef CFG_CORE_WORKAROUND_SPECTRE_BP_SEC
1039 	uint32_t midr = read_midr();
1040 
1041 	if (get_midr_implementer(midr) != MIDR_IMPLEMENTER_ARM)
1042 		return (vaddr_t)thread_excp_vect;
1043 
1044 	switch (get_midr_primary_part(midr)) {
1045 #ifdef ARM32
1046 	case CORTEX_A8_PART_NUM:
1047 	case CORTEX_A9_PART_NUM:
1048 	case CORTEX_A17_PART_NUM:
1049 #endif
1050 	case CORTEX_A57_PART_NUM:
1051 	case CORTEX_A72_PART_NUM:
1052 	case CORTEX_A73_PART_NUM:
1053 	case CORTEX_A75_PART_NUM:
1054 		return select_vector((vaddr_t)thread_excp_vect_workaround);
1055 #ifdef ARM32
1056 	case CORTEX_A15_PART_NUM:
1057 		return select_vector((vaddr_t)thread_excp_vect_workaround_a15);
1058 #endif
1059 	default:
1060 		return (vaddr_t)thread_excp_vect;
1061 	}
1062 #endif /*CFG_CORE_WORKAROUND_SPECTRE_BP_SEC*/
1063 
1064 	return (vaddr_t)thread_excp_vect;
1065 }
1066 
1067 void thread_init_per_cpu(void)
1068 {
1069 	size_t pos = get_core_pos();
1070 	struct thread_core_local *l = thread_get_core_local();
1071 
1072 	init_sec_mon(pos);
1073 
1074 	set_tmp_stack(l, GET_STACK(stack_tmp[pos]) - STACK_TMP_OFFS);
1075 	set_abt_stack(l, GET_STACK(stack_abt[pos]));
1076 
1077 	thread_init_vbar(get_excp_vect());
1078 
1079 #ifdef CFG_TA_FTRACE_SUPPORT
1080 	/*
1081 	 * Enable accesses to frequency register and physical counter
1082 	 * register in EL0/PL0 required for timestamping during
1083 	 * function tracing.
1084 	 */
1085 	write_cntkctl(read_cntkctl() | CNTKCTL_PL0PCTEN);
1086 #endif
1087 }
1088 
1089 struct thread_specific_data *thread_get_tsd(void)
1090 {
1091 	return &threads[thread_get_id()].tsd;
1092 }
1093 
1094 struct thread_ctx_regs *thread_get_ctx_regs(void)
1095 {
1096 	struct thread_core_local *l = thread_get_core_local();
1097 
1098 	assert(l->curr_thread != -1);
1099 	return &threads[l->curr_thread].regs;
1100 }
1101 
1102 void thread_set_foreign_intr(bool enable)
1103 {
1104 	/* thread_get_core_local() requires foreign interrupts to be disabled */
1105 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1106 	struct thread_core_local *l;
1107 
1108 	l = thread_get_core_local();
1109 
1110 	assert(l->curr_thread != -1);
1111 
1112 	if (enable) {
1113 		threads[l->curr_thread].flags |=
1114 					THREAD_FLAGS_FOREIGN_INTR_ENABLE;
1115 		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
1116 	} else {
1117 		/*
1118 		 * No need to disable foreign interrupts here since they're
1119 		 * already disabled above.
1120 		 */
1121 		threads[l->curr_thread].flags &=
1122 					~THREAD_FLAGS_FOREIGN_INTR_ENABLE;
1123 	}
1124 }
1125 
1126 void thread_restore_foreign_intr(void)
1127 {
1128 	/* thread_get_core_local() requires foreign interrupts to be disabled */
1129 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1130 	struct thread_core_local *l;
1131 
1132 	l = thread_get_core_local();
1133 
1134 	assert(l->curr_thread != -1);
1135 
1136 	if (threads[l->curr_thread].flags & THREAD_FLAGS_FOREIGN_INTR_ENABLE)
1137 		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
1138 }
1139 
1140 #ifdef CFG_WITH_VFP
1141 uint32_t thread_kernel_enable_vfp(void)
1142 {
1143 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1144 	struct thread_ctx *thr = threads + thread_get_id();
1145 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1146 
1147 	assert(!vfp_is_enabled());
1148 
1149 	if (!thr->vfp_state.ns_saved) {
1150 		vfp_lazy_save_state_final(&thr->vfp_state.ns,
1151 					  true /*force_save*/);
1152 		thr->vfp_state.ns_saved = true;
1153 	} else if (thr->vfp_state.sec_lazy_saved &&
1154 		   !thr->vfp_state.sec_saved) {
1155 		/*
1156 		 * This happens when we're handling an abort while the
1157 		 * thread was using the VFP state.
1158 		 */
1159 		vfp_lazy_save_state_final(&thr->vfp_state.sec,
1160 					  false /*!force_save*/);
1161 		thr->vfp_state.sec_saved = true;
1162 	} else if (tuv && tuv->lazy_saved && !tuv->saved) {
1163 		/*
1164 		 * This can happen either during syscall or abort
1165 		 * processing (while processing a syscall).
1166 		 */
1167 		vfp_lazy_save_state_final(&tuv->vfp, false /*!force_save*/);
1168 		tuv->saved = true;
1169 	}
1170 
1171 	vfp_enable();
1172 	return exceptions;
1173 }
1174 
1175 void thread_kernel_disable_vfp(uint32_t state)
1176 {
1177 	uint32_t exceptions;
1178 
1179 	assert(vfp_is_enabled());
1180 
1181 	vfp_disable();
1182 	exceptions = thread_get_exceptions();
1183 	assert(exceptions & THREAD_EXCP_FOREIGN_INTR);
1184 	exceptions &= ~THREAD_EXCP_FOREIGN_INTR;
1185 	exceptions |= state & THREAD_EXCP_FOREIGN_INTR;
1186 	thread_set_exceptions(exceptions);
1187 }
1188 
1189 void thread_kernel_save_vfp(void)
1190 {
1191 	struct thread_ctx *thr = threads + thread_get_id();
1192 
1193 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1194 	if (vfp_is_enabled()) {
1195 		vfp_lazy_save_state_init(&thr->vfp_state.sec);
1196 		thr->vfp_state.sec_lazy_saved = true;
1197 	}
1198 }
1199 
1200 void thread_kernel_restore_vfp(void)
1201 {
1202 	struct thread_ctx *thr = threads + thread_get_id();
1203 
1204 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1205 	assert(!vfp_is_enabled());
1206 	if (thr->vfp_state.sec_lazy_saved) {
1207 		vfp_lazy_restore_state(&thr->vfp_state.sec,
1208 				       thr->vfp_state.sec_saved);
1209 		thr->vfp_state.sec_saved = false;
1210 		thr->vfp_state.sec_lazy_saved = false;
1211 	}
1212 }
1213 
1214 void thread_user_enable_vfp(struct thread_user_vfp_state *uvfp)
1215 {
1216 	struct thread_ctx *thr = threads + thread_get_id();
1217 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1218 
1219 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1220 	assert(!vfp_is_enabled());
1221 
1222 	if (!thr->vfp_state.ns_saved) {
1223 		vfp_lazy_save_state_final(&thr->vfp_state.ns,
1224 					  true /*force_save*/);
1225 		thr->vfp_state.ns_saved = true;
1226 	} else if (tuv && uvfp != tuv) {
1227 		if (tuv->lazy_saved && !tuv->saved) {
1228 			vfp_lazy_save_state_final(&tuv->vfp,
1229 						  false /*!force_save*/);
1230 			tuv->saved = true;
1231 		}
1232 	}
1233 
1234 	if (uvfp->lazy_saved)
1235 		vfp_lazy_restore_state(&uvfp->vfp, uvfp->saved);
1236 	uvfp->lazy_saved = false;
1237 	uvfp->saved = false;
1238 
1239 	thr->vfp_state.uvfp = uvfp;
1240 	vfp_enable();
1241 }
1242 
1243 void thread_user_save_vfp(void)
1244 {
1245 	struct thread_ctx *thr = threads + thread_get_id();
1246 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1247 
1248 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1249 	if (!vfp_is_enabled())
1250 		return;
1251 
1252 	assert(tuv && !tuv->lazy_saved && !tuv->saved);
1253 	vfp_lazy_save_state_init(&tuv->vfp);
1254 	tuv->lazy_saved = true;
1255 }
1256 
1257 void thread_user_clear_vfp(struct thread_user_vfp_state *uvfp)
1258 {
1259 	struct thread_ctx *thr = threads + thread_get_id();
1260 
1261 	if (uvfp == thr->vfp_state.uvfp)
1262 		thr->vfp_state.uvfp = NULL;
1263 	uvfp->lazy_saved = false;
1264 	uvfp->saved = false;
1265 }
1266 #endif /*CFG_WITH_VFP*/
1267 
1268 #ifdef ARM32
1269 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1270 {
1271 	uint32_t s;
1272 
1273 	if (!is_32bit)
1274 		return false;
1275 
1276 	s = read_spsr();
1277 	s &= ~(CPSR_MODE_MASK | CPSR_T | CPSR_IT_MASK1 | CPSR_IT_MASK2);
1278 	s |= CPSR_MODE_USR;
1279 	if (entry_func & 1)
1280 		s |= CPSR_T;
1281 	*spsr = s;
1282 	return true;
1283 }
1284 #endif
1285 
1286 #ifdef ARM64
1287 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1288 {
1289 	uint32_t s;
1290 
1291 	if (is_32bit) {
1292 		s = read_daif() & (SPSR_32_AIF_MASK << SPSR_32_AIF_SHIFT);
1293 		s |= SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT;
1294 		s |= (entry_func & SPSR_32_T_MASK) << SPSR_32_T_SHIFT;
1295 	} else {
1296 		s = read_daif() & (SPSR_64_DAIF_MASK << SPSR_64_DAIF_SHIFT);
1297 	}
1298 
1299 	*spsr = s;
1300 	return true;
1301 }
1302 #endif
1303 
1304 uint32_t thread_enter_user_mode(unsigned long a0, unsigned long a1,
1305 		unsigned long a2, unsigned long a3, unsigned long user_sp,
1306 		unsigned long entry_func, bool is_32bit,
1307 		uint32_t *exit_status0, uint32_t *exit_status1)
1308 {
1309 	uint32_t spsr;
1310 
1311 	tee_ta_update_session_utime_resume();
1312 
1313 	if (!get_spsr(is_32bit, entry_func, &spsr)) {
1314 		*exit_status0 = 1; /* panic */
1315 		*exit_status1 = 0xbadbadba;
1316 		return 0;
1317 	}
1318 	return __thread_enter_user_mode(a0, a1, a2, a3, user_sp, entry_func,
1319 					spsr, exit_status0, exit_status1);
1320 }
1321 
1322 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
1323 void thread_get_user_kcode(struct mobj **mobj, size_t *offset,
1324 			   vaddr_t *va, size_t *sz)
1325 {
1326 	core_mmu_get_user_va_range(va, NULL);
1327 	*mobj = mobj_tee_ram;
1328 	*offset = thread_user_kcode_va - TEE_RAM_START;
1329 	*sz = thread_user_kcode_size;
1330 }
1331 #endif
1332 
1333 #if defined(CFG_CORE_UNMAP_CORE_AT_EL0) && \
1334 	defined(CFG_CORE_WORKAROUND_SPECTRE_BP_SEC) && defined(ARM64)
1335 void thread_get_user_kdata(struct mobj **mobj, size_t *offset,
1336 			   vaddr_t *va, size_t *sz)
1337 {
1338 	vaddr_t v;
1339 
1340 	core_mmu_get_user_va_range(&v, NULL);
1341 	*va = v + thread_user_kcode_size;
1342 	*mobj = mobj_tee_ram;
1343 	*offset = (vaddr_t)thread_user_kdata_page - TEE_RAM_START;
1344 	*sz = sizeof(thread_user_kdata_page);
1345 }
1346 #endif
1347 
1348 bool thread_disable_prealloc_rpc_cache(uint64_t *cookie)
1349 {
1350 	bool rv;
1351 	size_t n;
1352 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1353 
1354 	lock_global();
1355 
1356 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1357 		if (threads[n].state != THREAD_STATE_FREE) {
1358 			rv = false;
1359 			goto out;
1360 		}
1361 	}
1362 
1363 	rv = true;
1364 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1365 		if (threads[n].rpc_arg) {
1366 			*cookie = mobj_get_cookie(threads[n].rpc_mobj);
1367 			mobj_free(threads[n].rpc_mobj);
1368 			threads[n].rpc_arg = NULL;
1369 			goto out;
1370 		}
1371 	}
1372 
1373 	*cookie = 0;
1374 	thread_prealloc_rpc_cache = false;
1375 out:
1376 	unlock_global();
1377 	thread_unmask_exceptions(exceptions);
1378 	return rv;
1379 }
1380 
1381 bool thread_enable_prealloc_rpc_cache(void)
1382 {
1383 	bool rv;
1384 	size_t n;
1385 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1386 
1387 	lock_global();
1388 
1389 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1390 		if (threads[n].state != THREAD_STATE_FREE) {
1391 			rv = false;
1392 			goto out;
1393 		}
1394 	}
1395 
1396 	rv = true;
1397 	thread_prealloc_rpc_cache = true;
1398 out:
1399 	unlock_global();
1400 	thread_unmask_exceptions(exceptions);
1401 	return rv;
1402 }
1403 
1404 /**
1405  * Allocates data for struct optee_msg_arg.
1406  *
1407  * @size:	size in bytes of struct optee_msg_arg
1408  *
1409  * @returns	mobj that describes allocated buffer or NULL on error
1410  */
1411 static struct mobj *thread_rpc_alloc_arg(size_t size)
1412 {
1413 	paddr_t pa;
1414 	uint64_t co;
1415 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = {
1416 		OPTEE_SMC_RETURN_RPC_ALLOC, size
1417 	};
1418 	struct mobj *mobj = NULL;
1419 
1420 	thread_rpc(rpc_args);
1421 
1422 	pa = reg_pair_to_64(rpc_args[1], rpc_args[2]);
1423 	co = reg_pair_to_64(rpc_args[4], rpc_args[5]);
1424 
1425 	if (!ALIGNMENT_IS_OK(pa, struct optee_msg_arg))
1426 		goto err;
1427 
1428 	/* Check if this region is in static shared space */
1429 	if (core_pbuf_is(CORE_MEM_NSEC_SHM, pa, size))
1430 		mobj = mobj_shm_alloc(pa, size, co);
1431 #ifdef CFG_CORE_DYN_SHM
1432 	else if ((!(pa & SMALL_PAGE_MASK)) && size <= SMALL_PAGE_SIZE)
1433 		mobj = mobj_mapped_shm_alloc(&pa, 1, 0, co);
1434 #endif
1435 
1436 	if (!mobj)
1437 		goto err;
1438 
1439 	return mobj;
1440 err:
1441 	thread_rpc_free_arg(co);
1442 	mobj_free(mobj);
1443 	return NULL;
1444 }
1445 
1446 static bool set_rmem(struct optee_msg_param *param,
1447 		     struct thread_param *tpm)
1448 {
1449 	param->attr = tpm->attr - THREAD_PARAM_ATTR_MEMREF_IN +
1450 		      OPTEE_MSG_ATTR_TYPE_RMEM_INPUT;
1451 	param->u.rmem.offs = tpm->u.memref.offs;
1452 	param->u.rmem.size = tpm->u.memref.size;
1453 	if (tpm->u.memref.mobj) {
1454 		param->u.rmem.shm_ref = mobj_get_cookie(tpm->u.memref.mobj);
1455 		if (!param->u.rmem.shm_ref)
1456 			return false;
1457 	} else {
1458 		param->u.rmem.shm_ref = 0;
1459 	}
1460 
1461 	return true;
1462 }
1463 
1464 static bool set_tmem(struct optee_msg_param *param,
1465 		     struct thread_param *tpm)
1466 {
1467 	paddr_t pa = 0;
1468 	uint64_t shm_ref = 0;
1469 	struct mobj *mobj = tpm->u.memref.mobj;
1470 
1471 	param->attr = tpm->attr - THREAD_PARAM_ATTR_MEMREF_IN +
1472 		      OPTEE_MSG_ATTR_TYPE_TMEM_INPUT;
1473 	if (mobj) {
1474 		shm_ref = mobj_get_cookie(mobj);
1475 		if (!shm_ref)
1476 			return false;
1477 		if (mobj_get_pa(mobj, tpm->u.memref.offs, 0, &pa))
1478 			return false;
1479 	}
1480 
1481 	param->u.tmem.size = tpm->u.memref.size;
1482 	param->u.tmem.buf_ptr = pa;
1483 	param->u.tmem.shm_ref = shm_ref;
1484 
1485 	return true;
1486 }
1487 
1488 static uint32_t get_rpc_arg(uint32_t cmd, size_t num_params,
1489 			    struct thread_param *params, void **arg_ret,
1490 			    uint64_t *carg_ret)
1491 {
1492 	struct thread_ctx *thr = threads + thread_get_id();
1493 	struct optee_msg_arg *arg = thr->rpc_arg;
1494 	size_t sz = OPTEE_MSG_GET_ARG_SIZE(THREAD_RPC_MAX_NUM_PARAMS);
1495 
1496 	if (num_params > THREAD_RPC_MAX_NUM_PARAMS)
1497 		return TEE_ERROR_BAD_PARAMETERS;
1498 
1499 	if (!arg) {
1500 		struct mobj *mobj = thread_rpc_alloc_arg(sz);
1501 
1502 		if (!mobj)
1503 			return TEE_ERROR_OUT_OF_MEMORY;
1504 
1505 		arg = mobj_get_va(mobj, 0);
1506 		if (!arg) {
1507 			thread_rpc_free_arg(mobj_get_cookie(mobj));
1508 			return TEE_ERROR_OUT_OF_MEMORY;
1509 		}
1510 
1511 		thr->rpc_arg = arg;
1512 		thr->rpc_mobj = mobj;
1513 	}
1514 
1515 	memset(arg, 0, OPTEE_MSG_GET_ARG_SIZE(num_params));
1516 	arg->cmd = cmd;
1517 	arg->num_params = num_params;
1518 	arg->ret = TEE_ERROR_GENERIC; /* in case value isn't updated */
1519 
1520 	for (size_t n = 0; n < num_params; n++) {
1521 		switch (params[n].attr) {
1522 		case THREAD_PARAM_ATTR_NONE:
1523 			arg->params[n].attr = OPTEE_MSG_ATTR_TYPE_NONE;
1524 			break;
1525 		case THREAD_PARAM_ATTR_VALUE_IN:
1526 		case THREAD_PARAM_ATTR_VALUE_OUT:
1527 		case THREAD_PARAM_ATTR_VALUE_INOUT:
1528 			arg->params[n].attr = params[n].attr -
1529 					      THREAD_PARAM_ATTR_VALUE_IN +
1530 					      OPTEE_MSG_ATTR_TYPE_VALUE_INPUT;
1531 			arg->params[n].u.value.a = params[n].u.value.a;
1532 			arg->params[n].u.value.b = params[n].u.value.b;
1533 			arg->params[n].u.value.c = params[n].u.value.c;
1534 			break;
1535 		case THREAD_PARAM_ATTR_MEMREF_IN:
1536 		case THREAD_PARAM_ATTR_MEMREF_OUT:
1537 		case THREAD_PARAM_ATTR_MEMREF_INOUT:
1538 			if (!params[n].u.memref.mobj ||
1539 			    mobj_matches(params[n].u.memref.mobj,
1540 					 CORE_MEM_NSEC_SHM)) {
1541 				if (!set_tmem(arg->params + n, params + n))
1542 					return TEE_ERROR_BAD_PARAMETERS;
1543 			} else  if (mobj_matches(params[n].u.memref.mobj,
1544 						 CORE_MEM_REG_SHM)) {
1545 				if (!set_rmem(arg->params + n, params + n))
1546 					return TEE_ERROR_BAD_PARAMETERS;
1547 			} else {
1548 				return TEE_ERROR_BAD_PARAMETERS;
1549 			}
1550 			break;
1551 		default:
1552 			return TEE_ERROR_BAD_PARAMETERS;
1553 		}
1554 	}
1555 
1556 	*arg_ret = arg;
1557 	*carg_ret = mobj_get_cookie(thr->rpc_mobj);
1558 
1559 	return TEE_SUCCESS;
1560 }
1561 
1562 static uint32_t get_rpc_arg_res(struct optee_msg_arg *arg, size_t num_params,
1563 				struct thread_param *params)
1564 {
1565 	for (size_t n = 0; n < num_params; n++) {
1566 		switch (params[n].attr) {
1567 		case THREAD_PARAM_ATTR_VALUE_OUT:
1568 		case THREAD_PARAM_ATTR_VALUE_INOUT:
1569 			params[n].u.value.a = arg->params[n].u.value.a;
1570 			params[n].u.value.b = arg->params[n].u.value.b;
1571 			params[n].u.value.c = arg->params[n].u.value.c;
1572 			break;
1573 		case THREAD_PARAM_ATTR_MEMREF_OUT:
1574 		case THREAD_PARAM_ATTR_MEMREF_INOUT:
1575 			/*
1576 			 * rmem.size and tmem.size is the same type and
1577 			 * location.
1578 			 */
1579 			params[n].u.memref.size = arg->params[n].u.rmem.size;
1580 			break;
1581 		default:
1582 			break;
1583 		}
1584 	}
1585 
1586 	return arg->ret;
1587 }
1588 
1589 uint32_t thread_rpc_cmd(uint32_t cmd, size_t num_params,
1590 			struct thread_param *params)
1591 {
1592 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1593 	void *arg = NULL;
1594 	uint64_t carg = 0;
1595 	uint32_t ret = 0;
1596 
1597 	/* The source CRYPTO_RNG_SRC_JITTER_RPC is safe to use here */
1598 	plat_prng_add_jitter_entropy(CRYPTO_RNG_SRC_JITTER_RPC,
1599 				     &thread_rpc_pnum);
1600 
1601 	ret = get_rpc_arg(cmd, num_params, params, &arg, &carg);
1602 	if (ret)
1603 		return ret;
1604 
1605 	reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1606 	thread_rpc(rpc_args);
1607 
1608 	return get_rpc_arg_res(arg, num_params, params);
1609 }
1610 
1611 /**
1612  * Free physical memory previously allocated with thread_rpc_alloc()
1613  *
1614  * @cookie:	cookie received when allocating the buffer
1615  * @bt:		must be the same as supplied when allocating
1616  * @mobj:	mobj that describes allocated buffer
1617  *
1618  * This function also frees corresponding mobj.
1619  */
1620 static void thread_rpc_free(unsigned int bt, uint64_t cookie, struct mobj *mobj)
1621 {
1622 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1623 	void *arg = NULL;
1624 	uint64_t carg = 0;
1625 	struct thread_param param = THREAD_PARAM_VALUE(IN, bt, cookie, 0);
1626 	uint32_t ret = get_rpc_arg(OPTEE_RPC_CMD_SHM_FREE, 1, &param,
1627 				   &arg, &carg);
1628 
1629 	mobj_free(mobj);
1630 
1631 	if (!ret) {
1632 		reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1633 		thread_rpc(rpc_args);
1634 	}
1635 }
1636 
1637 static struct mobj *get_rpc_alloc_res(struct optee_msg_arg *arg,
1638 				      unsigned int bt, size_t size)
1639 {
1640 	struct mobj *mobj = NULL;
1641 	uint64_t cookie = 0;
1642 	size_t psize = 0;
1643 	uint64_t attr = 0;
1644 
1645 	if (arg->ret || arg->num_params != 1)
1646 		return NULL;
1647 
1648 	psize = READ_ONCE(arg->params[0].u.tmem.size);
1649 	if (psize < size)
1650 		return NULL;
1651 
1652 	attr = READ_ONCE(arg->params[0].attr);
1653 	if (attr == OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT) {
1654 		cookie = arg->params[0].u.tmem.shm_ref;
1655 		mobj = mobj_shm_alloc(arg->params[0].u.tmem.buf_ptr,
1656 				      psize,
1657 				      cookie);
1658 	} else if (attr == (OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT |
1659 			    OPTEE_MSG_ATTR_NONCONTIG)) {
1660 		cookie = arg->params[0].u.tmem.shm_ref;
1661 		mobj = msg_param_mobj_from_noncontig(
1662 			arg->params[0].u.tmem.buf_ptr,
1663 			psize,
1664 			cookie,
1665 			true);
1666 	} else {
1667 		return NULL;
1668 	}
1669 
1670 	if (!mobj) {
1671 		thread_rpc_free(bt, cookie, mobj);
1672 		return NULL;
1673 	}
1674 
1675 	assert(mobj_is_nonsec(mobj));
1676 
1677 	return mobj;
1678 }
1679 
1680 /**
1681  * Allocates shared memory buffer via RPC
1682  *
1683  * @size:	size in bytes of shared memory buffer
1684  * @align:	required alignment of buffer
1685  * @bt:		buffer type OPTEE_RPC_SHM_TYPE_*
1686  *
1687  * Returns a pointer to MOBJ for the memory on success, or NULL on failure.
1688  */
1689 static struct mobj *thread_rpc_alloc(size_t size, size_t align, unsigned int bt)
1690 {
1691 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1692 	void *arg = NULL;
1693 	uint64_t carg = 0;
1694 	struct thread_param param = THREAD_PARAM_VALUE(IN, bt, size, align);
1695 	uint32_t ret = get_rpc_arg(OPTEE_RPC_CMD_SHM_ALLOC, 1, &param,
1696 				   &arg, &carg);
1697 
1698 	if (ret)
1699 		return NULL;
1700 
1701 	reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1702 	thread_rpc(rpc_args);
1703 
1704 	return get_rpc_alloc_res(arg, bt, size);
1705 }
1706 
1707 struct mobj *thread_rpc_alloc_payload(size_t size)
1708 {
1709 	return thread_rpc_alloc(size, 8, OPTEE_RPC_SHM_TYPE_APPL);
1710 }
1711 
1712 void thread_rpc_free_payload(struct mobj *mobj)
1713 {
1714 	thread_rpc_free(OPTEE_RPC_SHM_TYPE_APPL, mobj_get_cookie(mobj),
1715 			mobj);
1716 }
1717 
1718 struct mobj *thread_rpc_alloc_global_payload(size_t size)
1719 {
1720 	return thread_rpc_alloc(size, 8, OPTEE_RPC_SHM_TYPE_GLOBAL);
1721 }
1722 
1723 void thread_rpc_free_global_payload(struct mobj *mobj)
1724 {
1725 	thread_rpc_free(OPTEE_RPC_SHM_TYPE_GLOBAL, mobj_get_cookie(mobj),
1726 			mobj);
1727 }
1728