Skip to content

rust: iomem: add try_memcpy_fromio method for IoMem<T> #681

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions rust/helpers.c
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,13 @@ void rust_helper_writeq_relaxed(u64 value, volatile void __iomem *addr)
}
EXPORT_SYMBOL_GPL(rust_helper_writeq_relaxed);
#endif

void rust_helper_memcpy_fromio(void *to, const volatile void __iomem *from, long count)
{
memcpy_fromio(to, from, count);
}
EXPORT_SYMBOL_GPL(rust_helper_memcpy_fromio);

void rust_helper___spin_lock_init(spinlock_t *lock, const char *name,
struct lock_class_key *key)
{
Expand Down
39 changes: 39 additions & 0 deletions rust/kernel/io_mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,45 @@ impl<const SIZE: usize> IoMem<SIZE> {
crate::build_assert!(Self::offset_ok::<T>(offset), "IoMem offset overflow");
}

/// Copy memory block from an i/o memory by filling the specified buffer with it.
///
/// # Examples
/// ```
/// # use kernel::prelude::*;
/// use kernel::io_mem::{self, IoMem, Resource};
///
/// fn test(res: Resource) -> Result {
/// // Create an i/o memory block of at least 100 bytes.
/// let mem = unsafe { IoMem::<100>::try_new(res) }?;
///
/// let mut buffer: [u8; 32] = [0; 32];
///
/// // Memcpy 16 bytes from an offset 10 of i/o memory block into the buffer.
/// mem.try_memcpy_fromio(&mut buffer[..16], 10)?;
///
/// Ok(())
/// }
/// ```
pub fn try_memcpy_fromio(&self, buffer: &mut [u8], offset: usize) -> Result {
if !Self::offset_ok_of_val(offset, buffer) {
return Err(EINVAL);
}

let ptr = self.ptr.wrapping_add(offset);

// SAFETY:
// - The type invariants guarantee that `ptr` is a valid pointer.
// - The bounds of `buffer` are checked with a call to `offset_ok_of_val()`.
unsafe {
bindings::memcpy_fromio(
buffer.as_mut_ptr() as *mut _,
ptr as *const _,
buffer.len() as _,
)
};
Ok(())
}

define_read!(readb, try_readb, u8);
define_read!(readw, try_readw, u16);
define_read!(readl, try_readl, u32);
Expand Down