Skip to content

Commit 26af856

Browse files
GnurouDanilo Krummrich
authored andcommitted
rust: dma: add dma_handle_with_offset method to CoherentAllocation
Sometimes one may want to obtain a DMA handle starting at a given offset. This can be done by adding said offset to the result of `dma_handle()`, but doing so on the client side carries the risk that the operation will go outside the bounds of the allocation. Thus, add a `dma_handle_with_offset` method that adds the desired offset after checking that it is still valid. Signed-off-by: Alexandre Courbot <acourbot@nvidia.com> Link: https://lore.kernel.org/r/20250619-nova-frts-v6-3-ecf41ef99252@nvidia.com Signed-off-by: Danilo Krummrich <dakr@kernel.org>
1 parent c0a3065 commit 26af856

1 file changed

Lines changed: 14 additions & 0 deletions

File tree

rust/kernel/dma.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,20 @@ impl<T: AsBytes + FromBytes> CoherentAllocation<T> {
238238
self.dma_handle
239239
}
240240

241+
/// Returns a DMA handle starting at `offset` (in units of `T`) which may be given to the
242+
/// device as the DMA address base of the region.
243+
///
244+
/// Returns `EINVAL` if `offset` is not within the bounds of the allocation.
245+
pub fn dma_handle_with_offset(&self, offset: usize) -> Result<bindings::dma_addr_t> {
246+
if offset >= self.count {
247+
Err(EINVAL)
248+
} else {
249+
// INVARIANT: The type invariant of `Self` guarantees that `size_of::<T> * count` fits
250+
// into a `usize`, and `offset` is inferior to `count`.
251+
Ok(self.dma_handle + (offset * core::mem::size_of::<T>()) as bindings::dma_addr_t)
252+
}
253+
}
254+
241255
/// Common helper to validate a range applied from the allocated region in the CPU's virtual
242256
/// address space.
243257
fn validate_range(&self, offset: usize, count: usize) -> Result {

0 commit comments

Comments
 (0)