xref: /linux-6.15/rust/kernel/error.rs (revision e37b654c)
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::{
8     alloc::{AllocError, LayoutError},
9     collections::TryReserveError,
10 };
11 
12 use core::convert::From;
13 use core::num::TryFromIntError;
14 use core::str::Utf8Error;
15 
16 /// Contains the C-compatible error codes.
17 #[rustfmt::skip]
18 pub mod code {
19     macro_rules! declare_err {
20         ($err:tt $(,)? $($doc:expr),+) => {
21             $(
22             #[doc = $doc]
23             )*
24             pub const $err: super::Error = super::Error(-(crate::bindings::$err as i32));
25         };
26     }
27 
28     declare_err!(EPERM, "Operation not permitted.");
29     declare_err!(ENOENT, "No such file or directory.");
30     declare_err!(ESRCH, "No such process.");
31     declare_err!(EINTR, "Interrupted system call.");
32     declare_err!(EIO, "I/O error.");
33     declare_err!(ENXIO, "No such device or address.");
34     declare_err!(E2BIG, "Argument list too long.");
35     declare_err!(ENOEXEC, "Exec format error.");
36     declare_err!(EBADF, "Bad file number.");
37     declare_err!(ECHILD, "Exec format error.");
38     declare_err!(EAGAIN, "Try again.");
39     declare_err!(ENOMEM, "Out of memory.");
40     declare_err!(EACCES, "Permission denied.");
41     declare_err!(EFAULT, "Bad address.");
42     declare_err!(ENOTBLK, "Block device required.");
43     declare_err!(EBUSY, "Device or resource busy.");
44     declare_err!(EEXIST, "File exists.");
45     declare_err!(EXDEV, "Cross-device link.");
46     declare_err!(ENODEV, "No such device.");
47     declare_err!(ENOTDIR, "Not a directory.");
48     declare_err!(EISDIR, "Is a directory.");
49     declare_err!(EINVAL, "Invalid argument.");
50     declare_err!(ENFILE, "File table overflow.");
51     declare_err!(EMFILE, "Too many open files.");
52     declare_err!(ENOTTY, "Not a typewriter.");
53     declare_err!(ETXTBSY, "Text file busy.");
54     declare_err!(EFBIG, "File too large.");
55     declare_err!(ENOSPC, "No space left on device.");
56     declare_err!(ESPIPE, "Illegal seek.");
57     declare_err!(EROFS, "Read-only file system.");
58     declare_err!(EMLINK, "Too many links.");
59     declare_err!(EPIPE, "Broken pipe.");
60     declare_err!(EDOM, "Math argument out of domain of func.");
61     declare_err!(ERANGE, "Math result not representable.");
62     declare_err!(ERESTARTSYS, "Restart the system call.");
63     declare_err!(ERESTARTNOINTR, "System call was interrupted by a signal and will be restarted.");
64     declare_err!(ERESTARTNOHAND, "Restart if no handler.");
65     declare_err!(ENOIOCTLCMD, "No ioctl command.");
66     declare_err!(ERESTART_RESTARTBLOCK, "Restart by calling sys_restart_syscall.");
67     declare_err!(EPROBE_DEFER, "Driver requests probe retry.");
68     declare_err!(EOPENSTALE, "Open found a stale dentry.");
69     declare_err!(ENOPARAM, "Parameter not supported.");
70     declare_err!(EBADHANDLE, "Illegal NFS file handle.");
71     declare_err!(ENOTSYNC, "Update synchronization mismatch.");
72     declare_err!(EBADCOOKIE, "Cookie is stale.");
73     declare_err!(ENOTSUPP, "Operation is not supported.");
74     declare_err!(ETOOSMALL, "Buffer or request is too small.");
75     declare_err!(ESERVERFAULT, "An untranslatable error occurred.");
76     declare_err!(EBADTYPE, "Type not supported by server.");
77     declare_err!(EJUKEBOX, "Request initiated, but will not complete before timeout.");
78     declare_err!(EIOCBQUEUED, "iocb queued, will get completion event.");
79     declare_err!(ERECALLCONFLICT, "Conflict with recalled state.");
80     declare_err!(ENOGRACE, "NFS file lock reclaim refused.");
81 }
82 
83 /// Generic integer kernel error.
84 ///
85 /// The kernel defines a set of integer generic error codes based on C and
86 /// POSIX ones. These codes may have a more specific meaning in some contexts.
87 ///
88 /// # Invariants
89 ///
90 /// The value is a valid `errno` (i.e. `>= -MAX_ERRNO && < 0`).
91 #[derive(Clone, Copy, PartialEq, Eq)]
92 pub struct Error(core::ffi::c_int);
93 
94 impl Error {
95     /// Creates an [`Error`] from a kernel error code.
96     ///
97     /// It is a bug to pass an out-of-range `errno`. `EINVAL` would
98     /// be returned in such a case.
99     pub(crate) fn from_errno(errno: core::ffi::c_int) -> Error {
100         if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
101             // TODO: Make it a `WARN_ONCE` once available.
102             crate::pr_warn!(
103                 "attempted to create `Error` with out of range `errno`: {}",
104                 errno
105             );
106             return code::EINVAL;
107         }
108 
109         // INVARIANT: The check above ensures the type invariant
110         // will hold.
111         Error(errno)
112     }
113 
114     /// Creates an [`Error`] from a kernel error code.
115     ///
116     /// # Safety
117     ///
118     /// `errno` must be within error code range (i.e. `>= -MAX_ERRNO && < 0`).
119     unsafe fn from_errno_unchecked(errno: core::ffi::c_int) -> Error {
120         // INVARIANT: The contract ensures the type invariant
121         // will hold.
122         Error(errno)
123     }
124 
125     /// Returns the kernel error code.
126     pub fn to_errno(self) -> core::ffi::c_int {
127         self.0
128     }
129 
130     /// Returns the error encoded as a pointer.
131     #[allow(dead_code)]
132     pub(crate) fn to_ptr<T>(self) -> *mut T {
133         // SAFETY: self.0 is a valid error due to its invariant.
134         unsafe { bindings::ERR_PTR(self.0.into()) as *mut _ }
135     }
136 }
137 
138 impl From<AllocError> for Error {
139     fn from(_: AllocError) -> Error {
140         code::ENOMEM
141     }
142 }
143 
144 impl From<TryFromIntError> for Error {
145     fn from(_: TryFromIntError) -> Error {
146         code::EINVAL
147     }
148 }
149 
150 impl From<Utf8Error> for Error {
151     fn from(_: Utf8Error) -> Error {
152         code::EINVAL
153     }
154 }
155 
156 impl From<TryReserveError> for Error {
157     fn from(_: TryReserveError) -> Error {
158         code::ENOMEM
159     }
160 }
161 
162 impl From<LayoutError> for Error {
163     fn from(_: LayoutError) -> Error {
164         code::ENOMEM
165     }
166 }
167 
168 impl From<core::fmt::Error> for Error {
169     fn from(_: core::fmt::Error) -> Error {
170         code::EINVAL
171     }
172 }
173 
174 impl From<core::convert::Infallible> for Error {
175     fn from(e: core::convert::Infallible) -> Error {
176         match e {}
177     }
178 }
179 
180 /// A [`Result`] with an [`Error`] error type.
181 ///
182 /// To be used as the return type for functions that may fail.
183 ///
184 /// # Error codes in C and Rust
185 ///
186 /// In C, it is common that functions indicate success or failure through
187 /// their return value; modifying or returning extra data through non-`const`
188 /// pointer parameters. In particular, in the kernel, functions that may fail
189 /// typically return an `int` that represents a generic error code. We model
190 /// those as [`Error`].
191 ///
192 /// In Rust, it is idiomatic to model functions that may fail as returning
193 /// a [`Result`]. Since in the kernel many functions return an error code,
194 /// [`Result`] is a type alias for a [`core::result::Result`] that uses
195 /// [`Error`] as its error type.
196 ///
197 /// Note that even if a function does not return anything when it succeeds,
198 /// it should still be modeled as returning a `Result` rather than
199 /// just an [`Error`].
200 pub type Result<T = (), E = Error> = core::result::Result<T, E>;
201 
202 /// Converts an integer as returned by a C kernel function to an error if it's negative, and
203 /// `Ok(())` otherwise.
204 pub fn to_result(err: core::ffi::c_int) -> Result {
205     if err < 0 {
206         Err(Error::from_errno(err))
207     } else {
208         Ok(())
209     }
210 }
211 
212 /// Transform a kernel "error pointer" to a normal pointer.
213 ///
214 /// Some kernel C API functions return an "error pointer" which optionally
215 /// embeds an `errno`. Callers are supposed to check the returned pointer
216 /// for errors. This function performs the check and converts the "error pointer"
217 /// to a normal pointer in an idiomatic fashion.
218 ///
219 /// # Examples
220 ///
221 /// ```ignore
222 /// # use kernel::from_err_ptr;
223 /// # use kernel::bindings;
224 /// fn devm_platform_ioremap_resource(
225 ///     pdev: &mut PlatformDevice,
226 ///     index: u32,
227 /// ) -> Result<*mut core::ffi::c_void> {
228 ///     // SAFETY: FFI call.
229 ///     unsafe {
230 ///         from_err_ptr(bindings::devm_platform_ioremap_resource(
231 ///             pdev.to_ptr(),
232 ///             index,
233 ///         ))
234 ///     }
235 /// }
236 /// ```
237 // TODO: Remove `dead_code` marker once an in-kernel client is available.
238 #[allow(dead_code)]
239 pub(crate) fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
240     // CAST: Casting a pointer to `*const core::ffi::c_void` is always valid.
241     let const_ptr: *const core::ffi::c_void = ptr.cast();
242     // SAFETY: The FFI function does not deref the pointer.
243     if unsafe { bindings::IS_ERR(const_ptr) } {
244         // SAFETY: The FFI function does not deref the pointer.
245         let err = unsafe { bindings::PTR_ERR(const_ptr) };
246         // CAST: If `IS_ERR()` returns `true`,
247         // then `PTR_ERR()` is guaranteed to return a
248         // negative value greater-or-equal to `-bindings::MAX_ERRNO`,
249         // which always fits in an `i16`, as per the invariant above.
250         // And an `i16` always fits in an `i32`. So casting `err` to
251         // an `i32` can never overflow, and is always valid.
252         //
253         // SAFETY: `IS_ERR()` ensures `err` is a
254         // negative value greater-or-equal to `-bindings::MAX_ERRNO`.
255         #[allow(clippy::unnecessary_cast)]
256         return Err(unsafe { Error::from_errno_unchecked(err as core::ffi::c_int) });
257     }
258     Ok(ptr)
259 }
260 
261 /// Calls a closure returning a [`crate::error::Result<T>`] and converts the result to
262 /// a C integer result.
263 ///
264 /// This is useful when calling Rust functions that return [`crate::error::Result<T>`]
265 /// from inside `extern "C"` functions that need to return an integer error result.
266 ///
267 /// `T` should be convertible from an `i16` via `From<i16>`.
268 ///
269 /// # Examples
270 ///
271 /// ```ignore
272 /// # use kernel::from_result;
273 /// # use kernel::bindings;
274 /// unsafe extern "C" fn probe_callback(
275 ///     pdev: *mut bindings::platform_device,
276 /// ) -> core::ffi::c_int {
277 ///     from_result(|| {
278 ///         let ptr = devm_alloc(pdev)?;
279 ///         bindings::platform_set_drvdata(pdev, ptr);
280 ///         Ok(0)
281 ///     })
282 /// }
283 /// ```
284 // TODO: Remove `dead_code` marker once an in-kernel client is available.
285 #[allow(dead_code)]
286 pub(crate) fn from_result<T, F>(f: F) -> T
287 where
288     T: From<i16>,
289     F: FnOnce() -> Result<T>,
290 {
291     match f() {
292         Ok(v) => v,
293         // NO-OVERFLOW: negative `errno`s are no smaller than `-bindings::MAX_ERRNO`,
294         // `-bindings::MAX_ERRNO` fits in an `i16` as per invariant above,
295         // therefore a negative `errno` always fits in an `i16` and will not overflow.
296         Err(e) => T::from(e.to_errno() as i16),
297     }
298 }
299