File: thread.c

package info (click to toggle)
optee-os 4.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 31,960 kB
  • sloc: ansic: 444,388; asm: 12,922; python: 3,719; makefile: 1,681; sh: 238
file content (861 lines) | stat: -rw-r--r-- 21,588 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
// SPDX-License-Identifier: BSD-2-Clause
/*
 * Copyright (c) 2016-2022, Linaro Limited
 * Copyright (c) 2014, STMicroelectronics International N.V.
 * Copyright (c) 2020-2021, Arm Limited
 */

#include <config.h>
#include <crypto/crypto.h>
#include <kernel/asan.h>
#include <kernel/boot.h>
#include <kernel/lockdep.h>
#include <kernel/misc.h>
#include <kernel/panic.h>
#include <kernel/spinlock.h>
#include <kernel/thread.h>
#include <kernel/thread_private.h>
#include <mm/mobj.h>
#include <mm/page_alloc.h>
#include <stdalign.h>

#if defined(CFG_DYN_CONFIG)
struct thread_core_local *thread_core_local __nex_bss;
size_t thread_core_count __nex_bss;
struct thread_ctx *threads;
size_t thread_count;
#else
static struct thread_core_local
	__thread_core_local[CFG_TEE_CORE_NB_CORE] __nex_bss;
struct thread_core_local *thread_core_local __nex_data = __thread_core_local;
size_t thread_core_count __nex_data = CFG_TEE_CORE_NB_CORE;
static struct thread_ctx __threads[CFG_NUM_THREADS];
struct thread_ctx *threads = __threads;
size_t thread_count = CFG_NUM_THREADS;
#endif
unsigned long thread_core_local_pa __nex_bss;
struct thread_core_local *__thread_core_local_new __nex_bss;
size_t __thread_core_count_new __nex_bss;

/*
 * Stacks
 *
 * [Lower addresses on the left]
 *
 * [ STACK_CANARY_SIZE/2 | STACK_CHECK_EXTRA | STACK_XXX_SIZE | STACK_CANARY_SIZE/2 ]
 * ^                     ^                   ^                ^
 * stack_xxx[n]          "hard" top          "soft" top       bottom
 */

static uint32_t start_canary_value = 0xdedede00;
static uint32_t end_canary_value = 0xababab00;

#define DECLARE_STACK(name, num_stacks, stack_size, linkage) \
linkage uint32_t name[num_stacks] \
		[ROUNDUP(stack_size + STACK_CANARY_SIZE + STACK_CHECK_EXTRA, \
			 STACK_ALIGNMENT) / sizeof(uint32_t)] \
		__attribute__((section(".nozi_stack." # name), \
			       aligned(STACK_ALIGNMENT)))

#ifndef CFG_DYN_CONFIG
DECLARE_STACK(stack_tmp, CFG_TEE_CORE_NB_CORE, STACK_TMP_SIZE,
	      /* global linkage */);
DECLARE_STACK(stack_abt, CFG_TEE_CORE_NB_CORE, STACK_ABT_SIZE, static);
#define GET_STACK_BOTTOM(stack, n) ((vaddr_t)&(stack)[n] + sizeof(stack[n]) - \
				    STACK_CANARY_SIZE / 2)
#else
/* Not used */
#define GET_STACK_BOTTOM(stack, n) 0
#endif

#if defined(CFG_DYN_CONFIG) || defined(CFG_WITH_PAGER)
/* Not used */
#define GET_STACK_THREAD_BOTTOM(n) 0
#else
DECLARE_STACK(stack_thread, CFG_NUM_THREADS, STACK_THREAD_SIZE, static);
#define GET_STACK_THREAD_BOTTOM(n) \
	((vaddr_t)&stack_thread[n] +  sizeof(stack_thread[n]) - \
	 STACK_CANARY_SIZE / 2)
#endif

#ifndef CFG_DYN_CONFIG
const uint32_t stack_tmp_stride __section(".identity_map.stack_tmp_stride") =
	sizeof(stack_tmp[0]);

/*
 * This stack setup info is required by secondary boot cores before they
 * each locally enable the pager (the mmu). Hence kept in pager sections.
 */
DECLARE_KEEP_PAGER(stack_tmp_stride);
#endif

static unsigned int thread_global_lock __nex_bss = SPINLOCK_UNLOCK;

static size_t stack_size_to_alloc_size(size_t stack_size)
{
	return ROUNDUP(stack_size + STACK_CANARY_SIZE + STACK_CHECK_EXTRA,
		       STACK_ALIGNMENT);
}

static vaddr_t stack_end_va_to_top_hard(size_t stack_size, vaddr_t end_va)
{
	size_t l = stack_size_to_alloc_size(stack_size);

	return end_va - l + STACK_CANARY_SIZE;
}

static vaddr_t stack_end_va_to_top_soft(size_t stack_size, vaddr_t end_va)
{
	return stack_end_va_to_top_hard(stack_size, end_va) + STACK_CHECK_EXTRA;
}

static vaddr_t stack_end_va_to_bottom(size_t stack_size __unused,
				      vaddr_t end_va)
{
	return end_va;
}

static uint32_t *stack_end_va_to_start_canary(size_t stack_size, vaddr_t end_va)
{
	return (uint32_t *)(stack_end_va_to_top_hard(stack_size, end_va) -
			    STACK_CANARY_SIZE / 2);
}

static uint32_t *stack_end_va_to_end_canary(size_t stack_size __unused,
					    vaddr_t end_va)
{
	return (uint32_t *)(end_va + STACK_CANARY_SIZE / 2 - sizeof(uint32_t));
}

static void init_canaries(size_t stack_size, vaddr_t va_end)
{
	uint32_t *canary = NULL;

	assert(va_end);
	canary = stack_end_va_to_start_canary(stack_size, va_end);
	*canary = start_canary_value;
	canary = stack_end_va_to_end_canary(stack_size, va_end);
	*canary = end_canary_value;
}

void thread_init_canaries(void)
{
	vaddr_t va = 0;
	size_t n = 0;

	if (IS_ENABLED(CFG_WITH_STACK_CANARIES)) {
		for (n = 0; n < thread_core_count; n++) {
			if (thread_core_local[n].tmp_stack_va_end) {
				va = thread_core_local[n].tmp_stack_va_end +
				     STACK_TMP_OFFS;
				init_canaries(STACK_TMP_SIZE, va);
			}
			va = thread_core_local[n].abt_stack_va_end;
			if (va)
				init_canaries(STACK_ABT_SIZE, va);
		}

	}

	if (IS_ENABLED(CFG_WITH_STACK_CANARIES) &&
	    !IS_ENABLED(CFG_WITH_PAGER) &&
	    !IS_ENABLED(CFG_NS_VIRTUALIZATION) && threads) {
		for (n = 0; n < thread_count; n++) {
			va = threads[n].stack_va_end;
			if (va)
				init_canaries(STACK_THREAD_SIZE, va);
		}
	}
}

#if defined(CFG_WITH_STACK_CANARIES)
void thread_update_canaries(void)
{
	uint32_t canary[2] = { };
	uint32_t exceptions = 0;

	plat_get_random_stack_canaries(canary, ARRAY_SIZE(canary),
				       sizeof(canary[0]));

	exceptions = thread_mask_exceptions(THREAD_EXCP_ALL);

	thread_check_canaries();

	start_canary_value = canary[0];
	end_canary_value = canary[1];
	thread_init_canaries();

	thread_unmask_exceptions(exceptions);
}
#endif

static void check_stack_canary(const char *stack_name __maybe_unused,
			       size_t n __maybe_unused,
			       size_t stack_size, vaddr_t end_va)
{
	uint32_t *canary = NULL;

	canary = stack_end_va_to_start_canary(stack_size, end_va);
	if (*canary != start_canary_value) {
		EMSG_RAW("Dead canary at start of '%s[%zu]' (%p)",
			 stack_name, n, (void *)canary);
		panic();
	}

	canary = stack_end_va_to_end_canary(stack_size, end_va);
	if (*canary != end_canary_value) {
		EMSG_RAW("Dead canary at end of '%s[%zu]' (%p)",
			 stack_name, n, (void *)canary);
		panic();
	}
}

void thread_check_canaries(void)
{
	vaddr_t va = 0;
	size_t n = 0;

	if (IS_ENABLED(CFG_WITH_STACK_CANARIES)) {
		for (n = 0; n < thread_core_count; n++) {
			if (thread_core_local[n].tmp_stack_va_end) {
				va = thread_core_local[n].tmp_stack_va_end +
				     STACK_TMP_OFFS;
				check_stack_canary("tmp_stack", n,
						   STACK_TMP_SIZE, va);
			}

			va = thread_core_local[n].abt_stack_va_end;
			if (va)
				check_stack_canary("abt_stack", n,
						   STACK_ABT_SIZE, va);
		}
	}

	if (IS_ENABLED(CFG_WITH_STACK_CANARIES) &&
	    !IS_ENABLED(CFG_WITH_PAGER) && !IS_ENABLED(CFG_NS_VIRTUALIZATION)) {
		for (n = 0; n < thread_count; n++) {
			va = threads[n].stack_va_end;
			if (va)
				check_stack_canary("thread_stack", n,
						   STACK_THREAD_SIZE, va);
		}
	}
}

void thread_lock_global(void)
{
	cpu_spin_lock(&thread_global_lock);
}

void thread_unlock_global(void)
{
	cpu_spin_unlock(&thread_global_lock);
}

static struct thread_core_local * __nostackcheck
get_core_local(unsigned int pos)
{
	/*
	 * Foreign interrupts must be disabled before playing with core_local
	 * since we otherwise may be rescheduled to a different core in the
	 * middle of this function.
	 */
	assert(thread_get_exceptions() & THREAD_EXCP_FOREIGN_INTR);

	/*
	 * We boot on a single core and have allocated only one struct
	 * thread_core_local so we return that regardless of pos.
	 */
	if (IS_ENABLED(CFG_DYN_CONFIG) &&
	    thread_core_local != __thread_core_local_new)
		return thread_core_local;

	assert(pos < thread_core_count);
	return &thread_core_local[pos];
}

struct thread_core_local * __nostackcheck thread_get_core_local(void)
{
	unsigned int pos = get_core_pos();

	return get_core_local(pos);
}

#ifdef CFG_CORE_DEBUG_CHECK_STACKS
static void print_stack_limits(void)
{
	size_t n = 0;
	vaddr_t __maybe_unused start = 0;
	vaddr_t __maybe_unused end = 0;
	vaddr_t va = 0;

	for (n = 0; n < thread_core_count; n++) {
		va = thread_core_local[n].tmp_stack_va_end + STACK_TMP_OFFS;
		start = stack_end_va_to_top_soft(STACK_TMP_SIZE, va);
		end = stack_end_va_to_bottom(STACK_TMP_SIZE, va);
		DMSG("tmp [%zu] 0x%" PRIxVA "..0x%" PRIxVA, n, start, end);

		va = thread_core_local[n].abt_stack_va_end;
		start = stack_end_va_to_top_soft(STACK_ABT_SIZE, va);
		end = stack_end_va_to_bottom(STACK_ABT_SIZE, va);
		DMSG("abt [%zu] 0x%" PRIxVA "..0x%" PRIxVA, n, start, end);
	}

	for (n = 0; n < thread_count; n++) {
		va = threads[n].stack_va_end;
		start = stack_end_va_to_top_soft(STACK_THREAD_SIZE, va);
		end = stack_end_va_to_bottom(STACK_THREAD_SIZE, va);
		DMSG("thr [%zu] 0x%" PRIxVA "..0x%" PRIxVA, n, start, end);
	}
}

static void check_stack_limits(void)
{
	vaddr_t stack_start = 0;
	vaddr_t stack_end = 0;
	/* Any value in the current stack frame will do */
	vaddr_t current_sp = (vaddr_t)&stack_start;

	if (!get_stack_soft_limits(&stack_start, &stack_end))
		panic("Unknown stack limits");
	if (current_sp < stack_start || current_sp > stack_end) {
		EMSG("Stack pointer out of range: 0x%" PRIxVA " not in [0x%"
		     PRIxVA " .. 0x%" PRIxVA "]", current_sp, stack_start,
		     stack_end);
		print_stack_limits();
		panic();
	}
}

static bool * __nostackcheck get_stackcheck_recursion_flag(void)
{
	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
	unsigned int pos = get_core_pos();
	struct thread_core_local *l = get_core_local(pos);
	int ct = l->curr_thread;
	bool *p = NULL;

	if (l->flags & (THREAD_CLF_ABORT | THREAD_CLF_TMP))
		p = &l->stackcheck_recursion;
	else if (!l->flags)
		p = &threads[ct].tsd.stackcheck_recursion;

	thread_unmask_exceptions(exceptions);
	return p;
}

void __cyg_profile_func_enter(void *this_fn, void *call_site);
void __nostackcheck __cyg_profile_func_enter(void *this_fn __unused,
					     void *call_site __unused)
{
	bool *p = get_stackcheck_recursion_flag();

	assert(p);
	if (*p)
		return;
	*p = true;
	check_stack_limits();
	*p = false;
}

void __cyg_profile_func_exit(void *this_fn, void *call_site);
void __nostackcheck __cyg_profile_func_exit(void *this_fn __unused,
					    void *call_site __unused)
{
}
#else
static void print_stack_limits(void)
{
}
#endif

void thread_init_boot_thread(void)
{
	struct thread_core_local *l = thread_get_core_local();

	l->curr_thread = 0;
	threads[0].state = THREAD_STATE_ACTIVE;
}

void __nostackcheck thread_clr_boot_thread(void)
{
	struct thread_core_local *l = thread_get_core_local();

	assert(l->curr_thread >= 0 && l->curr_thread < CFG_NUM_THREADS);
	assert(threads[l->curr_thread].state == THREAD_STATE_ACTIVE);
	threads[l->curr_thread].state = THREAD_STATE_FREE;
	l->curr_thread = THREAD_ID_INVALID;
	print_stack_limits();
}

void __nostackcheck *thread_get_tmp_sp(void)
{
	struct thread_core_local *l = thread_get_core_local();

	/*
	 * Called from assembly when switching to the temporary stack, so flags
	 * need updating
	 */
	l->flags |= THREAD_CLF_TMP;

	return (void *)l->tmp_stack_va_end;
}

vaddr_t thread_stack_start(void)
{
	struct thread_ctx *thr;
	int ct = thread_get_id_may_fail();

	if (ct == THREAD_ID_INVALID)
		return 0;

	thr = threads + ct;
	return stack_end_va_to_top_soft(STACK_THREAD_SIZE, thr->stack_va_end);
}

size_t thread_stack_size(void)
{
	return STACK_THREAD_SIZE;
}

bool get_stack_limits(vaddr_t *start, vaddr_t *end, bool hard)
{
	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
	unsigned int pos = get_core_pos();
	struct thread_core_local *l = get_core_local(pos);
	int ct = l->curr_thread;
	size_t stack_size = 0;
	bool ret = true;
	vaddr_t va = 0;

	if (l->flags & THREAD_CLF_TMP) {
		va = l->tmp_stack_va_end + STACK_TMP_OFFS;
		stack_size = STACK_TMP_SIZE;
	} else if (l->flags & THREAD_CLF_ABORT) {
		va = l->abt_stack_va_end;
		stack_size = STACK_ABT_SIZE;
	} else if (!l->flags && ct >= 0 && (size_t)ct < thread_count) {
		va = threads[ct].stack_va_end;
		stack_size = STACK_THREAD_SIZE;
	} else {
		ret = false;
		goto out;
	}

	*end = stack_end_va_to_bottom(stack_size, va);
	if (hard)
		*start = stack_end_va_to_top_hard(stack_size, va);
	else
		*start = stack_end_va_to_top_soft(stack_size, va);
out:
	thread_unmask_exceptions(exceptions);
	return ret;
}

bool thread_is_from_abort_mode(void)
{
	struct thread_core_local *l = thread_get_core_local();

	return (l->flags >> THREAD_CLF_SAVED_SHIFT) & THREAD_CLF_ABORT;
}

/*
 * This function should always be accurate, but it might be possible to
 * implement a more efficient depending on cpu architecture.
 */
bool __weak __noprof thread_is_in_normal_mode(void)
{
	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
	struct thread_core_local *l = thread_get_core_local();
	bool ret;

	/*
	 * If any bit in l->flags is set aside from THREAD_CLF_TMP we're
	 * handling some exception.
	 */
	ret = (l->curr_thread != THREAD_ID_INVALID) &&
	      !(l->flags & ~THREAD_CLF_TMP);
	thread_unmask_exceptions(exceptions);

	return ret;
}

short int __noprof thread_get_id_may_fail(void)
{
	/*
	 * thread_get_core_local() requires foreign interrupts to be disabled
	 */
	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
	struct thread_core_local *l = thread_get_core_local();
	short int ct = l->curr_thread;

	thread_unmask_exceptions(exceptions);
	return ct;
}

short int __noprof thread_get_id(void)
{
	short int ct = thread_get_id_may_fail();

	/* Thread ID has to fit in a short int */
	COMPILE_TIME_ASSERT(CFG_NUM_THREADS <= SHRT_MAX);
	assert(ct >= 0 && ct < CFG_NUM_THREADS);
	return ct;
}

static vaddr_t alloc_stack(size_t stack_size, bool nex)
{
	size_t l = stack_size_to_alloc_size(stack_size);
	size_t rl = ROUNDUP(l, SMALL_PAGE_SIZE);
	uint32_t flags = MAF_GUARD_HEAD;
	vaddr_t end_va = 0;
	vaddr_t va = 0;

	if (nex)
		flags |= MAF_NEX;
	va = virt_page_alloc(rl / SMALL_PAGE_SIZE, flags);
	if (!va)
		panic();

	end_va = va + l - STACK_CANARY_SIZE / 2;
	if (IS_ENABLED(CFG_WITH_STACK_CANARIES))
		init_canaries(stack_size, end_va);

	return end_va;
}

#ifdef CFG_WITH_PAGER
static void init_thread_stacks(void)
{
	size_t n = 0;

	/*
	 * Allocate virtual memory for thread stacks.
	 */
	for (n = 0; n < thread_count; n++) {
		tee_mm_entry_t *mm = NULL;
		vaddr_t sp = 0;
		size_t num_pages = 0;
		struct fobj *fobj = NULL;

		/* Find vmem for thread stack and its protection gap */
		mm = tee_mm_alloc(&core_virt_mem_pool,
				  SMALL_PAGE_SIZE + STACK_THREAD_SIZE);
		assert(mm);

		/* Claim eventual physical page */
		tee_pager_add_pages(tee_mm_get_smem(mm), tee_mm_get_size(mm),
				    true);

		num_pages = tee_mm_get_bytes(mm) / SMALL_PAGE_SIZE - 1;
		fobj = fobj_locked_paged_alloc(num_pages);

		/* Add the region to the pager */
		tee_pager_add_core_region(tee_mm_get_smem(mm) + SMALL_PAGE_SIZE,
					  PAGED_REGION_TYPE_LOCK, fobj);
		fobj_put(fobj);

		/* init effective stack */
		sp = tee_mm_get_smem(mm) + tee_mm_get_bytes(mm);
		asan_tag_access((void *)tee_mm_get_smem(mm), (void *)sp);
		threads[n].stack_va_end = sp;
	}
}
#else
static void init_thread_stacks(void)
{
	vaddr_t va = 0;
	size_t n = 0;

	/* Assign the thread stacks */
	for (n = 0; n < thread_count; n++) {
		if (IS_ENABLED(CFG_DYN_CONFIG))
			va = alloc_stack(STACK_THREAD_SIZE, false);
		else
			va = GET_STACK_THREAD_BOTTOM(n);
		threads[n].stack_va_end = va;
		if (IS_ENABLED(CFG_WITH_STACK_CANARIES))
			init_canaries(STACK_THREAD_SIZE, va);
	}
}
#endif /*CFG_WITH_PAGER*/

void thread_init_threads(size_t count)
{
	size_t n = 0;

	if (IS_ENABLED(CFG_DYN_CONFIG)) {
		assert(count <= CFG_NUM_THREADS);
		threads = calloc(count, sizeof(*threads));
		if (!threads)
			panic();
		thread_count = count;
	} else {
		assert(count == CFG_NUM_THREADS);
	}

	init_thread_stacks();
	print_stack_limits();
	pgt_init();

	mutex_lockdep_init();

	for (n = 0; n < thread_count; n++)
		TAILQ_INIT(&threads[n].tsd.sess_stack);
}

#ifndef CFG_DYN_CONFIG
vaddr_t __nostackcheck thread_get_abt_stack(void)
{
	return GET_STACK_BOTTOM(stack_abt, get_core_pos());
}
#endif

void thread_init_thread_core_local(size_t core_count)
{
	struct thread_core_local *tcl = NULL;
	const size_t core_pos = get_core_pos();
	vaddr_t va = 0;
	size_t n = 0;

	if (IS_ENABLED(CFG_DYN_CONFIG)) {
		assert(core_count <= CFG_TEE_CORE_NB_CORE);
		tcl = nex_calloc(core_count, sizeof(*tcl));
		if (!tcl)
			panic();
		__thread_core_local_new = tcl;
		__thread_core_count_new = core_count;
	} else {
		tcl = thread_core_local;
		assert(core_count == CFG_TEE_CORE_NB_CORE);

		for (n = 0; n < thread_core_count; n++) {
			init_canaries(STACK_TMP_SIZE,
				      GET_STACK_BOTTOM(stack_tmp, n));
			init_canaries(STACK_ABT_SIZE,
				      GET_STACK_BOTTOM(stack_abt, n));
		}
	}

	for (n = 0; n < core_count; n++) {
		if (n == core_pos) {
			if (IS_ENABLED(CFG_DYN_CONFIG))
				tcl[n] = thread_core_local[0];
			else
				continue;
		} else {
			tcl[n].curr_thread = THREAD_ID_INVALID;
			tcl[n].flags = THREAD_CLF_TMP;
		}

		if (IS_ENABLED(CFG_DYN_CONFIG))
			va = alloc_stack(STACK_TMP_SIZE, true);
		else
			va = GET_STACK_BOTTOM(stack_tmp, n);
		tcl[n].tmp_stack_va_end = va - STACK_TMP_OFFS;
#ifdef ARM32
		tcl[n].tmp_stack_pa_end =
			vaddr_to_phys(tcl[n].tmp_stack_va_end);
#endif

		if (IS_ENABLED(CFG_DYN_CONFIG))
			va = alloc_stack(STACK_ABT_SIZE, true);
		else
			va = GET_STACK_BOTTOM(stack_abt, n);
		tcl[n].abt_stack_va_end = va;
	}
}

#if defined(CFG_CORE_PAUTH)
void thread_init_thread_pauth_keys(void)
{
	size_t n = 0;

	for (n = 0; n < thread_count; n++)
		if (crypto_rng_read(&threads[n].keys, sizeof(threads[n].keys)))
			panic("Failed to init thread pauth keys");
}

void thread_init_core_local_pauth_keys(void)
{
	struct thread_core_local *tcl = thread_core_local;
	size_t n = 0;

	for (n = 0; n < thread_core_count; n++)
		if (crypto_rng_read(&tcl[n].keys, sizeof(tcl[n].keys)))
			panic("Failed to init core local pauth keys");
}
#endif

struct thread_specific_data * __noprof thread_get_tsd(void)
{
	return &threads[thread_get_id()].tsd;
}

struct thread_ctx_regs * __nostackcheck thread_get_ctx_regs(void)
{
	struct thread_core_local *l = thread_get_core_local();

	assert(l->curr_thread != THREAD_ID_INVALID);
	return &threads[l->curr_thread].regs;
}

void thread_set_foreign_intr(bool enable)
{
	/* thread_get_core_local() requires foreign interrupts to be disabled */
	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
	struct thread_core_local *l;

	l = thread_get_core_local();

	assert(l->curr_thread != THREAD_ID_INVALID);

	if (enable) {
		threads[l->curr_thread].flags |=
					THREAD_FLAGS_FOREIGN_INTR_ENABLE;
		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
	} else {
		/*
		 * No need to disable foreign interrupts here since they're
		 * already disabled above.
		 */
		threads[l->curr_thread].flags &=
					~THREAD_FLAGS_FOREIGN_INTR_ENABLE;
	}
}

void thread_restore_foreign_intr(void)
{
	/* thread_get_core_local() requires foreign interrupts to be disabled */
	uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_FOREIGN_INTR);
	struct thread_core_local *l;

	l = thread_get_core_local();

	assert(l->curr_thread != THREAD_ID_INVALID);

	if (threads[l->curr_thread].flags & THREAD_FLAGS_FOREIGN_INTR_ENABLE)
		thread_set_exceptions(exceptions & ~THREAD_EXCP_FOREIGN_INTR);
}

static struct mobj *alloc_shm(enum thread_shm_type shm_type, size_t size)
{
	switch (shm_type) {
	case THREAD_SHM_TYPE_APPLICATION:
		return thread_rpc_alloc_payload(size);
	case THREAD_SHM_TYPE_KERNEL_PRIVATE:
		return thread_rpc_alloc_kernel_payload(size);
	case THREAD_SHM_TYPE_GLOBAL:
		return thread_rpc_alloc_global_payload(size);
	default:
		return NULL;
	}
}

static void clear_shm_cache_entry(struct thread_shm_cache_entry *ce)
{
	if (ce->mobj) {
		switch (ce->type) {
		case THREAD_SHM_TYPE_APPLICATION:
			thread_rpc_free_payload(ce->mobj);
			break;
		case THREAD_SHM_TYPE_KERNEL_PRIVATE:
			thread_rpc_free_kernel_payload(ce->mobj);
			break;
		case THREAD_SHM_TYPE_GLOBAL:
			thread_rpc_free_global_payload(ce->mobj);
			break;
		default:
			assert(0); /* "can't happen" */
			break;
		}
	}
	ce->mobj = NULL;
	ce->size = 0;
}

static struct thread_shm_cache_entry *
get_shm_cache_entry(enum thread_shm_cache_user user)
{
	struct thread_shm_cache *cache = &threads[thread_get_id()].shm_cache;
	struct thread_shm_cache_entry *ce = NULL;

	SLIST_FOREACH(ce, cache, link)
		if (ce->user == user)
			return ce;

	ce = calloc(1, sizeof(*ce));
	if (ce) {
		ce->user = user;
		SLIST_INSERT_HEAD(cache, ce, link);
	}

	return ce;
}

void *thread_rpc_shm_cache_alloc(enum thread_shm_cache_user user,
				 enum thread_shm_type shm_type,
				 size_t size, struct mobj **mobj)
{
	struct thread_shm_cache_entry *ce = NULL;
	size_t sz = size;
	paddr_t p = 0;
	void *va = NULL;

	if (!size)
		return NULL;

	ce = get_shm_cache_entry(user);
	if (!ce)
		return NULL;

	/*
	 * Always allocate in page chunks as normal world allocates payload
	 * memory as complete pages.
	 */
	sz = ROUNDUP(size, SMALL_PAGE_SIZE);

	if (ce->type != shm_type || sz > ce->size) {
		clear_shm_cache_entry(ce);

		ce->mobj = alloc_shm(shm_type, sz);
		if (!ce->mobj)
			return NULL;

		if (mobj_get_pa(ce->mobj, 0, 0, &p))
			goto err;

		if (!IS_ALIGNED_WITH_TYPE(p, uint64_t))
			goto err;

		va = mobj_get_va(ce->mobj, 0, sz);
		if (!va)
			goto err;

		ce->size = sz;
		ce->type = shm_type;
	} else {
		va = mobj_get_va(ce->mobj, 0, sz);
		if (!va)
			goto err;
	}
	*mobj = ce->mobj;

	return va;
err:
	clear_shm_cache_entry(ce);
	return NULL;
}

void thread_rpc_shm_cache_clear(struct thread_shm_cache *cache)
{
	while (true) {
		struct thread_shm_cache_entry *ce = SLIST_FIRST(cache);

		if (!ce)
			break;
		SLIST_REMOVE_HEAD(cache, link);
		clear_shm_cache_entry(ce);
		free(ce);
	}
}