1 /*
2 * Copyright (c) 2008 Travis Geiselbrecht
3 *
4 * Use of this source code is governed by a MIT-style
5 * license that can be found in the LICENSE file or at
6 * https://opensource.org/licenses/MIT
7 */
8 #include <sys/types.h>
9 #include <string.h>
10 #include <stdlib.h>
11 #include <lk/debug.h>
12 #include <lk/trace.h>
13 #include <kernel/thread.h>
14 #include <arch/arm64.h>
15
16 #define LOCAL_TRACE 0
17
18 struct context_switch_frame {
19 vaddr_t lr;
20 vaddr_t pad; // Padding to keep frame size a multiple of
21 vaddr_t tpidr_el0; // sp alignment requirements (16 bytes)
22 vaddr_t tpidrro_el0;
23 vaddr_t r18;
24 vaddr_t r19;
25 vaddr_t r20;
26 vaddr_t r21;
27 vaddr_t r22;
28 vaddr_t r23;
29 vaddr_t r24;
30 vaddr_t r25;
31 vaddr_t r26;
32 vaddr_t r27;
33 vaddr_t r28;
34 vaddr_t r29;
35 };
36
37 extern void arm64_context_switch(addr_t *old_sp, addr_t new_sp);
38
39 static void initial_thread_func(void) __NO_RETURN;
initial_thread_func(void)40 static void initial_thread_func(void) {
41 int ret;
42
43 thread_t *current_thread = get_current_thread();
44
45 LTRACEF("initial_thread_func: thread %p calling %p with arg %p\n", current_thread, current_thread->entry, current_thread->arg);
46
47 /* release the thread lock that was implicitly held across the reschedule */
48 spin_unlock(&thread_lock);
49 arch_enable_ints();
50
51 ret = current_thread->entry(current_thread->arg);
52
53 LTRACEF("initial_thread_func: thread %p exiting with %d\n", current_thread, ret);
54
55 thread_exit(ret);
56 }
57
arch_thread_initialize(thread_t * t)58 void arch_thread_initialize(thread_t *t) {
59 // create a default stack frame on the stack
60 vaddr_t stack_top = (vaddr_t)t->stack + t->stack_size;
61
62 // make sure the top of the stack is 16 byte aligned for EABI compliance
63 stack_top = ROUNDDOWN(stack_top, 16);
64
65 struct context_switch_frame *frame = (struct context_switch_frame *)(stack_top);
66 frame--;
67
68 // fill it in
69 memset(frame, 0, sizeof(*frame));
70 frame->lr = (vaddr_t)&initial_thread_func;
71
72 // set the stack pointer
73 t->arch.sp = (vaddr_t)frame;
74 }
75
arch_context_switch(thread_t * oldthread,thread_t * newthread)76 void arch_context_switch(thread_t *oldthread, thread_t *newthread) {
77 LTRACEF("old %p (%s), new %p (%s)\n", oldthread, oldthread->name, newthread, newthread->name);
78 arm64_fpu_pre_context_switch(oldthread);
79 #if WITH_SMP
80 DSB; /* broadcast tlb operations in case the thread moves to another cpu */
81 #endif
82 arm64_context_switch(&oldthread->arch.sp, newthread->arch.sp);
83 }
84
arch_dump_thread(thread_t * t)85 void arch_dump_thread(thread_t *t) {
86 if (t->state != THREAD_RUNNING) {
87 dprintf(INFO, "\tarch: ");
88 dprintf(INFO, "sp 0x%lx\n", t->arch.sp);
89 }
90 }
91