Skip to main content

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)]
202pub struct Error(NonZeroI32);
203
204impl Error {
205    /// Creates an [`Error`] from a kernel error code.
206    ///
207    /// `errno` must be within error code range (i.e. `>= -MAX_ERRNO && < 0`).
208    ///
209    /// It is a bug to pass an out-of-range `errno`. [`code::EINVAL`] is returned in such a case.
210    ///
211    /// # Examples
212    ///
213    /// ```
214    /// assert_eq!(Error::from_errno(-1), EPERM);
215    /// assert_eq!(Error::from_errno(-2), ENOENT);
216    /// ```
217    ///
218    /// The following calls are considered a bug:
219    ///
220    /// ```
221    /// assert_eq!(Error::from_errno(0), EINVAL);
222    /// assert_eq!(Error::from_errno(-1000000), EINVAL);
223    /// ```
224    pub fn from_errno(errno: crate::ffi::c_int) -> Error {
225        if let Some(error) = Self::try_from_errno(errno) {
226            error
227        } else {
228            // TODO: Make it a `WARN_ONCE` once available.
229            crate::pr_warn!(
230                "attempted to create `Error` with out of range `errno`: {}\n",
231                errno
232            );
233            code::EINVAL
234        }
235    }
236
237    /// Creates an [`Error`] from a kernel error code.
238    ///
239    /// Returns [`None`] if `errno` is out-of-range.
240    const fn try_from_errno(errno: crate::ffi::c_int) -> Option<Error> {
241        if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
242            return None;
243        }
244
245        // SAFETY: `errno` is checked above to be in a valid range.
246        Some(unsafe { Error::from_errno_unchecked(errno) })
247    }
248
249    /// Creates an [`Error`] from a kernel error code.
250    ///
251    /// # Safety
252    ///
253    /// `errno` must be within error code range (i.e. `>= -MAX_ERRNO && < 0`).
254    const unsafe fn from_errno_unchecked(errno: crate::ffi::c_int) -> Error {
255        // INVARIANT: The contract ensures the type invariant
256        // will hold.
257        // SAFETY: The caller guarantees `errno` is non-zero.
258        Error(unsafe { NonZeroI32::new_unchecked(errno) })
259    }
260
261    /// Returns the kernel error code.
262    pub fn to_errno(self) -> crate::ffi::c_int {
263        self.0.get()
264    }
265
266    #[cfg(CONFIG_BLOCK)]
267    pub(crate) fn to_blk_status(self) -> bindings::blk_status_t {
268        // SAFETY: `self.0` is a valid error due to its invariant.
269        unsafe { bindings::errno_to_blk_status(self.0.get()) }
270    }
271
272    /// Returns the error encoded as a pointer.
273    pub fn to_ptr<T>(self) -> *mut T {
274        // SAFETY: `self.0` is a valid error due to its invariant.
275        unsafe { bindings::ERR_PTR(self.0.get() as crate::ffi::c_long).cast() }
276    }
277
278    /// Returns a string representing the error, if one exists.
279    #[cfg(not(testlib))]
280    pub fn name(&self) -> Option<&'static CStr> {
281        // SAFETY: Just an FFI call, there are no extra safety requirements.
282        let ptr = unsafe { bindings::errname(-self.0.get()) };
283        if ptr.is_null() {
284            None
285        } else {
286            use crate::str::CStrExt as _;
287
288            // SAFETY: The string returned by `errname` is static and `NUL`-terminated.
289            Some(unsafe { CStr::from_char_ptr(ptr) })
290        }
291    }
292
293    /// Returns a string representing the error, if one exists.
294    ///
295    /// When `testlib` is configured, this always returns `None` to avoid the dependency on a
296    /// kernel function so that tests that use this (e.g., by calling [`Result::unwrap`]) can still
297    /// run in userspace.
298    #[cfg(testlib)]
299    pub fn name(&self) -> Option<&'static CStr> {
300        None
301    }
302}
303
304impl fmt::Debug for Error {
305    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
306        match self.name() {
307            // Print out number if no name can be found.
308            None => f.debug_tuple("Error").field(&-self.0).finish(),
309            Some(name) => f
310                .debug_tuple(
311                    // SAFETY: These strings are ASCII-only.
312                    unsafe { core::str::from_utf8_unchecked(name.to_bytes()) },
313                )
314                .finish(),
315        }
316    }
317}
318
319impl From<AllocError> for Error {
320    #[inline]
321    fn from(_: AllocError) -> Error {
322        code::ENOMEM
323    }
324}
325
326impl From<TryFromIntError> for Error {
327    #[inline]
328    fn from(_: TryFromIntError) -> Error {
329        code::EINVAL
330    }
331}
332
333impl From<Utf8Error> for Error {
334    #[inline]
335    fn from(_: Utf8Error) -> Error {
336        code::EINVAL
337    }
338}
339
340impl From<LayoutError> for Error {
341    #[inline]
342    fn from(_: LayoutError) -> Error {
343        code::ENOMEM
344    }
345}
346
347impl From<fmt::Error> for Error {
348    #[inline]
349    fn from(_: fmt::Error) -> Error {
350        code::EINVAL
351    }
352}
353
354impl From<core::convert::Infallible> for Error {
355    #[inline]
356    fn from(e: core::convert::Infallible) -> Error {
357        match e {}
358    }
359}
360
361/// A [`Result`] with an [`Error`] error type.
362///
363/// To be used as the return type for functions that may fail.
364///
365/// # Error codes in C and Rust
366///
367/// In C, it is common that functions indicate success or failure through
368/// their return value; modifying or returning extra data through non-`const`
369/// pointer parameters. In particular, in the kernel, functions that may fail
370/// typically return an `int` that represents a generic error code. We model
371/// those as [`Error`].
372///
373/// In Rust, it is idiomatic to model functions that may fail as returning
374/// a [`Result`]. Since in the kernel many functions return an error code,
375/// [`Result`] is a type alias for a [`core::result::Result`] that uses
376/// [`Error`] as its error type.
377///
378/// Note that even if a function does not return anything when it succeeds,
379/// it should still be modeled as returning a [`Result`] rather than
380/// just an [`Error`].
381///
382/// Calling a function that returns [`Result`] forces the caller to handle
383/// the returned [`Result`].
384///
385/// This can be done "manually" by using [`match`]. Using [`match`] to decode
386/// the [`Result`] is similar to C where all the return value decoding and the
387/// error handling is done explicitly by writing handling code for each
388/// error to cover. Using [`match`] the error and success handling can be
389/// implemented in all detail as required. For example (inspired by
390/// [`samples/rust/rust_minimal.rs`]):
391///
392/// ```
393/// # #[allow(clippy::single_match)]
394/// fn example() -> Result {
395///     let mut numbers = KVec::new();
396///
397///     match numbers.push(72, GFP_KERNEL) {
398///         Err(e) => {
399///             pr_err!("Error pushing 72: {e:?}");
400///             return Err(e.into());
401///         }
402///         // Do nothing, continue.
403///         Ok(()) => (),
404///     }
405///
406///     match numbers.push(108, GFP_KERNEL) {
407///         Err(e) => {
408///             pr_err!("Error pushing 108: {e:?}");
409///             return Err(e.into());
410///         }
411///         // Do nothing, continue.
412///         Ok(()) => (),
413///     }
414///
415///     match numbers.push(200, GFP_KERNEL) {
416///         Err(e) => {
417///             pr_err!("Error pushing 200: {e:?}");
418///             return Err(e.into());
419///         }
420///         // Do nothing, continue.
421///         Ok(()) => (),
422///     }
423///
424///     Ok(())
425/// }
426/// # example()?;
427/// # Ok::<(), Error>(())
428/// ```
429///
430/// An alternative to be more concise is the [`if let`] syntax:
431///
432/// ```
433/// fn example() -> Result {
434///     let mut numbers = KVec::new();
435///
436///     if let Err(e) = numbers.push(72, GFP_KERNEL) {
437///         pr_err!("Error pushing 72: {e:?}");
438///         return Err(e.into());
439///     }
440///
441///     if let Err(e) = numbers.push(108, GFP_KERNEL) {
442///         pr_err!("Error pushing 108: {e:?}");
443///         return Err(e.into());
444///     }
445///
446///     if let Err(e) = numbers.push(200, GFP_KERNEL) {
447///         pr_err!("Error pushing 200: {e:?}");
448///         return Err(e.into());
449///     }
450///
451///     Ok(())
452/// }
453/// # example()?;
454/// # Ok::<(), Error>(())
455/// ```
456///
457/// Instead of these verbose [`match`]/[`if let`], the [`?`] operator can
458/// be used to handle the [`Result`]. Using the [`?`] operator is often
459/// the best choice to handle [`Result`] in a non-verbose way as done in
460/// [`samples/rust/rust_minimal.rs`]:
461///
462/// ```
463/// fn example() -> Result {
464///     let mut numbers = KVec::new();
465///
466///     numbers.push(72, GFP_KERNEL)?;
467///     numbers.push(108, GFP_KERNEL)?;
468///     numbers.push(200, GFP_KERNEL)?;
469///
470///     Ok(())
471/// }
472/// # example()?;
473/// # Ok::<(), Error>(())
474/// ```
475///
476/// Another possibility is to call [`unwrap()`](Result::unwrap) or
477/// [`expect()`](Result::expect). However, use of these functions is
478/// *heavily discouraged* in the kernel because they trigger a Rust
479/// [`panic!`] if an error happens, which may destabilize the system or
480/// entirely break it as a result -- just like the C [`BUG()`] macro.
481/// Please see the documentation for the C macro [`BUG()`] for guidance
482/// on when to use these functions.
483///
484/// Alternatively, depending on the use case, using [`unwrap_or()`],
485/// [`unwrap_or_else()`], [`unwrap_or_default()`] or [`unwrap_unchecked()`]
486/// might be an option, as well.
487///
488/// For even more details, please see the [Rust documentation].
489///
490/// [`match`]: https://doc.rust-lang.org/reference/expressions/match-expr.html
491/// [`samples/rust/rust_minimal.rs`]: srctree/samples/rust/rust_minimal.rs
492/// [`if let`]: https://doc.rust-lang.org/reference/expressions/if-expr.html#if-let-expressions
493/// [`?`]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator
494/// [`unwrap()`]: Result::unwrap
495/// [`expect()`]: Result::expect
496/// [`BUG()`]: https://docs.kernel.org/process/deprecated.html#bug-and-bug-on
497/// [`unwrap_or()`]: Result::unwrap_or
498/// [`unwrap_or_else()`]: Result::unwrap_or_else
499/// [`unwrap_or_default()`]: Result::unwrap_or_default
500/// [`unwrap_unchecked()`]: Result::unwrap_unchecked
501/// [Rust documentation]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html
502pub type Result<T = (), E = Error> = core::result::Result<T, E>;
503
504/// Converts an integer as returned by a C kernel function to a [`Result`].
505///
506/// If the integer is negative, an [`Err`] with an [`Error`] as given by [`Error::from_errno`] is
507/// returned. This means the integer must be `>= -MAX_ERRNO`.
508///
509/// Otherwise, it returns [`Ok`].
510///
511/// It is a bug to pass an out-of-range negative integer. `Err(EINVAL)` is returned in such a case.
512///
513/// # Examples
514///
515/// This function may be used to easily perform early returns with the [`?`] operator when working
516/// with C APIs within Rust abstractions:
517///
518/// ```
519/// # use kernel::error::to_result;
520/// # mod bindings {
521/// #     #![expect(clippy::missing_safety_doc)]
522/// #     use kernel::prelude::*;
523/// #     pub(super) unsafe fn f1() -> c_int { 0 }
524/// #     pub(super) unsafe fn f2() -> c_int { EINVAL.to_errno() }
525/// # }
526/// fn f() -> Result {
527///     // SAFETY: ...
528///     to_result(unsafe { bindings::f1() })?;
529///
530///     // SAFETY: ...
531///     to_result(unsafe { bindings::f2() })?;
532///
533///     // ...
534///
535///     Ok(())
536/// }
537/// # assert_eq!(f(), Err(EINVAL));
538/// ```
539///
540/// [`?`]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator
541pub fn to_result(err: crate::ffi::c_int) -> Result {
542    if err < 0 {
543        Err(Error::from_errno(err))
544    } else {
545        Ok(())
546    }
547}
548
549/// Transform a kernel "error pointer" to a normal pointer.
550///
551/// Some kernel C API functions return an "error pointer" which optionally
552/// embeds an `errno`. Callers are supposed to check the returned pointer
553/// for errors. This function performs the check and converts the "error pointer"
554/// to a normal pointer in an idiomatic fashion.
555///
556/// Note that a `NULL` pointer is not considered an error pointer, and is returned
557/// as-is, wrapped in [`Ok`].
558///
559/// # Examples
560///
561/// ```ignore
562/// # use kernel::from_err_ptr;
563/// # use kernel::bindings;
564/// fn devm_platform_ioremap_resource(
565///     pdev: &mut PlatformDevice,
566///     index: u32,
567/// ) -> Result<*mut kernel::ffi::c_void> {
568///     // SAFETY: `pdev` points to a valid platform device. There are no safety requirements
569///     // on `index`.
570///     from_err_ptr(unsafe { bindings::devm_platform_ioremap_resource(pdev.to_ptr(), index) })
571/// }
572/// ```
573///
574/// ```
575/// # use kernel::error::from_err_ptr;
576/// # mod bindings {
577/// #     #![expect(clippy::missing_safety_doc)]
578/// #     use kernel::prelude::*;
579/// #     pub(super) unsafe fn einval_err_ptr() -> *mut kernel::ffi::c_void {
580/// #         EINVAL.to_ptr()
581/// #     }
582/// #     pub(super) unsafe fn null_ptr() -> *mut kernel::ffi::c_void {
583/// #         core::ptr::null_mut()
584/// #     }
585/// #     pub(super) unsafe fn non_null_ptr() -> *mut kernel::ffi::c_void {
586/// #         0x1234 as *mut kernel::ffi::c_void
587/// #     }
588/// # }
589/// // SAFETY: ...
590/// let einval_err = from_err_ptr(unsafe { bindings::einval_err_ptr() });
591/// assert_eq!(einval_err, Err(EINVAL));
592///
593/// // SAFETY: ...
594/// let null_ok = from_err_ptr(unsafe { bindings::null_ptr() });
595/// assert_eq!(null_ok, Ok(core::ptr::null_mut()));
596///
597/// // SAFETY: ...
598/// let non_null = from_err_ptr(unsafe { bindings::non_null_ptr() }).unwrap();
599/// assert_ne!(non_null, core::ptr::null_mut());
600/// ```
601pub fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
602    // CAST: Casting a pointer to `*const crate::ffi::c_void` is always valid.
603    let const_ptr: *const crate::ffi::c_void = ptr.cast();
604    // SAFETY: The FFI function does not deref the pointer.
605    if unsafe { bindings::IS_ERR(const_ptr) } {
606        // SAFETY: The FFI function does not deref the pointer.
607        let err = unsafe { bindings::PTR_ERR(const_ptr) };
608
609        #[allow(clippy::unnecessary_cast)]
610        // CAST: If `IS_ERR()` returns `true`,
611        // then `PTR_ERR()` is guaranteed to return a
612        // negative value greater-or-equal to `-bindings::MAX_ERRNO`,
613        // which always fits in an `i16`, as per the invariant above.
614        // And an `i16` always fits in an `i32`. So casting `err` to
615        // an `i32` can never overflow, and is always valid.
616        //
617        // SAFETY: `IS_ERR()` ensures `err` is a
618        // negative value greater-or-equal to `-bindings::MAX_ERRNO`.
619        return Err(unsafe { Error::from_errno_unchecked(err as crate::ffi::c_int) });
620    }
621    Ok(ptr)
622}
623
624/// Calls a closure returning a [`crate::error::Result<T>`] and converts the result to
625/// a C integer result.
626///
627/// This is useful when calling Rust functions that return [`crate::error::Result<T>`]
628/// from inside `extern "C"` functions that need to return an integer error result.
629///
630/// `T` should be convertible from an `i16` via `From<i16>`.
631///
632/// # Examples
633///
634/// ```ignore
635/// # use kernel::from_result;
636/// # use kernel::bindings;
637/// unsafe extern "C" fn probe_callback(
638///     pdev: *mut bindings::platform_device,
639/// ) -> kernel::ffi::c_int {
640///     from_result(|| {
641///         let ptr = devm_alloc(pdev)?;
642///         bindings::platform_set_drvdata(pdev, ptr);
643///         Ok(0)
644///     })
645/// }
646/// ```
647pub fn from_result<T, F>(f: F) -> T
648where
649    T: From<i16>,
650    F: FnOnce() -> Result<T>,
651{
652    match f() {
653        Ok(v) => v,
654        // NO-OVERFLOW: negative `errno`s are no smaller than `-bindings::MAX_ERRNO`,
655        // `-bindings::MAX_ERRNO` fits in an `i16` as per invariant above,
656        // therefore a negative `errno` always fits in an `i16` and will not overflow.
657        Err(e) => T::from(e.to_errno() as i16),
658    }
659}
660
661/// Error message for calling a default function of a [`#[vtable]`](macros::vtable) trait.
662pub const VTABLE_DEFAULT_ERROR: &str =
663    "This function must not be called, see the #[vtable] documentation.";