static void stdio_init(void);
+/**
+ * Entry point for userland programs.
+ * Sets up stdio, then enters the program's main() before exiting with main()'s
+ * return code.
+ */
void _start(void)
{
stdio_init();
exit(main(0, 0));
}
+/**
+ * Initializes file handles for stdout, stdin, and stderr.
+ */
void stdio_init(void)
{
stderr = calloc(1, sizeof(FILE));
uint32_t size;
} initrd_info;
+// Defined by linker script
extern uint8_t _binary_initrd_img_start[];
extern uint8_t _binary_initrd_img_size[];
int initrd_close(vfs_file_info *info);
int initrd_seek(vfs_file_info *info, uint32_t offset, int whence);
+/**
+ * Gets the start of the offset-th file in the initrd.
+ * @return Pointer to the file, NULL otherwise
+ */
char *initrd_getfile(uint32_t offset);
static const vfs_volume_funcs initrd_funcs = {
initrd_seek
};
+/**
+ * Custom strncmp() implementation used by this driver.
+ */
int initrd_strncmp(const char *a, const char *b, unsigned int n)
{
for (unsigned int i = 0; i < n; i++) {
void *initrd_open(const char *file)
{
+ // Iterate through all files in the initrd
char *ptr;
for (uint32_t i = 0; ptr = initrd_getfile(i), ptr != 0; i++) {
uint32_t len = *((uint32_t *)ptr);
if (!initrd_strncmp(file, ptr + 4, len)) {
+ // If we found our file, create an info structure and return it
initrd_info *file = (initrd_info *)malloc(
sizeof(initrd_info));
file->address = ptr + len + 8;
int initrd_close(vfs_file_info *info)
{
- // Nothing to do
free(info->fsinfo);
return 0;
}
uint32_t initrd_read(vfs_file_info *info, uint32_t count, uint8_t *buffer)
{
+ // Confirm this is a valid file
initrd_info *iinfo = (initrd_info *)info->fsinfo;
if (iinfo == 0 || iinfo->address == 0)
return 0;
+ // Attempt to read 'count' bytes, breaking if we reach the end of the file
uint32_t i;
for (i = 0; i < count; i++) {
if (info->pos >= iinfo->size)
{
char *ptr = (char *)initrd_start;
for (uint32_t i = 0; i < offset; i++) {
+ // Move to the next file
uint32_t len = *((uint32_t *)ptr);
uint32_t datalen = *((uint32_t *)(ptr + 4 + len));
ptr += len + datalen + 8;
+
if (ptr >= (char *)(initrd_start + initrd_size))
return 0;
}
void initrd_init(void);
#endif // INITRD_H_
+
void *stdio_open(const char *path)
{
+ /**
+ * All we need is the correct file handle number.
+ */
int *id = malloc(sizeof(uint32_t));
if (path[0] == 'o' && path[1] == 'u' && path[2] == 't')
int stdio_close(vfs_file_info *info)
{
- // Nothing to do
free(info->fsinfo);
return 0;
}
uint32_t stdio_read(vfs_file_info *info, uint32_t count, uint8_t *buffer)
{
+ // TODO?
(void)info;
(void)count;
(void)buffer;
uint32_t stdio_write(vfs_file_info *info, uint32_t count, const uint8_t *buffer)
{
+ // For now, output to serial
(void)info;
for (uint32_t i = 0; i < count; i++)
serial_put(buffer[i]);
extern const vfs_volume_funcs stdio_funcs;
#endif // INITRD_H_
+
uint32_t clock_millis(void);
#endif // CLOCK_H_
+
#include <string.h>
+/**
+ * Finds the section with the given name in the ELF data, e.g. ".bss".
+ * @param ehdr ELF file header
+ * @param name Name of the section
+ * @return Section header of the section, NULL if not found
+ */
Elf32_Shdr *elf_find_section(Elf32_Ehdr *ehdr, const char *name)
{
Elf32_Shdr *shdr = (Elf32_Shdr *)((char *)ehdr + ehdr->e_shoff);
Elf32_Ehdr *ehdr = (Elf32_Ehdr *)elfData;
Elf32_Phdr *phdr = (Elf32_Phdr *)(elfData + ehdr->e_phoff);
+ // Search for the loadable program header
for (Elf32_Half i = 0; i < ehdr->e_phnum; i++) {
if (phdr->p_type == PT_LOAD) {
// There should only be one PT_LOAD section...
while (1);
ELF_OFFSET = (uint32_t)malloc(phdr->p_memsz + 8) & ~7;
+ // Copy the program data into RAM for execution
uint8_t *src = (uint8_t *)elfData + phdr->p_offset;
uint8_t *dst = (uint8_t *)(ELF_OFFSET + phdr->p_vaddr);
for (uint32_t j = 0; j < phdr->p_filesz; j++)
gotArray[i] += ELF_OFFSET;
}
- // Run any constructors
+ // Run any initial constructors
Elf32_Shdr *initArraySection = elf_find_section(ehdr, ".init_array");
if (initArraySection != 0) {
Elf32_Addr *initArray = (Elf32_Addr *)(ELF_OFFSET +
} __attribute__((packed)) Elf32_Phdr;
#endif // ELF_H_
+
// TODO have a real fault handler...
while (1);
}
+
{
return port->IDR & (1 << pin);
}
+
uint32_t gpio_din(GPIO_TypeDef *port, uint32_t pin);
#endif // GPIO_H_
+
#include "heap.h"
+// Defines size of alignment on memory allocations
#define HEAP_ALIGN 4
+// Linked list of free'd memory
static alloc_t *free_blocks;
static void *heap_end;
uint32_t heap_free(void)
{
uint32_t total = 0;
+ // Count free'd block sizes
for (alloc_t *node = free_blocks; node != 0; node = node->next)
total += node->size;
+ // Add remaining free memory to that total
return total + (0x20018000 - (uint32_t)heap_end);
}
if (size == 0)
return 0;
+ // Round size to an aligned value
size = (size + sizeof(alloc_t) + HEAP_ALIGN) & ~(HEAP_ALIGN - 1);
+ // Begin searching through free'd blocks to see if we can reuse some memory.
alloc_t *node = free_blocks;
alloc_t *prev = 0;
while (node != 0) {
if (node->size >= size) {
- // get out of the free chain
+ // If we can use this chunk, remove it from the free_blocks chain
if (prev != 0)
prev->next = node->next;
else
free_blocks = node->next;
node->next = 0;
- // split alloc if too big
- if (node->size > size + 64) {
+ // If this chunk is really big, give back the extra space
+ if (node->size > size + 64) { // TODO why 64..?
alloc_t *leftover = (alloc_t *)((uint32_t)node
+ sizeof(alloc_t) + size);
leftover->size = node->size - size - sizeof(alloc_t);
leftover->next = 0;
free((uint8_t *)leftover + sizeof(alloc_t));
+
node->size = size;
return (void *)((uint8_t *)node + sizeof(alloc_t));
}
node = node->next;
}
+ // No reusable chunks, take from the end of the heap
node = (alloc_t *)heap_end;
node->size = size;
node->next = 0;
void *calloc(uint32_t count, uint32_t size)
{
+ // Simply malloc and zero
uint8_t *buf = malloc(count * size);
for (uint32_t i = 0; i < count * size; i++)
- buf[i] = 0;
+ buf[i] = 0; // TODO safe?
return buf;
}
if (buf == 0)
return;
+ // Get the alloc_t structure of this chunk
alloc_t *alloc = (alloc_t *)((uint8_t *)buf - sizeof(alloc_t));
if (alloc->next != 0)
return;
- // check for adjacent free'd blocks
+ // Search through the free_blocks list to see if this free chunk can merge
+ // into an adjacent free chunk.
int merged = 0;
for (alloc_t *prev = 0, *node = free_blocks; node != 0; prev = node, node = node->next) {
+ // If the node after the current one is ours
if ((uint32_t)node + sizeof(alloc_t) + node->size == (uint32_t)alloc) {
- // block before
+ // Merge by adding our node's size to this one
merged |= 1;
node->size += sizeof(alloc_t) + alloc->size;
break;
- //alloc = node;
- } else if ((uint32_t)buf + alloc->size == (uint32_t)node) {
- // block after
+ }
+ // Or, if this current node is the one after ours
+ else if ((uint32_t)buf + alloc->size == (uint32_t)node) {
+ // Merge the current node into ours
merged |= 1;
alloc->size += sizeof(alloc_t) + node->size;
alloc->next = node->next;
+
+ // Take the current node's place in the free_blocks chain
if (prev != 0)
prev->next = alloc;
else
}
}
+ // If we couldn't merge, simply append to the chain
if (merged == 0) {
alloc->next = free_blocks;
free_blocks = alloc;
}
}
+
#include <stdint.h>
+/**
+ * Internal structure place before memory allocations, to track allocation size.
+ */
typedef struct {
uint32_t size;
void *next;
/**
* Initializes memory management of the given heap.
- * No overflow stuff is done, so... be careful.
+ * Note: Heap size is not accounted for.
* @param buf The heap to use for allocations
*/
void heap_init(void *buf);
/**
- * Returns the amount of free, allocatable memory, in bytes.
+ * Returns the amount of free, allocatable memory, in bytes, assuming that the
+ * heap has from its initial location to the end of SRAM.
* @return Amount of free memory in bytes
*/
uint32_t heap_free(void);
void free(void *buf);
#endif // HEAP_H_
+
#include <fs/initrd.h>\r
#include <arch/stm/stm32l476xx.h>\r
\r
+// Heap goes after the end of the BSS section\r
extern uint8_t __bss_end__;\r
\r
extern void user_main(void);\r
\r
int main(void)\r
{\r
+ // Disable interrupts while we get ready\r
asm("cpsid i");\r
- // disable cached writes for precise debug info\r
+\r
+ // Disabling cached writes can help give more precise debug info\r
//*((uint32_t *)0xE000E008) |= 2;\r
\r
- // prepare flash latency for 80MHz operation\r
+ // Prepare flash latency for 80MHz operation\r
FLASH->ACR &= ~(FLASH_ACR_LATENCY);\r
FLASH->ACR |= FLASH_ACR_LATENCY_4WS;\r
\r
- // init core components\r
+ // Initialize core components\r
clock_init();\r
heap_init(&__bss_end__);\r
gpio_init();\r
vfs_init();\r
initrd_init();\r
\r
- // enable FPU\r
+ // Enable FPU (TODO why isn't it enabled?)\r
//SCB->CPACR |= (0xF << 20);\r
\r
+ // Begin multi-tasking (enables interrupts)\r
task_init(init_idle, 512);\r
while (1);\r
}\r
\r
void init_idle(void)\r
{\r
+ // Start the main userspace task with a 4kB stack\r
task_start(user_main, 4096);\r
\r
+ // Idle\r
while (1)\r
clock_delay(10);\r
}\r
+\r
gpio_mode(GPIOA, 3, ALTERNATE);
GPIOA->AFR[0] &= ~(0x0000FF00);
GPIOA->AFR[0] |= 0x00007700;
- RCC->APB1ENR1 |= RCC_APB1ENR1_USART2EN;
- // start usart device
+ // Start usart device
+ RCC->APB1ENR1 |= RCC_APB1ENR1_USART2EN;
USART2->BRR = 80000000L / baud;
USART2->CR1 |= USART_CR1_TE | USART_CR1_RE | USART_CR1_UE;
}
} while (buf[index] != '\r' && index++ < max);
buf[index] = '\0';
}
+
void serial_gets(char *buf, int max);
#endif // SERIAL_H_
+
void SVC_Handler(void) {
uint32_t *stack;
+ // Get the appropriate stack (either kernel or process)
asm("\
tst lr, #4; \
ite eq; \
uint32_t *args = (uint32_t *)stack[2];
switch (svc_number) {
- case -1:
+ case -1: // TODO why?
case 0: /* Task-related calls
* 0 - _exit
* 1 - fork
* 2 - getpid
* 3 - waitpid
- * 4 - sbrk (TODO bad)
+ * 4 - sbrk (TODO poor implementation)
* 5 - execve
*/
task_svc(min_number, ret, args);
}
// Free this thread's stack, and task data.
- // Since we're single core, no one else can claim this memory until
- // a task switch, after which we're done with this memory anyway.
+ // The scheduler still needs to use the data we're about to free; however,
+ // our single-core implementation keeps us safe from anyone else claiming
+ // this memory in the meantime.
free(task_current->stack);
free(task_current->heap);
free(task_current);
/**
* 'Prepares' task for running.
- * Calls the task's main code, setting task_doexit() (_exit) as the return point.
+ * Calls the task's main code after making task_doexit() (_exit) main's return
+ * point.
*/
__attribute__ ((naked))
void task_crt0(void)
t->heap = 0;
t->stack = (uint32_t *)malloc(stackSize);
- void *sp = (uint8_t *)t->stack + stackSize - 68; // excep. stack + regs
+ void *sp = (uint8_t *)t->stack + stackSize - 68; // exception stack + regs
t->sp = sp;
/*
void task_init(void (*init)(void), uint16_t stackSize)
{
+ // Create a dummy current task that we'll "exit" from
task_current = (task_t *)malloc(sizeof(task_t));
task_current->next = 0;
task_current->stack = 0; // free() is called on this
task_current->status.state = TASK_SLEEPING;
task_current->status.value = 1000;
+ // Place the init task in the queue to take the dummy task's place
task_queue = task_create(init, stackSize);
task_disable = 0;
+ // Enter userspace process mode
// bit 0 - priv, bit 1 - psp/msp
asm("\
isb; \
msr control, r0; \
");
- // exit the current (fake) task
+ // Exit the current (fake) task
task_doexit();
}
if (task_disable != 0)
asm("bx lr");
- // TODO get back to c, implement task sleeping
+ // TODO get back to c, implement task sleeping TODO did we do this?
- // Save current stack pointer
+ // Finish saving current state
asm("\
mrs r0, psp; \
isb; \
#define WIFEXITED(w) (w & (1 << 8))
#define WEXITSTATUS(w) (w & 0xFF)
-
typedef uint16_t pid_t;
/**
void task_start(void (*task)(void), uint16_t stackSize);
/**
- * Allows task switching to be disabled, for low-level actions.
+ * Allows task switching to be disabled, for low-level/time-critical operations.
* Multiple holds can be placed, and all must be removed to continue task
* switching.
* @param hold non-zero for hold, zero to remove hold
*/
void task_hold(uint8_t hold);
+/**
+ * Puts the task to sleep for the given duration.
+ * @param ms Milliseconds to sleep for
+ */
void task_sleep(uint32_t ms);
+/**
+ * Called by the task when it's ready to exit.
+ * @param code Task's exit code
+ */
void task_exit(int code);
+/**
+ * Forks the task into two processes.
+ */
int task_fork(void);
+/**
+ * Gets the task's PID.
+ */
pid_t task_getpid(void);
+/**
+ * Waits for a task to change state (TODO confirm).
+ */
pid_t task_waitpid(pid_t pid, int *wstatus, int options);
+/**
+ * TODO
+ */
void *task_sbrk(uint32_t bytes);
#endif // TASK_H_
+
void vfs_init(void)
{
+ // Mark all volumes and files as empty
for (int i = 0; i < VFS_MAX_VOLS; i++)
vfs_volumes[i].flags = 0;
for (int i = 0; i < VFS_MAX_FILES; i++)
vfs_files[i].flags = 0;
vfs_mount(&stdio_funcs, 0);
- // order is crucial
+ // Order of opening here may be important TODO confirm
vfs_open(" in", VFS_FILE_READ);
vfs_open(" out", VFS_FILE_WRITE);
vfs_open(" err", VFS_FILE_WRITE);
int32_t vfs_tell(int fd);
#endif // VFS_H_
+
+/**
+ * @file gpio.c
+ * Userspace library for GPIO access
+ *
+ * Copyright (C) 2018 Clyne Sullivan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
#include "gpio.h"
#include <stdint.h>
+// SVC calls get messed up by GCC's optimization...
#define NOOPTIMIZE __attribute__((optimize(0)))
NOOPTIMIZE
+/**
+ * @file gpio.h
+ * Userspace library for GPIO access
+ *
+ * Copyright (C) 2018 Clyne Sullivan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
#ifndef STMOS_GPIO_H_
#define STMOS_GPIO_H_
int gpioRead(gpio_pin_t pin);
#endif // STMOS_GPIO_H_
+
void user_main(void)
{
- //gpio(GPIO_MODE, 5, OUTPUT);
+ // Just load the init program from the initrd.
+ // (A:/ is stdio, B:/ is initrd)
execve("B:/init", 0, 0);
}