1 /*
2  * Copyright (c) 2020, Shenzhen Academy of Aerospace Technology
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  *
6  * Change Logs:
7  * Date           Author       Notes
8  * 2020-10-16     Dystopia     the first version
9  */
10 
11 #include <rtthread.h>
12 
13 /**
14  * This function will initialize thread stack
15  *
16  * @param tentry the entry of thread
17  * @param parameter the parameter of entry
18  * @param stack_addr the beginning stack address
19  * @param texit the function will be called when thread exit
20  *
21  * @return stack address
22  */
rt_hw_stack_init(void * tentry,void * parameter,rt_uint8_t * stack_addr,void * texit)23 rt_uint8_t *rt_hw_stack_init(void *tentry, void *parameter,
24                              rt_uint8_t *stack_addr, void *texit)
25 {
26     rt_uint32_t *stk;
27     int window_index;
28     int register_index;
29 
30     stack_addr += sizeof(rt_uint32_t);
31     stack_addr  = (rt_uint8_t *)RT_ALIGN_DOWN((rt_uint32_t)stack_addr, 8);
32     stk      = (rt_uint32_t *)stack_addr;
33 
34     stk -= 24;
35     stk -= 8;
36 
37     for (register_index = 0; register_index != 8; register_index++)
38         stk[register_index] = 0xdeadbeef;
39 
40     for (window_index = 0; window_index != 8; window_index++)
41     {
42         stk -= 16;
43         for (register_index = 0; register_index != 16; register_index++)
44             stk[register_index] = 0xdeadbeef;
45         if (window_index == 0)
46         {
47             stk[8] = (rt_uint32_t)parameter;
48             stk[15] = (rt_uint32_t)texit - 8;
49         }
50     }
51 
52     stk -= 34;
53     for (register_index = 0; register_index != 34; register_index++)
54         stk[register_index] = 0;
55 
56     stk -= 4;
57     stk[0] = (rt_uint32_t)tentry; //pc
58     stk[1] = (rt_uint32_t)tentry + 4; //npc
59     stk[2] = 0x10C7; //psr
60     stk[3] = 0x2; //wim
61 
62     /* return task's current stack address */
63     return (rt_uint8_t *)stk;
64 }
65