System Calls cleanup, multiple Processes and context switch
[cortex-from-scratch] / systick.c
1 /* (CC-BY-NC-SA) ROBIN KRENS - ROBIN @ ROBINKRENS.NL
2  * 
3  * $LOG$
4  * 2019/8/14 - ROBIN KRENS      
5  * Initial version 
6  * 
7  * $DESCRIPTION$
8  * SysTick of Cortex M* MCUs. Have a look at the more complex RTC 
9  * in case more accurate timing is needed.
10  *
11  * 
12  * */
13
14 #include <stdbool.h>
15 #include <stddef.h>
16 #include <stdint.h>
17
18 #include <sys/robsys.h>
19 #include <sys/mmap.h>
20
21 #include <lib/regfunc.h>
22 #include <lib/tinyprintf.h>
23
24 struct interrupt_frame {
25
26         uint32_t r0; // N-32
27         uint32_t r1;
28         uint32_t r2;
29         uint32_t r3;
30         uint32_t r12;
31         uint32_t lr;
32         uint32_t pc;
33         uint32_t psr; // N-4
34 };
35
36 //__attribute__ ((interrupt))
37 void * systick_handler(/* struct interrupt_frame * frame */) {
38
39         printf("Ticking...\n");
40
41 }
42
43
44 __attribute__ ((naked))
45         void * pendsv_handler_c(void) {
46 //
47 //      asm volatile ("push {r0-r11, lr}");
48 //      asm volatile ("mrs %0, psp" : "=r" (oldpsp));
49 //      asm volatile ("push {lr}");
50 //
51 //      //asm volatile ("push {lr}");
52 //      
53 //      //printf("FROM MSP %x", oldpsp);
54 //      //PSP_array[curr_task] = oldpsp;
55 //      //curr_task = next_task;
56 //      //newpsp = PSP_array[next_task];        
57 //
58 //      asm volatile ("msr psp, %0" : : "r" (newpsp)); 
59 //
60 //      asm volatile("pop {lr}");
61 //      //asm volatile ("pop {r0-r12}");
62 //      asm volatile("bx lr"); // return
63 }
64
65 uint32_t set_psp(uint32_t) __attribute__( ( naked ) );
66 uint32_t set_psp(uint32_t stackie) {
67   
68         asm volatile ("msr psp, r0" "\n\t"
69                   "bx lr");
70 }
71
72 void systick_init() {
73
74         /* Every time the counter counts down to zero
75          * a systick exception is invoked. Systick has
76          * exception number 15. in the vector table  */
77         ivt_set_gate(15, systick_handler, 0); 
78
79         /* Get calibration and set this to 1 sec
80          * !Most boards have a 1 ms or 10 ms 
81          * calibration value */
82         int calib = (*STK_CALIB << 0) * 200;
83
84         /* The counter reload registers counts down to zero
85          * and then it is restores the value */
86         rwrite(STK_RELOAD, calib);
87         
88         /* Enable the counter and enable the interrupt
89          * associated with it */
90         rsetbit(STK_CTRL, 0);
91         rsetbit(STK_CTRL, 1);
92
93 }