Re: [PATCH v8 2/2] rust: add dma coherent allocator abstraction.

Thomas Hampton
2025-02-04T16:54:21Z

On 1/8/2025 6:27 AM, Abdiel Janulgue wrote:

> + /// Returns the base address, dma handle, attributes and the size of the allocated region.
> + /// The caller takes ownership of the returned resources, i.e., will have the responsibility
> + /// in calling `bindings::dma_free_attrs`.
> + pub fn into_parts(self) -> (*mut T, bindings::dma_addr_t, usize, usize) {
> + let size = self.count * core::mem::size_of::<T>();
> + let ret = (
> + self.cpu_addr,
> + self.dma_handle,
> + self.dma_attrs.as_raw(),
> + size,
> + );
> + // Drop the device's reference count associated with this object. This is needed as no
> + // destructor will be called on this object once this function returns.
> + // SAFETY: the device pointer is still valid as of this point due to the type invariants
> + // on `CoherentAllocation`.
> + unsafe { bindings::put_device(self.dev.as_raw()) }
> + core::mem::forget(self);
> + ret
> + }

Would it be feasible and prudent to avoid exposing `pub fn
into_parts`, `pub fn first_ptr`, `pub fn first_ptr_mut`?

It seems like some sort of functional access method might be better
for keeping future Rust code maintainable and Rusty.

For example, making client code from:

> {
> let ctrl_id = unsafe { &*(id.first_ptr() as *const NvmeIdCtrl) };
> number_of_namespaces = ctrl_id.nn.into();
> mdts = ctrl_id.mdts;
> }

Into something like,
pub fn expose(self, op: F)
where F: Fn(*const T) {
op(self.cpu_addr);
}

let number_of_namespaces;
let mdts;
id.expose(|data| {
let ctrl_id = &*(data as *const NvmeIdCtrl);
number_of_namespaces = ctrl_id.nn.into();
mdts = ctrl_id.mdts;
});

And to avoid code docs like:

> /// The caller <...> will have the responsibility in calling `bindings::dma_free_attrs`.