Skip to content

Commit

Permalink
rust: error: Introduce ptr_to_result
Browse files Browse the repository at this point in the history
Some of the kernel functions use a part of the pointer value range to
carry the error information, introduce `ptr_to_result` to decipher.

Signed-off-by: Boqun Feng <[email protected]>
  • Loading branch information
fbq committed Mar 19, 2021
1 parent af81ad9 commit 6f75590
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions rust/kernel/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,21 @@ impl From<AllocError> for Error {
Error::ENOMEM
}
}

/// Convert a kernel pointer to [`KernelResult`]
///
/// # Pointer value range
///
/// (According to include/linux/err.h)
/// [0, .., `core::usize::MAX - bindings::MAX_ERRNO`) is the range for normal values of pointer,
/// [`core::unsize::MAX - bindings::MAX_ERRNO`,..,`core::usize::MAX] is the range for error value
/// stored in pointer.
pub fn ptr_to_result<T>(ptr: *mut T) -> Result<*mut T, Error> {
let value = ptr as usize;

if value >= core::usize::MAX - bindings::MAX_ERRNO as usize {
Err(Error::from_kernel_errno(value as c_types::c_int))
} else {
Ok(ptr)
}
}

0 comments on commit 6f75590

Please sign in to comment.