lists.openwall.net   lists  /  announce  owl-users  owl-dev  john-users  john-dev  passwdqc-users  yescrypt  popa3d-users  /  oss-security  kernel-hardening  musl  sabotage  tlsify  passwords  /  crypt-dev  xvendor  /  Bugtraq  Full-Disclosure  linux-kernel  linux-netdev  linux-ext4  linux-hardening  linux-cve-announce  PHC 
Open Source and information security mailing list archives
 
Hash Suite: Windows password security audit tool. GUI, reports in PDF.
[<prev] [next>] [<thread-prev] [day] [month] [year] [list]
Message-ID: <20240627113641.18d77571@eugeo>
Date: Thu, 27 Jun 2024 11:36:41 +0100
From: Gary Guo <gary@...yguo.net>
To: Danilo Krummrich <dakr@...hat.com>
Cc: gregkh@...uxfoundation.org, rafael@...nel.org, mcgrof@...nel.org,
 russ.weight@...ux.dev, ojeda@...nel.org, alex.gaynor@...il.com,
 wedsonaf@...il.com, boqun.feng@...il.com, bjorn3_gh@...tonmail.com,
 benno.lossin@...ton.me, a.hindborg@...sung.com, aliceryhl@...gle.com,
 airlied@...il.com, fujita.tomonori@...il.com, pstanner@...hat.com,
 ajanulgu@...hat.com, lyude@...hat.com, rust-for-linux@...r.kernel.org,
 linux-kernel@...r.kernel.org
Subject: Re: [PATCH v4 2/2] rust: add firmware abstractions

On Thu, 20 Jun 2024 15:43:52 +0200
Danilo Krummrich <dakr@...hat.com> wrote:

> On 6/20/24 15:36, Gary Guo wrote:
> > On Tue, 18 Jun 2024 17:48:35 +0200
> > Danilo Krummrich <dakr@...hat.com> wrote:
> >   
> >> Add an abstraction around the kernels firmware API to request firmware
> >> images. The abstraction provides functions to access the firmware's size
> >> and backing buffer.
> >>
> >> The firmware is released once the abstraction instance is dropped.
> >>
> >> Signed-off-by: Danilo Krummrich <dakr@...hat.com>
> >> ---
> >>   drivers/base/firmware_loader/Kconfig |   7 ++
> >>   rust/bindings/bindings_helper.h      |   1 +
> >>   rust/kernel/firmware.rs              | 101 +++++++++++++++++++++++++++
> >>   rust/kernel/lib.rs                   |   2 +
> >>   4 files changed, 111 insertions(+)
> >>   create mode 100644 rust/kernel/firmware.rs
> >>
> >> diff --git a/rust/kernel/firmware.rs b/rust/kernel/firmware.rs
> >> new file mode 100644
> >> index 000000000000..b55ea1b45368
> >> --- /dev/null
> >> +++ b/rust/kernel/firmware.rs
> >> @@ -0,0 +1,101 @@
> >> +// SPDX-License-Identifier: GPL-2.0
> >> +
> >> +//! Firmware abstraction
> >> +//!
> >> +//! C header: [`include/linux/firmware.h`](srctree/include/linux/firmware.h")
> >> +
> >> +use crate::{bindings, device::Device, error::Error, error::Result, str::CStr};
> >> +use core::ptr::NonNull;
> >> +
> >> +// One of the following: `bindings::request_firmware`, `bindings::firmware_request_nowarn`,
> >> +// `firmware_request_platform`, `bindings::request_firmware_direct`
> >> +type FwFunc =
> >> +    unsafe extern "C" fn(*mut *const bindings::firmware, *const i8, *mut bindings::device) -> i32;
> >> +
> >> +/// Abstraction around a C `struct firmware`.
> >> +///
> >> +/// This is a simple abstraction around the C firmware API. Just like with the C API, firmware can
> >> +/// be requested. Once requested the abstraction provides direct access to the firmware buffer as
> >> +/// `&[u8]`. The firmware is released once [`Firmware`] is dropped.
> >> +///
> >> +/// # Invariants
> >> +///
> >> +/// The pointer is valid, and has ownership over the instance of `struct firmware`.
> >> +///
> >> +/// Once requested, the `Firmware` backing buffer is not modified until it is freed when `Firmware`
> >> +/// is dropped.
> >> +///
> >> +/// # Examples
> >> +///
> >> +/// ```
> >> +/// # use kernel::{c_str, device::Device, firmware::Firmware};
> >> +///
> >> +/// # // SAFETY: *NOT* safe, just for the example to get an `ARef<Device>` instance
> >> +/// # let dev = unsafe { Device::from_raw(core::ptr::null_mut()) };
> >> +///
> >> +/// let fw = Firmware::request(c_str!("path/to/firmware.bin"), &dev).unwrap();
> >> +/// let blob = fw.data();
> >> +/// ```
> >> +pub struct Firmware(NonNull<bindings::firmware>);
> >> +
> >> +impl Firmware {
> >> +    fn request_internal(name: &CStr, dev: &Device, func: FwFunc) -> Result<Self> {
> >> +        let mut fw: *mut bindings::firmware = core::ptr::null_mut();
> >> +        let pfw: *mut *mut bindings::firmware = &mut fw;
> >> +
> >> +        // SAFETY: `pfw` is a valid pointer to a NULL initialized `bindings::firmware` pointer.
> >> +        // `name` and `dev` are valid as by their type invariants.
> >> +        let ret = unsafe { func(pfw as _, name.as_char_ptr(), dev.as_raw()) };  
> > 
> > This is line is unsound if this function is called with an arbitrary
> > FwFunc, therefore the safety comment should also mention that `func`
> > cannot be an arbitrary function and it must be one of
> > `request_firmware`, `firmware_request_nowarn`,
> > `firmware_request_platform`, `request_firmware_direct`, and this is  
> 
> This is documented in the type definition of `FwFunc`. We can link to this invariant though
> and explicitly mark it as such. Does that make sense?

You can't really attach an invariant to `FwFunc` because it's just a
type alias, although linking to the comment in `FwFunc` and mentioning
that all users are within the module is good to me.

Some other options are:
* New type over FwFunc and attach invariant
* Make this function unsafe and have this as a safety precondition

Both would make the safety comment making local reasoning rather than
file-level reasoning. Although I don't think either is necessary since
this is a small file. But we need to be explicit file-level reasoning
is used here.

Best,
Gary

> - Danilo
> 
> > true because the function is not public and all users in the file
> > satisfy this safety precondition.
> > 
> >   
> >> +        if ret != 0 {
> >> +            return Err(Error::from_errno(ret));
> >> +        }
> >> +
> >> +        // SAFETY: `func` not bailing out with a non-zero error code, guarantees that `fw` is a
> >> +        // valid pointer to `bindings::firmware`.
> >> +        Ok(Firmware(unsafe { NonNull::new_unchecked(fw) }))
> >> +    }
> >> +
> >> +    /// Send a firmware request and wait for it. See also `bindings::request_firmware`.
> >> +    pub fn request(name: &CStr, dev: &Device) -> Result<Self> {
> >> +        Self::request_internal(name, dev, bindings::request_firmware)
> >> +    }
> >> +
> >> +    /// Send a request for an optional firmware module. See also
> >> +    /// `bindings::firmware_request_nowarn`.
> >> +    pub fn request_nowarn(name: &CStr, dev: &Device) -> Result<Self> {
> >> +        Self::request_internal(name, dev, bindings::firmware_request_nowarn)
> >> +    }
> >> +
> >> +    fn as_raw(&self) -> *mut bindings::firmware {
> >> +        self.0.as_ptr()
> >> +    }
> >> +
> >> +    /// Returns the size of the requested firmware in bytes.
> >> +    pub fn size(&self) -> usize {
> >> +        // SAFETY: Safe by the type invariant.
> >> +        unsafe { (*self.as_raw()).size }
> >> +    }
> >> +
> >> +    /// Returns the requested firmware as `&[u8]`.
> >> +    pub fn data(&self) -> &[u8] {
> >> +        // SAFETY: Safe by the type invariant. Additionally, `bindings::firmware` guarantees, if
> >> +        // successfully requested, that `bindings::firmware::data` has a size of
> >> +        // `bindings::firmware::size` bytes.
> >> +        unsafe { core::slice::from_raw_parts((*self.as_raw()).data, self.size()) }
> >> +    }
> >> +}
> >> +
> >> +impl Drop for Firmware {
> >> +    fn drop(&mut self) {
> >> +        // SAFETY: Safe by the type invariant.
> >> +        unsafe { bindings::release_firmware(self.as_raw()) };
> >> +    }
> >> +}
> >> +
> >> +// SAFETY: `Firmware` only holds a pointer to a C `struct firmware`, which is safe to be used from
> >> +// any thread.
> >> +unsafe impl Send for Firmware {}
> >> +
> >> +// SAFETY: `Firmware` only holds a pointer to a C `struct firmware`, references to which are safe to
> >> +// be used from any thread.
> >> +unsafe impl Sync for Firmware {}


Powered by blists - more mailing lists

Powered by Openwall GNU/*/Linux Powered by OpenVZ