git clone https://garage44.eu/jeroen/pinnacle.git.. /kernel/src/fdt.rs
//! The flattened device tree a bootloader passes: the command line in
//! `/chosen/bootargs`, and every node's `compatible`, `reg` and
//! `interrupts`, which is how the kernel finds its hardware (`device`).
const MAGIC: u32 = 0xd00d_feed;
const BEGIN_NODE: u32 = 1;
const END_NODE: u32 = 2;
const PROP: u32 = 3;
const NOP: u32 = 4;
/// The device tree at physical `address`, if there is one.
pub struct DeviceTree {
bytes: &'static [u8],
}
fn be32(bytes: &[u8], at: usize) -> Option<u32> {
Some(u32::from_be_bytes(bytes.get(at..at + 4)?.try_into().ok()?))
}
impl DeviceTree {
pub fn at(address: usize) -> Option<Self> {
if address == 0 {
return None;
}
let header = crate::mmu::virt(address) as *const u32;
// SAFETY: the loader passed a device tree here, in mapped RAM; the
// header's first two words say whether it is one and how long.
let (magic, size) = unsafe { (u32::from_be(header.read()), u32::from_be(header.add(1).read())) };
if magic != MAGIC {
return None;
}
// SAFETY: as above; `size` bytes, which `mm::init` keeps reserved.
let bytes = unsafe { core::slice::from_raw_parts(header.cast::<u8>(), size as usize) };
Some(Self { bytes })
}
/// A property of a node right under the root, as raw bytes.
pub fn property(&self, node: &str, name: &str) -> Option<&'static [u8]> {
let bytes = self.bytes;
let structure = be32(bytes, 8)? as usize;
let strings = be32(bytes, 12)? as usize;
let mut at = structure;
let mut depth = 0usize;
let mut inside = false;
loop {
let token = be32(bytes, at)?;
at += 4;
match token {
BEGIN_NODE => {
let len = bytes[at..].iter().position(|&b| b == 0)?;
depth += 1;
inside = depth == 2 && &bytes[at..at + len] == node.as_bytes();
at = (at + len + 1).next_multiple_of(4);
}
END_NODE => {
depth = depth.checked_sub(1)?;
inside = false;
}
PROP => {
let len = be32(bytes, at)? as usize;
let name_at = strings + be32(bytes, at + 4)? as usize;
let value = bytes.get(at + 8..at + 8 + len)?;
at = (at + 8 + len).next_multiple_of(4);
if inside {
let name_len = bytes[name_at..].iter().position(|&b| b == 0)?;
if &bytes[name_at..name_at + name_len] == name.as_bytes() {
return Some(value);
}
}
}
NOP => {}
_ => return None,
}
}
}
/// The kernel's command line.
pub fn bootargs(&self) -> &'static str {
self.property("chosen", "bootargs")
.and_then(|v| core::str::from_utf8(v.strip_suffix(&[0]).unwrap_or(v)).ok())
.unwrap_or("")
}
/// Calls `f` with every node, children before their parent ends,
/// parents before their children start.
pub fn nodes(&self, mut f: impl FnMut(&Node)) {
let _ = self.walk(&mut f);
}
fn walk(&self, f: &mut impl FnMut(&Node)) -> Option<()> {
let bytes = self.bytes;
let structure = be32(bytes, 8)? as usize;
let strings = be32(bytes, 12)? as usize;
// Each open node, as far as its properties have come; a node's
// children read their `reg` by its #address-cells and #size-cells,
// which come before them.
let mut open: alloc::vec::Vec<Node> = alloc::vec::Vec::new();
let mut at = structure;
loop {
let token = be32(bytes, at)?;
at += 4;
match token {
BEGIN_NODE => {
let len = bytes[at..].iter().position(|&b| b == 0)?;
let name = core::str::from_utf8(&bytes[at..at + len]).ok()?;
at = (at + len + 1).next_multiple_of(4);
// The root's own defaults, as the specification has them.
let (address_cells, size_cells) = open
.last()
.map_or((2, 1), |p| (p.child_address_cells, p.child_size_cells));
open.push(Node {
name,
depth: open.len(),
address_cells,
size_cells,
child_address_cells: 2,
child_size_cells: 1,
compatible: &[],
reg: &[],
interrupts: &[],
status: &[],
device_type: &[],
properties: alloc::vec::Vec::new(),
});
}
END_NODE => {
let node = open.pop()?;
f(&node);
if open.is_empty() {
return Some(());
}
}
PROP => {
let len = be32(bytes, at)? as usize;
let name_at = strings + be32(bytes, at + 4)? as usize;
let value: &'static [u8] = bytes.get(at + 8..at + 8 + len)?;
at = (at + 8 + len).next_multiple_of(4);
let name_len = bytes[name_at..].iter().position(|&b| b == 0)?;
let node = open.last_mut()?;
if let Ok(property) = core::str::from_utf8(&bytes[name_at..name_at + name_len]) {
node.properties.push((property, value));
}
match &bytes[name_at..name_at + name_len] {
b"compatible" => node.compatible = value,
b"reg" => node.reg = value,
b"interrupts" => node.interrupts = value,
b"status" => node.status = value,
b"device_type" => node.device_type = value,
b"#address-cells" => node.child_address_cells = be32(value, 0)?,
b"#size-cells" => node.child_size_cells = be32(value, 0)?,
_ => {}
}
}
NOP => {}
_ => return None,
}
}
}
}
/// One node of the tree, with the properties the kernel reads.
pub struct Node {
/// Its name with its unit address: `virtio_mmio@a000000`.
pub name: &'static str,
/// The root's is 0.
pub depth: usize,
/// The cells of one address and one size in its `reg` (its parent's).
address_cells: u32,
size_cells: u32,
child_address_cells: u32,
child_size_cells: u32,
compatible: &'static [u8],
reg: &'static [u8],
interrupts: &'static [u8],
status: &'static [u8],
device_type: &'static [u8],
/// Every property, by name, for what the fields above do not cover
/// (a PCI host's `ranges` and `interrupt-map`).
pub properties: alloc::vec::Vec<(&'static str, &'static [u8])>,
}
/// A number of `cells` big-endian 32-bit cells.
fn cells(bytes: &[u8], cells: u32) -> Option<u64> {
(0..cells as usize).try_fold(0u64, |n, i| Some(n << 32 | u64::from(be32(bytes, i * 4)?)))
}
/// The NUL-separated strings of a string-list property.
fn strings(value: &'static [u8]) -> impl Iterator<Item = &'static str> {
value
.split(|&b| b == 0)
.filter(|s| !s.is_empty())
.filter_map(|s| core::str::from_utf8(s).ok())
}
impl Node {
/// What it is compatible with, most specific first.
pub fn compatible(&self) -> impl Iterator<Item = &'static str> {
strings(self.compatible)
}
pub fn device_type(&self) -> Option<&'static str> {
strings(self.device_type).next()
}
/// Not switched off by the tree (`status = "disabled"`).
pub fn enabled(&self) -> bool {
strings(self.status)
.next()
.is_none_or(|s| s == "okay" || s == "ok")
}
/// Its register windows: (physical address, size). Read as its parent
/// gives them, without translating through the parent's `ranges`: on
/// the machines run so far every device sits right under the root.
pub fn regs(&self) -> impl Iterator<Item = (u64, u64)> + '_ {
let step = ((self.address_cells + self.size_cells) * 4) as usize;
self.reg.chunks_exact(step.max(4)).filter_map(move |chunk| {
let address = cells(chunk, self.address_cells)?;
let size = cells(&chunk[(self.address_cells * 4) as usize..], self.size_cells)?;
Some((address, size))
})
}
/// Its interrupts as GIC INTIDs, read as the GIC's three cells (kind,
/// number, flags): a shared one is number + 32, a private one + 16.
/// Every interrupt on the machines run so far goes to the GIC.
pub fn interrupts(&self) -> impl Iterator<Item = u32> + '_ {
self.interrupts.as_chunks::<12>().0.iter().filter_map(|cell| {
let (kind, number) = (be32(cell, 0)?, be32(cell, 4)?);
match kind {
0 => Some(number + 32),
1 => Some(number + 16),
_ => None,
}
})
}
}
/// One step through the tree, for walks that must not allocate (they run
/// before the page allocator has pages): a node begins (its name), one of
/// its properties, a node ends.
enum Token {
Begin(&'static str),
Property(&'static str, &'static [u8]),
End,
}
/// A `simple-framebuffer` node: a screen the bootloader lit and left on,
/// as the binding describes it.
#[derive(Clone, Copy)]
pub struct SimpleFramebuffer {
pub address: u64,
pub width: u32,
pub height: u32,
pub stride: u32,
pub format: &'static str,
}
/// How deep the allocation-free walks follow the tree.
const DEEPEST: usize = 16;
impl DeviceTree {
fn scan(&self, f: &mut impl FnMut(Token)) -> Option<()> {
let bytes = self.bytes;
let structure = be32(bytes, 8)? as usize;
let strings = be32(bytes, 12)? as usize;
let mut at = structure;
let mut depth = 0usize;
loop {
let token = be32(bytes, at)?;
at += 4;
match token {
BEGIN_NODE => {
let len = bytes.get(at..)?.iter().position(|&b| b == 0)?;
let name = core::str::from_utf8(&bytes[at..at + len]).ok()?;
at = (at + len + 1).next_multiple_of(4);
depth += 1;
f(Token::Begin(name));
}
END_NODE => {
f(Token::End);
depth = depth.checked_sub(1)?;
if depth == 0 {
return Some(());
}
}
PROP => {
let len = be32(bytes, at)? as usize;
let name_at = strings + be32(bytes, at + 4)? as usize;
let value: &'static [u8] = bytes.get(at + 8..at + 8 + len)?;
at = (at + 8 + len).next_multiple_of(4);
let name_len = bytes.get(name_at..)?.iter().position(|&b| b == 0)?;
let name = core::str::from_utf8(&bytes[name_at..name_at + name_len]).ok()?;
f(Token::Property(name, value));
}
NOP => {}
_ => return None,
}
}
}
/// Calls `f` with every range (physical start, size) the tree says the
/// kernel must leave alone: the reservation block in its header (where
/// U-Boot puts a framebuffer it lit) and the `reg` of each child of
/// `/reserved-memory`. Allocates nothing.
pub fn reserved(&self, mut f: impl FnMut(u64, u64)) {
let bytes = self.bytes;
if let Some(mut at) = be32(bytes, 16).map(|a| a as usize) {
while let (Some(address), Some(size)) = (
bytes.get(at..at + 8).and_then(|b| cells(b, 2)),
bytes.get(at + 8..at + 16).and_then(|b| cells(b, 2)),
) {
if address == 0 && size == 0 {
break;
}
f(address, size);
at += 16;
}
}
// Each open node's cells for its children; a node's properties
// come before its children, so a child reads its parent's.
let mut cells_of = [(2u32, 1u32); DEEPEST];
let mut depth = 0usize;
let mut inside_reserved = false;
let _ = self.scan(&mut |token| match token {
Token::Begin(name) => {
depth += 1;
if depth == 2 {
inside_reserved = name == "reserved-memory";
}
if let Some(slot) = cells_of.get_mut(depth) {
*slot = (2, 1);
}
}
Token::Property(name, value) => match name {
"#address-cells" | "#size-cells" => {
if let (Some(slot), Some(n)) = (cells_of.get_mut(depth), be32(value, 0)) {
if name == "#address-cells" {
slot.0 = n
} else {
slot.1 = n
}
}
}
"reg" if inside_reserved && depth == 3 => {
let (a, s) = cells_of[2];
for chunk in value.chunks_exact(((a + s) * 4).max(4) as usize) {
if let (Some(address), Some(size)) =
(cells(chunk, a), cells(&chunk[(a * 4) as usize..], s))
{
f(address, size);
}
}
}
_ => {}
},
Token::End => depth = depth.saturating_sub(1),
});
}
/// The first enabled `simple-framebuffer` node, anywhere in the tree
/// (U-Boot puts one at the root, Linux's bindings under `/chosen`).
/// Allocates nothing.
pub fn simple_framebuffer(&self) -> Option<SimpleFramebuffer> {
#[derive(Clone, Copy)]
struct Open {
cells: (u32, u32),
parent: (u32, u32),
framebuffer: bool,
enabled: bool,
reg: &'static [u8],
width: Option<u32>,
height: Option<u32>,
stride: Option<u32>,
format: Option<&'static str>,
}
let empty = Open {
cells: (2, 1),
parent: (2, 1),
framebuffer: false,
enabled: true,
reg: &[],
width: None,
height: None,
stride: None,
format: None,
};
let mut open = [empty; DEEPEST];
let mut depth = 0usize;
let mut found = None;
let _ = self.scan(&mut |token| {
if found.is_some() {
return;
}
match token {
Token::Begin(_) => {
depth += 1;
let parent = open.get(depth - 1).map_or((2, 1), |p| p.cells);
if let Some(slot) = open.get_mut(depth) {
*slot = Open { parent, ..empty };
}
}
Token::Property(name, value) => {
let Some(node) = open.get_mut(depth) else {
return;
};
let text = || strings(value).next();
match name {
"#address-cells" => node.cells.0 = be32(value, 0).unwrap_or(2),
"#size-cells" => node.cells.1 = be32(value, 0).unwrap_or(1),
"compatible" => node.framebuffer = strings(value).any(|c| c == "simple-framebuffer"),
"status" => node.enabled = text().is_none_or(|s| s == "okay" || s == "ok"),
"reg" => node.reg = value,
"width" => node.width = be32(value, 0),
"height" => node.height = be32(value, 0),
"stride" => node.stride = be32(value, 0),
"format" => node.format = text(),
_ => {}
}
}
Token::End => {
if let Some(node) = open.get(depth)
&& node.framebuffer
&& node.enabled
&& let (Some(width), Some(height), Some(stride), Some(format), Some(address)) = (
node.width,
node.height,
node.stride,
node.format,
cells(node.reg, node.parent.0),
)
{
found = Some(SimpleFramebuffer {
address,
width,
height,
stride,
format,
});
}
depth = depth.saturating_sub(1);
}
}
});
found
}
}