kernel/error.rs
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//! C header: [`include/uapi/asm-generic/errno.h`](srctree/include/uapi/asm-generic/errno.h)\
7//! C header: [`include/linux/errno.h`](srctree/include/linux/errno.h)
8
9use crate::{
10 alloc::{layout::LayoutError, AllocError},
11 fmt,
12 str::CStr,
13};
14
15use core::num::NonZeroI32;
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 =
28 super::Error::try_from_errno(-(crate::bindings::$err as i32))
29 .expect("Invalid errno in `declare_err!`");
30 };
31 }
32
33 // From `include/uapi/asm-generic/errno-base.h`.
34 declare_err!(EPERM, "Operation not permitted.");
35 declare_err!(ENOENT, "No such file or directory.");
36 declare_err!(ESRCH, "No such process.");
37 declare_err!(EINTR, "Interrupted system call.");
38 declare_err!(EIO, "I/O error.");
39 declare_err!(ENXIO, "No such device or address.");
40 declare_err!(E2BIG, "Argument list too long.");
41 declare_err!(ENOEXEC, "Exec format error.");
42 declare_err!(EBADF, "Bad file number.");
43 declare_err!(ECHILD, "No child processes.");
44 declare_err!(EAGAIN, "Try again.");
45 declare_err!(ENOMEM, "Out of memory.");
46 declare_err!(EACCES, "Permission denied.");
47 declare_err!(EFAULT, "Bad address.");
48 declare_err!(ENOTBLK, "Block device required.");
49 declare_err!(EBUSY, "Device or resource busy.");
50 declare_err!(EEXIST, "File exists.");
51 declare_err!(EXDEV, "Cross-device link.");
52 declare_err!(ENODEV, "No such device.");
53 declare_err!(ENOTDIR, "Not a directory.");
54 declare_err!(EISDIR, "Is a directory.");
55 declare_err!(EINVAL, "Invalid argument.");
56 declare_err!(ENFILE, "File table overflow.");
57 declare_err!(EMFILE, "Too many open files.");
58 declare_err!(ENOTTY, "Not a typewriter.");
59 declare_err!(ETXTBSY, "Text file busy.");
60 declare_err!(EFBIG, "File too large.");
61 declare_err!(ENOSPC, "No space left on device.");
62 declare_err!(ESPIPE, "Illegal seek.");
63 declare_err!(EROFS, "Read-only file system.");
64 declare_err!(EMLINK, "Too many links.");
65 declare_err!(EPIPE, "Broken pipe.");
66 declare_err!(EDOM, "Math argument out of domain of func.");
67 declare_err!(ERANGE, "Math result not representable.");
68
69 // From `include/uapi/asm-generic/errno.h`.
70 declare_err!(EDEADLK, "Resource deadlock would occur.");
71 declare_err!(ENAMETOOLONG, "File name too long.");
72 declare_err!(ENOLCK, "No record locks available.");
73 declare_err!(ENOSYS, "Invalid system call number.");
74 declare_err!(ENOTEMPTY, "Directory not empty.");
75 declare_err!(ELOOP, "Too many symbolic links encountered.");
76 declare_err!(ENOMSG, "No message of desired type.");
77 declare_err!(EIDRM, "Identifier removed.");
78 declare_err!(ECHRNG, "Channel number out of range.");
79 declare_err!(EL2NSYNC, "Level 2 not synchronized.");
80 declare_err!(EL3HLT, "Level 3 halted.");
81 declare_err!(EL3RST, "Level 3 reset.");
82 declare_err!(ELNRNG, "Link number out of range.");
83 declare_err!(EUNATCH, "Protocol driver not attached.");
84 declare_err!(ENOCSI, "No CSI structure available.");
85 declare_err!(EL2HLT, "Level 2 halted.");
86 declare_err!(EBADE, "Invalid exchange.");
87 declare_err!(EBADR, "Invalid request descriptor.");
88 declare_err!(EXFULL, "Exchange full.");
89 declare_err!(ENOANO, "No anode.");
90 declare_err!(EBADRQC, "Invalid request code.");
91 declare_err!(EBADSLT, "Invalid slot.");
92 declare_err!(EBFONT, "Bad font file format.");
93 declare_err!(ENOSTR, "Device not a stream.");
94 declare_err!(ENODATA, "No data available.");
95 declare_err!(ETIME, "Timer expired.");
96 declare_err!(ENOSR, "Out of streams resources.");
97 declare_err!(ENONET, "Machine is not on the network.");
98 declare_err!(ENOPKG, "Package not installed.");
99 declare_err!(EREMOTE, "Object is remote.");
100 declare_err!(ENOLINK, "Link has been severed.");
101 declare_err!(EADV, "Advertise error.");
102 declare_err!(ESRMNT, "Srmount error.");
103 declare_err!(ECOMM, "Communication error on send.");
104 declare_err!(EPROTO, "Protocol error.");
105 declare_err!(EMULTIHOP, "Multihop attempted.");
106 declare_err!(EDOTDOT, "RFS specific error.");
107 declare_err!(EBADMSG, "Not a data message.");
108 declare_err!(EFSBADCRC, "Bad CRC detected.");
109 declare_err!(EOVERFLOW, "Value too large for defined data type.");
110 declare_err!(ENOTUNIQ, "Name not unique on network.");
111 declare_err!(EBADFD, "File descriptor in bad state.");
112 declare_err!(EREMCHG, "Remote address changed.");
113 declare_err!(ELIBACC, "Can not access a needed shared library.");
114 declare_err!(ELIBBAD, "Accessing a corrupted shared library.");
115 declare_err!(ELIBSCN, ".lib section in a.out corrupted.");
116 declare_err!(ELIBMAX, "Attempting to link in too many shared libraries.");
117 declare_err!(ELIBEXEC, "Cannot exec a shared library directly.");
118 declare_err!(EILSEQ, "Illegal byte sequence.");
119 declare_err!(ERESTART, "Interrupted system call should be restarted.");
120 declare_err!(ESTRPIPE, "Streams pipe error.");
121 declare_err!(EUSERS, "Too many users.");
122 declare_err!(ENOTSOCK, "Socket operation on non-socket.");
123 declare_err!(EDESTADDRREQ, "Destination address required.");
124 declare_err!(EMSGSIZE, "Message too long.");
125 declare_err!(EPROTOTYPE, "Protocol wrong type for socket.");
126 declare_err!(ENOPROTOOPT, "Protocol not available.");
127 declare_err!(EPROTONOSUPPORT, "Protocol not supported.");
128 declare_err!(ESOCKTNOSUPPORT, "Socket type not supported.");
129 declare_err!(EOPNOTSUPP, "Operation not supported on transport endpoint.");
130 declare_err!(EPFNOSUPPORT, "Protocol family not supported.");
131 declare_err!(EAFNOSUPPORT, "Address family not supported by protocol.");
132 declare_err!(EADDRINUSE, "Address already in use.");
133 declare_err!(EADDRNOTAVAIL, "Cannot assign requested address.");
134 declare_err!(ENETDOWN, "Network is down.");
135 declare_err!(ENETUNREACH, "Network is unreachable.");
136 declare_err!(ENETRESET, "Network dropped connection because of reset.");
137 declare_err!(ECONNABORTED, "Software caused connection abort.");
138 declare_err!(ECONNRESET, "Connection reset by peer.");
139 declare_err!(ENOBUFS, "No buffer space available.");
140 declare_err!(EISCONN, "Transport endpoint is already connected.");
141 declare_err!(ENOTCONN, "Transport endpoint is not connected.");
142 declare_err!(ESHUTDOWN, "Cannot send after transport endpoint shutdown.");
143 declare_err!(ETOOMANYREFS, "Too many references: cannot splice.");
144 declare_err!(ETIMEDOUT, "Connection timed out.");
145 declare_err!(ECONNREFUSED, "Connection refused.");
146 declare_err!(EHOSTDOWN, "Host is down.");
147 declare_err!(EHOSTUNREACH, "No route to host.");
148 declare_err!(EALREADY, "Operation already in progress.");
149 declare_err!(EINPROGRESS, "Operation now in progress.");
150 declare_err!(ESTALE, "Stale file handle.");
151 declare_err!(EUCLEAN, "Structure needs cleaning.");
152 declare_err!(EFSCORRUPTED, "Filesystem is corrupted.");
153 declare_err!(ENOTNAM, "Not a XENIX named type file.");
154 declare_err!(ENAVAIL, "No XENIX semaphores available.");
155 declare_err!(EISNAM, "Is a named type file.");
156 declare_err!(EREMOTEIO, "Remote I/O error.");
157 declare_err!(EDQUOT, "Quota exceeded.");
158 declare_err!(ENOMEDIUM, "No medium found.");
159 declare_err!(EMEDIUMTYPE, "Wrong medium type.");
160 declare_err!(ECANCELED, "Operation Canceled.");
161 declare_err!(ENOKEY, "Required key not available.");
162 declare_err!(EKEYEXPIRED, "Key has expired.");
163 declare_err!(EKEYREVOKED, "Key has been revoked.");
164 declare_err!(EKEYREJECTED, "Key was rejected by service.");
165 declare_err!(EOWNERDEAD, "Owner died.");
166 declare_err!(ENOTRECOVERABLE, "State not recoverable.");
167 declare_err!(ERFKILL, "Operation not possible due to RF-kill.");
168 declare_err!(EHWPOISON, "Memory page has hardware error.");
169 declare_err!(EFTYPE, "Wrong file type for the intended operation.");
170
171 // From `include/linux/errno.h`.
172 declare_err!(ERESTARTSYS, "Restart the system call.");
173 declare_err!(ERESTARTNOINTR, "System call was interrupted by a signal and will be restarted.");
174 declare_err!(ERESTARTNOHAND, "Restart if no handler.");
175 declare_err!(ENOIOCTLCMD, "No ioctl command.");
176 declare_err!(ERESTART_RESTARTBLOCK, "Restart by calling sys_restart_syscall.");
177 declare_err!(EPROBE_DEFER, "Driver requests probe retry.");
178 declare_err!(EOPENSTALE, "Open found a stale dentry.");
179 declare_err!(ENOPARAM, "Parameter not supported.");
180 declare_err!(EBADHANDLE, "Illegal NFS file handle.");
181 declare_err!(ENOTSYNC, "Update synchronization mismatch.");
182 declare_err!(EBADCOOKIE, "Cookie is stale.");
183 declare_err!(ENOTSUPP, "Operation is not supported.");
184 declare_err!(ETOOSMALL, "Buffer or request is too small.");
185 declare_err!(ESERVERFAULT, "An untranslatable error occurred.");
186 declare_err!(EBADTYPE, "Type not supported by server.");
187 declare_err!(EJUKEBOX, "Request initiated, but will not complete before timeout.");
188 declare_err!(EIOCBQUEUED, "iocb queued, will get completion event.");
189 declare_err!(ERECALLCONFLICT, "Conflict with recalled state.");
190 declare_err!(ENOGRACE, "NFS file lock reclaim refused.");
191}
192
193/// Generic integer kernel error.
194///
195/// The kernel defines a set of integer generic error codes based on C and
196/// POSIX ones. These codes may have a more specific meaning in some contexts.
197///
198/// # Invariants
199///
200/// The value is a valid `errno` (i.e. `>= -MAX_ERRNO && < 0`).
201#[derive(Clone, Copy, PartialEq, Eq)]
202#[repr(transparent)]
203pub struct Error(NonZeroI32);
204
205// SAFETY: `Error` is `repr(transparent)` over `NonZeroI32`, which is part of the option layout
206// optimization guarantee, so all zeroes is a valid representation for `None`.
207unsafe impl pin_init::ZeroableOption for Error {}
208
209impl Error {
210 /// Creates an [`Error`] from a kernel error code.
211 ///
212 /// `errno` must be within error code range (i.e. `>= -MAX_ERRNO && < 0`).
213 ///
214 /// It is a bug to pass an out-of-range `errno`. [`code::EINVAL`] is returned in such a case.
215 ///
216 /// # Examples
217 ///
218 /// ```
219 /// assert_eq!(Error::from_errno(-1), EPERM);
220 /// assert_eq!(Error::from_errno(-2), ENOENT);
221 /// ```
222 ///
223 /// The following calls are considered a bug:
224 ///
225 /// ```
226 /// assert_eq!(Error::from_errno(0), EINVAL);
227 /// assert_eq!(Error::from_errno(-1000000), EINVAL);
228 /// ```
229 pub fn from_errno(errno: crate::ffi::c_int) -> Error {
230 if let Some(error) = Self::try_from_errno(errno) {
231 error
232 } else {
233 // TODO: Make it a `WARN_ONCE` once available.
234 crate::pr_warn!(
235 "attempted to create `Error` with out of range `errno`: {}\n",
236 errno
237 );
238 code::EINVAL
239 }
240 }
241
242 /// Creates an [`Error`] from a kernel error code.
243 ///
244 /// Returns [`None`] if `errno` is out-of-range.
245 const fn try_from_errno(errno: crate::ffi::c_int) -> Option<Error> {
246 if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
247 return None;
248 }
249
250 // SAFETY: `errno` is checked above to be in a valid range.
251 Some(unsafe { Error::from_errno_unchecked(errno) })
252 }
253
254 /// Creates an [`Error`] from a kernel error code.
255 ///
256 /// # Safety
257 ///
258 /// `errno` must be within error code range (i.e. `>= -MAX_ERRNO && < 0`).
259 const unsafe fn from_errno_unchecked(errno: crate::ffi::c_int) -> Error {
260 // INVARIANT: The contract ensures the type invariant
261 // will hold.
262 // SAFETY: The caller guarantees `errno` is non-zero.
263 Error(unsafe { NonZeroI32::new_unchecked(errno) })
264 }
265
266 /// Returns the kernel error code.
267 pub fn to_errno(self) -> crate::ffi::c_int {
268 self.0.get()
269 }
270
271 #[cfg(CONFIG_BLOCK)]
272 pub(crate) fn to_blk_status(self) -> bindings::blk_status_t {
273 // SAFETY: `self.0` is a valid error due to its invariant.
274 unsafe { bindings::errno_to_blk_status(self.0.get()) }
275 }
276
277 /// Returns the error encoded as a pointer.
278 pub fn to_ptr<T>(self) -> *mut T {
279 // SAFETY: `self.0` is a valid error due to its invariant.
280 unsafe { bindings::ERR_PTR(self.0.get() as crate::ffi::c_long).cast() }
281 }
282
283 /// Returns a string representing the error, if one exists.
284 #[cfg(not(testlib))]
285 pub fn name(&self) -> Option<&'static CStr> {
286 // SAFETY: Just an FFI call, there are no extra safety requirements.
287 let ptr = unsafe { bindings::errname(-self.0.get()) };
288 if ptr.is_null() {
289 None
290 } else {
291 use crate::str::CStrExt as _;
292
293 // SAFETY: The string returned by `errname` is static and `NUL`-terminated.
294 Some(unsafe { CStr::from_char_ptr(ptr) })
295 }
296 }
297
298 /// Returns a string representing the error, if one exists.
299 ///
300 /// When `testlib` is configured, this always returns `None` to avoid the dependency on a
301 /// kernel function so that tests that use this (e.g., by calling [`Result::unwrap`]) can still
302 /// run in userspace.
303 #[cfg(testlib)]
304 pub fn name(&self) -> Option<&'static CStr> {
305 None
306 }
307}
308
309impl fmt::Debug for Error {
310 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311 match self.name() {
312 // Print out number if no name can be found.
313 None => f.debug_tuple("Error").field(&-self.0).finish(),
314 Some(name) => f
315 .debug_tuple(
316 // SAFETY: These strings are ASCII-only.
317 unsafe { core::str::from_utf8_unchecked(name.to_bytes()) },
318 )
319 .finish(),
320 }
321 }
322}
323
324impl From<AllocError> for Error {
325 #[inline]
326 fn from(_: AllocError) -> Error {
327 code::ENOMEM
328 }
329}
330
331impl From<TryFromIntError> for Error {
332 #[inline]
333 fn from(_: TryFromIntError) -> Error {
334 code::EINVAL
335 }
336}
337
338impl From<Utf8Error> for Error {
339 #[inline]
340 fn from(_: Utf8Error) -> Error {
341 code::EINVAL
342 }
343}
344
345impl From<LayoutError> for Error {
346 #[inline]
347 fn from(_: LayoutError) -> Error {
348 code::ENOMEM
349 }
350}
351
352impl From<fmt::Error> for Error {
353 #[inline]
354 fn from(_: fmt::Error) -> Error {
355 code::EINVAL
356 }
357}
358
359impl From<core::convert::Infallible> for Error {
360 #[inline]
361 fn from(e: core::convert::Infallible) -> Error {
362 match e {}
363 }
364}
365
366/// A [`Result`] with an [`Error`] error type.
367///
368/// To be used as the return type for functions that may fail.
369///
370/// # Error codes in C and Rust
371///
372/// In C, it is common that functions indicate success or failure through
373/// their return value; modifying or returning extra data through non-`const`
374/// pointer parameters. In particular, in the kernel, functions that may fail
375/// typically return an `int` that represents a generic error code. We model
376/// those as [`Error`].
377///
378/// In Rust, it is idiomatic to model functions that may fail as returning
379/// a [`Result`]. Since in the kernel many functions return an error code,
380/// [`Result`] is a type alias for a [`core::result::Result`] that uses
381/// [`Error`] as its error type.
382///
383/// Note that even if a function does not return anything when it succeeds,
384/// it should still be modeled as returning a [`Result`] rather than
385/// just an [`Error`].
386///
387/// Calling a function that returns [`Result`] forces the caller to handle
388/// the returned [`Result`].
389///
390/// This can be done "manually" by using [`match`]. Using [`match`] to decode
391/// the [`Result`] is similar to C where all the return value decoding and the
392/// error handling is done explicitly by writing handling code for each
393/// error to cover. Using [`match`] the error and success handling can be
394/// implemented in all detail as required. For example (inspired by
395/// [`samples/rust/rust_minimal.rs`]):
396///
397/// ```
398/// # #[allow(clippy::single_match)]
399/// fn example() -> Result {
400/// let mut numbers = KVec::new();
401///
402/// match numbers.push(72, GFP_KERNEL) {
403/// Err(e) => {
404/// pr_err!("Error pushing 72: {e:?}");
405/// return Err(e.into());
406/// }
407/// // Do nothing, continue.
408/// Ok(()) => (),
409/// }
410///
411/// match numbers.push(108, GFP_KERNEL) {
412/// Err(e) => {
413/// pr_err!("Error pushing 108: {e:?}");
414/// return Err(e.into());
415/// }
416/// // Do nothing, continue.
417/// Ok(()) => (),
418/// }
419///
420/// match numbers.push(200, GFP_KERNEL) {
421/// Err(e) => {
422/// pr_err!("Error pushing 200: {e:?}");
423/// return Err(e.into());
424/// }
425/// // Do nothing, continue.
426/// Ok(()) => (),
427/// }
428///
429/// Ok(())
430/// }
431/// # example()?;
432/// # Ok::<(), Error>(())
433/// ```
434///
435/// An alternative to be more concise is the [`if let`] syntax:
436///
437/// ```
438/// fn example() -> Result {
439/// let mut numbers = KVec::new();
440///
441/// if let Err(e) = numbers.push(72, GFP_KERNEL) {
442/// pr_err!("Error pushing 72: {e:?}");
443/// return Err(e.into());
444/// }
445///
446/// if let Err(e) = numbers.push(108, GFP_KERNEL) {
447/// pr_err!("Error pushing 108: {e:?}");
448/// return Err(e.into());
449/// }
450///
451/// if let Err(e) = numbers.push(200, GFP_KERNEL) {
452/// pr_err!("Error pushing 200: {e:?}");
453/// return Err(e.into());
454/// }
455///
456/// Ok(())
457/// }
458/// # example()?;
459/// # Ok::<(), Error>(())
460/// ```
461///
462/// Instead of these verbose [`match`]/[`if let`], the [`?`] operator can
463/// be used to handle the [`Result`]. Using the [`?`] operator is often
464/// the best choice to handle [`Result`] in a non-verbose way as done in
465/// [`samples/rust/rust_minimal.rs`]:
466///
467/// ```
468/// fn example() -> Result {
469/// let mut numbers = KVec::new();
470///
471/// numbers.push(72, GFP_KERNEL)?;
472/// numbers.push(108, GFP_KERNEL)?;
473/// numbers.push(200, GFP_KERNEL)?;
474///
475/// Ok(())
476/// }
477/// # example()?;
478/// # Ok::<(), Error>(())
479/// ```
480///
481/// Another possibility is to call [`unwrap()`](Result::unwrap) or
482/// [`expect()`](Result::expect). However, use of these functions is
483/// *heavily discouraged* in the kernel because they trigger a Rust
484/// [`panic!`] if an error happens, which may destabilize the system or
485/// entirely break it as a result -- just like the C [`BUG()`] macro.
486/// Please see the documentation for the C macro [`BUG()`] for guidance
487/// on when to use these functions.
488///
489/// Alternatively, depending on the use case, using [`unwrap_or()`],
490/// [`unwrap_or_else()`], [`unwrap_or_default()`] or [`unwrap_unchecked()`]
491/// might be an option, as well.
492///
493/// For even more details, please see the [Rust documentation].
494///
495/// [`match`]: https://doc.rust-lang.org/reference/expressions/match-expr.html
496/// [`samples/rust/rust_minimal.rs`]: srctree/samples/rust/rust_minimal.rs
497/// [`if let`]: https://doc.rust-lang.org/reference/expressions/if-expr.html#if-let-expressions
498/// [`?`]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator
499/// [`unwrap()`]: Result::unwrap
500/// [`expect()`]: Result::expect
501/// [`BUG()`]: https://docs.kernel.org/process/deprecated.html#bug-and-bug-on
502/// [`unwrap_or()`]: Result::unwrap_or
503/// [`unwrap_or_else()`]: Result::unwrap_or_else
504/// [`unwrap_or_default()`]: Result::unwrap_or_default
505/// [`unwrap_unchecked()`]: Result::unwrap_unchecked
506/// [Rust documentation]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html
507pub type Result<T = (), E = Error> = core::result::Result<T, E>;
508
509/// Converts an integer as returned by a C kernel function to a [`Result`].
510///
511/// If the integer is negative, an [`Err`] with an [`Error`] as given by [`Error::from_errno`] is
512/// returned. This means the integer must be `>= -MAX_ERRNO`.
513///
514/// Otherwise, it returns [`Ok`].
515///
516/// It is a bug to pass an out-of-range negative integer. `Err(EINVAL)` is returned in such a case.
517///
518/// # Examples
519///
520/// This function may be used to easily perform early returns with the [`?`] operator when working
521/// with C APIs within Rust abstractions:
522///
523/// ```
524/// # use kernel::error::to_result;
525/// # mod bindings {
526/// # #![expect(clippy::missing_safety_doc)]
527/// # use kernel::prelude::*;
528/// # pub(super) unsafe fn f1() -> c_int { 0 }
529/// # pub(super) unsafe fn f2() -> c_int { EINVAL.to_errno() }
530/// # }
531/// fn f() -> Result {
532/// // SAFETY: ...
533/// to_result(unsafe { bindings::f1() })?;
534///
535/// // SAFETY: ...
536/// to_result(unsafe { bindings::f2() })?;
537///
538/// // ...
539///
540/// Ok(())
541/// }
542/// # assert_eq!(f(), Err(EINVAL));
543/// ```
544///
545/// [`?`]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator
546pub fn to_result(err: crate::ffi::c_int) -> Result {
547 if err < 0 {
548 Err(Error::from_errno(err))
549 } else {
550 Ok(())
551 }
552}
553
554/// Transform a kernel "error pointer" to a normal pointer.
555///
556/// Some kernel C API functions return an "error pointer" which optionally
557/// embeds an `errno`. Callers are supposed to check the returned pointer
558/// for errors. This function performs the check and converts the "error pointer"
559/// to a normal pointer in an idiomatic fashion.
560///
561/// Note that a `NULL` pointer is not considered an error pointer, and is returned
562/// as-is, wrapped in [`Ok`].
563///
564/// # Examples
565///
566/// ```ignore
567/// # use kernel::from_err_ptr;
568/// # use kernel::bindings;
569/// fn devm_platform_ioremap_resource(
570/// pdev: &mut PlatformDevice,
571/// index: u32,
572/// ) -> Result<*mut kernel::ffi::c_void> {
573/// // SAFETY: `pdev` points to a valid platform device. There are no safety requirements
574/// // on `index`.
575/// from_err_ptr(unsafe { bindings::devm_platform_ioremap_resource(pdev.to_ptr(), index) })
576/// }
577/// ```
578///
579/// ```
580/// # use kernel::error::from_err_ptr;
581/// # mod bindings {
582/// # #![expect(clippy::missing_safety_doc)]
583/// # use kernel::prelude::*;
584/// # pub(super) unsafe fn einval_err_ptr() -> *mut kernel::ffi::c_void {
585/// # EINVAL.to_ptr()
586/// # }
587/// # pub(super) unsafe fn null_ptr() -> *mut kernel::ffi::c_void {
588/// # core::ptr::null_mut()
589/// # }
590/// # pub(super) unsafe fn non_null_ptr() -> *mut kernel::ffi::c_void {
591/// # 0x1234 as *mut kernel::ffi::c_void
592/// # }
593/// # }
594/// // SAFETY: ...
595/// let einval_err = from_err_ptr(unsafe { bindings::einval_err_ptr() });
596/// assert_eq!(einval_err, Err(EINVAL));
597///
598/// // SAFETY: ...
599/// let null_ok = from_err_ptr(unsafe { bindings::null_ptr() });
600/// assert_eq!(null_ok, Ok(core::ptr::null_mut()));
601///
602/// // SAFETY: ...
603/// let non_null = from_err_ptr(unsafe { bindings::non_null_ptr() }).unwrap();
604/// assert_ne!(non_null, core::ptr::null_mut());
605/// ```
606pub fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
607 // CAST: Casting a pointer to `*const crate::ffi::c_void` is always valid.
608 let const_ptr: *const crate::ffi::c_void = ptr.cast();
609 // SAFETY: The FFI function does not deref the pointer.
610 if unsafe { bindings::IS_ERR(const_ptr) } {
611 // SAFETY: The FFI function does not deref the pointer.
612 let err = unsafe { bindings::PTR_ERR(const_ptr) };
613
614 #[allow(clippy::unnecessary_cast)]
615 // CAST: If `IS_ERR()` returns `true`,
616 // then `PTR_ERR()` is guaranteed to return a
617 // negative value greater-or-equal to `-bindings::MAX_ERRNO`,
618 // which always fits in an `i16`, as per the invariant above.
619 // And an `i16` always fits in an `i32`. So casting `err` to
620 // an `i32` can never overflow, and is always valid.
621 //
622 // SAFETY: `IS_ERR()` ensures `err` is a
623 // negative value greater-or-equal to `-bindings::MAX_ERRNO`.
624 return Err(unsafe { Error::from_errno_unchecked(err as crate::ffi::c_int) });
625 }
626 Ok(ptr)
627}
628
629/// Calls a closure returning a [`crate::error::Result<T>`] and converts the result to
630/// a C integer result.
631///
632/// This is useful when calling Rust functions that return [`crate::error::Result<T>`]
633/// from inside `extern "C"` functions that need to return an integer error result.
634///
635/// `T` should be convertible from an `i16` via `From<i16>`.
636///
637/// # Examples
638///
639/// ```ignore
640/// # use kernel::from_result;
641/// # use kernel::bindings;
642/// unsafe extern "C" fn probe_callback(
643/// pdev: *mut bindings::platform_device,
644/// ) -> kernel::ffi::c_int {
645/// from_result(|| {
646/// let ptr = devm_alloc(pdev)?;
647/// bindings::platform_set_drvdata(pdev, ptr);
648/// Ok(0)
649/// })
650/// }
651/// ```
652pub fn from_result<T, F>(f: F) -> T
653where
654 T: From<i16>,
655 F: FnOnce() -> Result<T>,
656{
657 match f() {
658 Ok(v) => v,
659 // NO-OVERFLOW: negative `errno`s are no smaller than `-bindings::MAX_ERRNO`,
660 // `-bindings::MAX_ERRNO` fits in an `i16` as per invariant above,
661 // therefore a negative `errno` always fits in an `i16` and will not overflow.
662 Err(e) => T::from(e.to_errno() as i16),
663 }
664}
665
666/// Error message for calling a default function of a [`#[vtable]`](macros::vtable) trait.
667pub const VTABLE_DEFAULT_ERROR: &str =
668 "This function must not be called, see the #[vtable] documentation.";