Loading...
1// SPDX-License-Identifier: GPL-2.0
2
3//! Kernel errors.
4//!
5//! C header: [`include/uapi/asm-generic/errno-base.h`](srctree/include/uapi/asm-generic/errno-base.h)
6
7use crate::str::CStr;
8
9use alloc::{
10 alloc::{AllocError, LayoutError},
11 collections::TryReserveError,
12};
13
14use core::convert::From;
15use core::fmt;
16use core::num::TryFromIntError;
17use core::str::Utf8Error;
18
19/// Contains the C-compatible error codes.
20#[rustfmt::skip]
21pub mod code {
22 macro_rules! declare_err {
23 ($err:tt $(,)? $($doc:expr),+) => {
24 $(
25 #[doc = $doc]
26 )*
27 pub const $err: super::Error = super::Error(-(crate::bindings::$err as i32));
28 };
29 }
30
31 declare_err!(EPERM, "Operation not permitted.");
32 declare_err!(ENOENT, "No such file or directory.");
33 declare_err!(ESRCH, "No such process.");
34 declare_err!(EINTR, "Interrupted system call.");
35 declare_err!(EIO, "I/O error.");
36 declare_err!(ENXIO, "No such device or address.");
37 declare_err!(E2BIG, "Argument list too long.");
38 declare_err!(ENOEXEC, "Exec format error.");
39 declare_err!(EBADF, "Bad file number.");
40 declare_err!(ECHILD, "No child processes.");
41 declare_err!(EAGAIN, "Try again.");
42 declare_err!(ENOMEM, "Out of memory.");
43 declare_err!(EACCES, "Permission denied.");
44 declare_err!(EFAULT, "Bad address.");
45 declare_err!(ENOTBLK, "Block device required.");
46 declare_err!(EBUSY, "Device or resource busy.");
47 declare_err!(EEXIST, "File exists.");
48 declare_err!(EXDEV, "Cross-device link.");
49 declare_err!(ENODEV, "No such device.");
50 declare_err!(ENOTDIR, "Not a directory.");
51 declare_err!(EISDIR, "Is a directory.");
52 declare_err!(EINVAL, "Invalid argument.");
53 declare_err!(ENFILE, "File table overflow.");
54 declare_err!(EMFILE, "Too many open files.");
55 declare_err!(ENOTTY, "Not a typewriter.");
56 declare_err!(ETXTBSY, "Text file busy.");
57 declare_err!(EFBIG, "File too large.");
58 declare_err!(ENOSPC, "No space left on device.");
59 declare_err!(ESPIPE, "Illegal seek.");
60 declare_err!(EROFS, "Read-only file system.");
61 declare_err!(EMLINK, "Too many links.");
62 declare_err!(EPIPE, "Broken pipe.");
63 declare_err!(EDOM, "Math argument out of domain of func.");
64 declare_err!(ERANGE, "Math result not representable.");
65 declare_err!(ERESTARTSYS, "Restart the system call.");
66 declare_err!(ERESTARTNOINTR, "System call was interrupted by a signal and will be restarted.");
67 declare_err!(ERESTARTNOHAND, "Restart if no handler.");
68 declare_err!(ENOIOCTLCMD, "No ioctl command.");
69 declare_err!(ERESTART_RESTARTBLOCK, "Restart by calling sys_restart_syscall.");
70 declare_err!(EPROBE_DEFER, "Driver requests probe retry.");
71 declare_err!(EOPENSTALE, "Open found a stale dentry.");
72 declare_err!(ENOPARAM, "Parameter not supported.");
73 declare_err!(EBADHANDLE, "Illegal NFS file handle.");
74 declare_err!(ENOTSYNC, "Update synchronization mismatch.");
75 declare_err!(EBADCOOKIE, "Cookie is stale.");
76 declare_err!(ENOTSUPP, "Operation is not supported.");
77 declare_err!(ETOOSMALL, "Buffer or request is too small.");
78 declare_err!(ESERVERFAULT, "An untranslatable error occurred.");
79 declare_err!(EBADTYPE, "Type not supported by server.");
80 declare_err!(EJUKEBOX, "Request initiated, but will not complete before timeout.");
81 declare_err!(EIOCBQUEUED, "iocb queued, will get completion event.");
82 declare_err!(ERECALLCONFLICT, "Conflict with recalled state.");
83 declare_err!(ENOGRACE, "NFS file lock reclaim refused.");
84}
85
86/// Generic integer kernel error.
87///
88/// The kernel defines a set of integer generic error codes based on C and
89/// POSIX ones. These codes may have a more specific meaning in some contexts.
90///
91/// # Invariants
92///
93/// The value is a valid `errno` (i.e. `>= -MAX_ERRNO && < 0`).
94#[derive(Clone, Copy, PartialEq, Eq)]
95pub struct Error(core::ffi::c_int);
96
97impl Error {
98 /// Creates an [`Error`] from a kernel error code.
99 ///
100 /// It is a bug to pass an out-of-range `errno`. `EINVAL` would
101 /// be returned in such a case.
102 pub(crate) fn from_errno(errno: core::ffi::c_int) -> Error {
103 if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
104 // TODO: Make it a `WARN_ONCE` once available.
105 crate::pr_warn!(
106 "attempted to create `Error` with out of range `errno`: {}",
107 errno
108 );
109 return code::EINVAL;
110 }
111
112 // INVARIANT: The check above ensures the type invariant
113 // will hold.
114 Error(errno)
115 }
116
117 /// Creates an [`Error`] from a kernel error code.
118 ///
119 /// # Safety
120 ///
121 /// `errno` must be within error code range (i.e. `>= -MAX_ERRNO && < 0`).
122 unsafe fn from_errno_unchecked(errno: core::ffi::c_int) -> Error {
123 // INVARIANT: The contract ensures the type invariant
124 // will hold.
125 Error(errno)
126 }
127
128 /// Returns the kernel error code.
129 pub fn to_errno(self) -> core::ffi::c_int {
130 self.0
131 }
132
133 /// Returns the error encoded as a pointer.
134 #[allow(dead_code)]
135 pub(crate) fn to_ptr<T>(self) -> *mut T {
136 // SAFETY: `self.0` is a valid error due to its invariant.
137 unsafe { bindings::ERR_PTR(self.0.into()) as *mut _ }
138 }
139
140 /// Returns a string representing the error, if one exists.
141 #[cfg(not(testlib))]
142 pub fn name(&self) -> Option<&'static CStr> {
143 // SAFETY: Just an FFI call, there are no extra safety requirements.
144 let ptr = unsafe { bindings::errname(-self.0) };
145 if ptr.is_null() {
146 None
147 } else {
148 // SAFETY: The string returned by `errname` is static and `NUL`-terminated.
149 Some(unsafe { CStr::from_char_ptr(ptr) })
150 }
151 }
152
153 /// Returns a string representing the error, if one exists.
154 ///
155 /// When `testlib` is configured, this always returns `None` to avoid the dependency on a
156 /// kernel function so that tests that use this (e.g., by calling [`Result::unwrap`]) can still
157 /// run in userspace.
158 #[cfg(testlib)]
159 pub fn name(&self) -> Option<&'static CStr> {
160 None
161 }
162}
163
164impl fmt::Debug for Error {
165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 match self.name() {
167 // Print out number if no name can be found.
168 None => f.debug_tuple("Error").field(&-self.0).finish(),
169 // SAFETY: These strings are ASCII-only.
170 Some(name) => f
171 .debug_tuple(unsafe { core::str::from_utf8_unchecked(name) })
172 .finish(),
173 }
174 }
175}
176
177impl From<AllocError> for Error {
178 fn from(_: AllocError) -> Error {
179 code::ENOMEM
180 }
181}
182
183impl From<TryFromIntError> for Error {
184 fn from(_: TryFromIntError) -> Error {
185 code::EINVAL
186 }
187}
188
189impl From<Utf8Error> for Error {
190 fn from(_: Utf8Error) -> Error {
191 code::EINVAL
192 }
193}
194
195impl From<TryReserveError> for Error {
196 fn from(_: TryReserveError) -> Error {
197 code::ENOMEM
198 }
199}
200
201impl From<LayoutError> for Error {
202 fn from(_: LayoutError) -> Error {
203 code::ENOMEM
204 }
205}
206
207impl From<core::fmt::Error> for Error {
208 fn from(_: core::fmt::Error) -> Error {
209 code::EINVAL
210 }
211}
212
213impl From<core::convert::Infallible> for Error {
214 fn from(e: core::convert::Infallible) -> Error {
215 match e {}
216 }
217}
218
219/// A [`Result`] with an [`Error`] error type.
220///
221/// To be used as the return type for functions that may fail.
222///
223/// # Error codes in C and Rust
224///
225/// In C, it is common that functions indicate success or failure through
226/// their return value; modifying or returning extra data through non-`const`
227/// pointer parameters. In particular, in the kernel, functions that may fail
228/// typically return an `int` that represents a generic error code. We model
229/// those as [`Error`].
230///
231/// In Rust, it is idiomatic to model functions that may fail as returning
232/// a [`Result`]. Since in the kernel many functions return an error code,
233/// [`Result`] is a type alias for a [`core::result::Result`] that uses
234/// [`Error`] as its error type.
235///
236/// Note that even if a function does not return anything when it succeeds,
237/// it should still be modeled as returning a `Result` rather than
238/// just an [`Error`].
239pub type Result<T = (), E = Error> = core::result::Result<T, E>;
240
241/// Converts an integer as returned by a C kernel function to an error if it's negative, and
242/// `Ok(())` otherwise.
243pub fn to_result(err: core::ffi::c_int) -> Result {
244 if err < 0 {
245 Err(Error::from_errno(err))
246 } else {
247 Ok(())
248 }
249}
250
251/// Transform a kernel "error pointer" to a normal pointer.
252///
253/// Some kernel C API functions return an "error pointer" which optionally
254/// embeds an `errno`. Callers are supposed to check the returned pointer
255/// for errors. This function performs the check and converts the "error pointer"
256/// to a normal pointer in an idiomatic fashion.
257///
258/// # Examples
259///
260/// ```ignore
261/// # use kernel::from_err_ptr;
262/// # use kernel::bindings;
263/// fn devm_platform_ioremap_resource(
264/// pdev: &mut PlatformDevice,
265/// index: u32,
266/// ) -> Result<*mut core::ffi::c_void> {
267/// // SAFETY: FFI call.
268/// unsafe {
269/// from_err_ptr(bindings::devm_platform_ioremap_resource(
270/// pdev.to_ptr(),
271/// index,
272/// ))
273/// }
274/// }
275/// ```
276// TODO: Remove `dead_code` marker once an in-kernel client is available.
277#[allow(dead_code)]
278pub(crate) fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
279 // CAST: Casting a pointer to `*const core::ffi::c_void` is always valid.
280 let const_ptr: *const core::ffi::c_void = ptr.cast();
281 // SAFETY: The FFI function does not deref the pointer.
282 if unsafe { bindings::IS_ERR(const_ptr) } {
283 // SAFETY: The FFI function does not deref the pointer.
284 let err = unsafe { bindings::PTR_ERR(const_ptr) };
285 // CAST: If `IS_ERR()` returns `true`,
286 // then `PTR_ERR()` is guaranteed to return a
287 // negative value greater-or-equal to `-bindings::MAX_ERRNO`,
288 // which always fits in an `i16`, as per the invariant above.
289 // And an `i16` always fits in an `i32`. So casting `err` to
290 // an `i32` can never overflow, and is always valid.
291 //
292 // SAFETY: `IS_ERR()` ensures `err` is a
293 // negative value greater-or-equal to `-bindings::MAX_ERRNO`.
294 #[allow(clippy::unnecessary_cast)]
295 return Err(unsafe { Error::from_errno_unchecked(err as core::ffi::c_int) });
296 }
297 Ok(ptr)
298}
299
300/// Calls a closure returning a [`crate::error::Result<T>`] and converts the result to
301/// a C integer result.
302///
303/// This is useful when calling Rust functions that return [`crate::error::Result<T>`]
304/// from inside `extern "C"` functions that need to return an integer error result.
305///
306/// `T` should be convertible from an `i16` via `From<i16>`.
307///
308/// # Examples
309///
310/// ```ignore
311/// # use kernel::from_result;
312/// # use kernel::bindings;
313/// unsafe extern "C" fn probe_callback(
314/// pdev: *mut bindings::platform_device,
315/// ) -> core::ffi::c_int {
316/// from_result(|| {
317/// let ptr = devm_alloc(pdev)?;
318/// bindings::platform_set_drvdata(pdev, ptr);
319/// Ok(0)
320/// })
321/// }
322/// ```
323// TODO: Remove `dead_code` marker once an in-kernel client is available.
324#[allow(dead_code)]
325pub(crate) fn from_result<T, F>(f: F) -> T
326where
327 T: From<i16>,
328 F: FnOnce() -> Result<T>,
329{
330 match f() {
331 Ok(v) => v,
332 // NO-OVERFLOW: negative `errno`s are no smaller than `-bindings::MAX_ERRNO`,
333 // `-bindings::MAX_ERRNO` fits in an `i16` as per invariant above,
334 // therefore a negative `errno` always fits in an `i16` and will not overflow.
335 Err(e) => T::from(e.to_errno() as i16),
336 }
337}
338
339/// Error message for calling a default function of a [`#[vtable]`](macros::vtable) trait.
340pub const VTABLE_DEFAULT_ERROR: &str =
341 "This function must not be called, see the #[vtable] documentation.";
1// SPDX-License-Identifier: GPL-2.0
2
3//! Kernel errors.
4//!
5//! C header: [`include/uapi/asm-generic/errno-base.h`](srctree/include/uapi/asm-generic/errno-base.h)
6
7use crate::{alloc::AllocError, str::CStr};
8
9use core::alloc::LayoutError;
10
11use core::fmt;
12use core::num::NonZeroI32;
13use core::num::TryFromIntError;
14use core::str::Utf8Error;
15
16/// Contains the C-compatible error codes.
17#[rustfmt::skip]
18pub mod code {
19 macro_rules! declare_err {
20 ($err:tt $(,)? $($doc:expr),+) => {
21 $(
22 #[doc = $doc]
23 )*
24 pub const $err: super::Error =
25 match super::Error::try_from_errno(-(crate::bindings::$err as i32)) {
26 Some(err) => err,
27 None => panic!("Invalid errno in `declare_err!`"),
28 };
29 };
30 }
31
32 declare_err!(EPERM, "Operation not permitted.");
33 declare_err!(ENOENT, "No such file or directory.");
34 declare_err!(ESRCH, "No such process.");
35 declare_err!(EINTR, "Interrupted system call.");
36 declare_err!(EIO, "I/O error.");
37 declare_err!(ENXIO, "No such device or address.");
38 declare_err!(E2BIG, "Argument list too long.");
39 declare_err!(ENOEXEC, "Exec format error.");
40 declare_err!(EBADF, "Bad file number.");
41 declare_err!(ECHILD, "No child processes.");
42 declare_err!(EAGAIN, "Try again.");
43 declare_err!(ENOMEM, "Out of memory.");
44 declare_err!(EACCES, "Permission denied.");
45 declare_err!(EFAULT, "Bad address.");
46 declare_err!(ENOTBLK, "Block device required.");
47 declare_err!(EBUSY, "Device or resource busy.");
48 declare_err!(EEXIST, "File exists.");
49 declare_err!(EXDEV, "Cross-device link.");
50 declare_err!(ENODEV, "No such device.");
51 declare_err!(ENOTDIR, "Not a directory.");
52 declare_err!(EISDIR, "Is a directory.");
53 declare_err!(EINVAL, "Invalid argument.");
54 declare_err!(ENFILE, "File table overflow.");
55 declare_err!(EMFILE, "Too many open files.");
56 declare_err!(ENOTTY, "Not a typewriter.");
57 declare_err!(ETXTBSY, "Text file busy.");
58 declare_err!(EFBIG, "File too large.");
59 declare_err!(ENOSPC, "No space left on device.");
60 declare_err!(ESPIPE, "Illegal seek.");
61 declare_err!(EROFS, "Read-only file system.");
62 declare_err!(EMLINK, "Too many links.");
63 declare_err!(EPIPE, "Broken pipe.");
64 declare_err!(EDOM, "Math argument out of domain of func.");
65 declare_err!(ERANGE, "Math result not representable.");
66 declare_err!(ERESTARTSYS, "Restart the system call.");
67 declare_err!(ERESTARTNOINTR, "System call was interrupted by a signal and will be restarted.");
68 declare_err!(ERESTARTNOHAND, "Restart if no handler.");
69 declare_err!(ENOIOCTLCMD, "No ioctl command.");
70 declare_err!(ERESTART_RESTARTBLOCK, "Restart by calling sys_restart_syscall.");
71 declare_err!(EPROBE_DEFER, "Driver requests probe retry.");
72 declare_err!(EOPENSTALE, "Open found a stale dentry.");
73 declare_err!(ENOPARAM, "Parameter not supported.");
74 declare_err!(EBADHANDLE, "Illegal NFS file handle.");
75 declare_err!(ENOTSYNC, "Update synchronization mismatch.");
76 declare_err!(EBADCOOKIE, "Cookie is stale.");
77 declare_err!(ENOTSUPP, "Operation is not supported.");
78 declare_err!(ETOOSMALL, "Buffer or request is too small.");
79 declare_err!(ESERVERFAULT, "An untranslatable error occurred.");
80 declare_err!(EBADTYPE, "Type not supported by server.");
81 declare_err!(EJUKEBOX, "Request initiated, but will not complete before timeout.");
82 declare_err!(EIOCBQUEUED, "iocb queued, will get completion event.");
83 declare_err!(ERECALLCONFLICT, "Conflict with recalled state.");
84 declare_err!(ENOGRACE, "NFS file lock reclaim refused.");
85}
86
87/// Generic integer kernel error.
88///
89/// The kernel defines a set of integer generic error codes based on C and
90/// POSIX ones. These codes may have a more specific meaning in some contexts.
91///
92/// # Invariants
93///
94/// The value is a valid `errno` (i.e. `>= -MAX_ERRNO && < 0`).
95#[derive(Clone, Copy, PartialEq, Eq)]
96pub struct Error(NonZeroI32);
97
98impl Error {
99 /// Creates an [`Error`] from a kernel error code.
100 ///
101 /// It is a bug to pass an out-of-range `errno`. `EINVAL` would
102 /// be returned in such a case.
103 pub fn from_errno(errno: crate::ffi::c_int) -> Error {
104 if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
105 // TODO: Make it a `WARN_ONCE` once available.
106 crate::pr_warn!(
107 "attempted to create `Error` with out of range `errno`: {}",
108 errno
109 );
110 return code::EINVAL;
111 }
112
113 // INVARIANT: The check above ensures the type invariant
114 // will hold.
115 // SAFETY: `errno` is checked above to be in a valid range.
116 unsafe { Error::from_errno_unchecked(errno) }
117 }
118
119 /// Creates an [`Error`] from a kernel error code.
120 ///
121 /// Returns [`None`] if `errno` is out-of-range.
122 const fn try_from_errno(errno: crate::ffi::c_int) -> Option<Error> {
123 if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
124 return None;
125 }
126
127 // SAFETY: `errno` is checked above to be in a valid range.
128 Some(unsafe { Error::from_errno_unchecked(errno) })
129 }
130
131 /// Creates an [`Error`] from a kernel error code.
132 ///
133 /// # Safety
134 ///
135 /// `errno` must be within error code range (i.e. `>= -MAX_ERRNO && < 0`).
136 const unsafe fn from_errno_unchecked(errno: crate::ffi::c_int) -> Error {
137 // INVARIANT: The contract ensures the type invariant
138 // will hold.
139 // SAFETY: The caller guarantees `errno` is non-zero.
140 Error(unsafe { NonZeroI32::new_unchecked(errno) })
141 }
142
143 /// Returns the kernel error code.
144 pub fn to_errno(self) -> crate::ffi::c_int {
145 self.0.get()
146 }
147
148 #[cfg(CONFIG_BLOCK)]
149 pub(crate) fn to_blk_status(self) -> bindings::blk_status_t {
150 // SAFETY: `self.0` is a valid error due to its invariant.
151 unsafe { bindings::errno_to_blk_status(self.0.get()) }
152 }
153
154 /// Returns the error encoded as a pointer.
155 pub fn to_ptr<T>(self) -> *mut T {
156 // SAFETY: `self.0` is a valid error due to its invariant.
157 unsafe { bindings::ERR_PTR(self.0.get() as _) as *mut _ }
158 }
159
160 /// Returns a string representing the error, if one exists.
161 #[cfg(not(any(test, testlib)))]
162 pub fn name(&self) -> Option<&'static CStr> {
163 // SAFETY: Just an FFI call, there are no extra safety requirements.
164 let ptr = unsafe { bindings::errname(-self.0.get()) };
165 if ptr.is_null() {
166 None
167 } else {
168 // SAFETY: The string returned by `errname` is static and `NUL`-terminated.
169 Some(unsafe { CStr::from_char_ptr(ptr) })
170 }
171 }
172
173 /// Returns a string representing the error, if one exists.
174 ///
175 /// When `testlib` is configured, this always returns `None` to avoid the dependency on a
176 /// kernel function so that tests that use this (e.g., by calling [`Result::unwrap`]) can still
177 /// run in userspace.
178 #[cfg(any(test, testlib))]
179 pub fn name(&self) -> Option<&'static CStr> {
180 None
181 }
182}
183
184impl fmt::Debug for Error {
185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186 match self.name() {
187 // Print out number if no name can be found.
188 None => f.debug_tuple("Error").field(&-self.0).finish(),
189 Some(name) => f
190 .debug_tuple(
191 // SAFETY: These strings are ASCII-only.
192 unsafe { core::str::from_utf8_unchecked(name) },
193 )
194 .finish(),
195 }
196 }
197}
198
199impl From<AllocError> for Error {
200 fn from(_: AllocError) -> Error {
201 code::ENOMEM
202 }
203}
204
205impl From<TryFromIntError> for Error {
206 fn from(_: TryFromIntError) -> Error {
207 code::EINVAL
208 }
209}
210
211impl From<Utf8Error> for Error {
212 fn from(_: Utf8Error) -> Error {
213 code::EINVAL
214 }
215}
216
217impl From<LayoutError> for Error {
218 fn from(_: LayoutError) -> Error {
219 code::ENOMEM
220 }
221}
222
223impl From<core::fmt::Error> for Error {
224 fn from(_: core::fmt::Error) -> Error {
225 code::EINVAL
226 }
227}
228
229impl From<core::convert::Infallible> for Error {
230 fn from(e: core::convert::Infallible) -> Error {
231 match e {}
232 }
233}
234
235/// A [`Result`] with an [`Error`] error type.
236///
237/// To be used as the return type for functions that may fail.
238///
239/// # Error codes in C and Rust
240///
241/// In C, it is common that functions indicate success or failure through
242/// their return value; modifying or returning extra data through non-`const`
243/// pointer parameters. In particular, in the kernel, functions that may fail
244/// typically return an `int` that represents a generic error code. We model
245/// those as [`Error`].
246///
247/// In Rust, it is idiomatic to model functions that may fail as returning
248/// a [`Result`]. Since in the kernel many functions return an error code,
249/// [`Result`] is a type alias for a [`core::result::Result`] that uses
250/// [`Error`] as its error type.
251///
252/// Note that even if a function does not return anything when it succeeds,
253/// it should still be modeled as returning a `Result` rather than
254/// just an [`Error`].
255pub type Result<T = (), E = Error> = core::result::Result<T, E>;
256
257/// Converts an integer as returned by a C kernel function to an error if it's negative, and
258/// `Ok(())` otherwise.
259pub fn to_result(err: crate::ffi::c_int) -> Result {
260 if err < 0 {
261 Err(Error::from_errno(err))
262 } else {
263 Ok(())
264 }
265}
266
267/// Transform a kernel "error pointer" to a normal pointer.
268///
269/// Some kernel C API functions return an "error pointer" which optionally
270/// embeds an `errno`. Callers are supposed to check the returned pointer
271/// for errors. This function performs the check and converts the "error pointer"
272/// to a normal pointer in an idiomatic fashion.
273///
274/// # Examples
275///
276/// ```ignore
277/// # use kernel::from_err_ptr;
278/// # use kernel::bindings;
279/// fn devm_platform_ioremap_resource(
280/// pdev: &mut PlatformDevice,
281/// index: u32,
282/// ) -> Result<*mut kernel::ffi::c_void> {
283/// // SAFETY: `pdev` points to a valid platform device. There are no safety requirements
284/// // on `index`.
285/// from_err_ptr(unsafe { bindings::devm_platform_ioremap_resource(pdev.to_ptr(), index) })
286/// }
287/// ```
288pub fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
289 // CAST: Casting a pointer to `*const crate::ffi::c_void` is always valid.
290 let const_ptr: *const crate::ffi::c_void = ptr.cast();
291 // SAFETY: The FFI function does not deref the pointer.
292 if unsafe { bindings::IS_ERR(const_ptr) } {
293 // SAFETY: The FFI function does not deref the pointer.
294 let err = unsafe { bindings::PTR_ERR(const_ptr) };
295
296 #[allow(clippy::unnecessary_cast)]
297 // CAST: If `IS_ERR()` returns `true`,
298 // then `PTR_ERR()` is guaranteed to return a
299 // negative value greater-or-equal to `-bindings::MAX_ERRNO`,
300 // which always fits in an `i16`, as per the invariant above.
301 // And an `i16` always fits in an `i32`. So casting `err` to
302 // an `i32` can never overflow, and is always valid.
303 //
304 // SAFETY: `IS_ERR()` ensures `err` is a
305 // negative value greater-or-equal to `-bindings::MAX_ERRNO`.
306 return Err(unsafe { Error::from_errno_unchecked(err as crate::ffi::c_int) });
307 }
308 Ok(ptr)
309}
310
311/// Calls a closure returning a [`crate::error::Result<T>`] and converts the result to
312/// a C integer result.
313///
314/// This is useful when calling Rust functions that return [`crate::error::Result<T>`]
315/// from inside `extern "C"` functions that need to return an integer error result.
316///
317/// `T` should be convertible from an `i16` via `From<i16>`.
318///
319/// # Examples
320///
321/// ```ignore
322/// # use kernel::from_result;
323/// # use kernel::bindings;
324/// unsafe extern "C" fn probe_callback(
325/// pdev: *mut bindings::platform_device,
326/// ) -> kernel::ffi::c_int {
327/// from_result(|| {
328/// let ptr = devm_alloc(pdev)?;
329/// bindings::platform_set_drvdata(pdev, ptr);
330/// Ok(0)
331/// })
332/// }
333/// ```
334pub fn from_result<T, F>(f: F) -> T
335where
336 T: From<i16>,
337 F: FnOnce() -> Result<T>,
338{
339 match f() {
340 Ok(v) => v,
341 // NO-OVERFLOW: negative `errno`s are no smaller than `-bindings::MAX_ERRNO`,
342 // `-bindings::MAX_ERRNO` fits in an `i16` as per invariant above,
343 // therefore a negative `errno` always fits in an `i16` and will not overflow.
344 Err(e) => T::from(e.to_errno() as i16),
345 }
346}
347
348/// Error message for calling a default function of a [`#[vtable]`](macros::vtable) trait.
349pub const VTABLE_DEFAULT_ERROR: &str =
350 "This function must not be called, see the #[vtable] documentation.";