+/rtos

git clone https://git.julia.blue/+/rtos

Joseph RyanAdd core temp reading413cd76

master
16.7 KiB607 linesraw
1#include "OS.h"
2#include "ADC.h"
3#include "ST7735.h"
4#include "eDisk.h"
5#include "esp8266.h"
6#include "heap.h"
7#include "interpreter.h"
8#include "interrupts.h"
9#include "io.h"
10#include "launchpad.h"
11#include "littlefs.h"
12#include "loader.h"
13#include "printf.h"
14#include "std.h"
15#include "timer.h"
16#include "tivaware/gpio.h"
17#include "tivaware/hw_gpio.h"
18#include "tivaware/hw_ints.h"
19#include "tivaware/hw_memmap.h"
20#include "tivaware/hw_nvic.h"
21#include "tivaware/hw_timer.h"
22#include "tivaware/hw_types.h"
23#include "tivaware/mpu.h"
24#include "tivaware/rom.h"
25#include "tivaware/timer.h"
26#include <stdint.h>
27#include <stdnoreturn.h>
28
29typedef struct {
30    uint32_t* text;
31    uint32_t* data;
32    uint16_t pid;
33    uint8_t threads;
34    bool alive;
35} PCB;
36
37typedef struct TCB {
38    uint32_t* sp;
39    struct TCB* next_tcb;
40    struct TCB* prev_tcb;
41    PCB* parent_process;
42
43    uint32_t id;
44    const char* name;
45    OutputDevice out_device;
46
47    struct TCB* next_blocked;
48
49    uint32_t sleep_time;
50
51    bool asleep;
52    bool blocked;
53    bool alive;
54    uint8_t priority;
55
56    uint32_t* stack;
57} TCB;
58
59#define MAX_THREADS 8
60#define MAX_PROCESSES 4
61#define MIN_STACK_SIZE 512
62
63static TCB threads[MAX_THREADS];
64static uint8_t thread_count = 0;
65
66static PCB processes[MAX_PROCESSES];
67static uint8_t process_count = 0;
68
69extern uint32_t _eheap;
70static TCB idle = {
71    .next_tcb = &idle,
72    .prev_tcb = &idle,
73    .id = 0,
74    .alive = true,
75    .priority = 255,
76    .name = "OS Idle",
77    .parent_process = 0,
78    .stack = (uint32_t*)&_eheap,
79};
80
81volatile TCB* current_thread = &idle;
82bool os_running;
83
84static noreturn void idle_task(void) {
85    os_running = true;
86    enable_interrupts();
87    while (true) { wait_for_interrupts(); }
88}
89
90static void insert_behind(TCB* a, TCB* b) {
91    a->next_tcb = b;
92    a->prev_tcb = b->prev_tcb;
93    a->prev_tcb->next_tcb = a;
94    b->prev_tcb = a;
95}
96
97static void insert_thread(TCB* adding) {
98    uint32_t crit = start_critical();
99    if (adding->priority < current_thread->priority) {
100        TCB* next = current_thread->next_tcb;
101        if (adding->priority < next->priority) {
102            adding->next_tcb = adding->prev_tcb = adding;
103            current_thread->next_tcb = adding;
104            OS_Suspend();
105        } else if (next->priority == adding->priority) {
106            insert_behind(adding, next);
107        }
108    } else if (adding->priority == current_thread->priority) {
109        insert_behind(adding,
110                      (current_thread->blocked || current_thread->asleep)
111                          ? current_thread->next_tcb
112                          : (TCB*)current_thread);
113    }
114    end_critical(crit);
115}
116
117// only called from sleep/kill/suspend so no additional critical section needed
118static void remove_current_thread() {
119    if (current_thread->next_tcb == current_thread) {
120        uint8_t my_count = thread_count;
121        TCB* new_current = &idle;
122        idle.next_tcb = &idle;
123        for (int i = 0; my_count > 0; ++i) {
124            if (!threads[i].alive) {
125                continue;
126            }
127            --my_count;
128            if (!(threads[i].asleep || threads[i].blocked)) {
129                if (threads[i].priority < new_current->priority) {
130                    new_current = &threads[i];
131                    new_current->next_tcb = new_current->prev_tcb = new_current;
132                } else if (threads[i].priority == new_current->priority) {
133                    insert_behind(&threads[i], new_current);
134                }
135            }
136        }
137        current_thread->next_tcb = new_current;
138    } else {
139        current_thread->prev_tcb->next_tcb = current_thread->next_tcb;
140        current_thread->next_tcb->prev_tcb = current_thread->prev_tcb;
141    }
142    OS_Suspend();
143}
144
145static void portd_init(void) {
146    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
147    ROM_GPIOPinTypeGPIOOutput(GPIO_PORTD_BASE, 0x0F);
148}
149
150void OS_Init(void) {
151    disable_interrupts();
152    os_running = false;
153    heap_init();
154    launchpad_init();
155    enable_button_interupts(3);
156    portd_init();
157    uart_init();
158    temperature_init();
159    SSI0_Init(10);
160}
161
162void OS_InitSemaphore(Sema4* sem, int32_t value) {
163    sem->value = value;
164    sem->blocked_head = 0;
165}
166
167void OS_Wait(Sema4* sem) {
168    uint32_t crit = start_critical();
169    current_thread->next_blocked = 0;
170    if (sem->value-- >= 0) {
171        end_critical(crit);
172        return;
173    }
174    current_thread->blocked = true;
175    if (!sem->blocked_head) {
176        sem->blocked_head = (TCB*)current_thread;
177    } else {
178        TCB* tail = sem->blocked_head;
179        while (tail->next_blocked &&
180               tail->next_blocked->priority <= current_thread->priority) {
181            tail = tail->next_blocked;
182        }
183        current_thread->next_blocked = tail->next_blocked;
184        tail->next_blocked = (TCB*)current_thread;
185    }
186    remove_current_thread();
187    end_critical(crit);
188}
189
190void OS_Signal(Sema4* sem) {
191    uint32_t crit = start_critical();
192    if (++sem->value >= 0) {
193        end_critical(crit);
194        return;
195    }
196    sem->blocked_head->blocked = false;
197    insert_thread(sem->blocked_head);
198    sem->blocked_head = sem->blocked_head->next_blocked;
199    end_critical(crit);
200}
201
202static uint32_t thread_uuid = 1;
203bool OS_AddThread(void (*task)(void), const char* name, uint32_t stack_size,
204                  uint32_t priority) {
205    uint32_t crit = start_critical();
206    if (thread_count >= MAX_THREADS - 1) {
207        end_critical(crit);
208        return false;
209    }
210    ++thread_count;
211    uint8_t thread_index = 0;
212    while (threads[thread_index].alive) { thread_index++; }
213    TCB* adding = &threads[thread_index];
214
215    if ((adding->parent_process = current_thread->parent_process)) {
216        ++adding->parent_process->threads;
217    }
218    adding->alive = true;
219    adding->asleep = false;
220    adding->sleep_time = 0;
221    adding->priority = priority;
222    adding->id = thread_uuid++;
223    adding->name = name;
224    adding->next_tcb = adding->prev_tcb = &idle;
225    adding->out_device = UART;
226
227    // initialize stack
228    stack_size = max(stack_size, MIN_STACK_SIZE) + 32; // extra is for MPU
229    adding->stack = malloc(stack_size);
230    if (!adding->stack) {
231        return false;
232    }
233    adding->sp = &adding->stack[stack_size / 4 - 1];
234    // TODO: check if 8 byte stack alignment matters
235    adding->sp = (uint32_t*)((uint8_t*)adding->sp - (uint32_t)adding->sp % 8);
236    adding->sp -= 18;                    // Space for floating point registers
237    *(--adding->sp) = 0x21000000;        // PSR
238    *(--adding->sp) = (uint32_t)task;    // PC
239    *(--adding->sp) = (uint32_t)OS_Kill; // LR
240    if (adding->parent_process) {
241        // R9 is the static base
242        *(adding->sp - 8) = (uint32_t)adding->parent_process->data;
243    }
244    adding->sp -= 13; // Space for R0-R12
245
246    insert_thread(adding);
247    end_critical(crit);
248    return true;
249}
250
251bool OS_AddProcess(void (*entry)(void), void* text, void* data,
252                   uint32_t stack_size, uint32_t priority) {
253    uint32_t crit = start_critical();
254    if (process_count == MAX_PROCESSES) {
255        return false;
256    }
257    ++process_count;
258    uint8_t add_idx = 0;
259    for (int i = 0; i < MAX_PROCESSES; ++i) {
260        if (!processes[i].alive) {
261            add_idx = i;
262            break;
263        }
264    }
265    processes[add_idx].text = text;
266    processes[add_idx].data = data;
267    processes[add_idx].alive = true;
268    PCB* saved_parent = current_thread->parent_process;
269    current_thread->parent_process = &processes[add_idx];
270    OS_AddThread(entry, "Process entry", stack_size, priority);
271    current_thread->parent_process = saved_parent;
272    end_critical(crit);
273    return true;
274}
275
276uint32_t OS_Id(void) {
277    return current_thread->id;
278}
279
280// performance measurments for periodic tasks
281#ifdef TRACK_JITTER
282static int32_t max_jitter;
283static uint32_t jitter_histogram[128] = {0};
284#endif
285
286typedef struct ptask {
287    void (*task)(void);
288    struct ptask* next;
289    uint32_t reload;
290    uint32_t current;
291    uint32_t last;
292    uint8_t priority;
293} PTask;
294
295#define MAX_PTASKS 4
296static PTask ptasks[MAX_PTASKS];
297static uint8_t num_ptasks;
298static PTask* current_ptask;
299
300static void setup_next_ptask(uint32_t lag);
301
302static void ptask_insert(PTask* task) {
303    if (!current_ptask) {
304        current_ptask = task;
305        task->next = 0;
306        return;
307    }
308    if (task->priority < current_ptask->priority) {
309        task->next = current_ptask;
310        current_ptask = task;
311    }
312    PTask* temp = current_ptask;
313    while (temp->next && task->priority > temp->next->priority) {
314        temp = temp->next;
315    }
316    task->next = temp->next;
317    temp->next = task;
318}
319
320static void periodic_task(void) {
321    uint32_t time = OS_Time();
322    do {
323        uint32_t current = OS_Time();
324#ifdef TRACK_JITTER
325        uint32_t jitter = to_us(
326            difference(current - current_ptask->last, current_ptask->reload));
327        max_jitter = max(max_jitter, jitter);
328        uint8_t idx = min(
329            sizeof(jitter_histogram) / sizeof(jitter_histogram[0]) - 1, jitter);
330        ++jitter_histogram[idx];
331#endif
332        current_ptask->last = current;
333        current_ptask->task();
334    } while ((current_ptask = current_ptask->next));
335    setup_next_ptask(OS_Time() - time);
336}
337
338static void setup_next_ptask(uint32_t lag) {
339    int32_t min_time = INT32_MAX;
340    for (int i = 0; i < num_ptasks; ++i) {
341        min_time = min(min_time, ptasks[i].current);
342    }
343    uint32_t threshold = max(min_time, lag);
344    for (int i = 0; i < num_ptasks; ++i) {
345        if (ptasks[i].current <= threshold) {
346            ptask_insert(&ptasks[i]);
347            ptasks[i].current =
348                max(0, ptasks[i].reload - (threshold - ptasks[i].current));
349        } else {
350            ptasks[i].current -= threshold;
351        }
352    }
353    timer_enable(2, max(min_time - lag, 1), periodic_task, 1, false);
354}
355
356bool OS_AddPeriodicThread(void (*task)(void), uint32_t period,
357                          uint32_t priority) {
358    if (num_ptasks >= MAX_PTASKS - 1) {
359        return false;
360    }
361    PTask* current = &ptasks[num_ptasks++];
362    current->priority = priority;
363    current->task = task;
364    current->last = os_running ? OS_Time() : 0;
365    current->current = current->reload = period;
366    // if the first periodic task is added after the OS starts, the oneshot
367    // timer isn't running yet
368    if (num_ptasks == 1 && os_running) {
369        setup_next_ptask(0);
370    }
371    return true;
372}
373
374static void (*sw1task)(void);
375static void (*sw2task)(void);
376
377const uint32_t debounce_ms = 20;
378static uint32_t last_sw1;
379static uint32_t last_sw2;
380
381void gpio_portf_handler(void) {
382    uint32_t now = to_ms(OS_Time());
383    if (HWREG(GPIO_PORTF_BASE + GPIO_O_RIS) & 0x01) {
384        if (sw1task && now - last_sw1 > debounce_ms) {
385            sw1task();
386        }
387        last_sw1 = now;
388    }
389    if (HWREG(GPIO_PORTF_BASE + GPIO_O_RIS) & 0x10) {
390        if (sw2task && now - last_sw2 > debounce_ms) {
391            sw2task();
392        }
393        last_sw2 = now;
394    }
395    HWREG(GPIO_PORTF_BASE + GPIO_O_ICR) = 0x11;
396}
397
398void OS_AddSW1Task(void (*task)(void)) {
399    sw1task = task;
400}
401
402void OS_AddSW2Task(void (*task)(void)) {
403    sw2task = task;
404}
405
406// TODO: structure this the same as periodic tasks to incur minimum overhead
407static void sleep_task(void) {
408    uint32_t reload = get_timer_reload(1);
409    for (int i = 0; i < MAX_THREADS; i++) {
410        if (threads[i].asleep) {
411            if (threads[i].sleep_time <= reload) {
412                threads[i].sleep_time = 0;
413                threads[i].asleep = false;
414                insert_thread(&threads[i]);
415            } else {
416                threads[i].sleep_time -= reload;
417            }
418        }
419    }
420}
421
422void OS_Sleep(uint32_t time) {
423    uint32_t crit = start_critical();
424    current_thread->asleep = true;
425    current_thread->sleep_time =
426        time + get_timer_reload(1) - get_timer_value(1);
427    remove_current_thread();
428    end_critical(crit);
429}
430
431void OS_Kill(void) {
432    uint32_t crit = start_critical();
433    --thread_count;
434    current_thread->alive = false;
435    free(current_thread->stack);
436    remove_current_thread();
437    // Handle process cleanup if needed
438    if (current_thread->parent_process) {
439        if (!--current_thread->parent_process->threads) {
440            --process_count;
441            current_thread->parent_process->alive = false;
442            free(current_thread->parent_process->data);
443            free(current_thread->parent_process->text);
444        }
445    }
446    end_critical(crit);
447}
448
449// Called from within the context switch to change which stack the MPU protects
450void mpu_swap_region(void) {
451    uint32_t temp = (uint32_t)current_thread->stack;
452    // 32 byte alignment required for MPU regions
453    if (temp % 32) {
454        temp += 32 - temp % 32;
455    }
456    ROM_MPURegionSet(0, temp,
457                     MPU_RGN_SIZE_32B | MPU_RGN_PERM_NOEXEC |
458                         MPU_RGN_PERM_PRV_NO_USR_NO | MPU_RGN_ENABLE);
459}
460
461void OS_Suspend(void) {
462    ROM_IntPendSet(FAULT_PENDSV);
463}
464
465void OS_ClearTime(void) {
466    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_WTIMER5);
467    ROM_TimerConfigure(WTIMER5_BASE, TIMER_CFG_PERIODIC_UP);
468    ROM_TimerControlStall(WTIMER5_BASE, TIMER_A, true);
469    ROM_TimerEnable(WTIMER5_BASE, TIMER_A);
470    HWREG(WTIMER5_BASE + TIMER_O_TAV) = 0;
471}
472
473uint32_t OS_Time(void) {
474    return ROM_TimerValueGet(WTIMER5_BASE, TIMER_A);
475}
476
477noreturn void OS_Launch(uint32_t time_slice) {
478    ROM_MPUEnable(MPU_CONFIG_PRIV_DEFAULT);
479    ROM_IntEnable(FAULT_MPU);
480    ROM_IntPrioritySet(FAULT_PENDSV, 0xff); // priority is high 3 bits
481    ROM_IntPrioritySet(FAULT_SYSTICK, 6 << 5);
482    ROM_SysTickPeriodSet(time_slice);
483    ROM_SysTickIntEnable();
484    ROM_SysTickEnable();
485    timer_enable(1, ms(1), &sleep_task, 3, true);
486    if (num_ptasks) {
487        setup_next_ptask(0);
488    }
489    OS_ClearTime();
490    idle_task();
491}
492
493void systick_handler() {
494    ROM_IntPendSet(FAULT_PENDSV);
495}
496
497void OS_ReportJitter(void) {
498#ifdef TRACK_JITTER
499    printf("Max Jitter: %d microseconds\n\r", max_jitter);
500    uint32_t most = 0, most_idx;
501    uint32_t sum = 0;
502    uint32_t total_num = 0;
503    for (int i = 0; i < sizeof(jitter_histogram) / sizeof(jitter_histogram[0]);
504         ++i) {
505        uint32_t num = jitter_histogram[i];
506        sum += i * num;
507        total_num += num;
508        if (num > most) {
509            most = num;
510            most_idx = i;
511        }
512    }
513    printf("Modal Jitter: %d microseconds\n\r", most_idx);
514    printf("Average Jitter: %d microseconds\n\r", sum / total_num);
515#else
516    puts("Jitter tracking not enabled...");
517#endif
518}
519
520// TODO: change the stack pointer so that using the stack in this handler
521// doesn't overwrite the HeapNode for the stack that just overflowed
522void memory_management_fault_handler(void) {
523    HeapNode* stack_allocation = heap_node_from_alloc(current_thread->stack);
524    uint16_t stack_size = stack_allocation->size - 32;
525    OS_RedirectOutput(UART);
526    printf("\n\n\rSTACK OVERFLOW\n\rThread '%s' overflowed its %d byte stack, "
527           "Consider increasing it.\n\r",
528           current_thread->name, stack_size);
529    printf("FAULTSTAT: 0x%08x\n\r", HWREG(NVIC_FAULT_STAT));
530    printf("Address accessed: 0x%08x\n\r", HWREG(NVIC_MM_ADDR));
531    while (true) {
532        busy_wait(7, ms(500));
533        led_toggle(RED_LED | BLUE_LED);
534    }
535}
536
537void hardfault_handler(void) {
538    OS_RedirectOutput(UART);
539    printf("\n\n\rHARD FAULT in thread '%s'\n\r", current_thread->name);
540    printf("FAULTSTAT:  0x%08x\n\r", HWREG(NVIC_FAULT_STAT));
541    printf("HFAULTSTAT: 0x%08x\n\r", HWREG(NVIC_HFAULT_STAT));
542    while (true) {
543        busy_wait(7, ms(500));
544        led_toggle(RED_LED);
545    }
546}
547
548// Exported symbol for dynamic function loading
549typedef struct {
550    const char* name;
551    void* ptr;
552} Symbol;
553
554static const Symbol symtab[] = {{"OS_Id", (void*)OS_Id},
555                                {"printf", (void*)printf}};
556
557void* OS_function_lookup(const char* name) {
558    for (int i = 0; i < sizeof(symtab) / sizeof(Symbol); ++i) {
559        if (streq(symtab[i].name, name)) {
560            return symtab[i].ptr;
561        }
562    }
563    return 0;
564}
565
566void OS_LoadProgram(char* name) {
567    printf("Loading: '%s'...\n\r", name);
568    if (!exec_elf(name)) {
569        puts("load program error");
570    }
571}
572
573void OS_RedirectOutput(OutputDevice device) {
574    current_thread->out_device = device;
575}
576
577void OS_RedirectString(const char* str) {
578    if (current_thread->out_device & UART) {
579        uart_puts(str);
580    }
581    if (current_thread->out_device & ESP) {
582        ESP8266_Send(str);
583        ESP8266_Send("\n\r");
584    }
585    if (current_thread->out_device & FS) {
586        // TODO: write to open file
587    }
588    if (current_thread->out_device & SCREEN) {
589        lcd_puts(str);
590    }
591}
592
593void OS_RedirectChar(char c) {
594    char buf[2] = {c, '\0'};
595    if (current_thread->out_device & UART) {
596        uart_putchar(c);
597    }
598    if (current_thread->out_device & ESP) {
599        ESP8266_Send(buf);
600    }
601    if (current_thread->out_device & FS) {
602        // TODO: write to open file
603    }
604    if (current_thread->out_device & SCREEN) {
605        lcd_putchar(c);
606    }
607}