1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2016-2022, Linaro Limited
4  * Copyright (c) 2014, STMicroelectronics International N.V.
5  * Copyright (c) 2020-2021, Arm Limited
6  */
7 
8 #include <config.h>
9 #include <crypto/crypto.h>
10 #include <kernel/asan.h>
11 #include <kernel/boot.h>
12 #include <kernel/lockdep.h>
13 #include <kernel/misc.h>
14 #include <kernel/panic.h>
15 #include <kernel/spinlock.h>
16 #include <kernel/thread.h>
17 #include <kernel/thread_private.h>
18 #include <mm/mobj.h>
19 
20 struct thread_ctx threads[CFG_NUM_THREADS];
21 
22 struct thread_core_local thread_core_local[CFG_TEE_CORE_NB_CORE] __nex_bss;
23 
24 /*
25  * Stacks
26  *
27  * [Lower addresses on the left]
28  *
29  * [ STACK_CANARY_SIZE/2 | STACK_CHECK_EXTRA | STACK_XXX_SIZE | STACK_CANARY_SIZE/2 ]
30  * ^                     ^                   ^                ^
31  * stack_xxx[n]          "hard" top          "soft" top       bottom
32  */
33 
34 #ifdef CFG_WITH_STACK_CANARIES
35 static uint32_t start_canary_value = 0xdedede00;
36 static uint32_t end_canary_value = 0xababab00;
37 #define GET_START_CANARY(name, stack_num) name[stack_num][0]
38 #define GET_END_CANARY(name, stack_num) \
39 	name[stack_num][sizeof(name[stack_num]) / sizeof(uint32_t) - 1]
40 #endif
41 
42 #define DECLARE_STACK(name, num_stacks, stack_size, linkage) \
43 linkage uint32_t name[num_stacks] \
44 		[ROUNDUP(stack_size + STACK_CANARY_SIZE + STACK_CHECK_EXTRA, \
45 			 STACK_ALIGNMENT) / sizeof(uint32_t)] \
46 		__attribute__((section(".nozi_stack." # name), \
47 			       aligned(STACK_ALIGNMENT)))
48 
49 #define GET_STACK(stack) ((vaddr_t)(stack) + STACK_SIZE(stack))
50 
51 DECLARE_STACK(stack_tmp, CFG_TEE_CORE_NB_CORE, STACK_TMP_SIZE,
52 	      /* global linkage */);
53 DECLARE_STACK(stack_abt, CFG_TEE_CORE_NB_CORE, STACK_ABT_SIZE, static);
54 #ifndef CFG_WITH_PAGER
55 DECLARE_STACK(stack_thread, CFG_NUM_THREADS, STACK_THREAD_SIZE, static);
56 #endif
57 
58 #define GET_STACK_TOP_HARD(stack, n) \
59 	((vaddr_t)&(stack)[n] + STACK_CANARY_SIZE / 2)
60 #define GET_STACK_TOP_SOFT(stack, n) \
61 	(GET_STACK_TOP_HARD(stack, n) + STACK_CHECK_EXTRA)
62 #define GET_STACK_BOTTOM(stack, n) ((vaddr_t)&(stack)[n] + sizeof(stack[n]) - \
63 				    STACK_CANARY_SIZE / 2)
64 
65 const uint32_t stack_tmp_stride __section(".identity_map.stack_tmp_stride") =
66 	sizeof(stack_tmp[0]);
67 
68 /*
69  * This stack setup info is required by secondary boot cores before they
70  * each locally enable the pager (the mmu). Hence kept in pager sections.
71  */
72 DECLARE_KEEP_PAGER(stack_tmp_stride);
73 
74 static unsigned int thread_global_lock __nex_bss = SPINLOCK_UNLOCK;
75 
thread_init_canaries(void)76 void thread_init_canaries(void)
77 {
78 #ifdef CFG_WITH_STACK_CANARIES
79 	size_t n;
80 #define INIT_CANARY(name)						\
81 	for (n = 0; n < ARRAY_SIZE(name); n++) {			\
82 		uint32_t *start_canary = &GET_START_CANARY(name, n);	\
83 		uint32_t *end_canary = &GET_END_CANARY(name, n);	\
84 									\
85 		*start_canary = start_canary_value;			\
86 		*end_canary = end_canary_value;				\
87 	}
88 
89 	INIT_CANARY(stack_tmp);
90 	INIT_CANARY(stack_abt);
91 #if !defined(CFG_WITH_PAGER) && !defined(CFG_NS_VIRTUALIZATION)
92 	INIT_CANARY(stack_thread);
93 #endif
94 #endif/*CFG_WITH_STACK_CANARIES*/
95 }
96 
97 #if defined(CFG_WITH_STACK_CANARIES)
thread_update_canaries(void)98 void thread_update_canaries(void)
99 {
100 	uint32_t canary[2] = { };
101 	uint32_t exceptions = 0;
102 
103 	plat_get_random_stack_canaries(canary, ARRAY_SIZE(canary),
104 				       sizeof(canary[0]));
105 
106 	exceptions = thread_mask_exceptions(THREAD_EXCP_ALL);
107 
108 	thread_check_canaries();
109 
110 	start_canary_value = canary[0];
111 	end_canary_value = canary[1];
112 	thread_init_canaries();
113 
114 	thread_unmask_exceptions(exceptions);
115 }
116 #endif
117 
118 #define CANARY_DIED(stack, loc, n, addr) \
119 	do { \
120 		EMSG_RAW("Dead canary at %s of '%s[%zu]' (%p)", #loc, #stack, \
121 			 n, (void *)addr); \
122 		panic(); \
123 	} while (0)
124 
thread_check_canaries(void)125 void thread_check_canaries(void)
126 {
127 #ifdef CFG_WITH_STACK_CANARIES
128 	uint32_t *canary = NULL;
129 	size_t n = 0;
130 
131 	for (n = 0; n < ARRAY_SIZE(stack_tmp); n++) {
132 		canary = &GET_START_CANARY(stack_tmp, n);
133 		if (*canary != start_canary_value)
134 			CANARY_DIED(stack_tmp, start, n, canary);
135 		canary = &GET_END_CANARY(stack_tmp, n);
136 		if (*canary != end_canary_value)
137 			CANARY_DIED(stack_tmp, end, n, canary);
138 	}
139 
140 	for (n = 0; n < ARRAY_SIZE(stack_abt); n++) {
141 		canary = &GET_START_CANARY(stack_abt, n);
142 		if (*canary != start_canary_value)
143 			CANARY_DIED(stack_abt, start, n, canary);
144 		canary = &GET_END_CANARY(stack_abt, n);
145 		if (*canary != end_canary_value)
146 			CANARY_DIED(stack_abt, end, n, canary);
147 	}
148 #if !defined(CFG_WITH_PAGER) && !defined(CFG_NS_VIRTUALIZATION)
149 	for (n = 0; n < ARRAY_SIZE(stack_thread); n++) {
150 		canary = &GET_START_CANARY(stack_thread, n);
151 		if (*canary != start_canary_value)
152 			CANARY_DIED(stack_thread, start, n, canary);
153 		canary = &GET_END_CANARY(stack_thread, n);
154 		if (*canary != end_canary_value)
155 			CANARY_DIED(stack_thread, end, n, canary);
156 	}
157 #endif
158 #endif/*CFG_WITH_STACK_CANARIES*/
159 }
160 
thread_lock_global(void)161 void thread_lock_global(void)
162 {
163 	cpu_spin_lock(&thread_global_lock);
164 }
165 
thread_unlock_global(void)166 void thread_unlock_global(void)
167 {
168 	cpu_spin_unlock(&thread_global_lock);
169 }
170 
171 static struct thread_core_local * __nostackcheck
get_core_local(unsigned int pos)172 get_core_local(unsigned int pos)
173 {
174 	/*
175 	 * Foreign interrupts must be disabled before playing with core_local
176 	 * since we otherwise may be rescheduled to a different core in the
177 	 * middle of this function.
178 	 */
179 	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);
180 
181 	assert(pos < CFG_TEE_CORE_NB_CORE);
182 	return &thread_core_local[pos];
183 }
184 
thread_get_core_local(void)185 struct thread_core_local * __nostackcheck thread_get_core_local(void)
186 {
187 	unsigned int pos = get_core_pos();
188 
189 	return get_core_local(pos);
190 }
191 
192 #ifdef CFG_CORE_DEBUG_CHECK_STACKS
print_stack_limits(void)193 static void print_stack_limits(void)
194 {
195 	size_t n = 0;
196 	vaddr_t __maybe_unused start = 0;
197 	vaddr_t __maybe_unused end = 0;
198 
199 	for (n = 0; n < CFG_TEE_CORE_NB_CORE; n++) {
200 		start = GET_STACK_TOP_SOFT(stack_tmp, n);
201 		end = GET_STACK_BOTTOM(stack_tmp, n);
202 		DMSG("tmp [%zu] 0x%" PRIxVA "..0x%" PRIxVA, n, start, end);
203 	}
204 	for (n = 0; n < CFG_TEE_CORE_NB_CORE; n++) {
205 		start = GET_STACK_TOP_SOFT(stack_abt, n);
206 		end = GET_STACK_BOTTOM(stack_abt, n);
207 		DMSG("abt [%zu] 0x%" PRIxVA "..0x%" PRIxVA, n, start, end);
208 	}
209 	for (n = 0; n < CFG_NUM_THREADS; n++) {
210 		end = threads[n].stack_va_end;
211 		start = end - STACK_THREAD_SIZE + STACK_CHECK_EXTRA;
212 		DMSG("thr [%zu] 0x%" PRIxVA "..0x%" PRIxVA, n, start, end);
213 	}
214 }
215 
check_stack_limits(void)216 static void check_stack_limits(void)
217 {
218 	vaddr_t stack_start = 0;
219 	vaddr_t stack_end = 0;
220 	/* Any value in the current stack frame will do */
221 	vaddr_t current_sp = (vaddr_t)&stack_start;
222 
223 	if (!get_stack_soft_limits(&stack_start, &stack_end))
224 		panic("Unknown stack limits");
225 	if (current_sp < stack_start || current_sp > stack_end) {
226 		EMSG("Stack pointer out of range: 0x%" PRIxVA " not in [0x%"
227 		     PRIxVA " .. 0x%" PRIxVA "]", current_sp, stack_start,
228 		     stack_end);
229 		print_stack_limits();
230 		panic();
231 	}
232 }
233 
get_stackcheck_recursion_flag(void)234 static bool * __nostackcheck get_stackcheck_recursion_flag(void)
235 {
236 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
237 	unsigned int pos = get_core_pos();
238 	struct thread_core_local *l = get_core_local(pos);
239 	int ct = l->curr_thread;
240 	bool *p = NULL;
241 
242 	if (l->flags & (THREAD_CLF_ABORT | THREAD_CLF_TMP))
243 		p = &l->stackcheck_recursion;
244 	else if (!l->flags)
245 		p = &threads[ct].tsd.stackcheck_recursion;
246 
247 	thread_unmask_exceptions(exceptions);
248 	return p;
249 }
250 
251 void __cyg_profile_func_enter(void *this_fn, void *call_site);
__cyg_profile_func_enter(void * this_fn __unused,void * call_site __unused)252 void __nostackcheck __cyg_profile_func_enter(void *this_fn __unused,
253 					     void *call_site __unused)
254 {
255 	bool *p = get_stackcheck_recursion_flag();
256 
257 	assert(p);
258 	if (*p)
259 		return;
260 	*p = true;
261 	check_stack_limits();
262 	*p = false;
263 }
264 
265 void __cyg_profile_func_exit(void *this_fn, void *call_site);
__cyg_profile_func_exit(void * this_fn __unused,void * call_site __unused)266 void __nostackcheck __cyg_profile_func_exit(void *this_fn __unused,
267 					    void *call_site __unused)
268 {
269 }
270 #else
print_stack_limits(void)271 static void print_stack_limits(void)
272 {
273 }
274 #endif
275 
thread_init_boot_thread(void)276 void thread_init_boot_thread(void)
277 {
278 	struct thread_core_local *l = thread_get_core_local();
279 
280 	thread_init_threads();
281 
282 	l->curr_thread = 0;
283 	threads[0].state = THREAD_STATE_ACTIVE;
284 }
285 
thread_clr_boot_thread(void)286 void __nostackcheck thread_clr_boot_thread(void)
287 {
288 	struct thread_core_local *l = thread_get_core_local();
289 
290 	assert(l->curr_thread >= 0 && l->curr_thread < CFG_NUM_THREADS);
291 	assert(threads[l->curr_thread].state == THREAD_STATE_ACTIVE);
292 	threads[l->curr_thread].state = THREAD_STATE_FREE;
293 	l->curr_thread = THREAD_ID_INVALID;
294 }
295 
thread_get_tmp_sp(void)296 void __nostackcheck *thread_get_tmp_sp(void)
297 {
298 	struct thread_core_local *l = thread_get_core_local();
299 
300 	/*
301 	 * Called from assembly when switching to the temporary stack, so flags
302 	 * need updating
303 	 */
304 	l->flags |= THREAD_CLF_TMP;
305 
306 	return (void *)l->tmp_stack_va_end;
307 }
308 
thread_stack_start(void)309 vaddr_t thread_stack_start(void)
310 {
311 	struct thread_ctx *thr;
312 	int ct = thread_get_id_may_fail();
313 
314 	if (ct == THREAD_ID_INVALID)
315 		return 0;
316 
317 	thr = threads + ct;
318 	return thr->stack_va_end - STACK_THREAD_SIZE;
319 }
320 
thread_stack_size(void)321 size_t thread_stack_size(void)
322 {
323 	return STACK_THREAD_SIZE;
324 }
325 
get_stack_limits(vaddr_t * start,vaddr_t * end,bool hard)326 bool get_stack_limits(vaddr_t *start, vaddr_t *end, bool hard)
327 {
328 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
329 	unsigned int pos = get_core_pos();
330 	struct thread_core_local *l = get_core_local(pos);
331 	int ct = l->curr_thread;
332 	bool ret = false;
333 
334 	if (l->flags & THREAD_CLF_TMP) {
335 		if (hard)
336 			*start = GET_STACK_TOP_HARD(stack_tmp, pos);
337 		else
338 			*start = GET_STACK_TOP_SOFT(stack_tmp, pos);
339 		*end = GET_STACK_BOTTOM(stack_tmp, pos);
340 		ret = true;
341 	} else if (l->flags & THREAD_CLF_ABORT) {
342 		if (hard)
343 			*start = GET_STACK_TOP_HARD(stack_abt, pos);
344 		else
345 			*start = GET_STACK_TOP_SOFT(stack_abt, pos);
346 		*end = GET_STACK_BOTTOM(stack_abt, pos);
347 		ret = true;
348 	} else if (!l->flags) {
349 		if (ct < 0 || ct >= CFG_NUM_THREADS)
350 			goto out;
351 
352 		*end = threads[ct].stack_va_end;
353 		*start = *end - STACK_THREAD_SIZE;
354 		if (!hard)
355 			*start += STACK_CHECK_EXTRA;
356 		ret = true;
357 	}
358 out:
359 	thread_unmask_exceptions(exceptions);
360 	return ret;
361 }
362 
thread_is_from_abort_mode(void)363 bool thread_is_from_abort_mode(void)
364 {
365 	struct thread_core_local *l = thread_get_core_local();
366 
367 	return (l->flags >> THREAD_CLF_SAVED_SHIFT) & THREAD_CLF_ABORT;
368 }
369 
370 /*
371  * This function should always be accurate, but it might be possible to
372  * implement a more efficient depending on cpu architecture.
373  */
thread_is_in_normal_mode(void)374 bool __weak thread_is_in_normal_mode(void)
375 {
376 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
377 	struct thread_core_local *l = thread_get_core_local();
378 	bool ret;
379 
380 	/*
381 	 * If any bit in l->flags is set aside from THREAD_CLF_TMP we're
382 	 * handling some exception.
383 	 */
384 	ret = (l->curr_thread != THREAD_ID_INVALID) &&
385 	      !(l->flags & ~THREAD_CLF_TMP);
386 	thread_unmask_exceptions(exceptions);
387 
388 	return ret;
389 }
390 
thread_get_id_may_fail(void)391 short int __noprof thread_get_id_may_fail(void)
392 {
393 	/*
394 	 * thread_get_core_local() requires foreign interrupts to be disabled
395 	 */
396 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
397 	struct thread_core_local *l = thread_get_core_local();
398 	short int ct = l->curr_thread;
399 
400 	thread_unmask_exceptions(exceptions);
401 	return ct;
402 }
403 
thread_get_id(void)404 short int __noprof thread_get_id(void)
405 {
406 	short int ct = thread_get_id_may_fail();
407 
408 	/* Thread ID has to fit in a short int */
409 	COMPILE_TIME_ASSERT(CFG_NUM_THREADS <= SHRT_MAX);
410 	assert(ct >= 0 && ct < CFG_NUM_THREADS);
411 	return ct;
412 }
413 
414 #ifdef CFG_WITH_PAGER
init_thread_stacks(void)415 static void init_thread_stacks(void)
416 {
417 	size_t n = 0;
418 
419 	/*
420 	 * Allocate virtual memory for thread stacks.
421 	 */
422 	for (n = 0; n < CFG_NUM_THREADS; n++) {
423 		tee_mm_entry_t *mm = NULL;
424 		vaddr_t sp = 0;
425 		size_t num_pages = 0;
426 		struct fobj *fobj = NULL;
427 
428 		/* Find vmem for thread stack and its protection gap */
429 		mm = tee_mm_alloc(&core_virt_mem_pool,
430 				  SMALL_PAGE_SIZE + STACK_THREAD_SIZE);
431 		assert(mm);
432 
433 		/* Claim eventual physical page */
434 		tee_pager_add_pages(tee_mm_get_smem(mm), tee_mm_get_size(mm),
435 				    true);
436 
437 		num_pages = tee_mm_get_bytes(mm) / SMALL_PAGE_SIZE - 1;
438 		fobj = fobj_locked_paged_alloc(num_pages);
439 
440 		/* Add the region to the pager */
441 		tee_pager_add_core_region(tee_mm_get_smem(mm) + SMALL_PAGE_SIZE,
442 					  PAGED_REGION_TYPE_LOCK, fobj);
443 		fobj_put(fobj);
444 
445 		/* init effective stack */
446 		sp = tee_mm_get_smem(mm) + tee_mm_get_bytes(mm);
447 		asan_tag_access((void *)tee_mm_get_smem(mm), (void *)sp);
448 		threads[n].stack_va_end = sp;
449 	}
450 }
451 #else
init_thread_stacks(void)452 static void init_thread_stacks(void)
453 {
454 	size_t n;
455 
456 	/* Assign the thread stacks */
457 	for (n = 0; n < CFG_NUM_THREADS; n++)
458 		threads[n].stack_va_end = GET_STACK_BOTTOM(stack_thread, n);
459 }
460 #endif /*CFG_WITH_PAGER*/
461 
thread_init_threads(void)462 void thread_init_threads(void)
463 {
464 	size_t n = 0;
465 
466 	init_thread_stacks();
467 	print_stack_limits();
468 	pgt_init();
469 
470 	mutex_lockdep_init();
471 
472 	for (n = 0; n < CFG_NUM_THREADS; n++)
473 		TAILQ_INIT(&threads[n].tsd.sess_stack);
474 }
475 
thread_init_thread_core_local(void)476 void __nostackcheck thread_init_thread_core_local(void)
477 {
478 	size_t n = 0;
479 	struct thread_core_local *tcl = thread_core_local;
480 
481 	for (n = 0; n < CFG_TEE_CORE_NB_CORE; n++) {
482 		tcl[n].curr_thread = THREAD_ID_INVALID;
483 		tcl[n].flags = THREAD_CLF_TMP;
484 	}
485 	tcl[0].tmp_stack_va_end = GET_STACK_BOTTOM(stack_tmp, 0);
486 }
487 
thread_init_core_local_stacks(void)488 void __nostackcheck thread_init_core_local_stacks(void)
489 {
490 	size_t n = 0;
491 	struct thread_core_local *tcl = thread_core_local;
492 
493 	for (n = 0; n < CFG_TEE_CORE_NB_CORE; n++) {
494 		tcl[n].tmp_stack_va_end = GET_STACK_BOTTOM(stack_tmp, n) -
495 					  STACK_TMP_OFFS;
496 		tcl[n].abt_stack_va_end = GET_STACK_BOTTOM(stack_abt, n);
497 	}
498 }
499 
500 #if defined(CFG_CORE_PAUTH)
thread_init_thread_pauth_keys(void)501 void thread_init_thread_pauth_keys(void)
502 {
503 	size_t n = 0;
504 
505 	for (n = 0; n < CFG_NUM_THREADS; n++)
506 		if (crypto_rng_read(&threads[n].keys, sizeof(threads[n].keys)))
507 			panic("Failed to init thread pauth keys");
508 }
509 
thread_init_core_local_pauth_keys(void)510 void thread_init_core_local_pauth_keys(void)
511 {
512 	struct thread_core_local *tcl = thread_core_local;
513 	size_t n = 0;
514 
515 	for (n = 0; n < CFG_TEE_CORE_NB_CORE; n++)
516 		if (crypto_rng_read(&tcl[n].keys, sizeof(tcl[n].keys)))
517 			panic("Failed to init core local pauth keys");
518 }
519 #endif
520 
thread_get_tsd(void)521 struct thread_specific_data * __noprof thread_get_tsd(void)
522 {
523 	return &threads[thread_get_id()].tsd;
524 }
525 
thread_get_ctx_regs(void)526 struct thread_ctx_regs * __nostackcheck thread_get_ctx_regs(void)
527 {
528 	struct thread_core_local *l = thread_get_core_local();
529 
530 	assert(l->curr_thread != THREAD_ID_INVALID);
531 	return &threads[l->curr_thread].regs;
532 }
533 
thread_set_foreign_intr(bool enable)534 void thread_set_foreign_intr(bool enable)
535 {
536 	/* thread_get_core_local() requires foreign interrupts to be disabled */
537 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
538 	struct thread_core_local *l;
539 
540 	l = thread_get_core_local();
541 
542 	assert(l->curr_thread != THREAD_ID_INVALID);
543 
544 	if (enable) {
545 		threads[l->curr_thread].flags |=
546 					THREAD_FLAGS_FOREIGN_INTR_ENABLE;
547 		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
548 	} else {
549 		/*
550 		 * No need to disable foreign interrupts here since they're
551 		 * already disabled above.
552 		 */
553 		threads[l->curr_thread].flags &=
554 					~THREAD_FLAGS_FOREIGN_INTR_ENABLE;
555 	}
556 }
557 
thread_restore_foreign_intr(void)558 void thread_restore_foreign_intr(void)
559 {
560 	/* thread_get_core_local() requires foreign interrupts to be disabled */
561 	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
562 	struct thread_core_local *l;
563 
564 	l = thread_get_core_local();
565 
566 	assert(l->curr_thread != THREAD_ID_INVALID);
567 
568 	if (threads[l->curr_thread].flags & THREAD_FLAGS_FOREIGN_INTR_ENABLE)
569 		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
570 }
571 
alloc_shm(enum thread_shm_type shm_type,size_t size)572 static struct mobj *alloc_shm(enum thread_shm_type shm_type, size_t size)
573 {
574 	switch (shm_type) {
575 	case THREAD_SHM_TYPE_APPLICATION:
576 		return thread_rpc_alloc_payload(size);
577 	case THREAD_SHM_TYPE_KERNEL_PRIVATE:
578 		return thread_rpc_alloc_kernel_payload(size);
579 	case THREAD_SHM_TYPE_GLOBAL:
580 		return thread_rpc_alloc_global_payload(size);
581 	default:
582 		return NULL;
583 	}
584 }
585 
clear_shm_cache_entry(struct thread_shm_cache_entry * ce)586 static void clear_shm_cache_entry(struct thread_shm_cache_entry *ce)
587 {
588 	if (ce->mobj) {
589 		switch (ce->type) {
590 		case THREAD_SHM_TYPE_APPLICATION:
591 			thread_rpc_free_payload(ce->mobj);
592 			break;
593 		case THREAD_SHM_TYPE_KERNEL_PRIVATE:
594 			thread_rpc_free_kernel_payload(ce->mobj);
595 			break;
596 		case THREAD_SHM_TYPE_GLOBAL:
597 			thread_rpc_free_global_payload(ce->mobj);
598 			break;
599 		default:
600 			assert(0); /* "can't happen" */
601 			break;
602 		}
603 	}
604 	ce->mobj = NULL;
605 	ce->size = 0;
606 }
607 
608 static struct thread_shm_cache_entry *
get_shm_cache_entry(enum thread_shm_cache_user user)609 get_shm_cache_entry(enum thread_shm_cache_user user)
610 {
611 	struct thread_shm_cache *cache = &threads[thread_get_id()].shm_cache;
612 	struct thread_shm_cache_entry *ce = NULL;
613 
614 	SLIST_FOREACH(ce, cache, link)
615 		if (ce->user == user)
616 			return ce;
617 
618 	ce = calloc(1, sizeof(*ce));
619 	if (ce) {
620 		ce->user = user;
621 		SLIST_INSERT_HEAD(cache, ce, link);
622 	}
623 
624 	return ce;
625 }
626 
thread_rpc_shm_cache_alloc(enum thread_shm_cache_user user,enum thread_shm_type shm_type,size_t size,struct mobj ** mobj)627 void *thread_rpc_shm_cache_alloc(enum thread_shm_cache_user user,
628 				 enum thread_shm_type shm_type,
629 				 size_t size, struct mobj **mobj)
630 {
631 	struct thread_shm_cache_entry *ce = NULL;
632 	size_t sz = size;
633 	paddr_t p = 0;
634 	void *va = NULL;
635 
636 	if (!size)
637 		return NULL;
638 
639 	ce = get_shm_cache_entry(user);
640 	if (!ce)
641 		return NULL;
642 
643 	/*
644 	 * Always allocate in page chunks as normal world allocates payload
645 	 * memory as complete pages.
646 	 */
647 	sz = ROUNDUP(size, SMALL_PAGE_SIZE);
648 
649 	if (ce->type != shm_type || sz > ce->size) {
650 		clear_shm_cache_entry(ce);
651 
652 		ce->mobj = alloc_shm(shm_type, sz);
653 		if (!ce->mobj)
654 			return NULL;
655 
656 		if (mobj_get_pa(ce->mobj, 0, 0, &p))
657 			goto err;
658 
659 		if (!IS_ALIGNED_WITH_TYPE(p, uint64_t))
660 			goto err;
661 
662 		va = mobj_get_va(ce->mobj, 0, sz);
663 		if (!va)
664 			goto err;
665 
666 		ce->size = sz;
667 		ce->type = shm_type;
668 	} else {
669 		va = mobj_get_va(ce->mobj, 0, sz);
670 		if (!va)
671 			goto err;
672 	}
673 	*mobj = ce->mobj;
674 
675 	return va;
676 err:
677 	clear_shm_cache_entry(ce);
678 	return NULL;
679 }
680 
thread_rpc_shm_cache_clear(struct thread_shm_cache * cache)681 void thread_rpc_shm_cache_clear(struct thread_shm_cache *cache)
682 {
683 	while (true) {
684 		struct thread_shm_cache_entry *ce = SLIST_FIRST(cache);
685 
686 		if (!ce)
687 			break;
688 		SLIST_REMOVE_HEAD(cache, link);
689 		clear_shm_cache_entry(ce);
690 		free(ce);
691 	}
692 }
693