xref: /optee_os/core/arch/arm/kernel/thread.c (revision 41e5aa8f18c4d48083341ff3df9e75f0c77cf703)
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		(1536 + 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 (is_user_mode(&threads[n].regs))
537 		tee_ta_update_session_utime_resume();
538 
539 	if (threads[n].have_user_map)
540 		core_mmu_set_user_map(&threads[n].user_map);
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 
1080 struct thread_specific_data *thread_get_tsd(void)
1081 {
1082 	return &threads[thread_get_id()].tsd;
1083 }
1084 
1085 struct thread_ctx_regs *thread_get_ctx_regs(void)
1086 {
1087 	struct thread_core_local *l = thread_get_core_local();
1088 
1089 	assert(l->curr_thread != -1);
1090 	return &threads[l->curr_thread].regs;
1091 }
1092 
1093 void thread_set_foreign_intr(bool enable)
1094 {
1095 	/* thread_get_core_local() requires foreign interrupts to be disabled */
1096 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1097 	struct thread_core_local *l;
1098 
1099 	l = thread_get_core_local();
1100 
1101 	assert(l->curr_thread != -1);
1102 
1103 	if (enable) {
1104 		threads[l->curr_thread].flags |=
1105 					THREAD_FLAGS_FOREIGN_INTR_ENABLE;
1106 		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
1107 	} else {
1108 		/*
1109 		 * No need to disable foreign interrupts here since they're
1110 		 * already disabled above.
1111 		 */
1112 		threads[l->curr_thread].flags &=
1113 					~THREAD_FLAGS_FOREIGN_INTR_ENABLE;
1114 	}
1115 }
1116 
1117 void thread_restore_foreign_intr(void)
1118 {
1119 	/* thread_get_core_local() requires foreign interrupts to be disabled */
1120 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1121 	struct thread_core_local *l;
1122 
1123 	l = thread_get_core_local();
1124 
1125 	assert(l->curr_thread != -1);
1126 
1127 	if (threads[l->curr_thread].flags & THREAD_FLAGS_FOREIGN_INTR_ENABLE)
1128 		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
1129 }
1130 
1131 #ifdef CFG_WITH_VFP
1132 uint32_t thread_kernel_enable_vfp(void)
1133 {
1134 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1135 	struct thread_ctx *thr = threads + thread_get_id();
1136 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1137 
1138 	assert(!vfp_is_enabled());
1139 
1140 	if (!thr->vfp_state.ns_saved) {
1141 		vfp_lazy_save_state_final(&thr->vfp_state.ns,
1142 					  true /*force_save*/);
1143 		thr->vfp_state.ns_saved = true;
1144 	} else if (thr->vfp_state.sec_lazy_saved &&
1145 		   !thr->vfp_state.sec_saved) {
1146 		/*
1147 		 * This happens when we're handling an abort while the
1148 		 * thread was using the VFP state.
1149 		 */
1150 		vfp_lazy_save_state_final(&thr->vfp_state.sec,
1151 					  false /*!force_save*/);
1152 		thr->vfp_state.sec_saved = true;
1153 	} else if (tuv && tuv->lazy_saved && !tuv->saved) {
1154 		/*
1155 		 * This can happen either during syscall or abort
1156 		 * processing (while processing a syscall).
1157 		 */
1158 		vfp_lazy_save_state_final(&tuv->vfp, false /*!force_save*/);
1159 		tuv->saved = true;
1160 	}
1161 
1162 	vfp_enable();
1163 	return exceptions;
1164 }
1165 
1166 void thread_kernel_disable_vfp(uint32_t state)
1167 {
1168 	uint32_t exceptions;
1169 
1170 	assert(vfp_is_enabled());
1171 
1172 	vfp_disable();
1173 	exceptions = thread_get_exceptions();
1174 	assert(exceptions & THREAD_EXCP_FOREIGN_INTR);
1175 	exceptions &= ~THREAD_EXCP_FOREIGN_INTR;
1176 	exceptions |= state & THREAD_EXCP_FOREIGN_INTR;
1177 	thread_set_exceptions(exceptions);
1178 }
1179 
1180 void thread_kernel_save_vfp(void)
1181 {
1182 	struct thread_ctx *thr = threads + thread_get_id();
1183 
1184 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1185 	if (vfp_is_enabled()) {
1186 		vfp_lazy_save_state_init(&thr->vfp_state.sec);
1187 		thr->vfp_state.sec_lazy_saved = true;
1188 	}
1189 }
1190 
1191 void thread_kernel_restore_vfp(void)
1192 {
1193 	struct thread_ctx *thr = threads + thread_get_id();
1194 
1195 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1196 	assert(!vfp_is_enabled());
1197 	if (thr->vfp_state.sec_lazy_saved) {
1198 		vfp_lazy_restore_state(&thr->vfp_state.sec,
1199 				       thr->vfp_state.sec_saved);
1200 		thr->vfp_state.sec_saved = false;
1201 		thr->vfp_state.sec_lazy_saved = false;
1202 	}
1203 }
1204 
1205 void thread_user_enable_vfp(struct thread_user_vfp_state *uvfp)
1206 {
1207 	struct thread_ctx *thr = threads + thread_get_id();
1208 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1209 
1210 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1211 	assert(!vfp_is_enabled());
1212 
1213 	if (!thr->vfp_state.ns_saved) {
1214 		vfp_lazy_save_state_final(&thr->vfp_state.ns,
1215 					  true /*force_save*/);
1216 		thr->vfp_state.ns_saved = true;
1217 	} else if (tuv && uvfp != tuv) {
1218 		if (tuv->lazy_saved && !tuv->saved) {
1219 			vfp_lazy_save_state_final(&tuv->vfp,
1220 						  false /*!force_save*/);
1221 			tuv->saved = true;
1222 		}
1223 	}
1224 
1225 	if (uvfp->lazy_saved)
1226 		vfp_lazy_restore_state(&uvfp->vfp, uvfp->saved);
1227 	uvfp->lazy_saved = false;
1228 	uvfp->saved = false;
1229 
1230 	thr->vfp_state.uvfp = uvfp;
1231 	vfp_enable();
1232 }
1233 
1234 void thread_user_save_vfp(void)
1235 {
1236 	struct thread_ctx *thr = threads + thread_get_id();
1237 	struct thread_user_vfp_state *tuv = thr->vfp_state.uvfp;
1238 
1239 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
1240 	if (!vfp_is_enabled())
1241 		return;
1242 
1243 	assert(tuv && !tuv->lazy_saved && !tuv->saved);
1244 	vfp_lazy_save_state_init(&tuv->vfp);
1245 	tuv->lazy_saved = true;
1246 }
1247 
1248 void thread_user_clear_vfp(struct thread_user_vfp_state *uvfp)
1249 {
1250 	struct thread_ctx *thr = threads + thread_get_id();
1251 
1252 	if (uvfp == thr->vfp_state.uvfp)
1253 		thr->vfp_state.uvfp = NULL;
1254 	uvfp->lazy_saved = false;
1255 	uvfp->saved = false;
1256 }
1257 #endif /*CFG_WITH_VFP*/
1258 
1259 #ifdef ARM32
1260 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1261 {
1262 	uint32_t s;
1263 
1264 	if (!is_32bit)
1265 		return false;
1266 
1267 	s = read_spsr();
1268 	s &= ~(CPSR_MODE_MASK | CPSR_T | CPSR_IT_MASK1 | CPSR_IT_MASK2);
1269 	s |= CPSR_MODE_USR;
1270 	if (entry_func & 1)
1271 		s |= CPSR_T;
1272 	*spsr = s;
1273 	return true;
1274 }
1275 #endif
1276 
1277 #ifdef ARM64
1278 static bool get_spsr(bool is_32bit, unsigned long entry_func, uint32_t *spsr)
1279 {
1280 	uint32_t s;
1281 
1282 	if (is_32bit) {
1283 		s = read_daif() & (SPSR_32_AIF_MASK << SPSR_32_AIF_SHIFT);
1284 		s |= SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT;
1285 		s |= (entry_func & SPSR_32_T_MASK) << SPSR_32_T_SHIFT;
1286 	} else {
1287 		s = read_daif() & (SPSR_64_DAIF_MASK << SPSR_64_DAIF_SHIFT);
1288 	}
1289 
1290 	*spsr = s;
1291 	return true;
1292 }
1293 #endif
1294 
1295 uint32_t thread_enter_user_mode(unsigned long a0, unsigned long a1,
1296 		unsigned long a2, unsigned long a3, unsigned long user_sp,
1297 		unsigned long entry_func, bool is_32bit,
1298 		uint32_t *exit_status0, uint32_t *exit_status1)
1299 {
1300 	uint32_t spsr;
1301 
1302 	tee_ta_update_session_utime_resume();
1303 
1304 	if (!get_spsr(is_32bit, entry_func, &spsr)) {
1305 		*exit_status0 = 1; /* panic */
1306 		*exit_status1 = 0xbadbadba;
1307 		return 0;
1308 	}
1309 	return __thread_enter_user_mode(a0, a1, a2, a3, user_sp, entry_func,
1310 					spsr, exit_status0, exit_status1);
1311 }
1312 
1313 #ifdef CFG_CORE_UNMAP_CORE_AT_EL0
1314 void thread_get_user_kcode(struct mobj **mobj, size_t *offset,
1315 			   vaddr_t *va, size_t *sz)
1316 {
1317 	core_mmu_get_user_va_range(va, NULL);
1318 	*mobj = mobj_tee_ram;
1319 	*offset = thread_user_kcode_va - TEE_RAM_START;
1320 	*sz = thread_user_kcode_size;
1321 }
1322 #endif
1323 
1324 #if defined(CFG_CORE_UNMAP_CORE_AT_EL0) && \
1325 	defined(CFG_CORE_WORKAROUND_SPECTRE_BP_SEC) && defined(ARM64)
1326 void thread_get_user_kdata(struct mobj **mobj, size_t *offset,
1327 			   vaddr_t *va, size_t *sz)
1328 {
1329 	vaddr_t v;
1330 
1331 	core_mmu_get_user_va_range(&v, NULL);
1332 	*va = v + thread_user_kcode_size;
1333 	*mobj = mobj_tee_ram;
1334 	*offset = (vaddr_t)thread_user_kdata_page - TEE_RAM_START;
1335 	*sz = sizeof(thread_user_kdata_page);
1336 }
1337 #endif
1338 
1339 bool thread_disable_prealloc_rpc_cache(uint64_t *cookie)
1340 {
1341 	bool rv;
1342 	size_t n;
1343 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1344 
1345 	lock_global();
1346 
1347 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1348 		if (threads[n].state != THREAD_STATE_FREE) {
1349 			rv = false;
1350 			goto out;
1351 		}
1352 	}
1353 
1354 	rv = true;
1355 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1356 		if (threads[n].rpc_arg) {
1357 			*cookie = mobj_get_cookie(threads[n].rpc_mobj);
1358 			mobj_free(threads[n].rpc_mobj);
1359 			threads[n].rpc_arg = NULL;
1360 			goto out;
1361 		}
1362 	}
1363 
1364 	*cookie = 0;
1365 	thread_prealloc_rpc_cache = false;
1366 out:
1367 	unlock_global();
1368 	thread_unmask_exceptions(exceptions);
1369 	return rv;
1370 }
1371 
1372 bool thread_enable_prealloc_rpc_cache(void)
1373 {
1374 	bool rv;
1375 	size_t n;
1376 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
1377 
1378 	lock_global();
1379 
1380 	for (n = 0; n < CFG_NUM_THREADS; n++) {
1381 		if (threads[n].state != THREAD_STATE_FREE) {
1382 			rv = false;
1383 			goto out;
1384 		}
1385 	}
1386 
1387 	rv = true;
1388 	thread_prealloc_rpc_cache = true;
1389 out:
1390 	unlock_global();
1391 	thread_unmask_exceptions(exceptions);
1392 	return rv;
1393 }
1394 
1395 /**
1396  * Allocates data for struct optee_msg_arg.
1397  *
1398  * @size:	size in bytes of struct optee_msg_arg
1399  *
1400  * @returns	mobj that describes allocated buffer or NULL on error
1401  */
1402 static struct mobj *thread_rpc_alloc_arg(size_t size)
1403 {
1404 	paddr_t pa;
1405 	uint64_t co;
1406 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = {
1407 		OPTEE_SMC_RETURN_RPC_ALLOC, size
1408 	};
1409 	struct mobj *mobj = NULL;
1410 
1411 	thread_rpc(rpc_args);
1412 
1413 	pa = reg_pair_to_64(rpc_args[1], rpc_args[2]);
1414 	co = reg_pair_to_64(rpc_args[4], rpc_args[5]);
1415 
1416 	if (!ALIGNMENT_IS_OK(pa, struct optee_msg_arg))
1417 		goto err;
1418 
1419 	/* Check if this region is in static shared space */
1420 	if (core_pbuf_is(CORE_MEM_NSEC_SHM, pa, size))
1421 		mobj = mobj_shm_alloc(pa, size, co);
1422 #ifdef CFG_CORE_DYN_SHM
1423 	else if ((!(pa & SMALL_PAGE_MASK)) && size <= SMALL_PAGE_SIZE)
1424 		mobj = mobj_mapped_shm_alloc(&pa, 1, 0, co);
1425 #endif
1426 
1427 	if (!mobj)
1428 		goto err;
1429 
1430 	return mobj;
1431 err:
1432 	thread_rpc_free_arg(co);
1433 	mobj_free(mobj);
1434 	return NULL;
1435 }
1436 
1437 static bool set_rmem(struct optee_msg_param *param,
1438 		     struct thread_param *tpm)
1439 {
1440 	param->attr = tpm->attr - THREAD_PARAM_ATTR_MEMREF_IN +
1441 		      OPTEE_MSG_ATTR_TYPE_RMEM_INPUT;
1442 	param->u.rmem.offs = tpm->u.memref.offs;
1443 	param->u.rmem.size = tpm->u.memref.size;
1444 	if (tpm->u.memref.mobj) {
1445 		param->u.rmem.shm_ref = mobj_get_cookie(tpm->u.memref.mobj);
1446 		if (!param->u.rmem.shm_ref)
1447 			return false;
1448 	} else {
1449 		param->u.rmem.shm_ref = 0;
1450 	}
1451 
1452 	return true;
1453 }
1454 
1455 static bool set_tmem(struct optee_msg_param *param,
1456 		     struct thread_param *tpm)
1457 {
1458 	paddr_t pa = 0;
1459 	uint64_t shm_ref = 0;
1460 	struct mobj *mobj = tpm->u.memref.mobj;
1461 
1462 	param->attr = tpm->attr - THREAD_PARAM_ATTR_MEMREF_IN +
1463 		      OPTEE_MSG_ATTR_TYPE_TMEM_INPUT;
1464 	if (mobj) {
1465 		shm_ref = mobj_get_cookie(mobj);
1466 		if (!shm_ref)
1467 			return false;
1468 		if (mobj_get_pa(mobj, tpm->u.memref.offs, 0, &pa))
1469 			return false;
1470 	}
1471 
1472 	param->u.tmem.size = tpm->u.memref.size;
1473 	param->u.tmem.buf_ptr = pa;
1474 	param->u.tmem.shm_ref = shm_ref;
1475 
1476 	return true;
1477 }
1478 
1479 static uint32_t get_rpc_arg(uint32_t cmd, size_t num_params,
1480 			    struct thread_param *params, void **arg_ret,
1481 			    uint64_t *carg_ret)
1482 {
1483 	struct thread_ctx *thr = threads + thread_get_id();
1484 	struct optee_msg_arg *arg = thr->rpc_arg;
1485 	size_t sz = OPTEE_MSG_GET_ARG_SIZE(THREAD_RPC_MAX_NUM_PARAMS);
1486 
1487 	if (num_params > THREAD_RPC_MAX_NUM_PARAMS)
1488 		return TEE_ERROR_BAD_PARAMETERS;
1489 
1490 	if (!arg) {
1491 		struct mobj *mobj = thread_rpc_alloc_arg(sz);
1492 
1493 		if (!mobj)
1494 			return TEE_ERROR_OUT_OF_MEMORY;
1495 
1496 		arg = mobj_get_va(mobj, 0);
1497 		if (!arg) {
1498 			thread_rpc_free_arg(mobj_get_cookie(mobj));
1499 			return TEE_ERROR_OUT_OF_MEMORY;
1500 		}
1501 
1502 		thr->rpc_arg = arg;
1503 		thr->rpc_mobj = mobj;
1504 	}
1505 
1506 	memset(arg, 0, OPTEE_MSG_GET_ARG_SIZE(num_params));
1507 	arg->cmd = cmd;
1508 	arg->num_params = num_params;
1509 	arg->ret = TEE_ERROR_GENERIC; /* in case value isn't updated */
1510 
1511 	for (size_t n = 0; n < num_params; n++) {
1512 		switch (params[n].attr) {
1513 		case THREAD_PARAM_ATTR_NONE:
1514 			arg->params[n].attr = OPTEE_MSG_ATTR_TYPE_NONE;
1515 			break;
1516 		case THREAD_PARAM_ATTR_VALUE_IN:
1517 		case THREAD_PARAM_ATTR_VALUE_OUT:
1518 		case THREAD_PARAM_ATTR_VALUE_INOUT:
1519 			arg->params[n].attr = params[n].attr -
1520 					      THREAD_PARAM_ATTR_VALUE_IN +
1521 					      OPTEE_MSG_ATTR_TYPE_VALUE_INPUT;
1522 			arg->params[n].u.value.a = params[n].u.value.a;
1523 			arg->params[n].u.value.b = params[n].u.value.b;
1524 			arg->params[n].u.value.c = params[n].u.value.c;
1525 			break;
1526 		case THREAD_PARAM_ATTR_MEMREF_IN:
1527 		case THREAD_PARAM_ATTR_MEMREF_OUT:
1528 		case THREAD_PARAM_ATTR_MEMREF_INOUT:
1529 			if (!params[n].u.memref.mobj ||
1530 			    mobj_matches(params[n].u.memref.mobj,
1531 					 CORE_MEM_NSEC_SHM)) {
1532 				if (!set_tmem(arg->params + n, params + n))
1533 					return TEE_ERROR_BAD_PARAMETERS;
1534 			} else  if (mobj_matches(params[n].u.memref.mobj,
1535 						 CORE_MEM_REG_SHM)) {
1536 				if (!set_rmem(arg->params + n, params + n))
1537 					return TEE_ERROR_BAD_PARAMETERS;
1538 			} else {
1539 				return TEE_ERROR_BAD_PARAMETERS;
1540 			}
1541 			break;
1542 		default:
1543 			return TEE_ERROR_BAD_PARAMETERS;
1544 		}
1545 	}
1546 
1547 	*arg_ret = arg;
1548 	*carg_ret = mobj_get_cookie(thr->rpc_mobj);
1549 
1550 	return TEE_SUCCESS;
1551 }
1552 
1553 static uint32_t get_rpc_arg_res(struct optee_msg_arg *arg, size_t num_params,
1554 				struct thread_param *params)
1555 {
1556 	for (size_t n = 0; n < num_params; n++) {
1557 		switch (params[n].attr) {
1558 		case THREAD_PARAM_ATTR_VALUE_OUT:
1559 		case THREAD_PARAM_ATTR_VALUE_INOUT:
1560 			params[n].u.value.a = arg->params[n].u.value.a;
1561 			params[n].u.value.b = arg->params[n].u.value.b;
1562 			params[n].u.value.c = arg->params[n].u.value.c;
1563 			break;
1564 		case THREAD_PARAM_ATTR_MEMREF_OUT:
1565 		case THREAD_PARAM_ATTR_MEMREF_INOUT:
1566 			/*
1567 			 * rmem.size and tmem.size is the same type and
1568 			 * location.
1569 			 */
1570 			params[n].u.memref.size = arg->params[n].u.rmem.size;
1571 			break;
1572 		default:
1573 			break;
1574 		}
1575 	}
1576 
1577 	return arg->ret;
1578 }
1579 
1580 uint32_t thread_rpc_cmd(uint32_t cmd, size_t num_params,
1581 			struct thread_param *params)
1582 {
1583 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1584 	void *arg = NULL;
1585 	uint64_t carg = 0;
1586 	uint32_t ret = 0;
1587 
1588 	/* The source CRYPTO_RNG_SRC_JITTER_RPC is safe to use here */
1589 	plat_prng_add_jitter_entropy(CRYPTO_RNG_SRC_JITTER_RPC,
1590 				     &thread_rpc_pnum);
1591 
1592 	ret = get_rpc_arg(cmd, num_params, params, &arg, &carg);
1593 	if (ret)
1594 		return ret;
1595 
1596 	reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1597 	thread_rpc(rpc_args);
1598 
1599 	return get_rpc_arg_res(arg, num_params, params);
1600 }
1601 
1602 /**
1603  * Free physical memory previously allocated with thread_rpc_alloc()
1604  *
1605  * @cookie:	cookie received when allocating the buffer
1606  * @bt:		must be the same as supplied when allocating
1607  * @mobj:	mobj that describes allocated buffer
1608  *
1609  * This function also frees corresponding mobj.
1610  */
1611 static void thread_rpc_free(unsigned int bt, uint64_t cookie, struct mobj *mobj)
1612 {
1613 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1614 	void *arg = NULL;
1615 	uint64_t carg = 0;
1616 	struct thread_param param = THREAD_PARAM_VALUE(IN, bt, cookie, 0);
1617 	uint32_t ret = get_rpc_arg(OPTEE_RPC_CMD_SHM_FREE, 1, &param,
1618 				   &arg, &carg);
1619 
1620 	mobj_free(mobj);
1621 
1622 	if (!ret) {
1623 		reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1624 		thread_rpc(rpc_args);
1625 	}
1626 }
1627 
1628 static struct mobj *get_rpc_alloc_res(struct optee_msg_arg *arg,
1629 				      unsigned int bt, size_t size)
1630 {
1631 	struct mobj *mobj = NULL;
1632 	uint64_t cookie = 0;
1633 	size_t psize = 0;
1634 	uint64_t attr = 0;
1635 
1636 	if (arg->ret || arg->num_params != 1)
1637 		return NULL;
1638 
1639 	psize = READ_ONCE(arg->params[0].u.tmem.size);
1640 	if (psize < size)
1641 		return NULL;
1642 
1643 	attr = READ_ONCE(arg->params[0].attr);
1644 	if (attr == OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT) {
1645 		cookie = arg->params[0].u.tmem.shm_ref;
1646 		mobj = mobj_shm_alloc(arg->params[0].u.tmem.buf_ptr,
1647 				      psize,
1648 				      cookie);
1649 	} else if (attr == (OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT |
1650 			    OPTEE_MSG_ATTR_NONCONTIG)) {
1651 		cookie = arg->params[0].u.tmem.shm_ref;
1652 		mobj = msg_param_mobj_from_noncontig(
1653 			arg->params[0].u.tmem.buf_ptr,
1654 			psize,
1655 			cookie,
1656 			true);
1657 	} else {
1658 		return NULL;
1659 	}
1660 
1661 	if (!mobj) {
1662 		thread_rpc_free(bt, cookie, mobj);
1663 		return NULL;
1664 	}
1665 
1666 	assert(mobj_is_nonsec(mobj));
1667 
1668 	return mobj;
1669 }
1670 
1671 /**
1672  * Allocates shared memory buffer via RPC
1673  *
1674  * @size:	size in bytes of shared memory buffer
1675  * @align:	required alignment of buffer
1676  * @bt:		buffer type OPTEE_RPC_SHM_TYPE_*
1677  *
1678  * Returns a pointer to MOBJ for the memory on success, or NULL on failure.
1679  */
1680 static struct mobj *thread_rpc_alloc(size_t size, size_t align, unsigned int bt)
1681 {
1682 	uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
1683 	void *arg = NULL;
1684 	uint64_t carg = 0;
1685 	struct thread_param param = THREAD_PARAM_VALUE(IN, bt, size, align);
1686 	uint32_t ret = get_rpc_arg(OPTEE_RPC_CMD_SHM_ALLOC, 1, &param,
1687 				   &arg, &carg);
1688 
1689 	if (ret)
1690 		return NULL;
1691 
1692 	reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
1693 	thread_rpc(rpc_args);
1694 
1695 	return get_rpc_alloc_res(arg, bt, size);
1696 }
1697 
1698 struct mobj *thread_rpc_alloc_payload(size_t size)
1699 {
1700 	return thread_rpc_alloc(size, 8, OPTEE_RPC_SHM_TYPE_APPL);
1701 }
1702 
1703 void thread_rpc_free_payload(struct mobj *mobj)
1704 {
1705 	thread_rpc_free(OPTEE_RPC_SHM_TYPE_APPL, mobj_get_cookie(mobj),
1706 			mobj);
1707 }
1708 
1709 struct mobj *thread_rpc_alloc_global_payload(size_t size)
1710 {
1711 	return thread_rpc_alloc(size, 8, OPTEE_RPC_SHM_TYPE_GLOBAL);
1712 }
1713 
1714 void thread_rpc_free_global_payload(struct mobj *mobj)
1715 {
1716 	thread_rpc_free(OPTEE_RPC_SHM_TYPE_GLOBAL, mobj_get_cookie(mobj),
1717 			mobj);
1718 }
1719