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