Major restructure

This commit is contained in:
Imbus 2025-09-01 22:22:35 +02:00
parent 0562c2fe5a
commit c52e19de83
25 changed files with 574 additions and 188 deletions

View file

@ -1,5 +1,5 @@
#pragma once
#include <types.h>
#include <stdint.h>
typedef struct {
volatile uint32_t v; // 0 = unlocked, 1 = locked

View file

@ -4,7 +4,7 @@
#include <panic.h>
#include <riscv.h>
#include <string.h>
#include <types.h>
#include <stdint.h>
// Physical memory allocator, for user processes,
// kernel stacks, page-table pages,

92
kern/libkern/endian.h Normal file
View file

@ -0,0 +1,92 @@
#ifndef ENDIAN_KERNEL_H
#define ENDIAN_KERNEL_H
#include <types.h>
/** Swap byte order of 16-bit value */
static inline u16 swap16(u16 x) { return (x >> 8) | (x << 8); }
/** Swap byte order of 32-bit value */
static inline u32 swap32(u32 x) {
return ((x >> 24) & 0x000000ff) | ((x >> 8) & 0x0000ff00) |
((x << 8) & 0x00ff0000) | ((x << 24) & 0xff000000);
}
/** Swap byte order of 64-bit value */
static inline u64 swap64(u64 x) {
return ((x >> 56) & 0x00000000000000ffULL) |
((x >> 40) & 0x000000000000ff00ULL) |
((x >> 24) & 0x0000000000ff0000ULL) |
((x >> 8) & 0x00000000ff000000ULL) |
((x << 8) & 0x000000ff00000000ULL) |
((x << 24) & 0x0000ff0000000000ULL) |
((x << 40) & 0x00ff000000000000ULL) |
((x << 56) & 0xff00000000000000ULL);
}
#ifdef __LITTLE_ENDIAN__
/** Convert 16-bit value to little-endian */
static inline u16 to_le16(u16 x) { return x; }
/** Convert 16-bit little-endian value to host */
static inline u16 from_le16(u16 x) { return x; }
/** Convert 32-bit value to little-endian */
static inline u32 to_le32(u32 x) { return x; }
/** Convert 32-bit little-endian value to host */
static inline u32 from_le32(u32 x) { return x; }
/** Convert 64-bit value to little-endian */
static inline u64 to_le64(u64 x) { return x; }
/** Convert 64-bit little-endian value to host */
static inline u64 from_le64(u64 x) { return x; }
/** Convert 16-bit value to big-endian */
static inline u16 to_be16(u16 x) { return swap16(x); }
/** Convert 16-bit big-endian value to host */
static inline u16 from_be16(u16 x) { return swap16(x); }
/** Convert 32-bit value to big-endian */
static inline u32 to_be32(u32 x) { return swap32(x); }
/** Convert 32-bit big-endian value to host */
static inline u32 from_be32(u32 x) { return swap32(x); }
/** Convert 64-bit value to big-endian */
static inline u64 to_be64(u64 x) { return swap64(x); }
/** Convert 64-bit big-endian value to host */
static inline u64 from_be64(u64 x) { return swap64(x); }
#else // Big-endian
/** Convert 16-bit value to little-endian */
static inline u16 to_le16(u16 x) { return swap16(x); }
/** Convert 16-bit little-endian value to host */
static inline u16 from_le16(u16 x) { return swap16(x); }
/** Convert 32-bit value to little-endian */
static inline u32 to_le32(u32 x) { return swap32(x); }
/** Convert 32-bit little-endian value to host */
static inline u32 from_le32(u32 x) { return swap32(x); }
/** Convert 64-bit value to little-endian */
static inline u64 to_le64(u64 x) { return swap64(x); }
/** Convert 64-bit little-endian value to host */
static inline u64 from_le64(u64 x) { return swap64(x); }
/** Convert 16-bit value to big-endian */
static inline u16 to_be16(u16 x) { return x; }
/** Convert 16-bit big-endian value to host */
static inline u16 from_be16(u16 x) { return x; }
/** Convert 32-bit value to big-endian */
static inline u32 to_be32(u32 x) { return x; }
/** Convert 32-bit big-endian value to host */
static inline u32 from_be32(u32 x) { return x; }
/** Convert 64-bit value to big-endian */
static inline u64 to_be64(u64 x) { return x; }
/** Convert 64-bit big-endian value to host */
static inline u64 from_be64(u64 x) { return x; }
#endif // __LITTLE_ENDIAN__
#endif // ENDIAN_KERNEL_H

29
kern/libkern/memory.c Normal file
View file

@ -0,0 +1,29 @@
#include <memory.h>
#include <string.h>
#include <uart.h>
#define MAX_PROBE_SIZE (256 * 1024 * 1024) // Probe up to 256 MiB max
#define PROBE_STEP 0x1000 // Probe every 4 KiB page
size_t probe_memory(void) {
volatile u32 *addr;
u32 test_pattern = 0xA5A5A5A5;
size_t detected = 0;
for (size_t offset = 4096 * 16; offset < MAX_PROBE_SIZE;
offset += PROBE_STEP) {
addr = (volatile u32 *)(KERNBASE + offset);
u32 old = *addr;
*addr = test_pattern;
if (*addr != test_pattern) {
break; // Memory not readable/writable here, stop probing
}
*addr = old; // restore original data
detected = offset + PROBE_STEP;
}
return detected;
}

16
kern/libkern/memory.h Normal file
View file

@ -0,0 +1,16 @@
#ifndef MEMORY_KERNEL_H
#define MEMORY_KERNEL_H
#include <stdint.h>
/* These are hardcoded for now */
#define KERNBASE 0x80000000L
#define PHYSTOP (KERNBASE + 128 * 1024 * 1024)
/**
* Returns size in bytes of detected RAM In qemu, it requires a trap handler to
* handle the interrupt when accessing unavailable memory.
*/
size_t probe_memory(void);
#endif

311
kern/libkern/mini-printf.c Normal file
View file

@ -0,0 +1,311 @@
/*
* The Minimal snprintf() implementation
*
* Copyright (c) 2013,2014 Michal Ludvig <michal@logix.cz>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the auhor nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ----
*
* This is a minimal snprintf() implementation optimised
* for embedded systems with a very limited program memory.
* mini_snprintf() doesn't support _all_ the formatting
* the glibc does but on the other hand is a lot smaller.
* Here are some numbers from my STM32 project (.bin file size):
* no snprintf(): 10768 bytes
* mini snprintf(): 11420 bytes (+ 652 bytes)
* glibc snprintf(): 34860 bytes (+24092 bytes)
* Wasting nearly 24kB of memory just for snprintf() on
* a chip with 32kB flash is crazy. Use mini_snprintf() instead.
*
*/
#include "mini-printf.h"
static int
mini_strlen(const char *s)
{
int len = 0;
while (s[len] != '\0') len++;
return len;
}
static int
mini_itoa(long value, unsigned int radix, int uppercase, int unsig,
char *buffer)
{
char *pbuffer = buffer;
int negative = 0;
int i, len;
/* No support for unusual radixes. */
if (radix > 16)
return 0;
if (value < 0 && !unsig) {
negative = 1;
value = -value;
}
/* This builds the string back to front ... */
do {
int digit = value % radix;
*(pbuffer++) = (digit < 10 ? '0' + digit : (uppercase ? 'A' : 'a') + digit - 10);
value /= radix;
} while (value > 0);
if (negative)
*(pbuffer++) = '-';
*(pbuffer) = '\0';
/* ... now we reverse it (could do it recursively but will
* conserve the stack space) */
len = (pbuffer - buffer);
for (i = 0; i < len / 2; i++) {
char j = buffer[i];
buffer[i] = buffer[len-i-1];
buffer[len-i-1] = j;
}
return len;
}
static int
mini_pad(char* ptr, int len, char pad_char, int pad_to, char *buffer)
{
int i;
int overflow = 0;
char * pbuffer = buffer;
if(pad_to == 0) pad_to = len;
if(len > pad_to) {
len = pad_to;
overflow = 1;
}
for(i = pad_to - len; i > 0; i --) {
*(pbuffer++) = pad_char;
}
for(i = len; i > 0; i --) {
*(pbuffer++) = *(ptr++);
}
len = pbuffer - buffer;
if(overflow) {
for (i = 0; i < 3 && pbuffer > buffer; i ++) {
*(pbuffer-- - 1) = '*';
}
}
return len;
}
struct mini_buff {
char *buffer, *pbuffer;
unsigned int buffer_len;
};
static int
_puts(char *s, int len, void *buf)
{
if(!buf) return len;
struct mini_buff *b = buf;
char * p0 = b->buffer;
int i;
/* Copy to buffer */
for (i = 0; i < len; i++) {
if(b->pbuffer == b->buffer + b->buffer_len - 1) {
break;
}
*(b->pbuffer ++) = s[i];
}
*(b->pbuffer) = 0;
return b->pbuffer - p0;
}
#ifdef MINI_PRINTF_ENABLE_OBJECTS
static int (*mini_handler) (void* data, void* obj, int ch, int lhint, char** bf) = 0;
static void (*mini_handler_freeor)(void* data, void*) = 0;
static void * mini_handler_data = 0;
void mini_printf_set_handler(
void* data,
int (*handler)(void* data, void* obj, int ch, int len_hint, char** buf),
void (*freeor)(void* data, void* buf))
{
mini_handler = handler;
mini_handler_freeor = freeor;
mini_handler_data = data;
}
#endif
int
mini_vsnprintf(char *buffer, unsigned int buffer_len, const char *fmt, va_list va)
{
struct mini_buff b;
b.buffer = buffer;
b.pbuffer = buffer;
b.buffer_len = buffer_len;
if(buffer_len == 0) buffer = (void*) 0;
int n = mini_vpprintf(_puts, (buffer != (void*)0)?&b:(void*)0, fmt, va);
if(buffer == (void*) 0) {
return n;
}
return b.pbuffer - b.buffer;
}
int
mini_vpprintf(int (*puts)(char* s, int len, void* buf), void* buf, const char *fmt, va_list va)
{
char bf[24];
char bf2[24];
char ch;
#ifdef MINI_PRINTF_ENABLE_OBJECTS
void* obj;
#endif
if(puts == (void*)0) {
/* run puts in counting mode. */
puts = _puts; buf = (void*)0;
}
int n = 0;
while ((ch=*(fmt++))) {
int len;
if (ch!='%') {
len = 1;
len = puts(&ch, len, buf);
} else {
char pad_char = ' ';
int pad_to = 0;
char l = 0;
char *ptr;
ch=*(fmt++);
/* Zero padding requested */
if (ch == '0') pad_char = '0';
while (ch >= '0' && ch <= '9') {
pad_to = pad_to * 10 + (ch - '0');
ch=*(fmt++);
}
if(pad_to > (signed int) sizeof(bf)) {
pad_to = sizeof(bf);
}
if (ch == 'l') {
l = 1;
ch=*(fmt++);
}
switch (ch) {
case 0:
goto end;
case 'u':
case 'd':
if(l) {
len = mini_itoa(va_arg(va, unsigned long), 10, 0, (ch=='u'), bf2);
} else {
if(ch == 'u') {
len = mini_itoa((unsigned long) va_arg(va, unsigned int), 10, 0, 1, bf2);
} else {
len = mini_itoa((long) va_arg(va, int), 10, 0, 0, bf2);
}
}
len = mini_pad(bf2, len, pad_char, pad_to, bf);
len = puts(bf, len, buf);
break;
case 'x':
case 'X':
if(l) {
len = mini_itoa(va_arg(va, unsigned long), 16, (ch=='X'), 1, bf2);
} else {
len = mini_itoa((unsigned long) va_arg(va, unsigned int), 16, (ch=='X'), 1, bf2);
}
len = mini_pad(bf2, len, pad_char, pad_to, bf);
len = puts(bf, len, buf);
break;
case 'c' :
ch = (char)(va_arg(va, int));
len = mini_pad(&ch, 1, pad_char, pad_to, bf);
len = puts(bf, len, buf);
break;
case 's' :
ptr = va_arg(va, char*);
len = mini_strlen(ptr);
if (pad_to > 0) {
len = mini_pad(ptr, len, pad_char, pad_to, bf);
len = puts(bf, len, buf);
} else {
len = puts(ptr, len, buf);
}
break;
#ifdef MINI_PRINTF_ENABLE_OBJECTS
case 'O' : /* Object by content (e.g. str) */
case 'R' : /* Object by representation (e.g. repr)*/
obj = va_arg(va, void*);
len = mini_handler(mini_handler_data, obj, ch, pad_to, &ptr);
if (pad_to > 0) {
len = mini_pad(ptr, len, pad_char, pad_to, bf);
len = puts(bf, len, buf);
} else {
len = puts(ptr, len, buf);
}
mini_handler_freeor(mini_handler_data, ptr);
break;
#endif
default:
len = 1;
len = puts(&ch, len, buf);
break;
}
}
n = n + len;
}
end:
return n;
}
int
mini_snprintf(char* buffer, unsigned int buffer_len, const char *fmt, ...)
{
int ret;
va_list va;
va_start(va, fmt);
ret = mini_vsnprintf(buffer, buffer_len, fmt, va);
va_end(va);
return ret;
}
int
mini_pprintf(int (*puts)(char*s, int len, void* buf), void* buf, const char *fmt, ...)
{
int ret;
va_list va;
va_start(va, fmt);
ret = mini_vpprintf(puts, buf, fmt, va);
va_end(va);
return ret;
}

View file

@ -0,0 +1,73 @@
/*
* The Minimal snprintf() implementation
*
* Copyright (c) 2013 Michal Ludvig <michal@logix.cz>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the auhor nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __MINI_PRINTF__
#define __MINI_PRINTF__
#ifdef __cplusplus
extern "C" {
#endif
#include <stdarg.h>
#ifdef MINI_PRINTF_ENABLE_OBJECTS
/* If enabled, callback for object types (O and R).
* void* arguments matching %O and %R are sent to handler as obj.
* the result string created by handler at *buf is freed by freeor.
* */
void mini_printf_set_handler(
void * data,
/* handler returns number of chars in *buf; *buf is not NUL-terminated. */
int (*handler)(void* data, void* obj, int ch, int len_hint, char** buf),
void (*freeor)(void* data, void* buf));
#endif
/* String IO interface; returns number of bytes written, not including the ending NUL.
* Always appends a NUL at the end, therefore buffer_len shall be at least 1 in normal operation.
* If buffer is NULL or buffer_len is 0, returns number of bytes to be written, not including the ending NUL.
*/
int mini_vsnprintf(char* buffer, unsigned int buffer_len, const char *fmt, va_list va);
int mini_snprintf(char* buffer, unsigned int buffer_len, const char *fmt, ...);
/* Stream IO interface; returns number of bytes written.
* If puts is NULL, number of bytes to be written.
* puts shall return number of bytes written.
*/
int mini_vpprintf(int (*puts)(char* s, int len, void* buf), void* buf, const char *fmt, va_list va);
int mini_pprintf(int (*puts)(char*s, int len, void* buf), void* buf, const char *fmt, ...);
#ifdef __cplusplus
}
#endif
#define vsnprintf mini_vsnprintf
#define snprintf mini_snprintf
#endif

8
kern/libkern/panic.c Normal file
View file

@ -0,0 +1,8 @@
#include <uart.h>
volatile int panicked;
void panic(char *s) {
panicked = 1;
uart_puts(s);
while (1);
}

6
kern/libkern/panic.h Normal file
View file

@ -0,0 +1,6 @@
#ifndef KERNEL_PANIC_H
#define KERNEL_PANIC_H
void panic(char *s);
#endif

21
kern/libkern/proc.c Normal file
View file

@ -0,0 +1,21 @@
#include <proc.h>
struct Cpu cpus[NCPU];
/**
* Must be called with interrupts disabled, to prevent race with process being
* moved to a different CPU.
*/
int cpuid() {
int id = read_tp();
return id;
}
/**
* Return this CPU's cpu struct. Interrupts must be disabled.
*/
struct Cpu *mycpu(void) {
int id = cpuid();
struct Cpu *c = &cpus[id];
return c;
}

74
kern/libkern/riscv.h Normal file
View file

@ -0,0 +1,74 @@
#ifndef RISCV_KERNEL_H
#define RISCV_KERNEL_H
#include <stdint.h>
/** Page Size */
#define PGSIZE 4096 // bytes per page
// /** Page Shift, bits of offset within a page */
#define PGSHIFT 12
#define PGROUNDUP(sz) (((sz) + PGSIZE - 1) & ~(PGSIZE - 1))
#define PGROUNDDOWN(a) (((a)) & ~(PGSIZE - 1))
// Supervisor Status Register, sstatus
#define SSTATUS_SPP (1L << 8) /** Supervisor Previous Privilege 1=S, 0=U */
#define SSTATUS_SPIE (1L << 5) /** Supervisor Previous Interrupt Enable */
#define SSTATUS_UPIE (1L << 4) /** User Previous Interrupt Enable */
#define SSTATUS_SIE (1L << 1) /** Supervisor Interrupt Enable */
#define SSTATUS_UIE (1L << 0) /** User Interrupt Enable */
/** Page Table Entry Type */
typedef u64 pte_t;
/** Page Table Type */
typedef u64 *pagetable_t; // 512 PTEs
/** Returns the current hart id */
static inline u64 read_mhartid() {
u64 x;
asm volatile("csrr %0, mhartid" : "=r"(x));
return x;
}
/** Read thread pointer */
static inline u64 read_tp() {
u64 x;
asm volatile("mv %0, tp" : "=r"(x));
return x;
}
/** Write thread pointer */
static inline void write_tp(u64 x) { asm volatile("mv tp, %0" : : "r"(x)); }
/**
* Read the value of the sstatus register.
* (Supervisor Status Register)
*/
static inline u64 r_sstatus() {
u64 x;
asm volatile("csrr %0, sstatus" : "=r"(x));
return x;
}
/**
* Write a value to the sstatus register.
* (Supervisor Status Register)
*/
static inline void w_sstatus(u64 x) {
asm volatile("csrw sstatus, %0" : : "r"(x));
}
/** Enable device interrupts */
static inline void intr_on() { w_sstatus(r_sstatus() | SSTATUS_SIE); }
/** Disable device interrupts */
static inline void intr_off() { w_sstatus(r_sstatus() & ~SSTATUS_SIE); }
/** Are device interrupts enabled? */
static inline int intr_get() {
u64 x = r_sstatus();
return (x & SSTATUS_SIE) != 0;
}
#endif

124
kern/libkern/spinlock.c Normal file
View file

@ -0,0 +1,124 @@
/**
* Mutual exclusion spin locks.
* (Not mutexes as these are spinning locks).
*/
// #include <lib/stdio.h>
#include "string.h"
#include <panic.h>
#include <proc.h>
#include <riscv.h>
#include <spinlock.h>
#include <uart.h>
/**
* The aquire() and release() functions control ownership of the lock.
* To perform these operations, modern CPU's provide atomic instructions
* that prevent the cores from stepping on each other's toes, otherwise known
* as a deadlock.
*
* GCC provides a set of built-in functions that allow you to use atomic
* instructions in an architecture-independent way. These functions are
* defined in the GCC manual:
*
* See: https://gcc.gnu.org/onlinedocs/gcc/_005f_005fsync-Builtins.html
* See: https://en.wikipedia.org/wiki/Memory_barrier
*
* On RISC-V, sync_lock_test_and_set turns into an atomic swap:
* a5 = 1
* s1 = &lk->locked
* amoswap.w.aq a5, a5, (s1)
*
* On RISC-V, sync_lock_release turns into an atomic swap:
* s1 = &lk->locked
* amoswap.w zero, zero, (s1)
*
* __sync_synchronize();
*
* This function tells the C compiler and the processor to not move loads or
* stores past this point, to ensure that the critical section's memory
* references happen strictly after the lock is acquired/locked.
* On RISC-V, this emits a fence instruction.
*/
/** Initialize Spinlock */
void initlock(struct Spinlock *lk, char *name) {
lk->name = name;
lk->locked = 0;
lk->cpu = 0;
}
/**
* Acquire the lock.
* Loops (spins) until the lock is acquired.
* Panics if the lock is already held by this cpu.
*/
void acquire(struct Spinlock *lk) {
push_off(); // disable interrupts to avoid deadlock.
if (holding(lk)) // If the lock is already held, panic.
panic("acquire");
// Spin until aquired. See file header for details
while (__sync_lock_test_and_set(&lk->locked, 1) != 0);
__sync_synchronize(); // No loads/stores after this point
// Record info about lock acquisition for holding() and debugging.
lk->cpu = mycpu();
}
/**
* Release the lock.
* Panics if the lock is not held.
*/
void release(struct Spinlock *lk) {
if (!holding(lk)) // If the lock is not held, panic.
panic("release");
lk->cpu = 0; // 0 means unheld
__sync_synchronize(); // No loads/stores after this point
__sync_lock_release(&lk->locked); // Essentially lk->locked = 0
pop_off();
}
// Check whether this cpu is holding the lock.
// Interrupts must be off.
int holding(struct Spinlock *lk) {
int r;
r = (lk->locked && lk->cpu == mycpu());
return r;
}
// push_off/pop_off are like intr_off()/intr_on() except that they are matched:
// it takes two pop_off()s to undo two push_off()s. Also, if interrupts
// are initially off, then push_off, pop_off leaves them off.
void push_off(void) {
int old = intr_get();
intr_off();
if (mycpu()->noff == 0)
mycpu()->intena = old;
mycpu()->noff += 1;
}
void pop_off(void) {
struct Cpu *c = mycpu();
if (intr_get())
panic("pop_off - interruptible");
if (c->noff < 1) {
{
// TODO: Remove this block when fixed
char amt[100];
itoa(c->noff, amt, 10);
uart_puts(amt);
}
panic("pop_off");
}
c->noff -= 1;
if (c->noff == 0 && c->intena)
intr_on();
}

51
kern/libkern/spinlock.h Normal file
View file

@ -0,0 +1,51 @@
#ifndef KERNEL_Spinlock_H
#define KERNEL_Spinlock_H
#include <stdint.h>
/** Mutual exclusion spin lock */
struct Spinlock {
u32 locked; // Is the lock held?
// NOTE: Perhaps feature gate this?
// For debugging:
char *name; // Name of lock.
struct Cpu *cpu; // The cpu holding the lock.
};
/**
* Acquire the lock.
* Loops (spins) until the lock is acquired.
* Panics if the lock is already held by this cpu.
*/
void acquire(struct Spinlock *);
/**
* Check whether this cpu is holding the lock.
* Interrupts must be off.
*/
int holding(struct Spinlock *);
/**
* Initialize Spinlock
*/
void initlock(struct Spinlock *, char *);
/**
* Release the lock.
* Panics if the lock is not held.
*/
void release(struct Spinlock *);
/**
* @brief push_off/pop_off are like intr_off()/intr_on() except that they are
* matched: it takes two pop_off()s to undo two push_off()s. Also, if
* interrupts are initially off, then push_off, pop_off leaves them off.
*/
void push_off(void);
/** @copydoc pop_off */
void pop_off(void);
#endif

11
kern/libkern/stdarg.h Normal file
View file

@ -0,0 +1,11 @@
#ifndef _STDARG_H
#define _STDARG_H
typedef __builtin_va_list va_list;
#define va_start(ap, last) __builtin_va_start(ap, last)
#define va_arg(ap, type) __builtin_va_arg(ap, type)
#define va_end(ap) __builtin_va_end(ap)
#define va_copy(dest, src) __builtin_va_copy(dest, src)
#endif

16
kern/libkern/stdint.h Normal file
View file

@ -0,0 +1,16 @@
#pragma once
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
typedef unsigned long u64;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long uint64_t;
typedef uint64_t size_t;
typedef uint64_t uintptr_t;
// typedef u8 bool;

View file

@ -114,14 +114,112 @@ void *memset(void *dest, int c, size_t n) {
return dest;
}
int memcmp(const void *s1, const void *s2, size_t n) {
if (n != 0) {
const unsigned char *p1 = s1, *p2 = s2;
// int memcmp(const void *s1, const void *s2, size_t n) {
// if (n != 0) {
// const unsigned char *p1 = s1, *p2 = s2;
//
// do {
// if (*p1++ != *p2++)
// return (*--p1 - *--p2);
// } while (--n != 0);
// }
// return (0);
// }
do {
if (*p1++ != *p2++)
return (*--p1 - *--p2);
} while (--n != 0);
char *itoa(int value, char *str, int base) {
char *p = str;
char *p1, *p2;
unsigned int uvalue = value;
int negative = 0;
if (base < 2 || base > 36) {
*str = '\0';
return str;
}
return (0);
if (value < 0 && base == 10) {
negative = 1;
uvalue = -value;
}
// Convert to string
do {
int digit = uvalue % base;
*p++ = (digit < 10) ? '0' + digit : 'a' + (digit - 10);
uvalue /= base;
} while (uvalue);
if (negative)
*p++ = '-';
*p = '\0';
// Reverse string
p1 = str;
p2 = p - 1;
while (p1 < p2) {
char tmp = *p1;
*p1++ = *p2;
*p2-- = tmp;
}
return str;
}
// void *memset(void *dst, int c, size_t length) {
// u8 *ptr = (u8 *)dst;
// const u8 value = (u8)c;
//
// while (length--) *(ptr++) = value;
//
// return dst;
// }
// void *memcpy(void *dst, const void *src, size_t len) {
// u8 *d = (u8 *)dst;
// const u8 *s = (const u8 *)src;
// for (size_t i = 0; i < len; i++) {
// d[i] = s[i];
// }
// return dst;
// }
// void *memmove(void *dst, const void *src, size_t len) {
// u8 *d = (u8 *)dst;
// const u8 *s = (const u8 *)src;
// if (d < s) {
// for (size_t i = 0; i < len; i++) {
// d[i] = s[i];
// }
// } else if (d > s) {
// for (size_t i = len; i > 0; i--) {
// d[i - 1] = s[i - 1];
// }
// }
// return dst;
// }
int memcmp(const void *s1, const void *s2, size_t len) {
const u8 *a = (const u8 *)s1;
const u8 *b = (const u8 *)s2;
for (size_t i = 0; i < len; i++) {
if (a[i] != b[i]) {
return (int)a[i] - (int)b[i];
}
}
return 0;
}
size_t strlen(const char *s) {
const char *p = s;
while (*p) ++p;
return (size_t)(p - s);
}
size_t strnlen(const char *s, size_t maxlen) {
size_t len = 0;
while (len < maxlen && s[len] != '\0') {
len++;
}
return len;
}

View file

@ -1,7 +1,45 @@
#pragma once
#include <types.h>
#ifndef KERNEL_STRING_H
#define KERNEL_STRING_H
void *memcpy(void *s1, const void *s2, size_t n);
void *memmove(void *s1, const void *s2, size_t n);
void *memset(void *dest, int c, size_t n);
int memcmp(const void *s1, const void *s2, size_t n);
#include <stdint.h>
// void *memcpy(void *s1, const void *s2, size_t n);
// void *memmove(void *s1, const void *s2, size_t n);
// void *memset(void *dest, int c, size_t n);
// int memcmp(const void *s1, const void *s2, size_t n);
/** Integer to ascii */
char *itoa(int value, char *str, int base);
/** Fill memory with constant byte */
void *memset(void *dst, int c, size_t len);
/** Copy `len` bytes from `src` to `dst`. Undefined if regions overlap. */
void *memcpy(void *dst, const void *src, size_t len);
/** Copy `len` bytes from `src` to `dst`, safe for overlapping regions. */
void *memmove(void *dst, const void *src, size_t len);
/** Compare `len` bytes of `s1` and `s2`.
* Returns 0 if equal, <0 if s1 < s2, >0 if s1 > s2. */
int memcmp(const void *s1, const void *s2, size_t len);
/** Returns the length of a null-terminated string */
size_t strlen(const char *s);
/** Return length of string `s`, up to a max of `maxlen` bytes */
size_t strnlen(const char *s, size_t maxlen);
// TODO: These:
/*
int strcmp(const char *s1, const char *s2);
int strncmp(const char *s1, const char *s2, size_t n);
char *strcpy(char *dst, const char *src);
char *strncpy(char *dst, const char *src, size_t n);
char *strchr(const char *s, int c);
char *strrchr(const char *s, int c);
*/
#endif

8
kern/libkern/uart.c Normal file
View file

@ -0,0 +1,8 @@
/* QEMU memory maps a UART device here. */
#define UART_BASE ((volatile char *)0x10000000)
void uart_putc(char c) { *UART_BASE = c; }
void uart_puts(const char *s) {
while (*s) uart_putc(*s++);
}

10
kern/libkern/uart.h Normal file
View file

@ -0,0 +1,10 @@
#ifndef UART_KERNEL_H
#define UART_KERNEL_H
/** Send a single character to the UART device */
void uart_putc(char c);
/** Send a **NULL TERMINATED** string to the UART device */
void uart_puts(const char *s);
#endif

View file

@ -1,3 +1,6 @@
#include <config.h>
#include <spinlock.h>
#include <riscv.h>
#include <stdint.h>
typedef enum {
@ -37,6 +40,7 @@ struct Cpu {
int intena; // Were interrupts enabled before push_off()?
};
/** Saved registers for kernel context switches. */
typedef struct {
/* 0 */ uint64_t kernel_satp; // kernel page table
/* 8 */ uint64_t kernel_sp; // top of process's kernel stack
@ -75,3 +79,10 @@ typedef struct {
/* 272 */ uint64_t t5;
/* 280 */ uint64_t t6;
} TrapFrame_t;
struct Cpu *mycpu(void);
extern struct Cpu cpus[NCPU];
/** Per-process state */
struct Proc {};