diff mbox series

[1/2] rust: pwm: Fix potential memory leak on init error

Message ID 20251219-pwm-rust-v1-1-46873e19679d@gmail.com
State Superseded
Delegated to: Michał Wilczyński
Headers show
Series rust: pwm: Fix init error handling and tidy style | expand

Commit Message

Kari Argillander Dec. 19, 2025, 5:02 p.m. UTC
When initializing a PWM chip using pwmchip_alloc(), the allocated device
owns an initial reference that must be released on all error paths.

If __pinned_init() were to fail, the allocated pwm_chip would currently
leak because the error path returned without calling pwmchip_put().

While __pinned_init() does not currently have any failure paths in code
base, this change makes the ownership transfer explicit and keeps the
code correct if failure paths are added in the future.

Signed-off-by: Kari Argillander <kari.argillander@gmail.com>
---
 rust/kernel/pwm.rs | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
diff mbox series

Patch

diff --git a/rust/kernel/pwm.rs b/rust/kernel/pwm.rs
index 2dd72a39acb5..4b6a3b5ef929 100644
--- a/rust/kernel/pwm.rs
+++ b/rust/kernel/pwm.rs
@@ -607,7 +607,12 @@  pub fn new<'a>(
         let drvdata_ptr = unsafe { bindings::pwmchip_get_drvdata(c_chip_ptr) };
 
         // SAFETY: We construct the `T` object in-place in the allocated private memory.
-        unsafe { data.__pinned_init(drvdata_ptr.cast())? };
+        if let Err(e) = unsafe { data.__pinned_init(drvdata_ptr.cast()) } {
+            // SAFETY: It is safe to call `pwmchip_put()` with a valid pointer
+            // obtained from `pwmchip_alloc()`.
+            unsafe { bindings::pwmchip_put(c_chip_ptr) };
+            return Err(e);
+        }
 
         // SAFETY: `c_chip_ptr` points to a valid chip.
         unsafe {