// SPDX-License-Identifier: GPL-2.012//! Kernel errors.3//!4//! C header: [`include/uapi/asm-generic/errno-base.h`](srctree/include/uapi/asm-generic/errno-base.h)\5//! C header: [`include/uapi/asm-generic/errno.h`](srctree/include/uapi/asm-generic/errno.h)\6//! C header: [`include/linux/errno.h`](srctree/include/linux/errno.h)78use crate::{9alloc::{layout::LayoutError, AllocError},10fmt,11str::CStr,12};1314use core::num::NonZeroI32;15use core::num::TryFromIntError;16use core::str::Utf8Error;1718/// Contains the C-compatible error codes.19#[rustfmt::skip]20pub mod code {21macro_rules! declare_err {22($err:tt $(,)? $($doc:expr),+) => {23$(24#[doc = $doc]25)*26pub const $err: super::Error =27match super::Error::try_from_errno(-(crate::bindings::$err as i32)) {28Some(err) => err,29None => panic!("Invalid errno in `declare_err!`"),30};31};32}3334declare_err!(EPERM, "Operation not permitted.");35declare_err!(ENOENT, "No such file or directory.");36declare_err!(ESRCH, "No such process.");37declare_err!(EINTR, "Interrupted system call.");38declare_err!(EIO, "I/O error.");39declare_err!(ENXIO, "No such device or address.");40declare_err!(E2BIG, "Argument list too long.");41declare_err!(ENOEXEC, "Exec format error.");42declare_err!(EBADF, "Bad file number.");43declare_err!(ECHILD, "No child processes.");44declare_err!(EAGAIN, "Try again.");45declare_err!(ENOMEM, "Out of memory.");46declare_err!(EACCES, "Permission denied.");47declare_err!(EFAULT, "Bad address.");48declare_err!(ENOTBLK, "Block device required.");49declare_err!(EBUSY, "Device or resource busy.");50declare_err!(EEXIST, "File exists.");51declare_err!(EXDEV, "Cross-device link.");52declare_err!(ENODEV, "No such device.");53declare_err!(ENOTDIR, "Not a directory.");54declare_err!(EISDIR, "Is a directory.");55declare_err!(EINVAL, "Invalid argument.");56declare_err!(ENFILE, "File table overflow.");57declare_err!(EMFILE, "Too many open files.");58declare_err!(ENOTTY, "Not a typewriter.");59declare_err!(ETXTBSY, "Text file busy.");60declare_err!(EFBIG, "File too large.");61declare_err!(ENOSPC, "No space left on device.");62declare_err!(ESPIPE, "Illegal seek.");63declare_err!(EROFS, "Read-only file system.");64declare_err!(EMLINK, "Too many links.");65declare_err!(EPIPE, "Broken pipe.");66declare_err!(EDOM, "Math argument out of domain of func.");67declare_err!(ERANGE, "Math result not representable.");68declare_err!(EOVERFLOW, "Value too large for defined data type.");69declare_err!(ETIMEDOUT, "Connection timed out.");70declare_err!(ERESTARTSYS, "Restart the system call.");71declare_err!(ERESTARTNOINTR, "System call was interrupted by a signal and will be restarted.");72declare_err!(ERESTARTNOHAND, "Restart if no handler.");73declare_err!(ENOIOCTLCMD, "No ioctl command.");74declare_err!(ERESTART_RESTARTBLOCK, "Restart by calling sys_restart_syscall.");75declare_err!(EPROBE_DEFER, "Driver requests probe retry.");76declare_err!(EOPENSTALE, "Open found a stale dentry.");77declare_err!(ENOPARAM, "Parameter not supported.");78declare_err!(EBADHANDLE, "Illegal NFS file handle.");79declare_err!(ENOTSYNC, "Update synchronization mismatch.");80declare_err!(EBADCOOKIE, "Cookie is stale.");81declare_err!(ENOTSUPP, "Operation is not supported.");82declare_err!(ETOOSMALL, "Buffer or request is too small.");83declare_err!(ESERVERFAULT, "An untranslatable error occurred.");84declare_err!(EBADTYPE, "Type not supported by server.");85declare_err!(EJUKEBOX, "Request initiated, but will not complete before timeout.");86declare_err!(EIOCBQUEUED, "iocb queued, will get completion event.");87declare_err!(ERECALLCONFLICT, "Conflict with recalled state.");88declare_err!(ENOGRACE, "NFS file lock reclaim refused.");89}9091/// Generic integer kernel error.92///93/// The kernel defines a set of integer generic error codes based on C and94/// POSIX ones. These codes may have a more specific meaning in some contexts.95///96/// # Invariants97///98/// The value is a valid `errno` (i.e. `>= -MAX_ERRNO && < 0`).99#[derive(Clone, Copy, PartialEq, Eq)]100pub struct Error(NonZeroI32);101102impl Error {103/// Creates an [`Error`] from a kernel error code.104///105/// `errno` must be within error code range (i.e. `>= -MAX_ERRNO && < 0`).106///107/// It is a bug to pass an out-of-range `errno`. [`code::EINVAL`] is returned in such a case.108///109/// # Examples110///111/// ```112/// assert_eq!(Error::from_errno(-1), EPERM);113/// assert_eq!(Error::from_errno(-2), ENOENT);114/// ```115///116/// The following calls are considered a bug:117///118/// ```119/// assert_eq!(Error::from_errno(0), EINVAL);120/// assert_eq!(Error::from_errno(-1000000), EINVAL);121/// ```122pub fn from_errno(errno: crate::ffi::c_int) -> Error {123if let Some(error) = Self::try_from_errno(errno) {124error125} else {126// TODO: Make it a `WARN_ONCE` once available.127crate::pr_warn!(128"attempted to create `Error` with out of range `errno`: {}\n",129errno130);131code::EINVAL132}133}134135/// Creates an [`Error`] from a kernel error code.136///137/// Returns [`None`] if `errno` is out-of-range.138const fn try_from_errno(errno: crate::ffi::c_int) -> Option<Error> {139if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {140return None;141}142143// SAFETY: `errno` is checked above to be in a valid range.144Some(unsafe { Error::from_errno_unchecked(errno) })145}146147/// Creates an [`Error`] from a kernel error code.148///149/// # Safety150///151/// `errno` must be within error code range (i.e. `>= -MAX_ERRNO && < 0`).152const unsafe fn from_errno_unchecked(errno: crate::ffi::c_int) -> Error {153// INVARIANT: The contract ensures the type invariant154// will hold.155// SAFETY: The caller guarantees `errno` is non-zero.156Error(unsafe { NonZeroI32::new_unchecked(errno) })157}158159/// Returns the kernel error code.160pub fn to_errno(self) -> crate::ffi::c_int {161self.0.get()162}163164#[cfg(CONFIG_BLOCK)]165pub(crate) fn to_blk_status(self) -> bindings::blk_status_t {166// SAFETY: `self.0` is a valid error due to its invariant.167unsafe { bindings::errno_to_blk_status(self.0.get()) }168}169170/// Returns the error encoded as a pointer.171pub fn to_ptr<T>(self) -> *mut T {172// SAFETY: `self.0` is a valid error due to its invariant.173unsafe { bindings::ERR_PTR(self.0.get() as crate::ffi::c_long).cast() }174}175176/// Returns a string representing the error, if one exists.177#[cfg(not(testlib))]178pub fn name(&self) -> Option<&'static CStr> {179// SAFETY: Just an FFI call, there are no extra safety requirements.180let ptr = unsafe { bindings::errname(-self.0.get()) };181if ptr.is_null() {182None183} else {184// SAFETY: The string returned by `errname` is static and `NUL`-terminated.185Some(unsafe { CStr::from_char_ptr(ptr) })186}187}188189/// Returns a string representing the error, if one exists.190///191/// When `testlib` is configured, this always returns `None` to avoid the dependency on a192/// kernel function so that tests that use this (e.g., by calling [`Result::unwrap`]) can still193/// run in userspace.194#[cfg(testlib)]195pub fn name(&self) -> Option<&'static CStr> {196None197}198}199200impl fmt::Debug for Error {201fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {202match self.name() {203// Print out number if no name can be found.204None => f.debug_tuple("Error").field(&-self.0).finish(),205Some(name) => f206.debug_tuple(207// SAFETY: These strings are ASCII-only.208unsafe { core::str::from_utf8_unchecked(name.to_bytes()) },209)210.finish(),211}212}213}214215impl From<AllocError> for Error {216fn from(_: AllocError) -> Error {217code::ENOMEM218}219}220221impl From<TryFromIntError> for Error {222fn from(_: TryFromIntError) -> Error {223code::EINVAL224}225}226227impl From<Utf8Error> for Error {228fn from(_: Utf8Error) -> Error {229code::EINVAL230}231}232233impl From<LayoutError> for Error {234fn from(_: LayoutError) -> Error {235code::ENOMEM236}237}238239impl From<fmt::Error> for Error {240fn from(_: fmt::Error) -> Error {241code::EINVAL242}243}244245impl From<core::convert::Infallible> for Error {246fn from(e: core::convert::Infallible) -> Error {247match e {}248}249}250251/// A [`Result`] with an [`Error`] error type.252///253/// To be used as the return type for functions that may fail.254///255/// # Error codes in C and Rust256///257/// In C, it is common that functions indicate success or failure through258/// their return value; modifying or returning extra data through non-`const`259/// pointer parameters. In particular, in the kernel, functions that may fail260/// typically return an `int` that represents a generic error code. We model261/// those as [`Error`].262///263/// In Rust, it is idiomatic to model functions that may fail as returning264/// a [`Result`]. Since in the kernel many functions return an error code,265/// [`Result`] is a type alias for a [`core::result::Result`] that uses266/// [`Error`] as its error type.267///268/// Note that even if a function does not return anything when it succeeds,269/// it should still be modeled as returning a [`Result`] rather than270/// just an [`Error`].271///272/// Calling a function that returns [`Result`] forces the caller to handle273/// the returned [`Result`].274///275/// This can be done "manually" by using [`match`]. Using [`match`] to decode276/// the [`Result`] is similar to C where all the return value decoding and the277/// error handling is done explicitly by writing handling code for each278/// error to cover. Using [`match`] the error and success handling can be279/// implemented in all detail as required. For example (inspired by280/// [`samples/rust/rust_minimal.rs`]):281///282/// ```283/// # #[allow(clippy::single_match)]284/// fn example() -> Result {285/// let mut numbers = KVec::new();286///287/// match numbers.push(72, GFP_KERNEL) {288/// Err(e) => {289/// pr_err!("Error pushing 72: {e:?}");290/// return Err(e.into());291/// }292/// // Do nothing, continue.293/// Ok(()) => (),294/// }295///296/// match numbers.push(108, GFP_KERNEL) {297/// Err(e) => {298/// pr_err!("Error pushing 108: {e:?}");299/// return Err(e.into());300/// }301/// // Do nothing, continue.302/// Ok(()) => (),303/// }304///305/// match numbers.push(200, GFP_KERNEL) {306/// Err(e) => {307/// pr_err!("Error pushing 200: {e:?}");308/// return Err(e.into());309/// }310/// // Do nothing, continue.311/// Ok(()) => (),312/// }313///314/// Ok(())315/// }316/// # example()?;317/// # Ok::<(), Error>(())318/// ```319///320/// An alternative to be more concise is the [`if let`] syntax:321///322/// ```323/// fn example() -> Result {324/// let mut numbers = KVec::new();325///326/// if let Err(e) = numbers.push(72, GFP_KERNEL) {327/// pr_err!("Error pushing 72: {e:?}");328/// return Err(e.into());329/// }330///331/// if let Err(e) = numbers.push(108, GFP_KERNEL) {332/// pr_err!("Error pushing 108: {e:?}");333/// return Err(e.into());334/// }335///336/// if let Err(e) = numbers.push(200, GFP_KERNEL) {337/// pr_err!("Error pushing 200: {e:?}");338/// return Err(e.into());339/// }340///341/// Ok(())342/// }343/// # example()?;344/// # Ok::<(), Error>(())345/// ```346///347/// Instead of these verbose [`match`]/[`if let`], the [`?`] operator can348/// be used to handle the [`Result`]. Using the [`?`] operator is often349/// the best choice to handle [`Result`] in a non-verbose way as done in350/// [`samples/rust/rust_minimal.rs`]:351///352/// ```353/// fn example() -> Result {354/// let mut numbers = KVec::new();355///356/// numbers.push(72, GFP_KERNEL)?;357/// numbers.push(108, GFP_KERNEL)?;358/// numbers.push(200, GFP_KERNEL)?;359///360/// Ok(())361/// }362/// # example()?;363/// # Ok::<(), Error>(())364/// ```365///366/// Another possibility is to call [`unwrap()`](Result::unwrap) or367/// [`expect()`](Result::expect). However, use of these functions is368/// *heavily discouraged* in the kernel because they trigger a Rust369/// [`panic!`] if an error happens, which may destabilize the system or370/// entirely break it as a result -- just like the C [`BUG()`] macro.371/// Please see the documentation for the C macro [`BUG()`] for guidance372/// on when to use these functions.373///374/// Alternatively, depending on the use case, using [`unwrap_or()`],375/// [`unwrap_or_else()`], [`unwrap_or_default()`] or [`unwrap_unchecked()`]376/// might be an option, as well.377///378/// For even more details, please see the [Rust documentation].379///380/// [`match`]: https://doc.rust-lang.org/reference/expressions/match-expr.html381/// [`samples/rust/rust_minimal.rs`]: srctree/samples/rust/rust_minimal.rs382/// [`if let`]: https://doc.rust-lang.org/reference/expressions/if-expr.html#if-let-expressions383/// [`?`]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator384/// [`unwrap()`]: Result::unwrap385/// [`expect()`]: Result::expect386/// [`BUG()`]: https://docs.kernel.org/process/deprecated.html#bug-and-bug-on387/// [`unwrap_or()`]: Result::unwrap_or388/// [`unwrap_or_else()`]: Result::unwrap_or_else389/// [`unwrap_or_default()`]: Result::unwrap_or_default390/// [`unwrap_unchecked()`]: Result::unwrap_unchecked391/// [Rust documentation]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html392pub type Result<T = (), E = Error> = core::result::Result<T, E>;393394/// Converts an integer as returned by a C kernel function to a [`Result`].395///396/// If the integer is negative, an [`Err`] with an [`Error`] as given by [`Error::from_errno`] is397/// returned. This means the integer must be `>= -MAX_ERRNO`.398///399/// Otherwise, it returns [`Ok`].400///401/// It is a bug to pass an out-of-range negative integer. `Err(EINVAL)` is returned in such a case.402///403/// # Examples404///405/// This function may be used to easily perform early returns with the [`?`] operator when working406/// with C APIs within Rust abstractions:407///408/// ```409/// # use kernel::error::to_result;410/// # mod bindings {411/// # #![expect(clippy::missing_safety_doc)]412/// # use kernel::prelude::*;413/// # pub(super) unsafe fn f1() -> c_int { 0 }414/// # pub(super) unsafe fn f2() -> c_int { EINVAL.to_errno() }415/// # }416/// fn f() -> Result {417/// // SAFETY: ...418/// to_result(unsafe { bindings::f1() })?;419///420/// // SAFETY: ...421/// to_result(unsafe { bindings::f2() })?;422///423/// // ...424///425/// Ok(())426/// }427/// # assert_eq!(f(), Err(EINVAL));428/// ```429///430/// [`?`]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator431pub fn to_result(err: crate::ffi::c_int) -> Result {432if err < 0 {433Err(Error::from_errno(err))434} else {435Ok(())436}437}438439/// Transform a kernel "error pointer" to a normal pointer.440///441/// Some kernel C API functions return an "error pointer" which optionally442/// embeds an `errno`. Callers are supposed to check the returned pointer443/// for errors. This function performs the check and converts the "error pointer"444/// to a normal pointer in an idiomatic fashion.445///446/// # Examples447///448/// ```ignore449/// # use kernel::from_err_ptr;450/// # use kernel::bindings;451/// fn devm_platform_ioremap_resource(452/// pdev: &mut PlatformDevice,453/// index: u32,454/// ) -> Result<*mut kernel::ffi::c_void> {455/// // SAFETY: `pdev` points to a valid platform device. There are no safety requirements456/// // on `index`.457/// from_err_ptr(unsafe { bindings::devm_platform_ioremap_resource(pdev.to_ptr(), index) })458/// }459/// ```460pub fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {461// CAST: Casting a pointer to `*const crate::ffi::c_void` is always valid.462let const_ptr: *const crate::ffi::c_void = ptr.cast();463// SAFETY: The FFI function does not deref the pointer.464if unsafe { bindings::IS_ERR(const_ptr) } {465// SAFETY: The FFI function does not deref the pointer.466let err = unsafe { bindings::PTR_ERR(const_ptr) };467468#[allow(clippy::unnecessary_cast)]469// CAST: If `IS_ERR()` returns `true`,470// then `PTR_ERR()` is guaranteed to return a471// negative value greater-or-equal to `-bindings::MAX_ERRNO`,472// which always fits in an `i16`, as per the invariant above.473// And an `i16` always fits in an `i32`. So casting `err` to474// an `i32` can never overflow, and is always valid.475//476// SAFETY: `IS_ERR()` ensures `err` is a477// negative value greater-or-equal to `-bindings::MAX_ERRNO`.478return Err(unsafe { Error::from_errno_unchecked(err as crate::ffi::c_int) });479}480Ok(ptr)481}482483/// Calls a closure returning a [`crate::error::Result<T>`] and converts the result to484/// a C integer result.485///486/// This is useful when calling Rust functions that return [`crate::error::Result<T>`]487/// from inside `extern "C"` functions that need to return an integer error result.488///489/// `T` should be convertible from an `i16` via `From<i16>`.490///491/// # Examples492///493/// ```ignore494/// # use kernel::from_result;495/// # use kernel::bindings;496/// unsafe extern "C" fn probe_callback(497/// pdev: *mut bindings::platform_device,498/// ) -> kernel::ffi::c_int {499/// from_result(|| {500/// let ptr = devm_alloc(pdev)?;501/// bindings::platform_set_drvdata(pdev, ptr);502/// Ok(0)503/// })504/// }505/// ```506pub fn from_result<T, F>(f: F) -> T507where508T: From<i16>,509F: FnOnce() -> Result<T>,510{511match f() {512Ok(v) => v,513// NO-OVERFLOW: negative `errno`s are no smaller than `-bindings::MAX_ERRNO`,514// `-bindings::MAX_ERRNO` fits in an `i16` as per invariant above,515// therefore a negative `errno` always fits in an `i16` and will not overflow.516Err(e) => T::from(e.to_errno() as i16),517}518}519520/// Error message for calling a default function of a [`#[vtable]`](macros::vtable) trait.521pub const VTABLE_DEFAULT_ERROR: &str =522"This function must not be called, see the #[vtable] documentation.";523524525