|
| 1 | +// SPDX-License-Identifier: GPL-2.0 |
| 2 | + |
| 3 | +//! Generic devices that are part of the kernel's driver model. |
| 4 | +//! |
| 5 | +//! C header: [`include/linux/device.h`](../../../../include/linux/device.h) |
| 6 | +
|
| 7 | +use crate::bindings; |
| 8 | + |
| 9 | +/// A raw device. |
| 10 | +/// |
| 11 | +/// # Safety |
| 12 | +/// |
| 13 | +/// Implementers must ensure that the `*mut device` returned by [`RawDevice::raw_device`] is |
| 14 | +/// related to `self`, that is, actions on it will affect `self`. For example, if one calls |
| 15 | +/// `get_device`, then the refcount on the device represented by `self` will be incremented. |
| 16 | +pub unsafe trait RawDevice { |
| 17 | + /// Returns the raw `struct device` related to `self`. |
| 18 | + fn raw_device(&self) -> *mut bindings::device; |
| 19 | +} |
| 20 | + |
| 21 | +/// A ref-counted device. |
| 22 | +/// |
| 23 | +/// # Invariants |
| 24 | +/// |
| 25 | +/// `ptr` is valid, non-null, and has a non-zero reference count. One of the references is owned by |
| 26 | +/// `self`, and will be decremented when `self` is dropped. |
| 27 | +pub struct Device { |
| 28 | + pub(crate) ptr: *mut bindings::device, |
| 29 | +} |
| 30 | + |
| 31 | +impl Device { |
| 32 | + /// Creates a new device instance. |
| 33 | + /// |
| 34 | + /// # Safety |
| 35 | + /// |
| 36 | + /// Callers must ensure that `ptr` is valid, non-null, and has a non-zero reference count. |
| 37 | + pub unsafe fn new(ptr: *mut bindings::device) -> Self { |
| 38 | + // SAFETY: By the safety requiments, ptr is valid and its refcounted will be incremented. |
| 39 | + unsafe { bindings::get_device(ptr) }; |
| 40 | + // INVARIANT: The safety requirements satisfy all but one invariant, which is that `self` |
| 41 | + // owns a reference. This is satisfied by the call to `get_device` above. |
| 42 | + Self { ptr } |
| 43 | + } |
| 44 | + |
| 45 | + /// Creates a new device instance from an existing [`RawDevice`] instance. |
| 46 | + pub fn from_dev(dev: &dyn RawDevice) -> Self { |
| 47 | + // SAFETY: The requirements are satisfied by the existence of `RawDevice` and its safety |
| 48 | + // requirements. |
| 49 | + unsafe { Self::new(dev.raw_device()) } |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +impl Drop for Device { |
| 54 | + fn drop(&mut self) { |
| 55 | + // SAFETY: By the type invariants, we know that `self` owns a reference, so it is safe to |
| 56 | + // relinquish it now. |
| 57 | + unsafe { bindings::put_device(self.ptr) }; |
| 58 | + } |
| 59 | +} |
0 commit comments