1 /*
2  * Copyright (c) 2015 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 <lk/debug.h>
9 #include <lk/trace.h>
10 #include <sys/types.h>
11 #include <string.h>
12 #include <stdlib.h>
13 #include <kernel/thread.h>
14 #include <arch/mips.h>
15 
16 #define LOCAL_TRACE 0
17 
18 struct thread *_current_thread;
19 
20 static void initial_thread_func(void) __NO_RETURN;
initial_thread_func(void)21 static void initial_thread_func(void) {
22     thread_t *ct = get_current_thread();
23 
24 #if LOCAL_TRACE
25     LTRACEF("thread %p calling %p with arg %p\n", ct, ct->entry, ct->arg);
26     dump_thread(ct);
27 #endif
28 
29     /* release the thread lock that was implicitly held across the reschedule */
30     spin_unlock(&thread_lock);
31     arch_enable_ints();
32 
33     int ret = ct->entry(ct->arg);
34 
35     LTRACEF("thread %p exiting with %d\n", ct, ret);
36 
37     thread_exit(ret);
38 }
39 
arch_thread_initialize(thread_t * t)40 void arch_thread_initialize(thread_t *t) {
41     LTRACEF("t %p (%s)\n", t, t->name);
42 
43     /* zero out the thread context */
44     memset(&t->arch.cs_frame, 0, sizeof(t->arch.cs_frame));
45 
46     t->arch.cs_frame.ra = (vaddr_t)&initial_thread_func;
47     t->arch.cs_frame.sp = (vaddr_t)t->stack + t->stack_size;
48 }
49 
arch_context_switch(thread_t * oldthread,thread_t * newthread)50 void arch_context_switch(thread_t *oldthread, thread_t *newthread) {
51     LTRACEF("old %p (%s), new %p (%s)\n", oldthread, oldthread->name, newthread, newthread->name);
52 
53     mips_context_switch(&oldthread->arch.cs_frame, &newthread->arch.cs_frame);
54 }
55 
arch_dump_thread(thread_t * t)56 void arch_dump_thread(thread_t *t) {
57     if (t->state != THREAD_RUNNING) {
58         dprintf(INFO, "\tarch: ");
59         dprintf(INFO, "sp 0x%x\n", t->arch.cs_frame.sp);
60     }
61 }
62 
63