Files
MontaukOS/kernel/src/Drivers/Serial/BtUart.cpp
T

489 lines
19 KiB
C++

/*
* BtUart.cpp
* Interrupt-driven UART to an on-board Bluetooth controller
* Copyright (c) 2026 Daniel Hammer
*/
#include "BtUart.hpp"
#include <ACPI/GsiRouting.hpp>
#include <Arch/Cpu.hpp>
#include <Arch/Interrupts.hpp>
#include <CppLib/Spinlock.hpp>
#include <CppLib/Stream.hpp>
#include <Memory/HHDM.hpp>
#include <Memory/Paging.hpp>
#include <Sched/Scheduler.hpp>
#include <Terminal/Terminal.hpp>
#include <Timekeeping/Timer.hpp>
#include <atomic>
using namespace Kt;
namespace Drivers::Serial::BtUart {
// =========================================================================
// Registers
// =========================================================================
// Mini UART, offsets from the AUX block (BCM2711 ARM Peripherals 2.2,
// with the elinux.org BCM2835 datasheet errata: IER bit 0 enables the
// receive interrupt and bit 1 the transmit one, IER bits 3:2 must be set
// for interrupts to be raised, LCR needs 0b11 for 8 data bits).
static constexpr uint32_t AUX_ENABLES = 0x04;
static constexpr uint32_t MU_IO = 0x40;
static constexpr uint32_t MU_IER = 0x44;
static constexpr uint32_t MU_IIR = 0x48;
static constexpr uint32_t MU_LCR = 0x4C;
static constexpr uint32_t MU_MCR = 0x50;
static constexpr uint32_t MU_LSR = 0x54;
static constexpr uint32_t MU_CNTL = 0x60;
static constexpr uint32_t MU_BAUD = 0x68;
static constexpr uint32_t AUX_ENABLE_MU = 1u << 0;
static constexpr uint32_t MU_IER_RX = 1u << 0;
static constexpr uint32_t MU_IER_TX = 1u << 1;
static constexpr uint32_t MU_IER_REQUIRED = 3u << 2;
static constexpr uint32_t MU_IIR_FLUSH = 0xC6; // clear both FIFOs, FIFOs on
static constexpr uint32_t MU_LCR_8BIT = 0x03;
static constexpr uint32_t MU_MCR_RTS = 1u << 1; // RTS pin low (asserted)
static constexpr uint32_t MU_LSR_DATA_READY = 1u << 0;
static constexpr uint32_t MU_LSR_OVERRUN = 1u << 1;
static constexpr uint32_t MU_LSR_TX_SPACE = 1u << 5; // FIFO accepts a byte
static constexpr uint32_t MU_LSR_TX_IDLE = 1u << 6; // FIFO empty, shifter idle
static constexpr uint32_t MU_CNTL_RXEN = 1u << 0;
static constexpr uint32_t MU_CNTL_TXEN = 1u << 1;
// Auto RTS at the default level (deassert with 3 FIFO spaces left).
// Bit 6 picks the level auto RTS asserts: set = low, clear (the reset
// value) = high. A UART's RTS is active low, so it must be set: left
// clear, RTS reads "stop" to the controller the moment auto RTS is on.
// Bits 3 and 7 are the same for CTS: on a Pi 400, with bit 7 clear the
// transmitter held its bytes while the controller drove CTS low (ready).
static constexpr uint32_t MU_CNTL_AUTORTS = 1u << 2;
static constexpr uint32_t MU_CNTL_AUTOCTS = 1u << 3;
static constexpr uint32_t MU_CNTL_RTS_LOW = 1u << 6;
static constexpr uint32_t MU_CNTL_CTS_LOW = 1u << 7;
// PL011 (ARM PrimeCell UART TRM)
static constexpr uint32_t PL_DR = 0x00;
static constexpr uint32_t PL_FR = 0x18;
static constexpr uint32_t PL_IBRD = 0x24;
static constexpr uint32_t PL_FBRD = 0x28;
static constexpr uint32_t PL_LCRH = 0x2C;
static constexpr uint32_t PL_CR = 0x30;
static constexpr uint32_t PL_IFLS = 0x34;
static constexpr uint32_t PL_IMSC = 0x38;
static constexpr uint32_t PL_ICR = 0x44;
static constexpr uint32_t PL_DR_OE = 1u << 11;
static constexpr uint32_t PL_FR_BUSY = 1u << 3;
static constexpr uint32_t PL_FR_RXFE = 1u << 4;
static constexpr uint32_t PL_FR_TXFF = 1u << 5;
static constexpr uint32_t PL_FR_TXFE = 1u << 7;
static constexpr uint32_t PL_LCRH_FEN = 1u << 4;
static constexpr uint32_t PL_LCRH_8BIT = 3u << 5;
static constexpr uint32_t PL_CR_UARTEN = 1u << 0;
static constexpr uint32_t PL_CR_TXE = 1u << 8;
static constexpr uint32_t PL_CR_RXE = 1u << 9;
static constexpr uint32_t PL_CR_RTS = 1u << 11;
static constexpr uint32_t PL_CR_RTSEN = 1u << 14;
static constexpr uint32_t PL_CR_CTSEN = 1u << 15;
static constexpr uint32_t PL_INT_RX = 1u << 4;
static constexpr uint32_t PL_INT_TX = 1u << 5;
static constexpr uint32_t PL_INT_RT = 1u << 6; // receive timeout
static constexpr uint32_t PL_INT_OE = 1u << 10;
static constexpr uint32_t PL_IFLS_RX_HALF = 2u << 3;
static constexpr uint32_t PL_IFLS_TX_EIGHTH = 0;
// =========================================================================
// State
// =========================================================================
static constexpr uint32_t RX_RING_SIZE = 16384; // powers of two
static constexpr uint32_t TX_RING_SIZE = 16384;
static Kind g_kind = Kind::MiniUart;
static volatile uint8_t* g_mmio = nullptr;
static uint32_t g_clockHz = 0;
static uint32_t g_baud = 0;
static bool g_flowControl = false;
static bool g_interrupt = false;
static bool g_initialized = false;
// Guards the hardware and the transmit ring: taken by the IRQ handler,
// Service() and every producer, with interrupts off.
static kcp::Spinlock g_hwLock;
// Receive ring: produced under g_hwLock, consumed by Read() (one reader).
static uint8_t g_rxRing[RX_RING_SIZE];
static std::atomic<uint32_t> g_rxHead{0};
static std::atomic<uint32_t> g_rxTail{0};
// Transmit ring: entirely under g_hwLock. g_txCount mirrors the fill for
// lock-free readers.
static uint8_t g_txRing[TX_RING_SIZE];
static uint32_t g_txHead = 0;
static uint32_t g_txTail = 0;
static std::atomic<uint32_t> g_txCount{0};
static bool g_txIrqEnabled = false;
static Stats g_stats = {};
static inline uint32_t Read32(uint32_t offset) {
return *(volatile uint32_t*)(g_mmio + offset);
}
static inline void Write32(uint32_t offset, uint32_t value) {
*(volatile uint32_t*)(g_mmio + offset) = value;
}
// =========================================================================
// FIFO service (caller holds g_hwLock)
// =========================================================================
static inline void PushRx(uint8_t byte) {
uint32_t head = g_rxHead.load(std::memory_order_relaxed);
if (head - g_rxTail.load(std::memory_order_acquire) >= RX_RING_SIZE) {
g_stats.rxDropped++;
return;
}
g_rxRing[head & (RX_RING_SIZE - 1)] = byte;
g_rxHead.store(head + 1, std::memory_order_release);
g_stats.rxBytes++;
}
static bool DrainRxLocked() {
bool any = false;
if (g_kind == Kind::MiniUart) {
for (;;) {
uint32_t lsr = Read32(MU_LSR);
if (lsr & MU_LSR_OVERRUN) g_stats.overruns++;
if (!(lsr & MU_LSR_DATA_READY)) break;
PushRx((uint8_t)Read32(MU_IO));
any = true;
}
} else {
while (!(Read32(PL_FR) & PL_FR_RXFE)) {
uint32_t data = Read32(PL_DR);
if (data & PL_DR_OE) g_stats.overruns++;
PushRx((uint8_t)data);
any = true;
}
Write32(PL_ICR, PL_INT_RX | PL_INT_RT | PL_INT_OE);
}
return any;
}
static void SetTxIrqLocked(bool on) {
if (on == g_txIrqEnabled || !g_interrupt) return;
g_txIrqEnabled = on;
if (g_kind == Kind::MiniUart) {
Write32(MU_IER, MU_IER_RX | MU_IER_REQUIRED | (on ? MU_IER_TX : 0));
} else {
Write32(PL_IMSC, PL_INT_RX | PL_INT_RT | PL_INT_OE | (on ? PL_INT_TX : 0));
}
}
// Move queued bytes into the transmit FIFO. The transmit interrupt stays
// enabled exactly while bytes remain queued: the PL011's only fires on
// crossing its FIFO threshold, so the FIFO must be refilled here first.
static void FillTxLocked() {
while (g_txHead != g_txTail) {
bool space = (g_kind == Kind::MiniUart)
? (Read32(MU_LSR) & MU_LSR_TX_SPACE) != 0
: (Read32(PL_FR) & PL_FR_TXFF) == 0;
if (!space) break;
uint8_t byte = g_txRing[g_txTail & (TX_RING_SIZE - 1)];
g_txTail++;
Write32(g_kind == Kind::MiniUart ? MU_IO : PL_DR, byte);
g_stats.txBytes++;
}
g_txCount.store(g_txHead - g_txTail, std::memory_order_release);
if (g_kind == Kind::Pl011) Write32(PL_ICR, PL_INT_TX);
SetTxIrqLocked(g_txHead != g_txTail);
}
static bool TransmitterIdleLocked() {
if (g_txHead != g_txTail) return false;
if (g_kind == Kind::MiniUart) return (Read32(MU_LSR) & MU_LSR_TX_IDLE) != 0;
uint32_t fr = Read32(PL_FR);
return (fr & PL_FR_TXFE) && !(fr & PL_FR_BUSY);
}
static void HandleInterrupt(uint8_t, bool fromUser) {
g_hwLock.Acquire();
g_stats.interrupts++;
bool received = DrainRxLocked();
FillTxLocked();
g_hwLock.Release();
// Received bytes are parsed in process context. When this interrupt
// landed in user mode, ask for an idle-context pass at once (as the
// timer does for USB) instead of waiting for the core to go idle.
if (received && fromUser) Sched::RequestKernelWork();
}
// =========================================================================
// Baud rate (caller holds g_hwLock, transmitter idle)
// =========================================================================
static bool WithinTolerance(uint64_t actual, uint32_t wanted) {
uint64_t diff = actual > wanted ? actual - wanted : wanted - actual;
return diff * 40 <= wanted; // 2.5%
}
// The divisor for `baud`: mini UART, baud = clock / (8 * divisor) (the
// register holds divisor - 1); PL011, clock / (16 * baud) in 16.6 fixed
// point (IBRD = divisor >> 6, FBRD = divisor & 63).
static bool ComputeDivisor(uint32_t baud, uint64_t& divisor) {
if (baud == 0 || g_clockHz == 0) return false;
if (g_kind == Kind::MiniUart) {
divisor = ((uint64_t)g_clockHz + 4ull * baud) / (8ull * baud);
if (divisor < 1 || divisor > 0x10000) return false;
return WithinTolerance((uint64_t)g_clockHz / (8 * divisor), baud);
}
divisor = ((uint64_t)g_clockHz * 8 / baud + 1) / 2;
if ((divisor >> 6) < 1 || (divisor >> 6) > 0xFFFF) return false;
return WithinTolerance((uint64_t)g_clockHz * 4 / divisor, baud);
}
static bool ProgramBaudLocked(uint32_t baud) {
uint64_t divisor = 0;
if (!ComputeDivisor(baud, divisor)) return false;
if (g_kind == Kind::MiniUart) {
uint32_t cntl = Read32(MU_CNTL);
Write32(MU_CNTL, 0);
Write32(MU_BAUD, (uint32_t)(divisor - 1));
Write32(MU_CNTL, cntl);
} else {
uint32_t ibrd = (uint32_t)(divisor >> 6);
uint32_t fbrd = (uint32_t)(divisor & 63);
uint32_t cr = Read32(PL_CR);
Write32(PL_CR, 0);
for (int i = 0; i < 100000 && (Read32(PL_FR) & PL_FR_BUSY); i++) Arch::Pause();
Write32(PL_LCRH, 0); // flush the FIFOs
Write32(PL_IBRD, ibrd);
Write32(PL_FBRD, fbrd);
Write32(PL_LCRH, PL_LCRH_8BIT | PL_LCRH_FEN); // latches IBRD/FBRD
Write32(PL_CR, cr);
}
g_baud = baud;
return true;
}
// =========================================================================
// Public API
// =========================================================================
bool Initialize(const Config& config) {
if (g_initialized) return true;
if (config.mmioPhys == 0 || config.clockHz == 0) return false;
g_kind = config.kind;
g_clockHz = config.clockHz;
// The mini UART lives 0x40 into the AUX block; accept either base.
uint64_t base = config.mmioPhys;
if (g_kind == Kind::MiniUart && (base & 0xFF) == MU_IO) base -= MU_IO;
uint64_t page = base & ~0xFFFULL;
Memory::VMM::g_paging->MapMMIO(page, Memory::HHDM(page));
g_mmio = (volatile uint8_t*)Memory::HHDM(base);
g_hwLock.Acquire();
if (g_kind == Kind::MiniUart) {
// AUX_ENABLES also gates SPI1/SPI2; leave their bits alone.
Write32(AUX_ENABLES, Read32(AUX_ENABLES) | AUX_ENABLE_MU);
Write32(MU_CNTL, 0);
Write32(MU_IER, 0);
Write32(MU_LCR, MU_LCR_8BIT);
Write32(MU_MCR, MU_MCR_RTS);
Write32(MU_IIR, MU_IIR_FLUSH);
Write32(MU_CNTL, MU_CNTL_RXEN | MU_CNTL_TXEN);
} else {
Write32(PL_CR, 0);
Write32(PL_IMSC, 0);
Write32(PL_ICR, 0x7FF);
Write32(PL_IFLS, PL_IFLS_RX_HALF | PL_IFLS_TX_EIGHTH);
Write32(PL_LCRH, PL_LCRH_8BIT | PL_LCRH_FEN);
Write32(PL_CR, PL_CR_UARTEN | PL_CR_TXE | PL_CR_RXE | PL_CR_RTS);
}
bool baudOk = ProgramBaudLocked(115200);
while (DrainRxLocked()) {}
g_rxTail.store(g_rxHead.load(std::memory_order_relaxed), std::memory_order_release);
g_hwLock.Release();
if (!baudOk) {
KernelLogStream(ERROR, "BtUart") << "115200 baud unreachable from a "
<< (uint64_t)g_clockHz << " Hz clock";
return false;
}
if (config.gsi != 0) {
uint8_t line = Hal::GsiRouting::LineForGsi(config.gsi, config.levelTriggered,
config.activeLow);
if (line != 0) {
Arch::RegisterIrqHandler(line, HandleInterrupt);
g_interrupt = true;
g_hwLock.Acquire();
if (g_kind == Kind::MiniUart) {
Write32(MU_IER, MU_IER_RX | MU_IER_REQUIRED);
} else {
Write32(PL_IMSC, PL_INT_RX | PL_INT_RT | PL_INT_OE);
}
g_hwLock.Release();
Arch::EnableLegacyIrq(line);
}
}
g_initialized = true;
KernelLogStream(OK, "BtUart") << (g_kind == Kind::MiniUart ? "Mini UART" : "PL011")
<< " at 0x" << base::hex << base << base::dec << ", " << (uint64_t)g_clockHz
<< " Hz clock, " << (g_interrupt ? "interrupt driven" : "polled (no interrupt)");
return true;
}
bool IsInitialized() { return g_initialized; }
bool HasInterrupt() { return g_interrupt; }
uint32_t GetBaud() { return g_baud; }
Kind GetKind() { return g_kind; }
bool FlowControl() { return g_flowControl; }
bool BaudReachable(uint32_t baud) {
uint64_t divisor = 0;
return g_initialized && ComputeDivisor(baud, divisor);
}
bool SetBaud(uint32_t baud) {
if (!g_initialized) return false;
WaitTxIdle(1000);
g_hwLock.Acquire();
bool ok = ProgramBaudLocked(baud);
g_hwLock.Release();
return ok;
}
void SetFlowControl(bool on) {
if (!g_initialized) return;
g_hwLock.Acquire();
if (g_kind == Kind::MiniUart) {
uint32_t cntl = MU_CNTL_RXEN | MU_CNTL_TXEN
| (on ? MU_CNTL_AUTORTS | MU_CNTL_RTS_LOW
| MU_CNTL_AUTOCTS | MU_CNTL_CTS_LOW : 0);
Write32(MU_CNTL, cntl);
// With auto RTS off, hold RTS asserted by hand.
Write32(MU_MCR, MU_MCR_RTS);
} else {
uint32_t cr = Read32(PL_CR) & ~(PL_CR_RTSEN | PL_CR_CTSEN);
if (on) cr |= PL_CR_RTSEN | PL_CR_CTSEN;
Write32(PL_CR, cr | PL_CR_RTS);
}
g_flowControl = on;
g_hwLock.Release();
}
void DeassertRts() {
if (!g_initialized) return;
g_hwLock.Acquire();
if (g_kind == Kind::MiniUart) {
Write32(MU_CNTL, MU_CNTL_RXEN | MU_CNTL_TXEN);
Write32(MU_MCR, 0);
} else {
Write32(PL_CR, Read32(PL_CR) & ~(PL_CR_RTSEN | PL_CR_CTSEN | PL_CR_RTS));
}
g_flowControl = false;
g_hwLock.Release();
}
int Read(uint8_t* buffer, int maxLength) {
if (buffer == nullptr || maxLength <= 0) return 0;
uint32_t tail = g_rxTail.load(std::memory_order_relaxed);
uint32_t head = g_rxHead.load(std::memory_order_acquire);
uint32_t available = head - tail;
uint32_t n = available < (uint32_t)maxLength ? available : (uint32_t)maxLength;
for (uint32_t i = 0; i < n; i++) {
buffer[i] = g_rxRing[(tail + i) & (RX_RING_SIZE - 1)];
}
g_rxTail.store(tail + n, std::memory_order_release);
return (int)n;
}
bool HasRxData() {
if (!g_initialized) return false;
if (g_rxHead.load(std::memory_order_acquire) != g_rxTail.load(std::memory_order_relaxed))
return true;
// Polled: nothing fills the ring until Service() runs, so look at
// the FIFO itself.
if (g_interrupt) return false;
return g_kind == Kind::MiniUart ? (Read32(MU_LSR) & MU_LSR_DATA_READY) != 0
: (Read32(PL_FR) & PL_FR_RXFE) == 0;
}
void FlushRx() {
if (!g_initialized) return;
g_hwLock.Acquire();
while (DrainRxLocked()) {}
g_rxTail.store(g_rxHead.load(std::memory_order_relaxed), std::memory_order_release);
g_hwLock.Release();
}
bool Write(const uint8_t* head, uint32_t headLength,
const uint8_t* body, uint32_t bodyLength) {
if (body == nullptr) bodyLength = 0;
uint32_t length = headLength + bodyLength;
if (!g_initialized || length == 0) return length == 0;
if (length > TX_RING_SIZE) return false;
g_hwLock.Acquire();
if (TX_RING_SIZE - (g_txHead - g_txTail) < length) {
g_hwLock.Release();
return false;
}
for (uint32_t i = 0; i < headLength; i++) {
g_txRing[(g_txHead + i) & (TX_RING_SIZE - 1)] = head[i];
}
for (uint32_t i = 0; i < bodyLength; i++) {
g_txRing[(g_txHead + headLength + i) & (TX_RING_SIZE - 1)] = body[i];
}
g_txHead += length;
FillTxLocked();
g_hwLock.Release();
return true;
}
uint32_t TxFree() {
return TX_RING_SIZE - g_txCount.load(std::memory_order_acquire);
}
uint32_t TxPending() {
return g_txCount.load(std::memory_order_acquire);
}
bool WaitTxIdle(uint32_t timeoutMs) {
if (!g_initialized) return false;
uint64_t start = Timekeeping::GetMilliseconds();
for (;;) {
g_hwLock.Acquire();
FillTxLocked();
bool idle = TransmitterIdleLocked();
g_hwLock.Release();
if (idle) return true;
if (Timekeeping::GetMilliseconds() - start > timeoutMs) return false;
Arch::Pause();
}
}
void Service() {
if (!g_initialized) return;
g_hwLock.Acquire();
DrainRxLocked();
FillTxLocked();
g_hwLock.Release();
}
void GetStats(Stats& out) {
g_hwLock.Acquire();
out = g_stats;
g_hwLock.Release();
}
}