Skip to content

Commit a995fe1

Browse files
author
Danilo Krummrich
committed
rust: driver: drop device private data post unbind
Currently, the driver's device private data is allocated and initialized from driver core code called from bus abstractions after the driver's probe() callback returned the corresponding initializer. Similarly, the driver's device private data is dropped within the remove() callback of bus abstractions after calling the remove() callback of the corresponding driver. However, commit 6f61a26 ("rust: device: introduce Device::drvdata()") introduced an accessor for the driver's device private data for a Device<Bound>, i.e. a device that is currently bound to a driver. Obviously, this is in conflict with dropping the driver's device private data in remove(), since a device can not be considered to be fully unbound after remove() has finished: We also have to consider registrations guarded by devres - such as IRQ or class device registrations - which are torn down after remove() in devres_release_all(). Thus, it can happen that, for instance, a class device or IRQ callback still calls Device::drvdata(), which then runs concurrently to remove() (which sets dev->driver_data to NULL and drops the driver's device private data), before devres_release_all() started to tear down the corresponding registration. This is because devres guarded registrations can, as expected, access the corresponding Device<Bound> that defines their scope. In C it simply is the driver's responsibility to ensure that its device private data is freed after e.g. an IRQ registration is unregistered. Typically, C drivers achieve this by allocating their device private data with e.g. devm_kzalloc() before doing anything else, i.e. before e.g. registering an IRQ with devm_request_threaded_irq(), relying on the reverse order cleanup of devres. Technically, we could do something similar in Rust. However, the resulting code would be pretty messy: In Rust we have to differentiate between allocated but uninitialized memory and initialized memory in the type system. Thus, we would need to somehow keep track of whether the driver's device private data object has been initialized (i.e. probe() was successful and returned a valid initializer for this memory) and conditionally call the destructor of the corresponding object when it is freed. This is because we'd need to allocate and register the memory of the driver's device private data *before* it is initialized by the initializer returned by the driver's probe() callback, because the driver could already register devres guarded registrations within probe() outside of the driver's device private data initializer. Luckily there is a much simpler solution: Instead of dropping the driver's device private data at the end of remove(), we just drop it after the device has been fully unbound, i.e. after all devres callbacks have been processed. For this, we introduce a new post_unbind() callback private to the driver-core, i.e. the callback is neither exposed to drivers, nor to bus abstractions. This way, the driver-core code can simply continue to conditionally allocate the memory for the driver's device private data when the driver's initializer is returned from probe() - no change needed - and drop it when the driver-core code receives the post_unbind() callback. Closes: https://lore.kernel.org/all/DEZMS6Y4A7XE.XE7EUBT5SJFJ@kernel.org/ Fixes: 6f61a26 ("rust: device: introduce Device::drvdata()") Acked-by: Alice Ryhl <aliceryhl@google.com> Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Acked-by: Igor Korotin <igor.korotin.linux@gmail.com> Link: https://patch.msgid.link/20260107103511.570525-7-dakr@kernel.org [ Remove #ifdef CONFIG_RUST, rename post_unbind() to post_unbind_rust(). - Danilo] Signed-off-by: Danilo Krummrich <dakr@kernel.org>
1 parent 2ad0f49 commit a995fe1

File tree

9 files changed

+67
-20
lines changed

9 files changed

+67
-20
lines changed

drivers/base/dd.c

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -548,6 +548,8 @@ static DEVICE_ATTR_RW(state_synced);
548548
static void device_unbind_cleanup(struct device *dev)
549549
{
550550
devres_release_all(dev);
551+
if (dev->driver->p_cb.post_unbind_rust)
552+
dev->driver->p_cb.post_unbind_rust(dev);
551553
arch_teardown_dma_ops(dev);
552554
kfree(dev->dma_range_map);
553555
dev->dma_range_map = NULL;

include/linux/device/driver.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,8 @@ enum probe_type {
8585
* uevent.
8686
* @p: Driver core's private data, no one other than the driver
8787
* core can touch this.
88+
* @p_cb: Callbacks private to the driver core; no one other than the
89+
* driver core is allowed to touch this.
8890
*
8991
* The device driver-model tracks all of the drivers known to the system.
9092
* The main reason for this tracking is to enable the driver core to match
@@ -119,6 +121,13 @@ struct device_driver {
119121
void (*coredump) (struct device *dev);
120122

121123
struct driver_private *p;
124+
struct {
125+
/*
126+
* Called after remove() and after all devres entries have been
127+
* processed. This is a Rust only callback.
128+
*/
129+
void (*post_unbind_rust)(struct device *dev);
130+
} p_cb;
122131
};
123132

124133

rust/kernel/auxiliary.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,9 +96,9 @@ impl<T: Driver + 'static> Adapter<T> {
9696
// SAFETY: `remove_callback` is only ever called after a successful call to
9797
// `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
9898
// and stored a `Pin<KBox<T>>`.
99-
let data = unsafe { adev.as_ref().drvdata_obtain::<T>() };
99+
let data = unsafe { adev.as_ref().drvdata_borrow::<T>() };
100100

101-
T::unbind(adev, data.as_ref());
101+
T::unbind(adev, data);
102102
}
103103
}
104104

rust/kernel/device.rs

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -232,30 +232,32 @@ impl Device<CoreInternal> {
232232
///
233233
/// # Safety
234234
///
235-
/// - Must only be called once after a preceding call to [`Device::set_drvdata`].
236235
/// - The type `T` must match the type of the `ForeignOwnable` previously stored by
237236
/// [`Device::set_drvdata`].
238-
pub unsafe fn drvdata_obtain<T: 'static>(&self) -> Pin<KBox<T>> {
237+
pub(crate) unsafe fn drvdata_obtain<T: 'static>(&self) -> Option<Pin<KBox<T>>> {
239238
// SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`.
240239
let ptr = unsafe { bindings::dev_get_drvdata(self.as_raw()) };
241240

242241
// SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`.
243242
unsafe { bindings::dev_set_drvdata(self.as_raw(), core::ptr::null_mut()) };
244243

244+
if ptr.is_null() {
245+
return None;
246+
}
247+
245248
// SAFETY:
246-
// - By the safety requirements of this function, `ptr` comes from a previous call to
247-
// `into_foreign()`.
249+
// - If `ptr` is not NULL, it comes from a previous call to `into_foreign()`.
248250
// - `dev_get_drvdata()` guarantees to return the same pointer given to `dev_set_drvdata()`
249251
// in `into_foreign()`.
250-
unsafe { Pin::<KBox<T>>::from_foreign(ptr.cast()) }
252+
Some(unsafe { Pin::<KBox<T>>::from_foreign(ptr.cast()) })
251253
}
252254

253255
/// Borrow the driver's private data bound to this [`Device`].
254256
///
255257
/// # Safety
256258
///
257-
/// - Must only be called after a preceding call to [`Device::set_drvdata`] and before
258-
/// [`Device::drvdata_obtain`].
259+
/// - Must only be called after a preceding call to [`Device::set_drvdata`] and before the
260+
/// device is fully unbound.
259261
/// - The type `T` must match the type of the `ForeignOwnable` previously stored by
260262
/// [`Device::set_drvdata`].
261263
pub unsafe fn drvdata_borrow<T: 'static>(&self) -> Pin<&T> {
@@ -271,7 +273,7 @@ impl Device<Bound> {
271273
/// # Safety
272274
///
273275
/// - Must only be called after a preceding call to [`Device::set_drvdata`] and before
274-
/// [`Device::drvdata_obtain`].
276+
/// the device is fully unbound.
275277
/// - The type `T` must match the type of the `ForeignOwnable` previously stored by
276278
/// [`Device::set_drvdata`].
277279
unsafe fn drvdata_unchecked<T: 'static>(&self) -> Pin<&T> {
@@ -320,7 +322,7 @@ impl Device<Bound> {
320322

321323
// SAFETY:
322324
// - The above check of `dev_get_drvdata()` guarantees that we are called after
323-
// `set_drvdata()` and before `drvdata_obtain()`.
325+
// `set_drvdata()`.
324326
// - We've just checked that the type of the driver's private data is in fact `T`.
325327
Ok(unsafe { self.drvdata_unchecked() })
326328
}

rust/kernel/driver.rs

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,39 @@ unsafe impl<T: RegistrationOps> Sync for Registration<T> {}
177177
// any thread, so `Registration` is `Send`.
178178
unsafe impl<T: RegistrationOps> Send for Registration<T> {}
179179

180-
impl<T: RegistrationOps> Registration<T> {
180+
impl<T: RegistrationOps + 'static> Registration<T> {
181+
extern "C" fn post_unbind_callback(dev: *mut bindings::device) {
182+
// SAFETY: The driver core only ever calls the post unbind callback with a valid pointer to
183+
// a `struct device`.
184+
//
185+
// INVARIANT: `dev` is valid for the duration of the `post_unbind_callback()`.
186+
let dev = unsafe { &*dev.cast::<device::Device<device::CoreInternal>>() };
187+
188+
// `remove()` and all devres callbacks have been completed at this point, hence drop the
189+
// driver's device private data.
190+
//
191+
// SAFETY: By the safety requirements of the `Driver` trait, `T::DriverData` is the
192+
// driver's device private data type.
193+
drop(unsafe { dev.drvdata_obtain::<T::DriverData>() });
194+
}
195+
196+
/// Attach generic `struct device_driver` callbacks.
197+
fn callbacks_attach(drv: &Opaque<T::DriverType>) {
198+
let ptr = drv.get().cast::<u8>();
199+
200+
// SAFETY:
201+
// - `drv.get()` yields a valid pointer to `Self::DriverType`.
202+
// - Adding `DEVICE_DRIVER_OFFSET` yields the address of the embedded `struct device_driver`
203+
// as guaranteed by the safety requirements of the `Driver` trait.
204+
let base = unsafe { ptr.add(T::DEVICE_DRIVER_OFFSET) };
205+
206+
// CAST: `base` points to the offset of the embedded `struct device_driver`.
207+
let base = base.cast::<bindings::device_driver>();
208+
209+
// SAFETY: It is safe to set the fields of `struct device_driver` on initialization.
210+
unsafe { (*base).p_cb.post_unbind_rust = Some(Self::post_unbind_callback) };
211+
}
212+
181213
/// Creates a new instance of the registration object.
182214
pub fn new(name: &'static CStr, module: &'static ThisModule) -> impl PinInit<Self, Error> {
183215
try_pin_init!(Self {
@@ -189,6 +221,8 @@ impl<T: RegistrationOps> Registration<T> {
189221
// just been initialised above, so it's also valid for read.
190222
let drv = unsafe { &*(ptr as *const Opaque<T::DriverType>) };
191223

224+
Self::callbacks_attach(drv);
225+
192226
// SAFETY: `drv` is guaranteed to be pinned until `T::unregister`.
193227
unsafe { T::register(drv, name, module) }
194228
}),

rust/kernel/i2c.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -178,9 +178,9 @@ impl<T: Driver + 'static> Adapter<T> {
178178
// SAFETY: `remove_callback` is only ever called after a successful call to
179179
// `probe_callback`, hence it's guaranteed that `I2cClient::set_drvdata()` has been called
180180
// and stored a `Pin<KBox<T>>`.
181-
let data = unsafe { idev.as_ref().drvdata_obtain::<T>() };
181+
let data = unsafe { idev.as_ref().drvdata_borrow::<T>() };
182182

183-
T::unbind(idev, data.as_ref());
183+
T::unbind(idev, data);
184184
}
185185

186186
extern "C" fn shutdown_callback(idev: *mut bindings::i2c_client) {

rust/kernel/pci.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,9 +123,9 @@ impl<T: Driver + 'static> Adapter<T> {
123123
// SAFETY: `remove_callback` is only ever called after a successful call to
124124
// `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
125125
// and stored a `Pin<KBox<T>>`.
126-
let data = unsafe { pdev.as_ref().drvdata_obtain::<T>() };
126+
let data = unsafe { pdev.as_ref().drvdata_borrow::<T>() };
127127

128-
T::unbind(pdev, data.as_ref());
128+
T::unbind(pdev, data);
129129
}
130130
}
131131

rust/kernel/platform.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,9 +101,9 @@ impl<T: Driver + 'static> Adapter<T> {
101101
// SAFETY: `remove_callback` is only ever called after a successful call to
102102
// `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
103103
// and stored a `Pin<KBox<T>>`.
104-
let data = unsafe { pdev.as_ref().drvdata_obtain::<T>() };
104+
let data = unsafe { pdev.as_ref().drvdata_borrow::<T>() };
105105

106-
T::unbind(pdev, data.as_ref());
106+
T::unbind(pdev, data);
107107
}
108108
}
109109

rust/kernel/usb.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,9 +103,9 @@ impl<T: Driver + 'static> Adapter<T> {
103103
// SAFETY: `disconnect_callback` is only ever called after a successful call to
104104
// `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
105105
// and stored a `Pin<KBox<T>>`.
106-
let data = unsafe { dev.drvdata_obtain::<T>() };
106+
let data = unsafe { dev.drvdata_borrow::<T>() };
107107

108-
T::disconnect(intf, data.as_ref());
108+
T::disconnect(intf, data);
109109
}
110110
}
111111

0 commit comments

Comments
 (0)