From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796141574; b=KTQSLVwgZAZP+9QPbHUzF2DBdhQ0n/l2iWoRJ12phNGLq8b3NEQp9osXTrPytgtpg1IJ ZOul6WDghm7jvK5CBHXGcR7J1BNWmxI0uqvKiCFpbuP3soIx8Vr14xUnPhwE1vKstq4yB OHuug8gRDJ3LxejyMO1DkxcSZJb3Tdsao+QhGtyQZOTYn3LH8R9WdbIDeRzUisbV57FD7 E9RigXoj+FQQWNvgFkK0XULEY6/3Bn1OLquJRPxPGkcn80Nwju2cVxjikEp6UWm6NOHPh pY3JlUtSy6Yaj7H4flPXkI7V5YH+CbMLsp6AugtU+oholR1l5jQ8IhU9LE0+WIsg+HA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796141574; h=Received:DKIM-Signature:From:Date:Subject:MIME-Version:Content-Type: Content-Transfer-Encoding:Message-Id:X-B4-Tracking:X-Change-ID:To:Cc: X-Mailer:X-Developer-Signature:X-Developer-Key; bh=eYOcz1bEzsm1mEO+PmR+qNJMET0jAR8Q9z15vERMi5Q=; b=gqqKh6p0r1SerEs+K55BxG+bVDUF1WXQFZI4bBgRbkG2IV5oB4xjwI4kDy+mms7/k2Pu Iw870MxIHPbGhwE4NkS57oeMQdwL/znSKtxusGUA1U/AJ+OwIA2T1M9+fkHS36g/jB295 X4Lu9Y59iaErikowMuGGYY6rjOW8K8x9Z7rHCCeOvENn7XA1Cx3jTQlskAkD1Gc/01Nq3 2FLnAWdKz0CeVwmnXeC5EbQcBeZhaaEJg1gfLfLn33rHGkFe5mjQVkUNEIxkVVU/nhKs7 9nkJ3A6dDBcC7BzRGupLr3IpCLO+5nR2nMLPxiufP24PYPePyYfpG5/j5rgb8wxsFag== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=TM6uDL2m; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E6CC2606A31A; Tue, 1 Dec 2026 16:12:53 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=TM6uDL2m Received: by smtp.kernel.org (Postfix) with ESMTPSA id 86A1B1F00897; Tue, 1 Dec 2026 16:12:50 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1796141573; bh=eYOcz1bEzsm1mEO+PmR+qNJMET0jAR8Q9z15vERMi5Q=; h=From:Date:Subject:To:Cc; b=TM6uDL2mnSpp95TQoFsiIG09BvUssH84CR3svdz4OHPOwPeYO1WjXVUVhq3xV+bh2 7RcJl7ljXjPTvp6cpuLR7A3T8DblER9/NeX2YjVCeaXPBzo3skYyIR5MGx2ydERE1g 6qwKstSyb3pUqrkYkY7Xy9Ks8ouj8+kkYdXNztZrdQUYKcgzNMy40qqIyIusxRP9yk u5vwh3QlAz4McNZpH0VHScKpkkmDLh/hdW+97gpo5lysbRCPnYYl4wzP46Q4zQG3kn boxXX+AxdVtf+hEqMmrgfOPm/IQUstpXbyNRRzUlMCxmr4D3467MqrUa7Y6lxcRNRj 6wuluHPQFmnJQ== From: Andreas Hindborg Date: Tue, 01 Dec 2026 17:08:45 +0100 Subject: [PATCH v4] fault-inject: rust: add a Rust API for fault-injection X-Mailing-List: rust-for-linux@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit Message-Id: <20261201-rust-fault-inject-v4-1-ebe48c72cc34@kernel.org> X-B4-Tracking: v=1; b=H4sIAA3xDmsC/33P307DIBiH4VtpOJaFf2Vdj7wP4wF8fHToViZQo ll679Y2mRoXD38kPC9cScYUMJO+uZKENeQQx2Woh4bA0YwD0uCWTQQTmgne0jTlQr2ZToWG8QW hUAtaeM462TJBlnuXhD68r+bT87YTvk0LXbZDYk1GCvF8DqVv6n6naAJOfib75haEOPow+EyBO tzCQ4rTJVPrLDNKaSmN7qsiX7FjyCWmj/U/la+1f55eOeVUI6j2ALYFsI+vmEY87WIaVq6Kb0K zu4RYCGP8Yd91nQQQfwh5Izjn8h4hF8J11gnFvBAOfhHzPH8CYzCBJqYBAAA= X-Change-ID: 20260215-rust-fault-inject-bc62f1083502 To: Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Alice Ryhl , Trevor Gross , Danilo Krummrich , Daniel Almeida , Tamir Duberstein , Alexandre Courbot , =?utf-8?q?Onur_=C3=96zkan?= Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Akinobu Mita , Andreas Hindborg X-Mailer: b4 0.16.0 X-Developer-Signature: v=1; a=openpgp-sha256; l=13509; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=6EBtM03JM8nV4VEYHD1jJiuCh7D6CmbevmuPJslYWtA=; b=owEBbQKS/ZANAwAKAfpQKQiqxb3QAcsmYgBrDvEQeII7r/61PJOWLQOsZY5kksawTuk+30kFU l7iws4FuA2JAjMEAAEKAB0WIQRXitnI2WZ2JirAaob6UCkIqsW90AUCaw7xEAAKCRD6UCkIqsW9 0HRaD/0ZEfI4tmAYl3lbwS5QTXjaO8F93QzYgO4p+1xlntxXjo8VGkBw+Fnt8q3Ys4fCgcuhmpB XCyR2l3XzohkPEFSsfdminYP3+41zcNl12pXV1+3LH/LRQb2vjs3kQZcwKVohgm5eLXBTy1VpAA NXI7bkziJnB9JlzXzOdFr2q0nMs3p4IDFpMt2c/c12HVNlJdpVQk0yJmhK/+rH25WCkNOX8qq1T k7dLCMMYI+C3YN20MTfYVlouAI6oRDkOj5Z8iFwAs8rSGe/Hx9rf6JTvw0gtwuHsSj8sap0RaTT 7MPVYVIcrGykPMuJaSHzlbR7eSXJVaMwU4Gp5ZHjarGXSVKVJYqBSDOliHT7tXApxNUuik7WVHc TcToVLsqNxAA2p/MDsGj5AoY87EHHwY16kxY29JN4uqgmB/rYraOqU2pU98wnjjQcDhm8YetHtM TscVPRPNJ0MuPRED9WC3WsmYfIB1btPihhHfLSWYdprVS9Sw5E4/hZvyX8n1FMh1wL+cfsPIzje 32a8tYaMQ/qxZvcKZ3O3U9PzboFKCNBnobYqouwVwucIg68mUIdqdQMpvuhgFwp8/eHa9zSRolp zx4QHL55vg7KH+UeV2/DfiK3BmrvALGitrYh5zrUeNjmG9q9nWoGJnTXXPQRAHKyJ4yFkqLgeNL BQBUdUBocuylnLw== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Add a way for Rust code to create fault-injection control points. The control points can be attached to a configfs tree as default groups and controlled from user space. On the kernel side, provide a `should_fail` method to query if an operation should fail. Cc: Akinobu Mita Signed-off-by: Andreas Hindborg --- This patch is a dependency for the rust null block driver fault injection feature. --- Changes in v4: - Initialize the embedded `struct fault_attr` in `FaultConfig::new()` to the values of C `FAULT_ATTR_INITIALIZER`, and initialize its ratelimit state with `ratelimit_state_init()`. The attributes were left zeroed, so the ratelimit lock was never initialized, and with `CONFIG_FAULT_INJECTION_STACKTRACE_FILTER` enabled `should_fail()` returned false until userspace wrote `require-end` (Sashiko). - Use the vertical import style (Sashiko). - Mark `FaultConfig::new()`, the `PinnedDrop` implementation and `CDefaultGroup::group_ptr()` as `#[inline]` (Sashiko). - Link to v3: https://msgid.link/20261113-rust-fault-inject-v3-1-d8bd240f22dc@kernel.org Changes in v3: - Sort the `fault-inject.h` include in `bindings_helper.h` (Miguel). - Use backticks for `FaultConfig` and `self` in code comments (Miguel). - Link to [`true`] in the `should_fail` rustdoc (Miguel). - Replace the stale `INVARIANT` comment that referred to a no longer existing `ffi_init` call (Miguel). - Add a `PinnedDrop` for `FaultConfig` that releases the reference on the embedded `struct config_item` acquired by `fault_config_init`. Nothing released it before, so creating a `FaultConfig` and dropping it leaked the resources configfs associated with the item, including the name allocation for names of 20 bytes or more. - Implement `CDefaultGroup` as an unsafe trait, following the configfs change, and document why `FaultConfig` meets the requirements. - Document the remaining `CDefaultGroup` safety requirement, that the implementer never attaches the group itself. - Say what the `Send` and `Sync` impls rely on instead of claiming that `struct fault_attr` applies internal synchronization. - Add an example for the module. - Link the module documentation to `UnattachedGroup` and `Group::new`. - Gate the module on `FAULT_INJECTION_CONFIGFS` alone, merge the two `impl FaultConfig` blocks and drop a `cast_mut`. - Link to v2: https://msgid.link/20260605-rust-fault-inject-v2-1-aaf978883cc2@kernel.org Changes in v2: - Mark `should_fail` as `#[inline]` (Gary). - Expand `should_fail` rustdoc to describe the `size` parameter, including the negative-`size` replenish semantics, and link to the fault injection documentation (Gary). - Link to v1: https://msgid.link/20260215-rust-fault-inject-v1-1-6ec459cb5ccb@kernel.org --- rust/bindings/bindings_helper.h | 1 + rust/kernel/fault_injection.rs | 186 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 3 files changed, 189 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 3791af0aadc7..08a10a7214b0 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -58,6 +58,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/kernel/fault_injection.rs b/rust/kernel/fault_injection.rs new file mode 100644 index 000000000000..4ae76787f1f9 --- /dev/null +++ b/rust/kernel/fault_injection.rs @@ -0,0 +1,186 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Fault injection capabilities infrastructure. +//! +//! This module provides a Rust API for the kernel fault injection framework. Fault injection allows +//! simulation of failures in kernel code paths to test error handling. +//! +//! [`FaultConfig`] represents a fault injection control point that can be: +//! +//! - Attached to a configfs tree as a default group, allowing userspace control of fault injection +//! parameters. Wrap it in an [`UnattachedGroup`] and pass that to [`Group::new`]. +//! - Queried via [`FaultConfig::should_fail`] to determine if an operation should be simulated as +//! failing. +//! +//! Please see the [fault injection documentation] for details on configuring and using fault +//! injection from userspace. +//! +//! C header: [`include/linux/fault-inject.h`](srctree/include/linux/fault-inject.h) +//! +//! # Examples +//! +//! ``` +//! use kernel::configfs::UnattachedGroup; +//! use kernel::fault_injection::FaultConfig; +//! +//! // The token grants permission to attach the control point to a `configfs::Group` as a +//! // default group. Pass it to `configfs::Group::new`. +//! let control_point = UnattachedGroup::new(FaultConfig::new(c"timeout_inject"), GFP_KERNEL)?; +//! +//! // Keep a handle for querying the control point from the code path under test. +//! let timeout_inject = control_point.clone_arc(); +//! +//! // A control point does not inject failures until userspace sets a non-zero probability. +//! assert!(!timeout_inject.should_fail(1)); +//! # Ok::<(), Error>(()) +//! ``` +//! +//! [fault injection documentation]: srctree/Documentation/fault-injection/fault-injection.rst +//! [`UnattachedGroup`]: kernel::configfs::UnattachedGroup +//! [`Group::new`]: kernel::configfs::Group::new + +use crate::{ + prelude::*, + types::Opaque, // +}; + +/// A fault injection control point. +/// +/// This type wraps a `struct fault_config` from the C fault injection framework. It provides a way +/// to create controllable fault injection points that can be configured via configfs. +/// +/// When attached to a configfs subsystem as a default group, userspace can configure fault +/// injection parameters through the configfs interface. The kernel code can then query +/// [`FaultConfig::should_fail`] to determine whether to simulate a failure. +/// +/// # Invariants +/// +/// - `self.inner` is always a valid `struct fault_config`. +/// - `self` owns the reference on the `struct config_item` embedded in `self.inner.group` that +/// `fault_config_init` acquired. +#[pin_data(PinnedDrop)] +pub struct FaultConfig { + #[pin] + inner: Opaque, +} + +#[pinned_drop] +impl PinnedDrop for FaultConfig { + #[inline] + fn drop(self: Pin<&mut Self>) { + // SAFETY: By type invariant, `self.inner` is a valid `struct fault_config`, so the embedded + // `struct config_item` is initialized, and `self` owns the reference that + // `fault_config_init` acquired on it. + // + // `fault_config_type` does not install a `release` operation, so this does not free the + // allocation backing `self`. It only releases the resources that configfs associated with + // the item. + unsafe { bindings::config_item_put(&raw mut (*self.inner.get()).group.cg_item) }; + } +} + +impl FaultConfig { + /// Create a new [`FaultConfig`]. + /// + /// If attached to a configfs group, this [`FaultConfig`] will appear as a directory named + /// `name`. + /// + /// The fault attributes start out with the same values as a C `struct fault_attr` defined with + /// `DECLARE_FAULT_ATTR`. In particular, `probability` is zero, so the control point does not + /// inject failures until userspace configures it. + #[inline] + pub fn new(name: &CStr) -> impl PinInit + use<'_> { + pin_init!(Self { + // INVARIANT: The allocation is zeroed. The closure then initializes `attr` to the + // values of C `FAULT_ATTR_INITIALIZER`, and `fault_config_init` initializes the + // embedded `struct config_group`, so `self.inner` is a valid `struct fault_config`. + inner <- Opaque::zeroed().chain(|inner| { + let ptr: *mut bindings::fault_config = inner.get(); + + // These are the values of the C `FAULT_ATTR_INITIALIZER`, which `bindgen` cannot + // expand. `ratelimit_state` is initialized separately below. + let attr = bindings::fault_attr { + interval: 1, + times: bindings::atomic_t { counter: 1 }, + require_end: c_ulong::MAX, + stacktrace_depth: 32, + verbose: 2, + ..pin_init::zeroed() + }; + + // SAFETY: `ptr` points to a `struct fault_config` that is valid for writes, and + // nothing else can access it until this initializer returns. + unsafe { (&raw mut (*ptr).attr).write(attr) }; + + // The C macro `FAULT_ATTR_INITIALIZER` uses the static initializer + // `RATELIMIT_STATE_INIT_DISABLED` here. That initializer does not assign a lockdep + // key to the lock, which lockdep only accepts for locks in static storage. Use the + // runtime initializer with the same interval and burst instead. + // + // SAFETY: `ptr` points to a `struct fault_config` that is valid for writes, and + // nothing else can access it until this initializer returns. + unsafe { + bindings::ratelimit_state_init( + &raw mut (*ptr).attr.ratelimit_state, + 0, + kernel::ratelimit::Ratelimit::DEFAULT_BURST, + ) + }; + + // SAFETY: `ptr` points to a `struct fault_config` whose embedded `struct + // config_group` is zeroed, and `name` is a null terminated string. + unsafe { bindings::fault_config_init(ptr, name.as_char_ptr()) }; + Ok(()) + }), + }) + } + + /// Query for failure. + /// + /// Returns [`true`] if the operation should fail. + /// + /// `size` is the amount of the resource consumed by the operation. It is subtracted from the + /// configured `space` budget on each call, and failure injection is suppressed while `space` is + /// greater than `size`. For allocation-style users this is typically the number of bytes; users + /// that inject based on the number of operations performed pass `1`. A negative `size` + /// replenishes the `space` budget by `-size` (i.e. grows the budget) and suppresses the failure + /// for that call. + /// + /// See the `space` field in the [fault injection documentation] for + /// details. + /// + /// [fault injection documentation]: srctree/Documentation/fault-injection/fault-injection.rst + #[inline] + pub fn should_fail(&self, size: isize) -> bool { + // SAFETY: By type invariant, `self` is always valid. + let attr = unsafe { &raw mut (*self.inner.get()).attr }; + + // SAFETY: By type invariant, `self` is always valid. + unsafe { bindings::should_fail(attr, size) } + } +} + +// SAFETY: `fault_config_init` initializes the embedded `struct config_group` with +// `config_group_init_type_name`, and by type invariant `self.inner` stays a valid `struct +// fault_config` in place for as long as `self` is live. `group_ptr` returns a pointer to a field of +// `self.inner`, so it returns the same pointer on every call. By type invariant, `self` owns the +// reference on the embedded `struct config_item` and releases it when dropped. No method of +// `FaultConfig` adds the group as a default group of any group. +unsafe impl kernel::configfs::CDefaultGroup for FaultConfig { + #[inline] + fn group_ptr(&self) -> *mut bindings::config_group { + // SAFETY: By type invariant, `self.inner` is valid. + unsafe { &raw mut (*self.inner.get()).group } + } +} + +// SAFETY: `FaultConfig` has no task affinity. The only operation it performs outside of +// `should_fail` is the `config_item_put` in `PinnedDrop`, which may run in any task. +unsafe impl Send for FaultConfig {} + +// SAFETY: The only method taking `&self` is `should_fail`, which the C fault injection framework +// supports calling concurrently from any task. The `times` and `space` counters it updates are +// atomics, and the verbose reporting path is serialized by `attr.ratelimit_state`. The remaining +// fields of `struct fault_attr` are plain integers that C races against concurrent configfs +// stores by design: they are statistical knobs and an inexact call counter. +unsafe impl Sync for FaultConfig {} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 1ab41129d557..156074709ed1 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -73,6 +73,8 @@ #[cfg(CONFIG_DRM = "y")] pub mod drm; pub mod error; +#[cfg(CONFIG_FAULT_INJECTION_CONFIGFS)] +pub mod fault_injection; pub mod faux; #[cfg(CONFIG_RUST_FW_LOADER_ABSTRACTIONS)] pub mod firmware; --- base-commit: bc71431221f5ba8bb33918399552636e059c2c45 change-id: 20260215-rust-fault-inject-bc62f1083502 prerequisite-change-id: 20260215-configfs-c-default-groups-bdb0a44633a6:v4 prerequisite-patch-id: 54d13c089786f6c33633e3df846ae2a573542dd6 Best regards, -- Andreas Hindborg