xref: /linux-6.15/rust/kernel/error.rs (revision 5ab560ce)
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 
7 use crate::str::CStr;
8 
9 use alloc::alloc::{AllocError, LayoutError};
10 
11 use core::convert::From;
12 use core::fmt;
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, "No child processes.");
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     /// Returns a string representing the error, if one exists.
138     #[cfg(not(testlib))]
139     pub fn name(&self) -> Option<&'static CStr> {
140         // SAFETY: Just an FFI call, there are no extra safety requirements.
141         let ptr = unsafe { bindings::errname(-self.0) };
142         if ptr.is_null() {
143             None
144         } else {
145             // SAFETY: The string returned by `errname` is static and `NUL`-terminated.
146             Some(unsafe { CStr::from_char_ptr(ptr) })
147         }
148     }
149 
150     /// Returns a string representing the error, if one exists.
151     ///
152     /// When `testlib` is configured, this always returns `None` to avoid the dependency on a
153     /// kernel function so that tests that use this (e.g., by calling [`Result::unwrap`]) can still
154     /// run in userspace.
155     #[cfg(testlib)]
156     pub fn name(&self) -> Option<&'static CStr> {
157         None
158     }
159 }
160 
161 impl fmt::Debug for Error {
162     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163         match self.name() {
164             // Print out number if no name can be found.
165             None => f.debug_tuple("Error").field(&-self.0).finish(),
166             // SAFETY: These strings are ASCII-only.
167             Some(name) => f
168                 .debug_tuple(unsafe { core::str::from_utf8_unchecked(name) })
169                 .finish(),
170         }
171     }
172 }
173 
174 impl From<AllocError> for Error {
175     fn from(_: AllocError) -> Error {
176         code::ENOMEM
177     }
178 }
179 
180 impl From<TryFromIntError> for Error {
181     fn from(_: TryFromIntError) -> Error {
182         code::EINVAL
183     }
184 }
185 
186 impl From<Utf8Error> for Error {
187     fn from(_: Utf8Error) -> Error {
188         code::EINVAL
189     }
190 }
191 
192 impl From<LayoutError> for Error {
193     fn from(_: LayoutError) -> Error {
194         code::ENOMEM
195     }
196 }
197 
198 impl From<core::fmt::Error> for Error {
199     fn from(_: core::fmt::Error) -> Error {
200         code::EINVAL
201     }
202 }
203 
204 impl From<core::convert::Infallible> for Error {
205     fn from(e: core::convert::Infallible) -> Error {
206         match e {}
207     }
208 }
209 
210 /// A [`Result`] with an [`Error`] error type.
211 ///
212 /// To be used as the return type for functions that may fail.
213 ///
214 /// # Error codes in C and Rust
215 ///
216 /// In C, it is common that functions indicate success or failure through
217 /// their return value; modifying or returning extra data through non-`const`
218 /// pointer parameters. In particular, in the kernel, functions that may fail
219 /// typically return an `int` that represents a generic error code. We model
220 /// those as [`Error`].
221 ///
222 /// In Rust, it is idiomatic to model functions that may fail as returning
223 /// a [`Result`]. Since in the kernel many functions return an error code,
224 /// [`Result`] is a type alias for a [`core::result::Result`] that uses
225 /// [`Error`] as its error type.
226 ///
227 /// Note that even if a function does not return anything when it succeeds,
228 /// it should still be modeled as returning a `Result` rather than
229 /// just an [`Error`].
230 pub type Result<T = (), E = Error> = core::result::Result<T, E>;
231 
232 /// Converts an integer as returned by a C kernel function to an error if it's negative, and
233 /// `Ok(())` otherwise.
234 pub fn to_result(err: core::ffi::c_int) -> Result {
235     if err < 0 {
236         Err(Error::from_errno(err))
237     } else {
238         Ok(())
239     }
240 }
241 
242 /// Transform a kernel "error pointer" to a normal pointer.
243 ///
244 /// Some kernel C API functions return an "error pointer" which optionally
245 /// embeds an `errno`. Callers are supposed to check the returned pointer
246 /// for errors. This function performs the check and converts the "error pointer"
247 /// to a normal pointer in an idiomatic fashion.
248 ///
249 /// # Examples
250 ///
251 /// ```ignore
252 /// # use kernel::from_err_ptr;
253 /// # use kernel::bindings;
254 /// fn devm_platform_ioremap_resource(
255 ///     pdev: &mut PlatformDevice,
256 ///     index: u32,
257 /// ) -> Result<*mut core::ffi::c_void> {
258 ///     // SAFETY: `pdev` points to a valid platform device. There are no safety requirements
259 ///     // on `index`.
260 ///     from_err_ptr(unsafe { bindings::devm_platform_ioremap_resource(pdev.to_ptr(), index) })
261 /// }
262 /// ```
263 // TODO: Remove `dead_code` marker once an in-kernel client is available.
264 #[allow(dead_code)]
265 pub(crate) fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
266     // CAST: Casting a pointer to `*const core::ffi::c_void` is always valid.
267     let const_ptr: *const core::ffi::c_void = ptr.cast();
268     // SAFETY: The FFI function does not deref the pointer.
269     if unsafe { bindings::IS_ERR(const_ptr) } {
270         // SAFETY: The FFI function does not deref the pointer.
271         let err = unsafe { bindings::PTR_ERR(const_ptr) };
272         // CAST: If `IS_ERR()` returns `true`,
273         // then `PTR_ERR()` is guaranteed to return a
274         // negative value greater-or-equal to `-bindings::MAX_ERRNO`,
275         // which always fits in an `i16`, as per the invariant above.
276         // And an `i16` always fits in an `i32`. So casting `err` to
277         // an `i32` can never overflow, and is always valid.
278         //
279         // SAFETY: `IS_ERR()` ensures `err` is a
280         // negative value greater-or-equal to `-bindings::MAX_ERRNO`.
281         #[allow(clippy::unnecessary_cast)]
282         return Err(unsafe { Error::from_errno_unchecked(err as core::ffi::c_int) });
283     }
284     Ok(ptr)
285 }
286 
287 /// Calls a closure returning a [`crate::error::Result<T>`] and converts the result to
288 /// a C integer result.
289 ///
290 /// This is useful when calling Rust functions that return [`crate::error::Result<T>`]
291 /// from inside `extern "C"` functions that need to return an integer error result.
292 ///
293 /// `T` should be convertible from an `i16` via `From<i16>`.
294 ///
295 /// # Examples
296 ///
297 /// ```ignore
298 /// # use kernel::from_result;
299 /// # use kernel::bindings;
300 /// unsafe extern "C" fn probe_callback(
301 ///     pdev: *mut bindings::platform_device,
302 /// ) -> core::ffi::c_int {
303 ///     from_result(|| {
304 ///         let ptr = devm_alloc(pdev)?;
305 ///         bindings::platform_set_drvdata(pdev, ptr);
306 ///         Ok(0)
307 ///     })
308 /// }
309 /// ```
310 // TODO: Remove `dead_code` marker once an in-kernel client is available.
311 #[allow(dead_code)]
312 pub(crate) fn from_result<T, F>(f: F) -> T
313 where
314     T: From<i16>,
315     F: FnOnce() -> Result<T>,
316 {
317     match f() {
318         Ok(v) => v,
319         // NO-OVERFLOW: negative `errno`s are no smaller than `-bindings::MAX_ERRNO`,
320         // `-bindings::MAX_ERRNO` fits in an `i16` as per invariant above,
321         // therefore a negative `errno` always fits in an `i16` and will not overflow.
322         Err(e) => T::from(e.to_errno() as i16),
323     }
324 }
325 
326 /// Error message for calling a default function of a [`#[vtable]`](macros::vtable) trait.
327 pub const VTABLE_DEFAULT_ERROR: &str =
328     "This function must not be called, see the #[vtable] documentation.";
329