xref: /openbmc/linux/rust/kernel/error.rs (revision 4b0c68bd0d8b0e23ab1763d4a6632720dd3f1a83)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! Kernel errors.
4 //!
5 //! C header: [`include/uapi/asm-generic/errno-base.h`](../../../include/uapi/asm-generic/errno-base.h)
6 
7 use alloc::collections::TryReserveError;
8 
9 /// Contains the C-compatible error codes.
10 pub mod code {
11     macro_rules! declare_err {
12         ($err:tt $(,)? $($doc:expr),+) => {
13             $(
14             #[doc = $doc]
15             )*
16             pub const $err: super::Error = super::Error(-(crate::bindings::$err as i32));
17         };
18     }
19 
20     declare_err!(ENOMEM, "Out of memory.");
21 }
22 
23 /// Generic integer kernel error.
24 ///
25 /// The kernel defines a set of integer generic error codes based on C and
26 /// POSIX ones. These codes may have a more specific meaning in some contexts.
27 ///
28 /// # Invariants
29 ///
30 /// The value is a valid `errno` (i.e. `>= -MAX_ERRNO && < 0`).
31 #[derive(Clone, Copy, PartialEq, Eq)]
32 pub struct Error(core::ffi::c_int);
33 
34 impl Error {
35     /// Returns the kernel error code.
36     pub fn to_kernel_errno(self) -> core::ffi::c_int {
37         self.0
38     }
39 }
40 
41 impl From<TryReserveError> for Error {
42     fn from(_: TryReserveError) -> Error {
43         code::ENOMEM
44     }
45 }
46 
47 /// A [`Result`] with an [`Error`] error type.
48 ///
49 /// To be used as the return type for functions that may fail.
50 ///
51 /// # Error codes in C and Rust
52 ///
53 /// In C, it is common that functions indicate success or failure through
54 /// their return value; modifying or returning extra data through non-`const`
55 /// pointer parameters. In particular, in the kernel, functions that may fail
56 /// typically return an `int` that represents a generic error code. We model
57 /// those as [`Error`].
58 ///
59 /// In Rust, it is idiomatic to model functions that may fail as returning
60 /// a [`Result`]. Since in the kernel many functions return an error code,
61 /// [`Result`] is a type alias for a [`core::result::Result`] that uses
62 /// [`Error`] as its error type.
63 ///
64 /// Note that even if a function does not return anything when it succeeds,
65 /// it should still be modeled as returning a `Result` rather than
66 /// just an [`Error`].
67 pub type Result<T = ()> = core::result::Result<T, Error>;
68