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