1 /*
2  * Copyright (c) 2015 Stefan Kristiansson
3  * Based on arch/microblaze/thread.c
4  * Copyright (c) 2015 Travis Geiselbrecht
5  *
6  * Use of this source code is governed by a MIT-style
7  * license that can be found in the LICENSE file or at
8  * https://opensource.org/licenses/MIT
9  */
10 #include <lk/debug.h>
11 #include <lk/trace.h>
12 #include <sys/types.h>
13 #include <string.h>
14 #include <stdlib.h>
15 #include <kernel/thread.h>
16 
17 #define LOCAL_TRACE 0
18 
19 struct thread *_current_thread;
20 
21 static void initial_thread_func(void) __NO_RETURN;
initial_thread_func(void)22 static void initial_thread_func(void) {
23     thread_t *ct = get_current_thread();
24 
25 #if LOCAL_TRACE
26     LTRACEF("thread %p calling %p with arg %p\n", ct, ct->entry, ct->arg);
27     dump_thread(ct);
28 #endif
29 
30     /* exit the implicit critical section we're within */
31     spin_unlock(&thread_lock);
32     arch_enable_ints();
33 
34     int ret = ct->entry(ct->arg);
35 
36     LTRACEF("thread %p exiting with %d\n", ct, ret);
37 
38     thread_exit(ret);
39 }
40 
arch_thread_initialize(thread_t * t)41 void arch_thread_initialize(thread_t *t) {
42     LTRACEF("t %p (%s)\n", t, t->name);
43 
44     /* some registers we want to clone for the new thread */
45     register uint32_t r2 asm("r2");
46 
47     /* zero out the thread context */
48     memset(&t->arch.cs_frame, 0, sizeof(t->arch.cs_frame));
49 
50     t->arch.cs_frame.r1 = (vaddr_t)t->stack + t->stack_size;
51     t->arch.cs_frame.r2 = r2;
52     t->arch.cs_frame.r9 = (vaddr_t)initial_thread_func;
53 }
54 
arch_context_switch(thread_t * oldthread,thread_t * newthread)55 void arch_context_switch(thread_t *oldthread, thread_t *newthread) {
56     LTRACEF("old %p (%s), new %p (%s)\n", oldthread, oldthread->name, newthread, newthread->name);
57 
58     or1k_context_switch(&oldthread->arch.cs_frame, &newthread->arch.cs_frame);
59 }
60 
arch_dump_thread(thread_t * t)61 void arch_dump_thread(thread_t *t) {
62     if (t->state != THREAD_RUNNING) {
63         dprintf(INFO, "\tarch: ");
64         dprintf(INFO, "sp 0x%x\n", t->arch.cs_frame.r1);
65     }
66 }
67