Skip to main content

kernel/
firmware.rs

1// SPDX-License-Identifier: GPL-2.0
2
3//! Firmware abstraction
4//!
5//! C header: [`include/linux/firmware.h`](srctree/include/linux/firmware.h)
6
7use crate::{
8    bindings,
9    device::Device,
10    error::Error,
11    error::Result,
12    ffi,
13    str::{CStr, CStrExt as _},
14    c_str,
15    dev_err
16};
17use core::ptr::NonNull;
18
19/// # Invariants
20///
21/// One of the following: `bindings::request_firmware`, `bindings::firmware_request_nowarn`,
22/// `bindings::firmware_request_platform`, `bindings::request_firmware_direct`.
23struct FwFunc(
24    unsafe extern "C" fn(
25        *mut *const bindings::firmware,
26        *const ffi::c_char,
27        *mut bindings::device,
28    ) -> i32,
29);
30
31impl FwFunc {
32    fn request() -> Self {
33        Self(bindings::request_firmware)
34    }
35
36    fn request_nowarn() -> Self {
37        Self(bindings::firmware_request_nowarn)
38    }
39}
40
41/// Abstraction around a C `struct firmware`.
42///
43/// This is a simple abstraction around the C firmware API. Just like with the C API, firmware can
44/// be requested. Once requested the abstraction provides direct access to the firmware buffer as
45/// `&[u8]`. The firmware is released once [`Firmware`] is dropped.
46///
47/// # Invariants
48///
49/// The pointer is valid, and has ownership over the instance of `struct firmware`.
50///
51/// The `Firmware`'s backing buffer is not modified.
52///
53/// # Examples
54///
55/// ```no_run
56/// # use kernel::{device::Device, firmware::Firmware};
57///
58/// # fn no_run() -> Result<(), Error> {
59/// # // SAFETY: *NOT* safe, just for the example to get an `ARef<Device>` instance
60/// # let dev = unsafe { Device::get_device(core::ptr::null_mut()) };
61///
62/// let fw = Firmware::request(c"path/to/firmware.bin", &dev)?;
63/// let blob = fw.data();
64///
65/// # Ok(())
66/// # }
67/// ```
68pub struct Firmware(NonNull<bindings::firmware>);
69
70impl Firmware {
71    fn request_internal(name: &CStr, dev: &Device, func: FwFunc) -> Result<Self> {
72        let mut fw: *mut bindings::firmware = core::ptr::null_mut();
73        let pfw: *mut *mut bindings::firmware = &mut fw;
74        let pfw: *mut *const bindings::firmware = pfw.cast();
75
76        // SAFETY: `pfw` is a valid pointer to a NULL initialized `bindings::firmware` pointer.
77        // `name` and `dev` are valid as by their type invariants.
78        let ret = unsafe { func.0(pfw, name.as_char_ptr(), dev.as_raw()) };
79        if ret != 0 {
80            return Err(Error::from_errno(ret));
81        }
82
83        // SAFETY: `func` not bailing out with a non-zero error code, guarantees that `fw` is a
84        // valid pointer to `bindings::firmware`.
85        Ok(Firmware(unsafe { NonNull::new_unchecked(fw) }))
86    }
87
88    /// Send a firmware request and wait for it. See also `bindings::request_firmware`.
89    pub fn request(name: &CStr, dev: &Device) -> Result<Self> {
90        Self::request_internal(name, dev, FwFunc::request())
91    }
92
93    /// Send a request for an optional firmware module. See also
94    /// `bindings::firmware_request_nowarn`.
95    pub fn request_nowarn(name: &CStr, dev: &Device) -> Result<Self> {
96        Self::request_internal(name, dev, FwFunc::request_nowarn())
97    }
98
99    /// Send a request for a nonresolvable name.
100    pub fn reject_nowarn(_name: &CStr, dev: &Device) -> Result<Self> {
101        Self::request_internal(c_str!("/*(DEBLOBBED)*/"), dev, FwFunc::request_nowarn())
102    }
103
104    /// Send a request for a nonresolvable name.
105    pub fn reject(name: &CStr, dev: &Device) -> Result<Self> {
106        dev_err!(dev, "Missing Free {} (non-Free firmware loading is disabled)\n", name);
107        Self::reject_nowarn(name, dev)
108    }
109
110
111    fn as_raw(&self) -> *mut bindings::firmware {
112        self.0.as_ptr()
113    }
114
115    /// Returns the size of the requested firmware in bytes.
116    pub fn size(&self) -> usize {
117        // SAFETY: `self.as_raw()` is valid by the type invariant.
118        unsafe { (*self.as_raw()).size }
119    }
120
121    /// Returns the requested firmware as `&[u8]`.
122    pub fn data(&self) -> &[u8] {
123        // SAFETY: `self.as_raw()` is valid by the type invariant. Additionally,
124        // `bindings::firmware` guarantees, if successfully requested, that
125        // `bindings::firmware::data` has a size of `bindings::firmware::size` bytes.
126        unsafe { core::slice::from_raw_parts((*self.as_raw()).data, self.size()) }
127    }
128}
129
130impl Drop for Firmware {
131    fn drop(&mut self) {
132        // SAFETY: `self.as_raw()` is valid by the type invariant.
133        unsafe { bindings::release_firmware(self.as_raw()) };
134    }
135}
136
137// SAFETY: `Firmware` only holds a pointer to a C `struct firmware`, which is safe to be used from
138// any thread.
139unsafe impl Send for Firmware {}
140
141// SAFETY: `Firmware` only holds a pointer to a C `struct firmware`, references to which are safe to
142// be used from any thread.
143unsafe impl Sync for Firmware {}
144
145/// Create firmware .modinfo entries.
146///
147/// This macro is the counterpart of the C macro `MODULE_FIRMWARE()`, but instead of taking a
148/// simple string literals, which is already covered by the `firmware` field of
149/// [`crate::prelude::module!`], it allows the caller to pass a builder type, based on the
150/// [`ModInfoBuilder`], which can create the firmware modinfo strings in a more flexible way.
151///
152/// Drivers should extend the [`ModInfoBuilder`] with their own driver specific builder type.
153///
154/// The `builder` argument must be a type which implements the following function.
155///
156/// `const fn create(module_name: &'static CStr) -> ModInfoBuilder`
157///
158/// `create` should pass the `module_name` to the [`ModInfoBuilder`] and, with the help of
159/// it construct the corresponding firmware modinfo.
160///
161/// Typically, such contracts would be enforced by a trait, however traits do not (yet) support
162/// const functions.
163///
164/// # Examples
165///
166/// ```
167/// # mod module_firmware_test {
168/// # use kernel::firmware;
169/// # use kernel::prelude::*;
170/// #
171/// # struct MyModule;
172/// #
173/// # impl kernel::Module for MyModule {
174/// #     fn init(_module: &'static ThisModule) -> Result<Self> {
175/// #         Ok(Self)
176/// #     }
177/// # }
178/// #
179/// #
180/// struct Builder<const N: usize>;
181///
182/// impl<const N: usize> Builder<N> {
183///     const DIR: &'static str = "vendor/chip/";
184///     const FILES: [&'static str; 3] = [ "foo", "bar", "baz" ];
185///
186///     const fn create(module_name: &'static kernel::str::CStr) -> firmware::ModInfoBuilder<N> {
187///         let mut builder = firmware::ModInfoBuilder::new(module_name);
188///
189///         let mut i = 0;
190///         while i < Self::FILES.len() {
191///             builder = builder.new_entry()
192///                 .push(Self::DIR)
193///                 .push(Self::FILES[i])
194///                 .push(".bin");
195///
196///                 i += 1;
197///         }
198///
199///         builder
200///      }
201/// }
202///
203/// module! {
204///    type: MyModule,
205///    name: "module_firmware_test",
206///    authors: ["Rust for Linux"],
207///    description: "module_firmware! test module",
208///    license: "GPL",
209/// }
210///
211/// kernel::module_firmware!(Builder);
212/// # }
213/// ```
214#[macro_export]
215macro_rules! module_firmware {
216    // The argument is the builder type without the const generic, since it's deferred from within
217    // this macro. Hence, we can neither use `expr` nor `ty`.
218    ($($builder:tt)*) => {
219        const _: () = {
220            const __MODULE_FIRMWARE_PREFIX: &'static $crate::str::CStr = if cfg!(MODULE) {
221                c""
222            } else {
223                <LocalModule as $crate::ModuleMetadata>::NAME
224            };
225
226            #[link_section = ".modinfo"]
227            #[used(compiler)]
228            static __MODULE_FIRMWARE: [u8; $($builder)*::create(__MODULE_FIRMWARE_PREFIX)
229                .build_length()] = $($builder)*::create(__MODULE_FIRMWARE_PREFIX).build();
230        };
231    };
232}
233
234/// Builder for firmware module info.
235///
236/// [`ModInfoBuilder`] is a helper component to flexibly compose firmware paths strings for the
237/// .modinfo section in const context.
238///
239/// Therefore the [`ModInfoBuilder`] provides the methods [`ModInfoBuilder::new_entry`] and
240/// [`ModInfoBuilder::push`], where the latter is used to push path components and the former to
241/// mark the beginning of a new path string.
242///
243/// [`ModInfoBuilder`] is meant to be used in combination with [`kernel::module_firmware!`].
244///
245/// The const generic `N` as well as the `module_name` parameter of [`ModInfoBuilder::new`] is an
246/// internal implementation detail and supplied through the above macro.
247pub struct ModInfoBuilder<const N: usize> {
248    buf: [u8; N],
249    n: usize,
250    module_name: &'static CStr,
251}
252
253impl<const N: usize> ModInfoBuilder<N> {
254    /// Create an empty builder instance.
255    pub const fn new(module_name: &'static CStr) -> Self {
256        Self {
257            buf: [0; N],
258            n: 0,
259            module_name,
260        }
261    }
262
263    const fn push_internal(mut self, bytes: &[u8]) -> Self {
264        let mut j = 0;
265
266        if N == 0 {
267            self.n += bytes.len();
268            return self;
269        }
270
271        while j < bytes.len() {
272            if self.n < N {
273                self.buf[self.n] = bytes[j];
274            }
275            self.n += 1;
276            j += 1;
277        }
278        self
279    }
280
281    /// Push an additional path component.
282    ///
283    /// Append path components to the [`ModInfoBuilder`] instance. Paths need to be separated
284    /// with [`ModInfoBuilder::new_entry`].
285    ///
286    /// # Examples
287    ///
288    /// ```
289    /// use kernel::firmware::ModInfoBuilder;
290    ///
291    /// # const DIR: &str = "vendor/chip/";
292    /// # const fn no_run<const N: usize>(builder: ModInfoBuilder<N>) {
293    /// let builder = builder.new_entry()
294    ///     .push(DIR)
295    ///     .push("foo.bin")
296    ///     .new_entry()
297    ///     .push(DIR)
298    ///     .push("bar.bin");
299    /// # }
300    /// ```
301    pub const fn push(self, s: &str) -> Self {
302        // Check whether there has been an initial call to `next_entry()`.
303        if N != 0 && self.n == 0 {
304            crate::build_error!("Must call next_entry() before push().");
305        }
306
307        self.push_internal(s.as_bytes())
308    }
309
310    const fn push_module_name(self) -> Self {
311        let mut this = self;
312        let module_name = this.module_name;
313
314        if !this.module_name.is_empty() {
315            this = this.push_internal(module_name.to_bytes_with_nul());
316
317            if N != 0 {
318                // Re-use the space taken by the NULL terminator and swap it with the '.' separator.
319                this.buf[this.n - 1] = b'.';
320            }
321        }
322
323        this
324    }
325
326    /// Prepare the [`ModInfoBuilder`] for the next entry.
327    ///
328    /// This method acts as a separator between module firmware path entries.
329    ///
330    /// Must be called before constructing a new entry with subsequent calls to
331    /// [`ModInfoBuilder::push`].
332    ///
333    /// See [`ModInfoBuilder::push`] for an example.
334    pub const fn new_entry(self) -> Self {
335        self.push_internal(b"\0")
336            .push_module_name()
337            .push_internal(b"firmware=")
338    }
339
340    /// Build the byte array.
341    pub const fn build(self) -> [u8; N] {
342        // Add the final NULL terminator.
343        let this = self.push_internal(b"\0");
344
345        if this.n == N {
346            this.buf
347        } else {
348            crate::build_error!("Length mismatch.");
349        }
350    }
351}
352
353impl ModInfoBuilder<0> {
354    /// Return the length of the byte array to build.
355    pub const fn build_length(self) -> usize {
356        // Compensate for the NULL terminator added by `build`.
357        self.n + 1
358    }
359}