// SPDX-License-Identifier: GPL-2.012//! Firmware abstraction3//!4//! C header: [`include/linux/firmware.h`](srctree/include/linux/firmware.h)56use crate::{7bindings,8device::Device,9error::Error,10error::Result,11ffi,12str::{CStr, CStrExt as _},13};14use core::ptr::NonNull;1516/// # Invariants17///18/// One of the following: `bindings::request_firmware`, `bindings::firmware_request_nowarn`,19/// `bindings::firmware_request_platform`, `bindings::request_firmware_direct`.20struct FwFunc(21unsafe extern "C" fn(22*mut *const bindings::firmware,23*const ffi::c_char,24*mut bindings::device,25) -> i32,26);2728impl FwFunc {29fn request() -> Self {30Self(bindings::request_firmware)31}3233fn request_nowarn() -> Self {34Self(bindings::firmware_request_nowarn)35}36}3738/// Abstraction around a C `struct firmware`.39///40/// This is a simple abstraction around the C firmware API. Just like with the C API, firmware can41/// be requested. Once requested the abstraction provides direct access to the firmware buffer as42/// `&[u8]`. The firmware is released once [`Firmware`] is dropped.43///44/// # Invariants45///46/// The pointer is valid, and has ownership over the instance of `struct firmware`.47///48/// The `Firmware`'s backing buffer is not modified.49///50/// # Examples51///52/// ```no_run53/// # use kernel::{device::Device, firmware::Firmware};54///55/// # fn no_run() -> Result<(), Error> {56/// # // SAFETY: *NOT* safe, just for the example to get an `ARef<Device>` instance57/// # let dev = unsafe { Device::get_device(core::ptr::null_mut()) };58///59/// let fw = Firmware::request(c"path/to/firmware.bin", &dev)?;60/// let blob = fw.data();61///62/// # Ok(())63/// # }64/// ```65pub struct Firmware(NonNull<bindings::firmware>);6667impl Firmware {68fn request_internal(name: &CStr, dev: &Device, func: FwFunc) -> Result<Self> {69let mut fw: *mut bindings::firmware = core::ptr::null_mut();70let pfw: *mut *mut bindings::firmware = &mut fw;71let pfw: *mut *const bindings::firmware = pfw.cast();7273// SAFETY: `pfw` is a valid pointer to a NULL initialized `bindings::firmware` pointer.74// `name` and `dev` are valid as by their type invariants.75let ret = unsafe { func.0(pfw, name.as_char_ptr(), dev.as_raw()) };76if ret != 0 {77return Err(Error::from_errno(ret));78}7980// SAFETY: `func` not bailing out with a non-zero error code, guarantees that `fw` is a81// valid pointer to `bindings::firmware`.82Ok(Firmware(unsafe { NonNull::new_unchecked(fw) }))83}8485/// Send a firmware request and wait for it. See also `bindings::request_firmware`.86pub fn request(name: &CStr, dev: &Device) -> Result<Self> {87Self::request_internal(name, dev, FwFunc::request())88}8990/// Send a request for an optional firmware module. See also91/// `bindings::firmware_request_nowarn`.92pub fn request_nowarn(name: &CStr, dev: &Device) -> Result<Self> {93Self::request_internal(name, dev, FwFunc::request_nowarn())94}9596fn as_raw(&self) -> *mut bindings::firmware {97self.0.as_ptr()98}99100/// Returns the size of the requested firmware in bytes.101pub fn size(&self) -> usize {102// SAFETY: `self.as_raw()` is valid by the type invariant.103unsafe { (*self.as_raw()).size }104}105106/// Returns the requested firmware as `&[u8]`.107pub fn data(&self) -> &[u8] {108// SAFETY: `self.as_raw()` is valid by the type invariant. Additionally,109// `bindings::firmware` guarantees, if successfully requested, that110// `bindings::firmware::data` has a size of `bindings::firmware::size` bytes.111unsafe { core::slice::from_raw_parts((*self.as_raw()).data, self.size()) }112}113}114115impl Drop for Firmware {116fn drop(&mut self) {117// SAFETY: `self.as_raw()` is valid by the type invariant.118unsafe { bindings::release_firmware(self.as_raw()) };119}120}121122// SAFETY: `Firmware` only holds a pointer to a C `struct firmware`, which is safe to be used from123// any thread.124unsafe impl Send for Firmware {}125126// SAFETY: `Firmware` only holds a pointer to a C `struct firmware`, references to which are safe to127// be used from any thread.128unsafe impl Sync for Firmware {}129130/// Create firmware .modinfo entries.131///132/// This macro is the counterpart of the C macro `MODULE_FIRMWARE()`, but instead of taking a133/// simple string literals, which is already covered by the `firmware` field of134/// [`crate::prelude::module!`], it allows the caller to pass a builder type, based on the135/// [`ModInfoBuilder`], which can create the firmware modinfo strings in a more flexible way.136///137/// Drivers should extend the [`ModInfoBuilder`] with their own driver specific builder type.138///139/// The `builder` argument must be a type which implements the following function.140///141/// `const fn create(module_name: &'static CStr) -> ModInfoBuilder`142///143/// `create` should pass the `module_name` to the [`ModInfoBuilder`] and, with the help of144/// it construct the corresponding firmware modinfo.145///146/// Typically, such contracts would be enforced by a trait, however traits do not (yet) support147/// const functions.148///149/// # Examples150///151/// ```152/// # mod module_firmware_test {153/// # use kernel::firmware;154/// # use kernel::prelude::*;155/// #156/// # struct MyModule;157/// #158/// # impl kernel::Module for MyModule {159/// # fn init(_module: &'static ThisModule) -> Result<Self> {160/// # Ok(Self)161/// # }162/// # }163/// #164/// #165/// struct Builder<const N: usize>;166///167/// impl<const N: usize> Builder<N> {168/// const DIR: &'static str = "vendor/chip/";169/// const FILES: [&'static str; 3] = [ "foo", "bar", "baz" ];170///171/// const fn create(module_name: &'static kernel::str::CStr) -> firmware::ModInfoBuilder<N> {172/// let mut builder = firmware::ModInfoBuilder::new(module_name);173///174/// let mut i = 0;175/// while i < Self::FILES.len() {176/// builder = builder.new_entry()177/// .push(Self::DIR)178/// .push(Self::FILES[i])179/// .push(".bin");180///181/// i += 1;182/// }183///184/// builder185/// }186/// }187///188/// module! {189/// type: MyModule,190/// name: "module_firmware_test",191/// authors: ["Rust for Linux"],192/// description: "module_firmware! test module",193/// license: "GPL",194/// }195///196/// kernel::module_firmware!(Builder);197/// # }198/// ```199#[macro_export]200macro_rules! module_firmware {201// The argument is the builder type without the const generic, since it's deferred from within202// this macro. Hence, we can neither use `expr` nor `ty`.203($($builder:tt)*) => {204const _: () = {205const __MODULE_FIRMWARE_PREFIX: &'static $crate::str::CStr = if cfg!(MODULE) {206c""207} else {208<LocalModule as $crate::ModuleMetadata>::NAME209};210211#[link_section = ".modinfo"]212#[used(compiler)]213static __MODULE_FIRMWARE: [u8; $($builder)*::create(__MODULE_FIRMWARE_PREFIX)214.build_length()] = $($builder)*::create(__MODULE_FIRMWARE_PREFIX).build();215};216};217}218219/// Builder for firmware module info.220///221/// [`ModInfoBuilder`] is a helper component to flexibly compose firmware paths strings for the222/// .modinfo section in const context.223///224/// Therefore the [`ModInfoBuilder`] provides the methods [`ModInfoBuilder::new_entry`] and225/// [`ModInfoBuilder::push`], where the latter is used to push path components and the former to226/// mark the beginning of a new path string.227///228/// [`ModInfoBuilder`] is meant to be used in combination with [`kernel::module_firmware!`].229///230/// The const generic `N` as well as the `module_name` parameter of [`ModInfoBuilder::new`] is an231/// internal implementation detail and supplied through the above macro.232pub struct ModInfoBuilder<const N: usize> {233buf: [u8; N],234n: usize,235module_name: &'static CStr,236}237238impl<const N: usize> ModInfoBuilder<N> {239/// Create an empty builder instance.240pub const fn new(module_name: &'static CStr) -> Self {241Self {242buf: [0; N],243n: 0,244module_name,245}246}247248const fn push_internal(mut self, bytes: &[u8]) -> Self {249let mut j = 0;250251if N == 0 {252self.n += bytes.len();253return self;254}255256while j < bytes.len() {257if self.n < N {258self.buf[self.n] = bytes[j];259}260self.n += 1;261j += 1;262}263self264}265266/// Push an additional path component.267///268/// Append path components to the [`ModInfoBuilder`] instance. Paths need to be separated269/// with [`ModInfoBuilder::new_entry`].270///271/// # Examples272///273/// ```274/// use kernel::firmware::ModInfoBuilder;275///276/// # const DIR: &str = "vendor/chip/";277/// # const fn no_run<const N: usize>(builder: ModInfoBuilder<N>) {278/// let builder = builder.new_entry()279/// .push(DIR)280/// .push("foo.bin")281/// .new_entry()282/// .push(DIR)283/// .push("bar.bin");284/// # }285/// ```286pub const fn push(self, s: &str) -> Self {287// Check whether there has been an initial call to `next_entry()`.288if N != 0 && self.n == 0 {289crate::build_error!("Must call next_entry() before push().");290}291292self.push_internal(s.as_bytes())293}294295const fn push_module_name(self) -> Self {296let mut this = self;297let module_name = this.module_name;298299if !this.module_name.is_empty() {300this = this.push_internal(module_name.to_bytes_with_nul());301302if N != 0 {303// Re-use the space taken by the NULL terminator and swap it with the '.' separator.304this.buf[this.n - 1] = b'.';305}306}307308this309}310311/// Prepare the [`ModInfoBuilder`] for the next entry.312///313/// This method acts as a separator between module firmware path entries.314///315/// Must be called before constructing a new entry with subsequent calls to316/// [`ModInfoBuilder::push`].317///318/// See [`ModInfoBuilder::push`] for an example.319pub const fn new_entry(self) -> Self {320self.push_internal(b"\0")321.push_module_name()322.push_internal(b"firmware=")323}324325/// Build the byte array.326pub const fn build(self) -> [u8; N] {327// Add the final NULL terminator.328let this = self.push_internal(b"\0");329330if this.n == N {331this.buf332} else {333crate::build_error!("Length mismatch.");334}335}336}337338impl ModInfoBuilder<0> {339/// Return the length of the byte array to build.340pub const fn build_length(self) -> usize {341// Compensate for the NULL terminator added by `build`.342self.n + 1343}344}345346347