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