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