error.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. // SPDX-License-Identifier: GPL-2.0
  2. //! Kernel errors.
  3. //!
  4. //! C header: [`include/uapi/asm-generic/errno-base.h`](srctree/include/uapi/asm-generic/errno-base.h)
  5. use crate::{alloc::AllocError, str::CStr};
  6. use core::alloc::LayoutError;
  7. use core::fmt;
  8. use core::num::NonZeroI32;
  9. use core::num::TryFromIntError;
  10. use core::str::Utf8Error;
  11. /// Contains the C-compatible error codes.
  12. #[rustfmt::skip]
  13. pub mod code {
  14. macro_rules! declare_err {
  15. ($err:tt $(,)? $($doc:expr),+) => {
  16. $(
  17. #[doc = $doc]
  18. )*
  19. pub const $err: super::Error =
  20. match super::Error::try_from_errno(-(crate::bindings::$err as i32)) {
  21. Some(err) => err,
  22. None => panic!("Invalid errno in `declare_err!`"),
  23. };
  24. };
  25. }
  26. declare_err!(EPERM, "Operation not permitted.");
  27. declare_err!(ENOENT, "No such file or directory.");
  28. declare_err!(ESRCH, "No such process.");
  29. declare_err!(EINTR, "Interrupted system call.");
  30. declare_err!(EIO, "I/O error.");
  31. declare_err!(ENXIO, "No such device or address.");
  32. declare_err!(E2BIG, "Argument list too long.");
  33. declare_err!(ENOEXEC, "Exec format error.");
  34. declare_err!(EBADF, "Bad file number.");
  35. declare_err!(ECHILD, "No child processes.");
  36. declare_err!(EAGAIN, "Try again.");
  37. declare_err!(ENOMEM, "Out of memory.");
  38. declare_err!(EACCES, "Permission denied.");
  39. declare_err!(EFAULT, "Bad address.");
  40. declare_err!(ENOTBLK, "Block device required.");
  41. declare_err!(EBUSY, "Device or resource busy.");
  42. declare_err!(EEXIST, "File exists.");
  43. declare_err!(EXDEV, "Cross-device link.");
  44. declare_err!(ENODEV, "No such device.");
  45. declare_err!(ENOTDIR, "Not a directory.");
  46. declare_err!(EISDIR, "Is a directory.");
  47. declare_err!(EINVAL, "Invalid argument.");
  48. declare_err!(ENFILE, "File table overflow.");
  49. declare_err!(EMFILE, "Too many open files.");
  50. declare_err!(ENOTTY, "Not a typewriter.");
  51. declare_err!(ETXTBSY, "Text file busy.");
  52. declare_err!(EFBIG, "File too large.");
  53. declare_err!(ENOSPC, "No space left on device.");
  54. declare_err!(ESPIPE, "Illegal seek.");
  55. declare_err!(EROFS, "Read-only file system.");
  56. declare_err!(EMLINK, "Too many links.");
  57. declare_err!(EPIPE, "Broken pipe.");
  58. declare_err!(EDOM, "Math argument out of domain of func.");
  59. declare_err!(ERANGE, "Math result not representable.");
  60. declare_err!(ERESTARTSYS, "Restart the system call.");
  61. declare_err!(ERESTARTNOINTR, "System call was interrupted by a signal and will be restarted.");
  62. declare_err!(ERESTARTNOHAND, "Restart if no handler.");
  63. declare_err!(ENOIOCTLCMD, "No ioctl command.");
  64. declare_err!(ERESTART_RESTARTBLOCK, "Restart by calling sys_restart_syscall.");
  65. declare_err!(EPROBE_DEFER, "Driver requests probe retry.");
  66. declare_err!(EOPENSTALE, "Open found a stale dentry.");
  67. declare_err!(ENOPARAM, "Parameter not supported.");
  68. declare_err!(EBADHANDLE, "Illegal NFS file handle.");
  69. declare_err!(ENOTSYNC, "Update synchronization mismatch.");
  70. declare_err!(EBADCOOKIE, "Cookie is stale.");
  71. declare_err!(ENOTSUPP, "Operation is not supported.");
  72. declare_err!(ETOOSMALL, "Buffer or request is too small.");
  73. declare_err!(ESERVERFAULT, "An untranslatable error occurred.");
  74. declare_err!(EBADTYPE, "Type not supported by server.");
  75. declare_err!(EJUKEBOX, "Request initiated, but will not complete before timeout.");
  76. declare_err!(EIOCBQUEUED, "iocb queued, will get completion event.");
  77. declare_err!(ERECALLCONFLICT, "Conflict with recalled state.");
  78. declare_err!(ENOGRACE, "NFS file lock reclaim refused.");
  79. }
  80. /// Generic integer kernel error.
  81. ///
  82. /// The kernel defines a set of integer generic error codes based on C and
  83. /// POSIX ones. These codes may have a more specific meaning in some contexts.
  84. ///
  85. /// # Invariants
  86. ///
  87. /// The value is a valid `errno` (i.e. `>= -MAX_ERRNO && < 0`).
  88. #[derive(Clone, Copy, PartialEq, Eq)]
  89. pub struct Error(NonZeroI32);
  90. impl Error {
  91. /// Creates an [`Error`] from a kernel error code.
  92. ///
  93. /// It is a bug to pass an out-of-range `errno`. `EINVAL` would
  94. /// be returned in such a case.
  95. pub fn from_errno(errno: crate::ffi::c_int) -> Error {
  96. if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
  97. // TODO: Make it a `WARN_ONCE` once available.
  98. crate::pr_warn!(
  99. "attempted to create `Error` with out of range `errno`: {}\n",
  100. errno
  101. );
  102. return code::EINVAL;
  103. }
  104. // INVARIANT: The check above ensures the type invariant
  105. // will hold.
  106. // SAFETY: `errno` is checked above to be in a valid range.
  107. unsafe { Error::from_errno_unchecked(errno) }
  108. }
  109. /// Creates an [`Error`] from a kernel error code.
  110. ///
  111. /// Returns [`None`] if `errno` is out-of-range.
  112. const fn try_from_errno(errno: crate::ffi::c_int) -> Option<Error> {
  113. if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
  114. return None;
  115. }
  116. // SAFETY: `errno` is checked above to be in a valid range.
  117. Some(unsafe { Error::from_errno_unchecked(errno) })
  118. }
  119. /// Creates an [`Error`] from a kernel error code.
  120. ///
  121. /// # Safety
  122. ///
  123. /// `errno` must be within error code range (i.e. `>= -MAX_ERRNO && < 0`).
  124. const unsafe fn from_errno_unchecked(errno: crate::ffi::c_int) -> Error {
  125. // INVARIANT: The contract ensures the type invariant
  126. // will hold.
  127. // SAFETY: The caller guarantees `errno` is non-zero.
  128. Error(unsafe { NonZeroI32::new_unchecked(errno) })
  129. }
  130. /// Returns the kernel error code.
  131. pub fn to_errno(self) -> crate::ffi::c_int {
  132. self.0.get()
  133. }
  134. #[cfg(CONFIG_BLOCK)]
  135. pub(crate) fn to_blk_status(self) -> bindings::blk_status_t {
  136. // SAFETY: `self.0` is a valid error due to its invariant.
  137. unsafe { bindings::errno_to_blk_status(self.0.get()) }
  138. }
  139. /// Returns the error encoded as a pointer.
  140. pub fn to_ptr<T>(self) -> *mut T {
  141. // SAFETY: `self.0` is a valid error due to its invariant.
  142. unsafe { bindings::ERR_PTR(self.0.get() as _) as *mut _ }
  143. }
  144. /// Returns a string representing the error, if one exists.
  145. #[cfg(not(any(test, testlib)))]
  146. pub fn name(&self) -> Option<&'static CStr> {
  147. // SAFETY: Just an FFI call, there are no extra safety requirements.
  148. let ptr = unsafe { bindings::errname(-self.0.get()) };
  149. if ptr.is_null() {
  150. None
  151. } else {
  152. // SAFETY: The string returned by `errname` is static and `NUL`-terminated.
  153. Some(unsafe { CStr::from_char_ptr(ptr) })
  154. }
  155. }
  156. /// Returns a string representing the error, if one exists.
  157. ///
  158. /// When `testlib` is configured, this always returns `None` to avoid the dependency on a
  159. /// kernel function so that tests that use this (e.g., by calling [`Result::unwrap`]) can still
  160. /// run in userspace.
  161. #[cfg(any(test, testlib))]
  162. pub fn name(&self) -> Option<&'static CStr> {
  163. None
  164. }
  165. }
  166. impl fmt::Debug for Error {
  167. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  168. match self.name() {
  169. // Print out number if no name can be found.
  170. None => f.debug_tuple("Error").field(&-self.0).finish(),
  171. Some(name) => f
  172. .debug_tuple(
  173. // SAFETY: These strings are ASCII-only.
  174. unsafe { core::str::from_utf8_unchecked(name) },
  175. )
  176. .finish(),
  177. }
  178. }
  179. }
  180. impl From<AllocError> for Error {
  181. fn from(_: AllocError) -> Error {
  182. code::ENOMEM
  183. }
  184. }
  185. impl From<TryFromIntError> for Error {
  186. fn from(_: TryFromIntError) -> Error {
  187. code::EINVAL
  188. }
  189. }
  190. impl From<Utf8Error> for Error {
  191. fn from(_: Utf8Error) -> Error {
  192. code::EINVAL
  193. }
  194. }
  195. impl From<LayoutError> for Error {
  196. fn from(_: LayoutError) -> Error {
  197. code::ENOMEM
  198. }
  199. }
  200. impl From<core::fmt::Error> for Error {
  201. fn from(_: core::fmt::Error) -> Error {
  202. code::EINVAL
  203. }
  204. }
  205. impl From<core::convert::Infallible> for Error {
  206. fn from(e: core::convert::Infallible) -> Error {
  207. match e {}
  208. }
  209. }
  210. /// A [`Result`] with an [`Error`] error type.
  211. ///
  212. /// To be used as the return type for functions that may fail.
  213. ///
  214. /// # Error codes in C and Rust
  215. ///
  216. /// In C, it is common that functions indicate success or failure through
  217. /// their return value; modifying or returning extra data through non-`const`
  218. /// pointer parameters. In particular, in the kernel, functions that may fail
  219. /// typically return an `int` that represents a generic error code. We model
  220. /// those as [`Error`].
  221. ///
  222. /// In Rust, it is idiomatic to model functions that may fail as returning
  223. /// a [`Result`]. Since in the kernel many functions return an error code,
  224. /// [`Result`] is a type alias for a [`core::result::Result`] that uses
  225. /// [`Error`] as its error type.
  226. ///
  227. /// Note that even if a function does not return anything when it succeeds,
  228. /// it should still be modeled as returning a `Result` rather than
  229. /// just an [`Error`].
  230. pub type Result<T = (), E = Error> = core::result::Result<T, E>;
  231. /// Converts an integer as returned by a C kernel function to an error if it's negative, and
  232. /// `Ok(())` otherwise.
  233. pub fn to_result(err: crate::ffi::c_int) -> Result {
  234. if err < 0 {
  235. Err(Error::from_errno(err))
  236. } else {
  237. Ok(())
  238. }
  239. }
  240. /// Transform a kernel "error pointer" to a normal pointer.
  241. ///
  242. /// Some kernel C API functions return an "error pointer" which optionally
  243. /// embeds an `errno`. Callers are supposed to check the returned pointer
  244. /// for errors. This function performs the check and converts the "error pointer"
  245. /// to a normal pointer in an idiomatic fashion.
  246. ///
  247. /// # Examples
  248. ///
  249. /// ```ignore
  250. /// # use kernel::from_err_ptr;
  251. /// # use kernel::bindings;
  252. /// fn devm_platform_ioremap_resource(
  253. /// pdev: &mut PlatformDevice,
  254. /// index: u32,
  255. /// ) -> Result<*mut kernel::ffi::c_void> {
  256. /// // SAFETY: `pdev` points to a valid platform device. There are no safety requirements
  257. /// // on `index`.
  258. /// from_err_ptr(unsafe { bindings::devm_platform_ioremap_resource(pdev.to_ptr(), index) })
  259. /// }
  260. /// ```
  261. pub fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
  262. // CAST: Casting a pointer to `*const crate::ffi::c_void` is always valid.
  263. let const_ptr: *const crate::ffi::c_void = ptr.cast();
  264. // SAFETY: The FFI function does not deref the pointer.
  265. if unsafe { bindings::IS_ERR(const_ptr) } {
  266. // SAFETY: The FFI function does not deref the pointer.
  267. let err = unsafe { bindings::PTR_ERR(const_ptr) };
  268. #[allow(clippy::unnecessary_cast)]
  269. // CAST: If `IS_ERR()` returns `true`,
  270. // then `PTR_ERR()` is guaranteed to return a
  271. // negative value greater-or-equal to `-bindings::MAX_ERRNO`,
  272. // which always fits in an `i16`, as per the invariant above.
  273. // And an `i16` always fits in an `i32`. So casting `err` to
  274. // an `i32` can never overflow, and is always valid.
  275. //
  276. // SAFETY: `IS_ERR()` ensures `err` is a
  277. // negative value greater-or-equal to `-bindings::MAX_ERRNO`.
  278. return Err(unsafe { Error::from_errno_unchecked(err as crate::ffi::c_int) });
  279. }
  280. Ok(ptr)
  281. }
  282. /// Calls a closure returning a [`crate::error::Result<T>`] and converts the result to
  283. /// a C integer result.
  284. ///
  285. /// This is useful when calling Rust functions that return [`crate::error::Result<T>`]
  286. /// from inside `extern "C"` functions that need to return an integer error result.
  287. ///
  288. /// `T` should be convertible from an `i16` via `From<i16>`.
  289. ///
  290. /// # Examples
  291. ///
  292. /// ```ignore
  293. /// # use kernel::from_result;
  294. /// # use kernel::bindings;
  295. /// unsafe extern "C" fn probe_callback(
  296. /// pdev: *mut bindings::platform_device,
  297. /// ) -> kernel::ffi::c_int {
  298. /// from_result(|| {
  299. /// let ptr = devm_alloc(pdev)?;
  300. /// bindings::platform_set_drvdata(pdev, ptr);
  301. /// Ok(0)
  302. /// })
  303. /// }
  304. /// ```
  305. pub fn from_result<T, F>(f: F) -> T
  306. where
  307. T: From<i16>,
  308. F: FnOnce() -> Result<T>,
  309. {
  310. match f() {
  311. Ok(v) => v,
  312. // NO-OVERFLOW: negative `errno`s are no smaller than `-bindings::MAX_ERRNO`,
  313. // `-bindings::MAX_ERRNO` fits in an `i16` as per invariant above,
  314. // therefore a negative `errno` always fits in an `i16` and will not overflow.
  315. Err(e) => T::from(e.to_errno() as i16),
  316. }
  317. }
  318. /// Error message for calling a default function of a [`#[vtable]`](macros::vtable) trait.
  319. pub const VTABLE_DEFAULT_ERROR: &str =
  320. "This function must not be called, see the #[vtable] documentation.";