mbv: move a few things around

This commit is contained in:
2025-09-04 15:01:50 +02:00
parent dd51b5d610
commit 9edebe637b
58 changed files with 68 additions and 494 deletions

View File

@@ -1,164 +0,0 @@
#include "async.h"
#include <array>
#include <atomic>
#include <chrono>
#include <utility>
#include "lock.h"
#include "trace.h"
namespace async {
namespace {
using namespace std::literals::chrono_literals;
struct Stuff {
std::coroutine_handle<> h;
std::chrono::system_clock::time_point expiration;
Stuff* next;
};
struct Notification {
bool pending; // can only be true if stuff is nullptr
Stuff* stuff;
};
std::atomic<Stuff*> work = nullptr;
std::array<Notification, static_cast<size_t>(AwaitableType::kNumTypes)>
notifications = {};
} // namespace
void schedule(std::coroutine_handle<> h, int ms) {
InterruptLock lock;
TRACE(tracing::TraceEvent::kAsyncSchedule);
std::chrono::system_clock::time_point exp =
std::chrono::system_clock::now() + std::chrono::milliseconds(ms);
Stuff* news = new Stuff{
.h = h,
.expiration = exp,
};
Stuff* stuff = work;
if (!stuff || stuff->expiration > exp) {
news->next = stuff;
work = news;
return;
}
Stuff* s = stuff;
while (s->next && s->next->expiration <= exp) {
s = s->next;
}
news->next = s->next;
s->next = news;
}
void step() {
Stuff* stuff;
// ensure all previous side effects are visible
{
InterruptLock lock;
stuff = work;
};
if (stuff == nullptr) {
return;
}
auto now = std::chrono::system_clock::now();
auto dt = stuff->expiration - now;
if (dt > 0ms) {
return;
}
int stuffinqueue = 0;
for (Stuff* s = stuff; s; s = s->next) stuffinqueue++;
TRACE(tracing::TraceEvent::kAsyncTask);
stuff->h();
TRACE(tracing::TraceEvent::kAsyncTaskDone);
{
InterruptLock lock;
work = stuff->next;
}
delete stuff;
}
void reset() {
Stuff* stuff = work;
while (stuff) {
Stuff* byebye = stuff;
stuff = stuff->next;
delete byebye;
}
work = nullptr;
}
void main_loop(bool (*idle_function)()) {
while (1) {
if (idle_function != nullptr) {
if (idle_function()) {
reset();
break;
};
}
step();
}
}
void enqueue(std::coroutine_handle<> h, AwaitableType type) {
auto ttype = static_cast<size_t>(type);
{
InterruptLock lock;
TRACE(tracing::TraceEvent::kAsyncEnqueue);
const bool was_notified =
std::exchange(notifications[ttype].pending, false);
if (was_notified) {
TRACE(tracing::TraceEvent::kAsyncAwaitWasNotified);
schedule(h);
return;
}
Stuff* item = new Stuff{.h = h};
Stuff* stuff = notifications[ttype].stuff;
if (stuff == nullptr) {
notifications[ttype].stuff = item;
return;
}
while (stuff->next != nullptr) {
stuff = stuff->next;
}
stuff->next = item;
}
}
void resume(AwaitableType type) {
auto ttype = static_cast<size_t>(type);
Stuff* stuff = nullptr;
{
InterruptLock lock;
stuff = notifications[ttype].stuff;
if (stuff == nullptr) {
notifications[ttype].pending = true;
return;
}
notifications[ttype].stuff = stuff->next;
schedule(stuff->h);
}
delete stuff;
}
} // namespace async

View File

@@ -1,197 +0,0 @@
#pragma once
#include <chrono>
#include <coroutine>
#include <utility>
#include "trace.h"
namespace async {
struct continuation : std::suspend_always {
void await_suspend(std::coroutine_handle<>) noexcept {
if (parent) {
parent.resume();
}
}
std::coroutine_handle<> parent;
};
template <typename T = void>
struct task;
template <>
struct task<void> {
struct promise_type;
using handle_type = std::coroutine_handle<promise_type>;
~task() {
if (h) {
h.destroy();
}
}
struct promise_type {
task get_return_object() {
return {.h = handle_type::from_promise(*this)};
}
std::suspend_always initial_suspend() noexcept { return {}; }
continuation final_suspend() noexcept { return {.parent = parent}; }
void return_void() {}
void unhandled_exception() {}
std::coroutine_handle<> parent;
};
// awaitable
bool await_ready() {
h.promise().parent = {};
h.resume();
if (h.done()) {
return true;
}
return false;
}
void await_suspend(std::coroutine_handle<> ha) { h.promise().parent = ha; }
void await_resume() {}
handle_type h;
};
template <typename T>
struct task {
struct promise_type;
using handle_type = std::coroutine_handle<promise_type>;
~task() {
if (h) {
h.destroy();
}
}
struct promise_type {
task get_return_object() {
return {.h = handle_type::from_promise(*this)};
}
std::suspend_always initial_suspend() noexcept { return {}; }
continuation final_suspend() noexcept { return {.parent = parent}; }
void return_value(T&& value) { ret_value = std::move(value); }
void unhandled_exception() {}
template <std::convertible_to<T> From>
continuation yield_value(From&& value) {
ret_value = std::forward<From>(value);
result_ready = true;
return {.parent = parent};
}
T ret_value;
bool result_ready = false;
std::coroutine_handle<> parent;
};
// awaitable
bool await_ready() {
h.promise().parent = {};
h.resume();
if (h.promise().result_ready || h.done()) {
return true;
}
return false;
}
void await_suspend(std::coroutine_handle<> ha) { h.promise().parent = ha; }
T await_resume() {
h.promise().result_ready = false;
return std::move(h.promise().ret_value);
}
std::coroutine_handle<promise_type> h;
};
enum class AwaitableType {
kUnknown = 0,
kUartRx = 1,
kUartTx = 2,
kNumTypes
};
void schedule(std::coroutine_handle<> h, int ms = 0);
void enqueue(std::coroutine_handle<> h, AwaitableType type);
void resume(AwaitableType type); // typically called from an ISR
void main_loop(bool (*idle_function)());
void step();
inline auto await(AwaitableType type) {
struct awaitable {
AwaitableType type;
bool await_ready() { return false; };
void await_suspend(std::coroutine_handle<> h) { enqueue(h, type); }
void await_resume() {}
};
return awaitable{type};
}
inline auto delay(int ms) {
struct awaitable {
int ms;
bool await_ready() { return false; };
void await_suspend(std::coroutine_handle<> h) { schedule(h, ms); }
void await_resume() {}
};
return awaitable{ms};
}
template <typename T>
struct gimme {
// child interface
bool await_ready() { return false; }
void await_suspend(std::coroutine_handle<> h) {
ha = h;
waiting = true;
TRACE(tracing::TraceEvent::kAsyncGimmeWaiting);
if (parent) {
schedule(parent);
}
}
T await_resume() {
waiting = false;
TRACE(tracing::TraceEvent::kAsyncGimmeResume);
return std::move(stuff);
}
// parent interface
auto feed(T&& s) {
struct awaitable {
bool await_ready() {
g.parent = {};
g.ha.resume();
return g.waiting;
}
void await_suspend(std::coroutine_handle<> h) { g.parent = h; }
void await_resume() {}
gimme<T>& g;
};
if (!waiting) {
__builtin_trap();
}
if (!ha) {
__builtin_trap();
}
stuff = std::move(s);
return awaitable{.g = *this};
}
bool waiting = false;
std::coroutine_handle<> ha;
std::coroutine_handle<> parent;
T stuff;
};
} // namespace async

View File

@@ -1,30 +0,0 @@
#pragma once
#include <span>
#include <utility>
struct buffer {
std::span<std::byte> data;
buffer() = default;
buffer(std::span<std::byte> d) : data(d) {}
static buffer make(size_t size) {
return buffer({new std::byte[size], size});
}
buffer(buffer& other) = delete;
buffer& operator=(buffer& other) = delete;
buffer(buffer&& other) : data(std::exchange(other.data, {})) {}
buffer& operator=(buffer&& other) {
data = std::exchange(other.data, {});
return *this;
}
~buffer() {
if (data.data()) {
delete[] data.data();
};
}
};

View File

@@ -1,27 +0,0 @@
#pragma once
#include <cstdint>
struct Gpio {
volatile uint32_t data;
};
#define gpio0 ((Gpio*)0x40000000)
inline void ToggleLed(int which) {
uint8_t data = gpio0->data;
data ^= (0x1 << which);
gpio0->data = data;
}
inline void SetLed(int which) {
uint8_t data = gpio0->data;
data |= (0x1 << which);
gpio0->data = data;
}
inline void ClearLed(int which) {
uint8_t data = gpio0->data;
data &= ~(0x1 << which);
gpio0->data = data;
}

View File

@@ -1,13 +0,0 @@
#pragma once
// out must be at least 8 bytes long
inline void itoa(int val, char* out) {
for (int i = 0; i < 8; i++) {
uint8_t digit = (val >> (28 - 4 * i)) & 0xf;
if (digit < 0xa) {
out[i] = '0' + digit;
} else {
out[i] = 'a' + digit - 0xa;
}
}
}

View File

@@ -1,5 +0,0 @@
#include "lock.h"
#ifdef __x86_64__
std::recursive_mutex InterruptLock::m;
#endif

View File

@@ -1,21 +0,0 @@
#pragma once
#ifndef __x86_64__
#include "interrupts.h"
struct InterruptLock {
bool was_on;
InterruptLock() : was_on(EnableInterrupts(false)) {}
~InterruptLock() { EnableInterrupts(was_on); }
};
#else // __x86_64__
#include <mutex>
struct InterruptLock {
static std::recursive_mutex m;
InterruptLock() { m.lock(); }
~InterruptLock() { m.unlock(); }
};
#endif // __x86_64__

View File

@@ -1,11 +1,11 @@
#include "async.h"
#include "buffer.h"
#include "gpio.h"
#include "intc.h"
#include "interrupts.h"
#include "pol0.h"
#include "timer.h"
#include "trace.h"
#include "hal/gpio.h"
#include "hal/intc.h"
#include "hal/interrupts.h"
#include "hal/pol0.h"
#include "hal/timer.h"
#include "lib/async.h"
#include "lib/buffer.h"
#include "uart.h"
#include "uart_async.h"
@@ -21,6 +21,26 @@ Timer* timer0;
volatile uint32_t t1overflowsecs = 0;
volatile uint32_t t1overflowusecs = 0;
Gpio* gpio0;
void ToggleLed(int which) {
uint8_t data = gpio0->data;
data ^= (0x1 << which);
gpio0->data = data;
}
void SetLed(int which) {
uint8_t data = gpio0->data;
data |= (0x1 << which);
gpio0->data = data;
}
void ClearLed(int which) {
uint8_t data = gpio0->data;
data &= ~(0x1 << which);
gpio0->data = data;
}
void Uart0Isr() { HandleUartIsr(); }
void Timer0Isr() {
@@ -85,12 +105,14 @@ async::task<> blink() {
} // namespace
int main() {
gpio0 = Gpio::Instance(GPIO0_BASE);
gpio0->data = 0;
SetupUart();
UartWriteBlocking("uart setup done\r\n");
SetupTimer();
UartWriteBlocking("timer setup done\r\n");
gpio0->data = 0;
SetupInterrupts();
auto e = echo();
@@ -112,8 +134,7 @@ int main() {
#include <cstdint>
#include "itoa.h"
#include "lock.h"
#include "lib/lock.h"
extern unsigned char _heap_begin, _heap_end;

View File

@@ -1,108 +0,0 @@
#include "buffer.h"
#include "gpio.h"
#include "intc.h"
#include "interrupts.h"
#include "pol0.h"
#include "timer.h"
#include "trace.h"
#include "uart2.h"
namespace {
Timer* timer0;
void Uart0Isr() {
// ToggleLed(7);
HandleUartIsr();
}
void Timer0Isr() {
SetLed(6);
__builtin_trap();
}
void SetupUart() {
InitUarts();
intc::SetIsr(UART0_IRQN, Uart0Isr);
intc::SetIrqEnabled(UART0_IRQN, true);
}
void SetupTimer() {
timer0 = Timer::Instance(TIMER0_BASE);
// timer0->SetupAsWdt(100'000 * 1000);
timer0->EnableT1();
intc::SetIsr(TIMER0_IRQN, Timer0Isr);
intc::SetIrqEnabled(TIMER0_IRQN, true);
}
void SetupInterrupts() {
intc::EnableInterrupts();
SetExternalInterruptHandler(intc::InterruptHandler);
EnableExternalInterrupts();
EnableInterrupts(true);
}
} // namespace
int main() {
SetupUart();
UartWriteCrash("uart setup done\r\n");
SetupTimer();
UartWriteCrash("timer setup done\r\n");
SetupInterrupts();
UartWriteCrash("init done. starting main loop\r\n");
UartEcho();
// should never get here
}
/// stdlib stuff
#include <sys/time.h>
#include <cstdint>
#include "itoa.h"
#include "lock.h"
extern unsigned char _heap_begin, _heap_end;
extern "C" void* _sbrk(int increment) {
static unsigned char* heap = &_heap_begin;
unsigned char* prev_heap = heap;
if (heap + increment >= &_heap_end) {
UartWriteCrash("Heap overflow!\r\n");
return reinterpret_cast<void*>(-1);
}
heap += increment;
return prev_heap;
}
extern "C" int _gettimeofday(struct timeval* tv, void* tzvp) {
(void)tzvp;
uint32_t ticks = timer0->GetT1Ticks();
tv->tv_sec = ticks / 100000000;
tv->tv_usec = (ticks % 100000000) / 100;
return 0;
}
extern "C" uint8_t __atomic_exchange_1(volatile void* ptr, uint8_t val,
int memorder) {
(void)memorder;
auto* dest = reinterpret_cast<volatile uint8_t*>(ptr);
bool ret;
{
InterruptLock lock;
ret = *dest;
*dest = val;
}
return ret;
}

View File

@@ -1,105 +0,0 @@
#pragma once
#include <span>
#include "lock.h"
struct RingBuffer {
std::span<std::byte> buffer;
size_t read_ptr = 0;
size_t write_ptr = 0;
size_t used = 0;
bool Store(std::span<const std::byte> data) {
InterruptLock lock;
if (data.size() > FreeSpace()) {
return false;
}
const size_t to_copy = std::min(buffer.size() - write_ptr, data.size());
std::copy(data.begin(), data.begin() + to_copy,
buffer.begin() + write_ptr);
if (to_copy < data.size()) {
std::copy(data.begin() + to_copy, data.end(), buffer.begin());
}
Push(data.size());
return true;
}
bool Load(std::span<std::byte> out) {
InterruptLock lock;
if (out.size() > AvailableData()) {
return false;
}
const size_t to_copy = std::min(buffer.size() - read_ptr, out.size());
std::copy(buffer.begin() + read_ptr,
buffer.begin() + read_ptr + to_copy, out.begin());
if (to_copy < out.size()) {
std::copy(buffer.begin(), buffer.begin() + out.size() - to_copy,
out.begin() + to_copy);
}
Pop(out.size());
return true;
}
bool Push(size_t amount) {
InterruptLock lock;
if (amount > FreeSpace()) {
return false;
}
write_ptr = (write_ptr + amount) % buffer.size();
used = used + amount;
return true;
}
bool Pop(size_t amount) {
InterruptLock lock;
if (amount > AvailableData()) {
return false;
}
read_ptr = (read_ptr + amount) % buffer.size();
used = used - amount;
return true;
}
size_t FreeSpace() const {
InterruptLock lock;
return buffer.size() - used;
}
size_t AvailableData() const {
InterruptLock lock;
return used;
}
uint8_t* RawReadPointer() const {
InterruptLock lock;
return reinterpret_cast<uint8_t*>(buffer.data() + read_ptr);
}
uint8_t* RawWritePointer() const {
InterruptLock lock;
return reinterpret_cast<uint8_t*>(buffer.data() + write_ptr);
}
size_t ContiguousFreeSpace() const {
InterruptLock lock;
return std::min(FreeSpace(), buffer.size() - write_ptr);
}
size_t ContiguousAvailableData() const {
InterruptLock lock;
return std::min(AvailableData(), buffer.size() - read_ptr);
}
};

View File

@@ -1,71 +0,0 @@
#include "trace.h"
#include <algorithm>
#include <chrono>
#include "itoa.h"
#include "lock.h"
#include "uart.h"
namespace tracing {
namespace {
struct Event {
uint32_t timestamp;
TraceEvent event;
};
constexpr size_t kTraceBufferSize = 256;
std::array<Event, kTraceBufferSize> buffer;
size_t write_ptr = 0;
size_t size = 0;
} // namespace
void trace(int raw_event) { trace(static_cast<TraceEvent>(raw_event)); }
void trace(TraceEvent event) {
const std::chrono::system_clock::time_point now =
std::chrono::system_clock::now();
const uint32_t uptime_ticks = now.time_since_epoch().count();
{
InterruptLock lock;
buffer[write_ptr] = {.timestamp = uptime_ticks, .event = event};
write_ptr = (write_ptr + 1) % buffer.size();
size = std::min(size + 1, kTraceBufferSize);
#if TRACE_DUMP_WHEN_FULL
if (size == kTraceBufferSize) {
dump();
}
#endif // TRACE_DUMP_WHEN_FULL
}
}
void dump() {
InterruptLock lock;
if (size == kTraceBufferSize) {
std::rotate(buffer.begin(), buffer.begin() + write_ptr, buffer.end());
}
char number[] = "00000000";
UartWriteCrash("----\r\n");
for (Event event : std::span{buffer}.subspan(0, size)) {
itoa(static_cast<int>(event.timestamp), number);
UartWriteCrash(number);
UartWriteCrash(" ");
itoa(static_cast<int>(event.event), number);
UartWriteCrash(number);
UartWriteCrash("\r\n");
}
UartWriteCrash("----\r\n");
size = 0;
write_ptr = 0;
}
} // namespace tracing

View File

@@ -1,51 +0,0 @@
#pragma once
#define TRACE_DUMP_WHEN_FULL 0
#ifdef __x86_64__
#include <cstdio>
#define TRACE(x) printf(#x "\n")
#else // __x86_64__
#define TRACE(...) tracing::trace(__VA_ARGS__)
#endif // __x86_64__
#include <cstdint>
namespace tracing {
enum class TraceEvent : uint8_t {
kUnknown = 0,
kUartIsr = 1,
kUartRxCb = 2,
kUartTxCb = 3,
kUartSend = 10,
kUartRecv = 11,
kUartTxBufferFull = 12,
kUartTxBufferNotFull = 13,
kUartWriteDone = 20,
kAsyncResume = 4,
kAsyncEnqueue = 5,
kAsyncTask = 6,
kAsyncResumeSetPending = 7,
kAsyncAwaitWasNotified = 8,
kAsyncSchedule = 9,
kAsyncTaskDone = 14,
kAsyncException = 15,
kAsyncCallParent = 16,
kAsyncCallParentDone = 17,
kAsyncCoAwait = 18,
kAsyncSuspend = 19,
kAsyncDestroy = 21,
kAsyncGimmeWaiting = 22,
kAsyncGimmeResume = 23,
};
void trace(TraceEvent event);
void trace(int raw_event);
void dump();
} // namespace tracing

View File

@@ -1,14 +1,14 @@
#include "uart.h"
#include "async.h"
#include "gpio.h"
#include "lock.h"
#include "pol0.h"
#include "ring_buffer.h"
#include "trace.h"
#include "uart_async.h"
#include "hal/gpio.h"
#include "hal/pol0.h"
#include "lib/async.h"
#include "lib/lock.h"
#include "lib/ring_buffer.h"
#include "xuartlite.h"
#include "uart_async.h"
namespace {
using async::AwaitableType;

View File

@@ -1,122 +0,0 @@
#include "uart2.h"
#include "gpio.h"
#include "lock.h"
#include "pol0.h"
#include "ring_buffer.h"
#include "xuartlite.h"
namespace {
constexpr uintptr_t kUart0BaseAddress = UART0_BASE;
XUartLite uart0_inst;
XUartLite_Config uart0_config = {
.DeviceId = 0,
.RegBaseAddr = kUart0BaseAddress,
.BaudRate = 115200,
.UseParity = false,
.DataBits = 8,
};
constexpr size_t kUartRxBufferSize = 256;
std::array<std::byte, kUartRxBufferSize> rx_buffer = {};
RingBuffer rx_ring_buffer{.buffer = rx_buffer};
constexpr size_t kUartTxBufferSize = 256;
std::array<std::byte, kUartTxBufferSize> tx_buffer = {};
RingBuffer tx_ring_buffer{.buffer = tx_buffer};
XUartLite* uart0 = &uart0_inst;
volatile int sending = 0;
void StartReceiving() {
while (1) {
if (rx_ring_buffer.FreeSpace() < 1) {
// woops, full. discard some data
// TODO: keep track of overrun stats
rx_ring_buffer.Pop(1);
}
if (XUartLite_Recv(uart0, rx_ring_buffer.RawWritePointer(), 1) < 1) {
break;
}
rx_ring_buffer.Push(1);
}
}
void StartSending() {
if (sending > 0) {
return;
}
size_t tosend = tx_ring_buffer.ContiguousAvailableData();
if (tosend < 1) {
return;
}
sending += 1;
XUartLite_Send(uart0, tx_ring_buffer.RawReadPointer(), tosend);
}
std::byte UartReadByte() {
std::byte c;
while (!rx_ring_buffer.Load(std::span{&c, 1})) {
}
return c;
}
void UartWriteByte(std::byte c) {
while (!tx_ring_buffer.Store(std::span{&c, 1})) {
}
{
InterruptLock lock;
StartSending();
}
}
} // namespace
void InitUarts() {
XUartLite_CfgInitialize(uart0, &uart0_config, uart0_config.RegBaseAddr);
XUartLite_SetSendHandler(uart0, HandleUartTxFromIsr, nullptr);
XUartLite_SetRecvHandler(uart0, HandleUartRxFromIsr, nullptr);
StartReceiving();
XUartLite_EnableInterrupt(uart0);
}
void UartWriteCrash(std::span<const std::byte> data) {
XUartLite_DisableInterrupt(uart0);
while (data.size() > 0) {
while (XUartLite_IsSending(uart0)) {
}
auto* dat =
reinterpret_cast<uint8_t*>(const_cast<std::byte*>(data.data()));
uint8_t sent = XUartLite_Send(uart0, dat, data.size());
data = data.subspan(sent);
}
while (XUartLite_IsSending(uart0)) {
}
XUartLite_Send(uart0, nullptr,
0); // reset buffer before enabling interrupts
XUartLite_EnableInterrupt(uart0);
}
void UartEcho() {
while (1) {
std::byte c = UartReadByte();
UartWriteByte(c);
}
}
void HandleUartTxFromIsr(void*, unsigned int transmitted) {
sending -= 1;
tx_ring_buffer.Pop(transmitted);
StartSending();
}
void HandleUartRxFromIsr(void*, unsigned int transmitted) {
rx_ring_buffer.Push(transmitted);
StartReceiving();
}
void HandleUartIsr() { XUartLite_InterruptHandler(uart0); }

View File

@@ -1,18 +0,0 @@
#pragma once
#include <span>
#include <string_view>
void InitUarts();
// send and poll the uart until transmitted
void UartWriteCrash(std::span<const std::byte> data);
inline void UartWriteCrash(std::string_view s) {
return UartWriteCrash(std::as_bytes(std::span{s.data(), s.size()}));
}
void UartEcho();
void HandleUartTxFromIsr(void*, unsigned int transmitted);
void HandleUartRxFromIsr(void*, unsigned int);
void HandleUartIsr();

View File

@@ -3,8 +3,8 @@
#include <span>
#include <string_view>
#include "async.h"
#include "buffer.h"
#include "lib/async.h"
#include "lib/buffer.h"
async::task<buffer> UartRead(int size);
async::task<std::byte> UartReadLoop();

View File

@@ -1,7 +1,7 @@
#include <cstdint>
#include "gpio.h"
#include "pol0.h"
#include "hal/gpio.h"
#include "hal/pol0.h"
namespace {

View File

@@ -1,12 +1,12 @@
#include "timer.h"
#include <cstdint>
#include "bios.h"
#include "gpio.h"
#include "intc.h"
#include "interrupts.h"
#include "pol0.h"
#include "hal/bios.h"
#include "hal/gpio.h"
#include "hal/intc.h"
#include "hal/interrupts.h"
#include "hal/pol0.h"
#include "hal/timer.h"
namespace {

View File

@@ -1,9 +1,9 @@
#include <cstdint>
#include "gpio.h"
#include "intc.h"
#include "interrupts.h"
#include "pol0.h"
#include "hal/gpio.h"
#include "hal/intc.h"
#include "hal/interrupts.h"
#include "hal/pol0.h"
#include "xuartlite.h"
namespace {