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