Skip to content

Commit 9e0471b

Browse files
committed
rust: error: Introduce ptr_to_result
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]>
1 parent df1e08b commit 9e0471b

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

rust/kernel/error.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,3 +85,21 @@ impl From<AllocError> for Error {
8585
Error::ENOMEM
8686
}
8787
}
88+
89+
/// Convert a kernel pointer to [`KernelResult`]
90+
///
91+
/// # Pointer value range
92+
///
93+
/// (According to include/linux/err.h)
94+
/// [0, .., `core::usize::MAX - bindings::MAX_ERRNO`) is the range for normal values of pointer,
95+
/// [`core::unsize::MAX - bindings::MAX_ERRNO`,..,`core::usize::MAX] is the range for error value
96+
/// stored in pointer.
97+
pub fn ptr_to_result<T>(ptr: *mut T) -> Result<*mut T, Error> {
98+
let value = ptr as usize;
99+
100+
if value >= core::usize::MAX - bindings::MAX_ERRNO as usize {
101+
Err(Error::from_kernel_errno(value as c_types::c_int))
102+
} else {
103+
Ok(ptr)
104+
}
105+
}

0 commit comments

Comments
 (0)