error.rs 12 KB

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