Re: [PATCH V7 03/16] rust: cpu: Add from_cpu()

From: Viresh Kumar
Date: Thu Jan 16 2025 - 04:17:22 EST


On 15-01-25, 09:09, Greg KH wrote:
> On Wed, Jan 15, 2025 at 01:28:59PM +0530, Viresh Kumar wrote:
> > On 15-01-25, 08:54, Greg KH wrote:
> > > Ah, but that's not really something that SAFETY should override, right?
> > >
> > > Yes, you know your implementation of this will stop using the pointer in
> > > the hotplug callback before it goes away but that's not documented here.
> > > And having the device "fail" afterward isn't really ok either as you are
> > > relying on the driver core to always check for this and I'm not so sure
> > > that it always does on all codepaths.
> > >
> > > But, I'm ok with this for now, as you are just copying the bad C model
> > > at the moment, but it really feels like a huge foot-gun waiting to go
> > > off. Any way to put some more documentation here as in "use this at
> > > your own risk!"?
> >
> > What about marking it unsafe ? That would require callers to document
> > why it is safe to call this. And yes add more documentation here too.
>
> Sure, that's fine with me.

+/// Creates a new instance of CPU's device.
+///
+/// # Safety
+///
+/// Reference counting is not implemented for the CPU device in the C code. When a CPU is
+/// hot-unplugged, the corresponding CPU device is unregistered, but its associated memory
+/// is not freed.
+///
+/// Callers must ensure that the CPU device is not used after it has been unregistered.
+/// This can be achieved, for example, by registering a CPU hotplug notifier and removing
+/// any references to the CPU device within the notifier's callback.
+pub unsafe fn from_cpu(cpu: u32) -> Result<&'static Device> {
+ // SAFETY: The pointer returned by `get_cpu_device()`, if not `NULL`, is a valid pointer to
+ // a `struct device` and is never freed by the C code.
+ let ptr = unsafe { bindings::get_cpu_device(cpu) };
+ if ptr.is_null() {
+ return Err(ENODEV);
+ }
+
+ // SAFETY: The pointer returned by `get_cpu_device()`, if not `NULL`, is a valid pointer to
+ // a `struct device` and is never freed by the C code.
+ Ok(unsafe { Device::as_ref(ptr) })
+}

--
viresh