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