// 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 {184use crate::str::CStrExt as _;185186// SAFETY: The string returned by `errname` is static and `NUL`-terminated.187Some(unsafe { CStr::from_char_ptr(ptr) })188}189}190191/// Returns a string representing the error, if one exists.192///193/// When `testlib` is configured, this always returns `None` to avoid the dependency on a194/// kernel function so that tests that use this (e.g., by calling [`Result::unwrap`]) can still195/// run in userspace.196#[cfg(testlib)]197pub fn name(&self) -> Option<&'static CStr> {198None199}200}201202impl fmt::Debug for Error {203fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {204match self.name() {205// Print out number if no name can be found.206None => f.debug_tuple("Error").field(&-self.0).finish(),207Some(name) => f208.debug_tuple(209// SAFETY: These strings are ASCII-only.210unsafe { core::str::from_utf8_unchecked(name.to_bytes()) },211)212.finish(),213}214}215}216217impl From<AllocError> for Error {218fn from(_: AllocError) -> Error {219code::ENOMEM220}221}222223impl From<TryFromIntError> for Error {224fn from(_: TryFromIntError) -> Error {225code::EINVAL226}227}228229impl From<Utf8Error> for Error {230fn from(_: Utf8Error) -> Error {231code::EINVAL232}233}234235impl From<LayoutError> for Error {236fn from(_: LayoutError) -> Error {237code::ENOMEM238}239}240241impl From<fmt::Error> for Error {242fn from(_: fmt::Error) -> Error {243code::EINVAL244}245}246247impl From<core::convert::Infallible> for Error {248fn from(e: core::convert::Infallible) -> Error {249match e {}250}251}252253/// A [`Result`] with an [`Error`] error type.254///255/// To be used as the return type for functions that may fail.256///257/// # Error codes in C and Rust258///259/// In C, it is common that functions indicate success or failure through260/// their return value; modifying or returning extra data through non-`const`261/// pointer parameters. In particular, in the kernel, functions that may fail262/// typically return an `int` that represents a generic error code. We model263/// those as [`Error`].264///265/// In Rust, it is idiomatic to model functions that may fail as returning266/// a [`Result`]. Since in the kernel many functions return an error code,267/// [`Result`] is a type alias for a [`core::result::Result`] that uses268/// [`Error`] as its error type.269///270/// Note that even if a function does not return anything when it succeeds,271/// it should still be modeled as returning a [`Result`] rather than272/// just an [`Error`].273///274/// Calling a function that returns [`Result`] forces the caller to handle275/// the returned [`Result`].276///277/// This can be done "manually" by using [`match`]. Using [`match`] to decode278/// the [`Result`] is similar to C where all the return value decoding and the279/// error handling is done explicitly by writing handling code for each280/// error to cover. Using [`match`] the error and success handling can be281/// implemented in all detail as required. For example (inspired by282/// [`samples/rust/rust_minimal.rs`]):283///284/// ```285/// # #[allow(clippy::single_match)]286/// fn example() -> Result {287/// let mut numbers = KVec::new();288///289/// match numbers.push(72, GFP_KERNEL) {290/// Err(e) => {291/// pr_err!("Error pushing 72: {e:?}");292/// return Err(e.into());293/// }294/// // Do nothing, continue.295/// Ok(()) => (),296/// }297///298/// match numbers.push(108, GFP_KERNEL) {299/// Err(e) => {300/// pr_err!("Error pushing 108: {e:?}");301/// return Err(e.into());302/// }303/// // Do nothing, continue.304/// Ok(()) => (),305/// }306///307/// match numbers.push(200, GFP_KERNEL) {308/// Err(e) => {309/// pr_err!("Error pushing 200: {e:?}");310/// return Err(e.into());311/// }312/// // Do nothing, continue.313/// Ok(()) => (),314/// }315///316/// Ok(())317/// }318/// # example()?;319/// # Ok::<(), Error>(())320/// ```321///322/// An alternative to be more concise is the [`if let`] syntax:323///324/// ```325/// fn example() -> Result {326/// let mut numbers = KVec::new();327///328/// if let Err(e) = numbers.push(72, GFP_KERNEL) {329/// pr_err!("Error pushing 72: {e:?}");330/// return Err(e.into());331/// }332///333/// if let Err(e) = numbers.push(108, GFP_KERNEL) {334/// pr_err!("Error pushing 108: {e:?}");335/// return Err(e.into());336/// }337///338/// if let Err(e) = numbers.push(200, GFP_KERNEL) {339/// pr_err!("Error pushing 200: {e:?}");340/// return Err(e.into());341/// }342///343/// Ok(())344/// }345/// # example()?;346/// # Ok::<(), Error>(())347/// ```348///349/// Instead of these verbose [`match`]/[`if let`], the [`?`] operator can350/// be used to handle the [`Result`]. Using the [`?`] operator is often351/// the best choice to handle [`Result`] in a non-verbose way as done in352/// [`samples/rust/rust_minimal.rs`]:353///354/// ```355/// fn example() -> Result {356/// let mut numbers = KVec::new();357///358/// numbers.push(72, GFP_KERNEL)?;359/// numbers.push(108, GFP_KERNEL)?;360/// numbers.push(200, GFP_KERNEL)?;361///362/// Ok(())363/// }364/// # example()?;365/// # Ok::<(), Error>(())366/// ```367///368/// Another possibility is to call [`unwrap()`](Result::unwrap) or369/// [`expect()`](Result::expect). However, use of these functions is370/// *heavily discouraged* in the kernel because they trigger a Rust371/// [`panic!`] if an error happens, which may destabilize the system or372/// entirely break it as a result -- just like the C [`BUG()`] macro.373/// Please see the documentation for the C macro [`BUG()`] for guidance374/// on when to use these functions.375///376/// Alternatively, depending on the use case, using [`unwrap_or()`],377/// [`unwrap_or_else()`], [`unwrap_or_default()`] or [`unwrap_unchecked()`]378/// might be an option, as well.379///380/// For even more details, please see the [Rust documentation].381///382/// [`match`]: https://doc.rust-lang.org/reference/expressions/match-expr.html383/// [`samples/rust/rust_minimal.rs`]: srctree/samples/rust/rust_minimal.rs384/// [`if let`]: https://doc.rust-lang.org/reference/expressions/if-expr.html#if-let-expressions385/// [`?`]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator386/// [`unwrap()`]: Result::unwrap387/// [`expect()`]: Result::expect388/// [`BUG()`]: https://docs.kernel.org/process/deprecated.html#bug-and-bug-on389/// [`unwrap_or()`]: Result::unwrap_or390/// [`unwrap_or_else()`]: Result::unwrap_or_else391/// [`unwrap_or_default()`]: Result::unwrap_or_default392/// [`unwrap_unchecked()`]: Result::unwrap_unchecked393/// [Rust documentation]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html394pub type Result<T = (), E = Error> = core::result::Result<T, E>;395396/// Converts an integer as returned by a C kernel function to a [`Result`].397///398/// If the integer is negative, an [`Err`] with an [`Error`] as given by [`Error::from_errno`] is399/// returned. This means the integer must be `>= -MAX_ERRNO`.400///401/// Otherwise, it returns [`Ok`].402///403/// It is a bug to pass an out-of-range negative integer. `Err(EINVAL)` is returned in such a case.404///405/// # Examples406///407/// This function may be used to easily perform early returns with the [`?`] operator when working408/// with C APIs within Rust abstractions:409///410/// ```411/// # use kernel::error::to_result;412/// # mod bindings {413/// # #![expect(clippy::missing_safety_doc)]414/// # use kernel::prelude::*;415/// # pub(super) unsafe fn f1() -> c_int { 0 }416/// # pub(super) unsafe fn f2() -> c_int { EINVAL.to_errno() }417/// # }418/// fn f() -> Result {419/// // SAFETY: ...420/// to_result(unsafe { bindings::f1() })?;421///422/// // SAFETY: ...423/// to_result(unsafe { bindings::f2() })?;424///425/// // ...426///427/// Ok(())428/// }429/// # assert_eq!(f(), Err(EINVAL));430/// ```431///432/// [`?`]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator433pub fn to_result(err: crate::ffi::c_int) -> Result {434if err < 0 {435Err(Error::from_errno(err))436} else {437Ok(())438}439}440441/// Transform a kernel "error pointer" to a normal pointer.442///443/// Some kernel C API functions return an "error pointer" which optionally444/// embeds an `errno`. Callers are supposed to check the returned pointer445/// for errors. This function performs the check and converts the "error pointer"446/// to a normal pointer in an idiomatic fashion.447///448/// # Examples449///450/// ```ignore451/// # use kernel::from_err_ptr;452/// # use kernel::bindings;453/// fn devm_platform_ioremap_resource(454/// pdev: &mut PlatformDevice,455/// index: u32,456/// ) -> Result<*mut kernel::ffi::c_void> {457/// // SAFETY: `pdev` points to a valid platform device. There are no safety requirements458/// // on `index`.459/// from_err_ptr(unsafe { bindings::devm_platform_ioremap_resource(pdev.to_ptr(), index) })460/// }461/// ```462pub fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {463// CAST: Casting a pointer to `*const crate::ffi::c_void` is always valid.464let const_ptr: *const crate::ffi::c_void = ptr.cast();465// SAFETY: The FFI function does not deref the pointer.466if unsafe { bindings::IS_ERR(const_ptr) } {467// SAFETY: The FFI function does not deref the pointer.468let err = unsafe { bindings::PTR_ERR(const_ptr) };469470#[allow(clippy::unnecessary_cast)]471// CAST: If `IS_ERR()` returns `true`,472// then `PTR_ERR()` is guaranteed to return a473// negative value greater-or-equal to `-bindings::MAX_ERRNO`,474// which always fits in an `i16`, as per the invariant above.475// And an `i16` always fits in an `i32`. So casting `err` to476// an `i32` can never overflow, and is always valid.477//478// SAFETY: `IS_ERR()` ensures `err` is a479// negative value greater-or-equal to `-bindings::MAX_ERRNO`.480return Err(unsafe { Error::from_errno_unchecked(err as crate::ffi::c_int) });481}482Ok(ptr)483}484485/// Calls a closure returning a [`crate::error::Result<T>`] and converts the result to486/// a C integer result.487///488/// This is useful when calling Rust functions that return [`crate::error::Result<T>`]489/// from inside `extern "C"` functions that need to return an integer error result.490///491/// `T` should be convertible from an `i16` via `From<i16>`.492///493/// # Examples494///495/// ```ignore496/// # use kernel::from_result;497/// # use kernel::bindings;498/// unsafe extern "C" fn probe_callback(499/// pdev: *mut bindings::platform_device,500/// ) -> kernel::ffi::c_int {501/// from_result(|| {502/// let ptr = devm_alloc(pdev)?;503/// bindings::platform_set_drvdata(pdev, ptr);504/// Ok(0)505/// })506/// }507/// ```508pub fn from_result<T, F>(f: F) -> T509where510T: From<i16>,511F: FnOnce() -> Result<T>,512{513match f() {514Ok(v) => v,515// NO-OVERFLOW: negative `errno`s are no smaller than `-bindings::MAX_ERRNO`,516// `-bindings::MAX_ERRNO` fits in an `i16` as per invariant above,517// therefore a negative `errno` always fits in an `i16` and will not overflow.518Err(e) => T::from(e.to_errno() as i16),519}520}521522/// Error message for calling a default function of a [`#[vtable]`](macros::vtable) trait.523pub const VTABLE_DEFAULT_ERROR: &str =524"This function must not be called, see the #[vtable] documentation.";525526527