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