Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions components/patina_acpi/src/acpi_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use patina::{
component::service::{
Service,
memory::{AllocationOptions, MemoryManager, PageAllocationStrategy},
uefi_services::config_table::ConfigTable,
},
uefi::memory::EfiMemoryType,
uefi_size_to_pages,
Expand Down Expand Up @@ -212,6 +213,10 @@ pub struct AcpiRsdp {
pub(crate) reserved: [u8; 3],
}

impl ConfigTable for AcpiRsdp {
const TABLE_GUID: patina::BinaryGuid = signature::ACPI_TABLE_GUID;
}

/// Represents the XSDT for ACPI 2.0+.
/// The XSDT has a standard header followed by 64-bit addresses of installed tables.
/// The `length` field of the header tells us the number of trailing bytes representing table entries.
Expand Down
1 change: 1 addition & 0 deletions components/patina_samples/src/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@
//! SPDX-License-Identifier: Apache-2.0
//!
pub mod hello_world;
pub mod uefi_services;
32 changes: 32 additions & 0 deletions components/patina_samples/src/component/uefi_services.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
//! UEFI Services Sample Components
//!
//! This module collects sample components that demonstrate the Patina UEFI Services from
//! [`patina::component::service::uefi_services`]. Each sample is a small, self-contained
//! component:
//!
//! - [`overview`] - A quick tour of timer, event, and protocol usage in one component.
//! - [`configuration_table`] - Installs a vendor configuration table and reads it back.
//! - [`driver_connect`] - Discovers controllers by protocol and connects drivers to them.
//! - [`end_of_dxe_protocol_consumer`] - Defers protocol consumption to End-of-DXE.
//! - [`protocol_consumer`] - Shows different ways to consume a protocol.
//! - [`protocol_publisher`] - Demonstrates one component publishing a protocol and another consuming it.
//! - [`timers`] - Drives work from one-shot and periodic timers using Rust closures.
//! - [`tpl_critical_section`] - Serializes access to shared state with TPL.
//!
//! ## License
//!
//! Copyright (c) Microsoft Corporation.
//!
//! SPDX-License-Identifier: Apache-2.0
//!

pub mod configuration_table;
pub mod driver_connect;
pub mod end_of_dxe_protocol_consumer;
pub mod overview;
pub mod protocol_consumer;
pub mod protocol_publisher;
pub mod timers;
pub mod tpl_critical_section;

pub use overview::UefiServicesSample;
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
//! Configuration Table Sample Component
//!
//! This component demonstrates [`ConfigurationTableServices`] by installing a vendor configuration
//! table under a GUID and reading it back. Configuration tables are how firmware publishes system-wide,
//! pointer-addressable tables such as ACPI RSDP. An OS or later component finds them by GUID in the UEFI
//! system table.
//!
//! [`SampleVendorTable`] implements [`ConfigTable`], which binds it to a GUID at the type level. This
//! lets the component install and retrieve it through [`ConfigurationTableServicesExt::install`] and
//! [`ConfigurationTableServicesExt::get`]. Neither method takes a raw pointer or directly requires the
//! GUID, so they're relatively straightforward and simple to use. `get` is not `unsafe`, because the
//! service verifies the installed type before casting the pointer.
//!
//! [`ConfigTable`] only supports tables whose size is known at compile time, but that type can be a
//! self-describing header whose own field covers trailing data laid out after it in the same allocation.
//! See [`SampleDynamicHeader`] below, for an example. Tables whose header type isn't owned by the installing
//! code at all must fall back to using [`ConfigurationTableServices::install_table`] with a raw
//! [`ConfigTablePtr`](patina::component::service::uefi_services::config_table::ConfigTablePtr) instead.
//!
//! ## License
//!
//! Copyright (c) Microsoft Corporation.
//!
//! SPDX-License-Identifier: Apache-2.0
//!

use patina::{
BinaryGuid,
component::{
component,
service::{
Service,
uefi_services::config_table::{ConfigTable, ConfigurationTableServices, ConfigurationTableServicesExt},
},
},
error::Result,
};

/// A sample vendor table laid out the way a typical firmware table would be as `#[repr(C)]`, with a
/// signature and version so consumers can validate it.
#[repr(C)]
pub struct SampleVendorTable {
/// Four-character signature identifying the table (`b"PTNA"`).
pub signature: [u8; 4],
/// Table format version.
pub version: u32,
/// Number of vendor-defined entries that follow in the real table.
pub entry_count: u32,
}

impl ConfigTable for SampleVendorTable {
/// GUID under which the table is installed in the system table.
const TABLE_GUID: BinaryGuid = BinaryGuid::from_string("0fedcba9-8765-4321-fedc-ba9876543210");
}

/// The table instance. It must be `'static` as the system table stores a pointer to it that outlives
/// this component's entry point.
static VENDOR_TABLE: SampleVendorTable = SampleVendorTable { signature: *b"PTNA", version: 1, entry_count: 0 };

/// Installs [`SampleVendorTable`] into the system configuration table, then reads it back to
/// confirm the table was installed correctly.
#[derive(Default)]
pub struct ConfigurationTableSample;

#[component]
impl ConfigurationTableSample {
/// Creates a new instance of the component.
pub fn new() -> Self {
Self
}

fn entry_point(self, config: Service<dyn ConfigurationTableServices>) -> Result<()> {
// Two methods are available to install configuration tables:
// 1. `install` - As shown below. This will return `ConfigTableError::AlreadyExists` instead of
// silently replacing an existing table, if a table is already installed under
// `SampleVendorTable::TABLE_GUID`.
// 2. `install_or_replace` - Replaces any existing table under the same GUID. This is useful
// for tables that may be updated or re-published during boot.
config.install(&VENDOR_TABLE)?;
log::info!("Installed SampleVendorTable v{}", VENDOR_TABLE.version);

// Read it back. Note that `unsafe` is not needed as the service only returns a table here if it was
// installed as `SampleVendorTable`, which is what `install` did above.
if let Some(table) = config.get::<SampleVendorTable>() {
log::info!(
"Read back signature {:?}, {} entries",
core::str::from_utf8(&table.signature).unwrap_or("????"),
table.entry_count
);
}

Ok(())
}
}

const ENTRY_COUNT: u32 = 3;

/// A sample vendor table with a self-describing header where `total_len` covers this header plus the
/// `entries` that follow it in memory.
#[repr(C)]
pub struct SampleDynamicHeader {
/// Four-character signature identifying the table (`b"PTNB"`).
pub signature: [u8; 4],
/// Total size of the table, in bytes, including this header and the trailing entries.
pub total_len: u32,
/// Number of trailing `u32` entries.
pub entry_count: u32,
}

impl ConfigTable for SampleDynamicHeader {
/// GUID under which the table is installed in the system table.
const TABLE_GUID: BinaryGuid = BinaryGuid::from_string("1a2b3c4d-5e6f-4788-99aa-bbccddeeff00");

fn table_len(&self) -> usize {
self.total_len as usize
}
}

/// The header and its trailing entries are laid out contiguously so `SampleDynamicHeader::table_len`
/// describes the whole allocation starting at `header`'s address.
#[repr(C)]
struct SampleDynamicTable {
header: SampleDynamicHeader,
entries: [u32; ENTRY_COUNT as usize],
}

static DYNAMIC_TABLE: SampleDynamicTable = SampleDynamicTable {
header: SampleDynamicHeader {
signature: *b"PTNB",
total_len: core::mem::size_of::<SampleDynamicTable>() as u32,
entry_count: ENTRY_COUNT,
},
entries: [10, 20, 30],
};

/// Installs [`SampleDynamicHeader`] into the system configuration table. This pattern can be used for a
/// self-describing header type, with trailing data laid out after it in the same allocation.
#[derive(Default)]
pub struct DynamicConfigurationTableSample;

#[component]
impl DynamicConfigurationTableSample {
/// Creates a new instance of the component.
pub fn new() -> Self {
Self
}

fn entry_point(self, config: Service<dyn ConfigurationTableServices>) -> Result<()> {
config.install(&DYNAMIC_TABLE.header)?;
log::info!("Installed SampleDynamicHeader with {} entries", DYNAMIC_TABLE.header.entry_count);

// SAFETY: `table_len` is implemented to report `DYNAMIC_TABLE`'s allocated size (header plus entries),
// matching what was installed above.
if let Some(bytes) = unsafe { config.get_bytes::<SampleDynamicHeader>() } {
let entries = bytes.get(core::mem::size_of::<SampleDynamicHeader>()..).unwrap_or(&[]);
log::info!("Read back {} bytes, including the trailing entries: {:?}", bytes.len(), entries);
}

Ok(())
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
//! Driver Connect Sample Component
//!
//! This component demonstrates combining [`ProtocolServices`] with [`DriverServices`]. It connects
//! a driver to each Block I/O controller as the protocol is installed, rather than waiting for a
//! fixed point in boot. Connecting drivers is commonly used to bring up a device stack (for example,
//! binding a disk driver onto every Block I/O controller).
//!
//! ## License
//!
//! Copyright (c) Microsoft Corporation.
//!
//! SPDX-License-Identifier: Apache-2.0
//!

use patina::standard::efi::protocols::block_io::Protocol as BlockIo;
use patina::{
component::{
component,
service::{
Service,
uefi_services::{
driver::DriverServices,
protocol::{ProtocolServices, ProtocolServicesExt, Tpl},
},
},
},
error::Result,
};

/// Connects a driver to each Block I/O controller as it is installed.
#[derive(Default)]
pub struct DriverConnectSample;

#[component]
impl DriverConnectSample {
/// Creates a new instance of the component.
pub fn new() -> Self {
Self
}

fn entry_point(self, protocols: Service<dyn ProtocolServices>, drivers: Service<dyn DriverServices>) -> Result<()> {
// Runs for every handle that already exposes Block I/O and for every future install.
protocols.on_protocol_installed::<BlockIo>(Tpl::Callback, move |controller| {
log::info!("Block I/O controller installed: {controller:?}");

if let Ok(controllers) = protocols.locate_handles_for::<BlockIo>() {
log::info!("There are currently {} Block I/O controllers installed", controllers.len());
}

// `recursive = true` also connects any child controllers the driver produces, bringing
// up the device tree. A failure to connect one controller should not stop future
// notifications, so log and continue.
log::info!("Calling connect_controller for {controller:?}");
if let Err(err) = drivers.connect_controller(controller, true) {
log::warn!("Failed to connect {controller:?}: {err:?}");
}
})?;

Ok(())
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
//! End-of-DXE Protocol Consumer Sample Component
//!
//! This component demonstrates deferring protocol consumption to an event group with
//! [`EventServicesExt`], rather than locating the protocol during normal component dispatch. It
//! registers a callback for [`END_OF_DXE_EVENT_GROUP_GUID`], the event group signaled once at the
//! end of the DXE phase, before BDS. When the callback runs, it locates the [`SampleVendorProtocol`]
//! published by the protocol publisher sample and logs the status returned through its interface.
//!
//! This pattern suits a component that must consume a protocol that may not be published yet when
//! it dispatches, without taking an explicit dispatch dependency on the publisher.
//!
//! ## License
//!
//! Copyright (c) Microsoft Corporation.
//!
//! SPDX-License-Identifier: Apache-2.0
//!

use patina::{
component::{
component,
service::{
Service,
uefi_services::{
event::{EventServices, EventServicesExt, Tpl},
protocol::{ProtocolServices, ProtocolServicesExt},
},
},
},
error::Result,
pi::event::END_OF_DXE_EVENT_GROUP_GUID,
};

use super::protocol_publisher::SampleVendorProtocol;

/// Registers an End-of-DXE callback that locates [`SampleVendorProtocol`] and logs its status.
#[derive(Default)]
pub struct EndOfDxeProtocolConsumerSample;

#[component]
impl EndOfDxeProtocolConsumerSample {
/// Creates a new instance of the component.
pub fn new() -> Self {
Self
}

fn entry_point(self, events: Service<dyn EventServices>, protocols: Service<dyn ProtocolServices>) -> Result<()> {
// This example checks for a protocol at End of DXE. The callback fires once every
// event that shares the group (including this one) is signaled. move is used to
// capture the protocols service by value for use in the closure. This allows the
// closure to take ownership of the protocols service so it can be used when the
// callback runs in the future (after this entry_point function returns).
events.on_event_group(END_OF_DXE_EVENT_GROUP_GUID, Tpl::Callback, move || {
match protocols.locate_protocol::<SampleVendorProtocol>() {
Ok(protocol) => {
let status = (protocol.get_status)();
log::info!("End of DXE: sample_get_status returned {status:#x}");
}
Err(_) => log::debug!("End of DXE: SampleVendorProtocol not published"),
}
})?;

log::info!("Registered End-of-DXE callback for SampleVendorProtocol");

Ok(())
}
}
Loading
Loading