xref: /linux/rust/kernel/error.rs (revision 352af6a011d586ff042db4b2d1f7421875eb8a14)
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::{
8     alloc::{layout::LayoutError, AllocError},
9     fmt,
10     str::CStr,
11 };
12 
13 use core::num::NonZeroI32;
14 use core::num::TryFromIntError;
15 use core::str::Utf8Error;
16 
17 /// Contains the C-compatible error codes.
18 #[rustfmt::skip]
19 pub mod code {
20     macro_rules! declare_err {
21         ($err:tt $(,)? $($doc:expr),+) => {
22             $(
23             #[doc = $doc]
24             )*
25             pub const $err: super::Error =
26                 match super::Error::try_from_errno(-(crate::bindings::$err as i32)) {
27                     Some(err) => err,
28                     None => panic!("Invalid errno in `declare_err!`"),
29                 };
30         };
31     }
32 
33     declare_err!(EPERM, "Operation not permitted.");
34     declare_err!(ENOENT, "No such file or directory.");
35     declare_err!(ESRCH, "No such process.");
36     declare_err!(EINTR, "Interrupted system call.");
37     declare_err!(EIO, "I/O error.");
38     declare_err!(ENXIO, "No such device or address.");
39     declare_err!(E2BIG, "Argument list too long.");
40     declare_err!(ENOEXEC, "Exec format error.");
41     declare_err!(EBADF, "Bad file number.");
42     declare_err!(ECHILD, "No child processes.");
43     declare_err!(EAGAIN, "Try again.");
44     declare_err!(ENOMEM, "Out of memory.");
45     declare_err!(EACCES, "Permission denied.");
46     declare_err!(EFAULT, "Bad address.");
47     declare_err!(ENOTBLK, "Block device required.");
48     declare_err!(EBUSY, "Device or resource busy.");
49     declare_err!(EEXIST, "File exists.");
50     declare_err!(EXDEV, "Cross-device link.");
51     declare_err!(ENODEV, "No such device.");
52     declare_err!(ENOTDIR, "Not a directory.");
53     declare_err!(EISDIR, "Is a directory.");
54     declare_err!(EINVAL, "Invalid argument.");
55     declare_err!(ENFILE, "File table overflow.");
56     declare_err!(EMFILE, "Too many open files.");
57     declare_err!(ENOTTY, "Not a typewriter.");
58     declare_err!(ETXTBSY, "Text file busy.");
59     declare_err!(EFBIG, "File too large.");
60     declare_err!(ENOSPC, "No space left on device.");
61     declare_err!(ESPIPE, "Illegal seek.");
62     declare_err!(EROFS, "Read-only file system.");
63     declare_err!(EMLINK, "Too many links.");
64     declare_err!(EPIPE, "Broken pipe.");
65     declare_err!(EDOM, "Math argument out of domain of func.");
66     declare_err!(ERANGE, "Math result not representable.");
67     declare_err!(EOVERFLOW, "Value too large for defined data type.");
68     declare_err!(ETIMEDOUT, "Connection timed out.");
69     declare_err!(ERESTARTSYS, "Restart the system call.");
70     declare_err!(ERESTARTNOINTR, "System call was interrupted by a signal and will be restarted.");
71     declare_err!(ERESTARTNOHAND, "Restart if no handler.");
72     declare_err!(ENOIOCTLCMD, "No ioctl command.");
73     declare_err!(ERESTART_RESTARTBLOCK, "Restart by calling sys_restart_syscall.");
74     declare_err!(EPROBE_DEFER, "Driver requests probe retry.");
75     declare_err!(EOPENSTALE, "Open found a stale dentry.");
76     declare_err!(ENOPARAM, "Parameter not supported.");
77     declare_err!(EBADHANDLE, "Illegal NFS file handle.");
78     declare_err!(ENOTSYNC, "Update synchronization mismatch.");
79     declare_err!(EBADCOOKIE, "Cookie is stale.");
80     declare_err!(ENOTSUPP, "Operation is not supported.");
81     declare_err!(ETOOSMALL, "Buffer or request is too small.");
82     declare_err!(ESERVERFAULT, "An untranslatable error occurred.");
83     declare_err!(EBADTYPE, "Type not supported by server.");
84     declare_err!(EJUKEBOX, "Request initiated, but will not complete before timeout.");
85     declare_err!(EIOCBQUEUED, "iocb queued, will get completion event.");
86     declare_err!(ERECALLCONFLICT, "Conflict with recalled state.");
87     declare_err!(ENOGRACE, "NFS file lock reclaim refused.");
88 }
89 
90 /// Generic integer kernel error.
91 ///
92 /// The kernel defines a set of integer generic error codes based on C and
93 /// POSIX ones. These codes may have a more specific meaning in some contexts.
94 ///
95 /// # Invariants
96 ///
97 /// The value is a valid `errno` (i.e. `>= -MAX_ERRNO && < 0`).
98 #[derive(Clone, Copy, PartialEq, Eq)]
99 pub struct Error(NonZeroI32);
100 
101 impl Error {
102     /// Creates an [`Error`] from a kernel error code.
103     ///
104     /// It is a bug to pass an out-of-range `errno`. `EINVAL` would
105     /// be returned in such a case.
from_errno(errno: crate::ffi::c_int) -> Error106     pub fn from_errno(errno: crate::ffi::c_int) -> Error {
107         if let Some(error) = Self::try_from_errno(errno) {
108             error
109         } else {
110             // TODO: Make it a `WARN_ONCE` once available.
111             crate::pr_warn!(
112                 "attempted to create `Error` with out of range `errno`: {}\n",
113                 errno
114             );
115             code::EINVAL
116         }
117     }
118 
119     /// Creates an [`Error`] from a kernel error code.
120     ///
121     /// Returns [`None`] if `errno` is out-of-range.
try_from_errno(errno: crate::ffi::c_int) -> Option<Error>122     const fn try_from_errno(errno: crate::ffi::c_int) -> Option<Error> {
123         if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
124             return None;
125         }
126 
127         // SAFETY: `errno` is checked above to be in a valid range.
128         Some(unsafe { Error::from_errno_unchecked(errno) })
129     }
130 
131     /// Creates an [`Error`] from a kernel error code.
132     ///
133     /// # Safety
134     ///
135     /// `errno` must be within error code range (i.e. `>= -MAX_ERRNO && < 0`).
from_errno_unchecked(errno: crate::ffi::c_int) -> Error136     const unsafe fn from_errno_unchecked(errno: crate::ffi::c_int) -> Error {
137         // INVARIANT: The contract ensures the type invariant
138         // will hold.
139         // SAFETY: The caller guarantees `errno` is non-zero.
140         Error(unsafe { NonZeroI32::new_unchecked(errno) })
141     }
142 
143     /// Returns the kernel error code.
to_errno(self) -> crate::ffi::c_int144     pub fn to_errno(self) -> crate::ffi::c_int {
145         self.0.get()
146     }
147 
148     #[cfg(CONFIG_BLOCK)]
to_blk_status(self) -> bindings::blk_status_t149     pub(crate) fn to_blk_status(self) -> bindings::blk_status_t {
150         // SAFETY: `self.0` is a valid error due to its invariant.
151         unsafe { bindings::errno_to_blk_status(self.0.get()) }
152     }
153 
154     /// Returns the error encoded as a pointer.
to_ptr<T>(self) -> *mut T155     pub fn to_ptr<T>(self) -> *mut T {
156         // SAFETY: `self.0` is a valid error due to its invariant.
157         unsafe { bindings::ERR_PTR(self.0.get() as crate::ffi::c_long).cast() }
158     }
159 
160     /// Returns a string representing the error, if one exists.
161     #[cfg(not(any(test, testlib)))]
name(&self) -> Option<&'static CStr>162     pub fn name(&self) -> Option<&'static CStr> {
163         // SAFETY: Just an FFI call, there are no extra safety requirements.
164         let ptr = unsafe { bindings::errname(-self.0.get()) };
165         if ptr.is_null() {
166             None
167         } else {
168             // SAFETY: The string returned by `errname` is static and `NUL`-terminated.
169             Some(unsafe { CStr::from_char_ptr(ptr) })
170         }
171     }
172 
173     /// Returns a string representing the error, if one exists.
174     ///
175     /// When `testlib` is configured, this always returns `None` to avoid the dependency on a
176     /// kernel function so that tests that use this (e.g., by calling [`Result::unwrap`]) can still
177     /// run in userspace.
178     #[cfg(any(test, testlib))]
name(&self) -> Option<&'static CStr>179     pub fn name(&self) -> Option<&'static CStr> {
180         None
181     }
182 }
183 
184 impl fmt::Debug for Error {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result185     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186         match self.name() {
187             // Print out number if no name can be found.
188             None => f.debug_tuple("Error").field(&-self.0).finish(),
189             Some(name) => f
190                 .debug_tuple(
191                     // SAFETY: These strings are ASCII-only.
192                     unsafe { core::str::from_utf8_unchecked(name.to_bytes()) },
193                 )
194                 .finish(),
195         }
196     }
197 }
198 
199 impl From<AllocError> for Error {
from(_: AllocError) -> Error200     fn from(_: AllocError) -> Error {
201         code::ENOMEM
202     }
203 }
204 
205 impl From<TryFromIntError> for Error {
from(_: TryFromIntError) -> Error206     fn from(_: TryFromIntError) -> Error {
207         code::EINVAL
208     }
209 }
210 
211 impl From<Utf8Error> for Error {
from(_: Utf8Error) -> Error212     fn from(_: Utf8Error) -> Error {
213         code::EINVAL
214     }
215 }
216 
217 impl From<LayoutError> for Error {
from(_: LayoutError) -> Error218     fn from(_: LayoutError) -> Error {
219         code::ENOMEM
220     }
221 }
222 
223 impl From<fmt::Error> for Error {
from(_: fmt::Error) -> Error224     fn from(_: fmt::Error) -> Error {
225         code::EINVAL
226     }
227 }
228 
229 impl From<core::convert::Infallible> for Error {
from(e: core::convert::Infallible) -> Error230     fn from(e: core::convert::Infallible) -> Error {
231         match e {}
232     }
233 }
234 
235 /// A [`Result`] with an [`Error`] error type.
236 ///
237 /// To be used as the return type for functions that may fail.
238 ///
239 /// # Error codes in C and Rust
240 ///
241 /// In C, it is common that functions indicate success or failure through
242 /// their return value; modifying or returning extra data through non-`const`
243 /// pointer parameters. In particular, in the kernel, functions that may fail
244 /// typically return an `int` that represents a generic error code. We model
245 /// those as [`Error`].
246 ///
247 /// In Rust, it is idiomatic to model functions that may fail as returning
248 /// a [`Result`]. Since in the kernel many functions return an error code,
249 /// [`Result`] is a type alias for a [`core::result::Result`] that uses
250 /// [`Error`] as its error type.
251 ///
252 /// Note that even if a function does not return anything when it succeeds,
253 /// it should still be modeled as returning a [`Result`] rather than
254 /// just an [`Error`].
255 ///
256 /// Calling a function that returns [`Result`] forces the caller to handle
257 /// the returned [`Result`].
258 ///
259 /// This can be done "manually" by using [`match`]. Using [`match`] to decode
260 /// the [`Result`] is similar to C where all the return value decoding and the
261 /// error handling is done explicitly by writing handling code for each
262 /// error to cover. Using [`match`] the error and success handling can be
263 /// implemented in all detail as required. For example (inspired by
264 /// [`samples/rust/rust_minimal.rs`]):
265 ///
266 /// ```
267 /// # #[allow(clippy::single_match)]
268 /// fn example() -> Result {
269 ///     let mut numbers = KVec::new();
270 ///
271 ///     match numbers.push(72, GFP_KERNEL) {
272 ///         Err(e) => {
273 ///             pr_err!("Error pushing 72: {e:?}");
274 ///             return Err(e.into());
275 ///         }
276 ///         // Do nothing, continue.
277 ///         Ok(()) => (),
278 ///     }
279 ///
280 ///     match numbers.push(108, GFP_KERNEL) {
281 ///         Err(e) => {
282 ///             pr_err!("Error pushing 108: {e:?}");
283 ///             return Err(e.into());
284 ///         }
285 ///         // Do nothing, continue.
286 ///         Ok(()) => (),
287 ///     }
288 ///
289 ///     match numbers.push(200, GFP_KERNEL) {
290 ///         Err(e) => {
291 ///             pr_err!("Error pushing 200: {e:?}");
292 ///             return Err(e.into());
293 ///         }
294 ///         // Do nothing, continue.
295 ///         Ok(()) => (),
296 ///     }
297 ///
298 ///     Ok(())
299 /// }
300 /// # example()?;
301 /// # Ok::<(), Error>(())
302 /// ```
303 ///
304 /// An alternative to be more concise is the [`if let`] syntax:
305 ///
306 /// ```
307 /// fn example() -> Result {
308 ///     let mut numbers = KVec::new();
309 ///
310 ///     if let Err(e) = numbers.push(72, GFP_KERNEL) {
311 ///         pr_err!("Error pushing 72: {e:?}");
312 ///         return Err(e.into());
313 ///     }
314 ///
315 ///     if let Err(e) = numbers.push(108, GFP_KERNEL) {
316 ///         pr_err!("Error pushing 108: {e:?}");
317 ///         return Err(e.into());
318 ///     }
319 ///
320 ///     if let Err(e) = numbers.push(200, GFP_KERNEL) {
321 ///         pr_err!("Error pushing 200: {e:?}");
322 ///         return Err(e.into());
323 ///     }
324 ///
325 ///     Ok(())
326 /// }
327 /// # example()?;
328 /// # Ok::<(), Error>(())
329 /// ```
330 ///
331 /// Instead of these verbose [`match`]/[`if let`], the [`?`] operator can
332 /// be used to handle the [`Result`]. Using the [`?`] operator is often
333 /// the best choice to handle [`Result`] in a non-verbose way as done in
334 /// [`samples/rust/rust_minimal.rs`]:
335 ///
336 /// ```
337 /// fn example() -> Result {
338 ///     let mut numbers = KVec::new();
339 ///
340 ///     numbers.push(72, GFP_KERNEL)?;
341 ///     numbers.push(108, GFP_KERNEL)?;
342 ///     numbers.push(200, GFP_KERNEL)?;
343 ///
344 ///     Ok(())
345 /// }
346 /// # example()?;
347 /// # Ok::<(), Error>(())
348 /// ```
349 ///
350 /// Another possibility is to call [`unwrap()`](Result::unwrap) or
351 /// [`expect()`](Result::expect). However, use of these functions is
352 /// *heavily discouraged* in the kernel because they trigger a Rust
353 /// [`panic!`] if an error happens, which may destabilize the system or
354 /// entirely break it as a result -- just like the C [`BUG()`] macro.
355 /// Please see the documentation for the C macro [`BUG()`] for guidance
356 /// on when to use these functions.
357 ///
358 /// Alternatively, depending on the use case, using [`unwrap_or()`],
359 /// [`unwrap_or_else()`], [`unwrap_or_default()`] or [`unwrap_unchecked()`]
360 /// might be an option, as well.
361 ///
362 /// For even more details, please see the [Rust documentation].
363 ///
364 /// [`match`]: https://doc.rust-lang.org/reference/expressions/match-expr.html
365 /// [`samples/rust/rust_minimal.rs`]: srctree/samples/rust/rust_minimal.rs
366 /// [`if let`]: https://doc.rust-lang.org/reference/expressions/if-expr.html#if-let-expressions
367 /// [`?`]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator
368 /// [`unwrap()`]: Result::unwrap
369 /// [`expect()`]: Result::expect
370 /// [`BUG()`]: https://docs.kernel.org/process/deprecated.html#bug-and-bug-on
371 /// [`unwrap_or()`]: Result::unwrap_or
372 /// [`unwrap_or_else()`]: Result::unwrap_or_else
373 /// [`unwrap_or_default()`]: Result::unwrap_or_default
374 /// [`unwrap_unchecked()`]: Result::unwrap_unchecked
375 /// [Rust documentation]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html
376 pub type Result<T = (), E = Error> = core::result::Result<T, E>;
377 
378 /// Converts an integer as returned by a C kernel function to an error if it's negative, and
379 /// `Ok(())` otherwise.
to_result(err: crate::ffi::c_int) -> Result380 pub fn to_result(err: crate::ffi::c_int) -> Result {
381     if err < 0 {
382         Err(Error::from_errno(err))
383     } else {
384         Ok(())
385     }
386 }
387 
388 /// Transform a kernel "error pointer" to a normal pointer.
389 ///
390 /// Some kernel C API functions return an "error pointer" which optionally
391 /// embeds an `errno`. Callers are supposed to check the returned pointer
392 /// for errors. This function performs the check and converts the "error pointer"
393 /// to a normal pointer in an idiomatic fashion.
394 ///
395 /// # Examples
396 ///
397 /// ```ignore
398 /// # use kernel::from_err_ptr;
399 /// # use kernel::bindings;
400 /// fn devm_platform_ioremap_resource(
401 ///     pdev: &mut PlatformDevice,
402 ///     index: u32,
403 /// ) -> Result<*mut kernel::ffi::c_void> {
404 ///     // SAFETY: `pdev` points to a valid platform device. There are no safety requirements
405 ///     // on `index`.
406 ///     from_err_ptr(unsafe { bindings::devm_platform_ioremap_resource(pdev.to_ptr(), index) })
407 /// }
408 /// ```
from_err_ptr<T>(ptr: *mut T) -> Result<*mut T>409 pub fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
410     // CAST: Casting a pointer to `*const crate::ffi::c_void` is always valid.
411     let const_ptr: *const crate::ffi::c_void = ptr.cast();
412     // SAFETY: The FFI function does not deref the pointer.
413     if unsafe { bindings::IS_ERR(const_ptr) } {
414         // SAFETY: The FFI function does not deref the pointer.
415         let err = unsafe { bindings::PTR_ERR(const_ptr) };
416 
417         #[allow(clippy::unnecessary_cast)]
418         // CAST: If `IS_ERR()` returns `true`,
419         // then `PTR_ERR()` is guaranteed to return a
420         // negative value greater-or-equal to `-bindings::MAX_ERRNO`,
421         // which always fits in an `i16`, as per the invariant above.
422         // And an `i16` always fits in an `i32`. So casting `err` to
423         // an `i32` can never overflow, and is always valid.
424         //
425         // SAFETY: `IS_ERR()` ensures `err` is a
426         // negative value greater-or-equal to `-bindings::MAX_ERRNO`.
427         return Err(unsafe { Error::from_errno_unchecked(err as crate::ffi::c_int) });
428     }
429     Ok(ptr)
430 }
431 
432 /// Calls a closure returning a [`crate::error::Result<T>`] and converts the result to
433 /// a C integer result.
434 ///
435 /// This is useful when calling Rust functions that return [`crate::error::Result<T>`]
436 /// from inside `extern "C"` functions that need to return an integer error result.
437 ///
438 /// `T` should be convertible from an `i16` via `From<i16>`.
439 ///
440 /// # Examples
441 ///
442 /// ```ignore
443 /// # use kernel::from_result;
444 /// # use kernel::bindings;
445 /// unsafe extern "C" fn probe_callback(
446 ///     pdev: *mut bindings::platform_device,
447 /// ) -> kernel::ffi::c_int {
448 ///     from_result(|| {
449 ///         let ptr = devm_alloc(pdev)?;
450 ///         bindings::platform_set_drvdata(pdev, ptr);
451 ///         Ok(0)
452 ///     })
453 /// }
454 /// ```
from_result<T, F>(f: F) -> T where T: From<i16>, F: FnOnce() -> Result<T>,455 pub fn from_result<T, F>(f: F) -> T
456 where
457     T: From<i16>,
458     F: FnOnce() -> Result<T>,
459 {
460     match f() {
461         Ok(v) => v,
462         // NO-OVERFLOW: negative `errno`s are no smaller than `-bindings::MAX_ERRNO`,
463         // `-bindings::MAX_ERRNO` fits in an `i16` as per invariant above,
464         // therefore a negative `errno` always fits in an `i16` and will not overflow.
465         Err(e) => T::from(e.to_errno() as i16),
466     }
467 }
468 
469 /// Error message for calling a default function of a [`#[vtable]`](macros::vtable) trait.
470 pub const VTABLE_DEFAULT_ERROR: &str =
471     "This function must not be called, see the #[vtable] documentation.";
472