xref: /linux/rust/kernel/i2c.rs (revision 59e6295fac26b8e85c1ea859cdd89fa1e47519d7)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! I2C Driver subsystem
4 
5 // I2C Driver abstractions.
6 use crate::{
7     acpi,
8     container_of,
9     device,
10     device_id::{
11         RawDeviceId,
12         RawDeviceIdIndex, //
13     },
14     devres::Devres,
15     driver,
16     error::*,
17     of,
18     prelude::*,
19     sync::aref::{
20         ARef,
21         AlwaysRefCounted, //
22     },
23     types::Opaque, //
24 };
25 
26 use core::{
27     marker::PhantomData,
28     mem::offset_of,
29     ptr::{
30         from_ref,
31         NonNull, //
32     }, //
33 };
34 
35 /// An I2C device id table.
36 #[repr(transparent)]
37 #[derive(Clone, Copy)]
38 pub struct DeviceId(bindings::i2c_device_id);
39 
40 impl DeviceId {
41     const I2C_NAME_SIZE: usize = 20;
42 
43     /// Create a new device id from an I2C 'id' string.
44     #[inline(always)]
45     pub const fn new(id: &'static CStr) -> Self {
46         let src = id.to_bytes_with_nul();
47         build_assert!(src.len() <= Self::I2C_NAME_SIZE, "ID exceeds 20 bytes");
48         let mut i2c: bindings::i2c_device_id = pin_init::zeroed();
49         let mut i = 0;
50         while i < src.len() {
51             i2c.name[i] = src[i];
52             i += 1;
53         }
54 
55         Self(i2c)
56     }
57 }
58 
59 // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `i2c_device_id` and does not add
60 // additional invariants, so it's safe to transmute to `RawType`.
61 unsafe impl RawDeviceId for DeviceId {
62     type RawType = bindings::i2c_device_id;
63 }
64 
65 // SAFETY: `DRIVER_DATA_OFFSET` is the offset to the `driver_data` field.
66 unsafe impl RawDeviceIdIndex for DeviceId {
67     const DRIVER_DATA_OFFSET: usize = core::mem::offset_of!(bindings::i2c_device_id, driver_data);
68 }
69 
70 /// IdTable type for I2C
71 pub type IdTable<T> = &'static dyn kernel::device_id::IdTable<DeviceId, T>;
72 
73 /// Create a I2C `IdTable` with its alias for modpost.
74 #[macro_export]
75 macro_rules! i2c_device_table {
76     ($($tt:tt)*) => {
77         $crate::module_device_table!("i2c", $crate::i2c::DeviceId, $($tt)*);
78     };
79 }
80 
81 /// An adapter for the registration of I2C drivers.
82 pub struct Adapter<T: Driver>(T);
83 
84 // SAFETY:
85 // - `bindings::i2c_driver` is a C type declared as `repr(C)`.
86 // - `T::Data` is the type of the driver's device private data.
87 // - `struct i2c_driver` embeds a `struct device_driver`.
88 // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`.
89 unsafe impl<T: Driver> driver::DriverLayout for Adapter<T> {
90     type DriverType = bindings::i2c_driver;
91     type DriverData<'bound> = T::Data<'bound>;
92     const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver);
93 }
94 
95 // SAFETY: A call to `unregister` for a given instance of `DriverType` is guaranteed to be valid if
96 // a preceding call to `register` has been successful.
97 unsafe impl<T: Driver> driver::RegistrationOps for Adapter<T> {
98     unsafe fn register(
99         idrv: &Opaque<Self::DriverType>,
100         name: &'static CStr,
101         module: &'static ThisModule,
102     ) -> Result {
103         build_assert!(
104             T::ACPI_ID_TABLE.is_some() || T::OF_ID_TABLE.is_some() || T::I2C_ID_TABLE.is_some(),
105             "At least one of ACPI/OF/Legacy tables must be present when registering an i2c driver"
106         );
107 
108         let i2c_table = match T::I2C_ID_TABLE {
109             Some(table) => table.as_ptr(),
110             None => core::ptr::null(),
111         };
112 
113         let of_table = match T::OF_ID_TABLE {
114             Some(table) => table.as_ptr(),
115             None => core::ptr::null(),
116         };
117 
118         let acpi_table = match T::ACPI_ID_TABLE {
119             Some(table) => table.as_ptr(),
120             None => core::ptr::null(),
121         };
122 
123         // SAFETY: It's safe to set the fields of `struct i2c_client` on initialization.
124         unsafe {
125             (*idrv.get()).driver.name = name.as_char_ptr();
126             (*idrv.get()).probe = Some(Self::probe_callback);
127             (*idrv.get()).remove = Some(Self::remove_callback);
128             (*idrv.get()).shutdown = Some(Self::shutdown_callback);
129             (*idrv.get()).id_table = i2c_table;
130             (*idrv.get()).driver.of_match_table = of_table;
131             (*idrv.get()).driver.acpi_match_table = acpi_table;
132         }
133 
134         // SAFETY: `idrv` is guaranteed to be a valid `DriverType`.
135         to_result(unsafe { bindings::i2c_register_driver(module.as_ptr(), idrv.get()) })
136     }
137 
138     unsafe fn unregister(idrv: &Opaque<Self::DriverType>) {
139         // SAFETY: `idrv` is guaranteed to be a valid `DriverType`.
140         unsafe { bindings::i2c_del_driver(idrv.get()) }
141     }
142 }
143 
144 impl<T: Driver> Adapter<T> {
145     extern "C" fn probe_callback(idev: *mut bindings::i2c_client) -> kernel::ffi::c_int {
146         // SAFETY: The I2C bus only ever calls the probe callback with a valid pointer to a
147         // `struct i2c_client`.
148         //
149         // INVARIANT: `idev` is valid for the duration of `probe_callback()`.
150         let idev = unsafe { &*idev.cast::<I2cClient<device::CoreInternal<'_>>>() };
151 
152         let info = Self::i2c_id_info(idev).or_else(|| {
153             // SAFETY: `idev` matched data is of type `Self::IdInfo`.
154             unsafe { <Self as driver::Adapter>::id_info(idev.as_ref()) }
155         });
156 
157         from_result(|| {
158             let data = T::probe(idev, info);
159 
160             idev.as_ref().set_drvdata(data)?;
161             Ok(0)
162         })
163     }
164 
165     extern "C" fn remove_callback(idev: *mut bindings::i2c_client) {
166         // SAFETY: `idev` is a valid pointer to a `struct i2c_client`.
167         let idev = unsafe { &*idev.cast::<I2cClient<device::CoreInternal<'_>>>() };
168 
169         // SAFETY: `remove_callback` is only ever called after a successful call to
170         // `probe_callback`, hence it's guaranteed that `I2cClient::set_drvdata()` has been called
171         // and stored a `Pin<KBox<T::Data<'_>>>`.
172         let data = unsafe { idev.as_ref().drvdata_borrow::<T::Data<'_>>() };
173 
174         T::unbind(idev, data);
175     }
176 
177     extern "C" fn shutdown_callback(idev: *mut bindings::i2c_client) {
178         // SAFETY: `shutdown_callback` is only ever called for a valid `idev`
179         let idev = unsafe { &*idev.cast::<I2cClient<device::CoreInternal<'_>>>() };
180 
181         // SAFETY: `shutdown_callback` is only ever called after a successful call to
182         // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
183         // and stored a `Pin<KBox<T::Data<'_>>>`.
184         let data = unsafe { idev.as_ref().drvdata_borrow::<T::Data<'_>>() };
185 
186         T::shutdown(idev, data);
187     }
188 
189     /// The [`i2c::IdTable`] of the corresponding driver.
190     fn i2c_id_table() -> Option<IdTable<<Self as driver::Adapter>::IdInfo>> {
191         T::I2C_ID_TABLE
192     }
193 
194     /// Returns the driver's private data from the matching entry in the [`i2c::IdTable`], if any.
195     ///
196     /// If this returns `None`, it means there is no match with an entry in the [`i2c::IdTable`].
197     fn i2c_id_info(dev: &I2cClient) -> Option<&'static <Self as driver::Adapter>::IdInfo> {
198         let table = Self::i2c_id_table()?;
199 
200         // SAFETY:
201         // - `table` has static lifetime, hence it's valid for reads
202         // - `dev` is guaranteed to be valid while it's alive, and so is `dev.as_raw()`.
203         let raw_id = unsafe { bindings::i2c_match_id(table.as_ptr(), dev.as_raw()) };
204 
205         if raw_id.is_null() {
206             return None;
207         }
208 
209         // SAFETY: `DeviceId` is a `#[repr(transparent)` wrapper of `struct i2c_device_id` and
210         // does not add additional invariants, so it's safe to transmute.
211         let id = unsafe { &*raw_id.cast::<DeviceId>() };
212 
213         // SAFETY: `id` comes from `table` which is of type `IdArray<_, Self::IdInfo>`.
214         Some(unsafe { id.info_unchecked::<T::IdInfo>() })
215     }
216 }
217 
218 impl<T: Driver> driver::Adapter for Adapter<T> {
219     type IdInfo = T::IdInfo;
220 
221     fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {
222         T::OF_ID_TABLE
223     }
224 
225     fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>> {
226         T::ACPI_ID_TABLE
227     }
228 }
229 
230 /// Declares a kernel module that exposes a single i2c driver.
231 ///
232 /// # Examples
233 ///
234 /// ```ignore
235 /// kernel::module_i2c_driver! {
236 ///     type: MyDriver,
237 ///     name: "Module name",
238 ///     authors: ["Author name"],
239 ///     description: "Description",
240 ///     license: "GPL v2",
241 /// }
242 /// ```
243 #[macro_export]
244 macro_rules! module_i2c_driver {
245     ($($f:tt)*) => {
246         $crate::module_driver!(<T>, $crate::i2c::Adapter<T>, { $($f)* });
247     };
248 }
249 
250 /// The i2c driver trait.
251 ///
252 /// Drivers must implement this trait in order to get a i2c driver registered.
253 ///
254 /// # Example
255 ///
256 ///```
257 /// # use kernel::{acpi, bindings, device::Core, i2c, of};
258 ///
259 /// struct MyDriver;
260 ///
261 /// kernel::acpi_device_table!(
262 ///     ACPI_TABLE,
263 ///     <MyDriver as i2c::Driver>::IdInfo,
264 ///     [
265 ///         (acpi::DeviceId::new(c"LNUXBEEF"), ())
266 ///     ]
267 /// );
268 ///
269 /// kernel::i2c_device_table!(
270 ///     I2C_TABLE,
271 ///     <MyDriver as i2c::Driver>::IdInfo,
272 ///     [
273 ///          (i2c::DeviceId::new(c"rust_driver_i2c"), ())
274 ///     ]
275 /// );
276 ///
277 /// kernel::of_device_table!(
278 ///     OF_TABLE,
279 ///     <MyDriver as i2c::Driver>::IdInfo,
280 ///     [
281 ///         (of::DeviceId::new(c"test,device"), ())
282 ///     ]
283 /// );
284 ///
285 /// impl i2c::Driver for MyDriver {
286 ///     type IdInfo = ();
287 ///     type Data<'bound> = Self;
288 ///     const I2C_ID_TABLE: Option<i2c::IdTable<Self::IdInfo>> = Some(&I2C_TABLE);
289 ///     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
290 ///     const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
291 ///
292 ///     fn probe<'bound>(
293 ///         _idev: &'bound i2c::I2cClient<Core<'_>>,
294 ///         _id_info: Option<&'bound Self::IdInfo>,
295 ///     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
296 ///         Err(ENODEV)
297 ///     }
298 ///
299 ///     fn shutdown<'bound>(
300 ///         _idev: &'bound i2c::I2cClient<Core<'_>>,
301 ///         this: Pin<&Self::Data<'bound>>,
302 ///     ) {
303 ///     }
304 /// }
305 ///```
306 pub trait Driver {
307     /// The type holding information about each device id supported by the driver.
308     // TODO: Use `associated_type_defaults` once stabilized:
309     //
310     // ```
311     // type IdInfo: 'static = ();
312     // ```
313     type IdInfo: 'static;
314 
315     /// The type of the driver's bus device private data.
316     type Data<'bound>: Send + 'bound;
317 
318     /// The table of device ids supported by the driver.
319     const I2C_ID_TABLE: Option<IdTable<Self::IdInfo>> = None;
320 
321     /// The table of OF device ids supported by the driver.
322     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;
323 
324     /// The table of ACPI device ids supported by the driver.
325     const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = None;
326 
327     /// I2C driver probe.
328     ///
329     /// Called when a new i2c client is added or discovered.
330     /// Implementers should attempt to initialize the client here.
331     fn probe<'bound>(
332         dev: &'bound I2cClient<device::Core<'_>>,
333         id_info: Option<&'bound Self::IdInfo>,
334     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound;
335 
336     /// I2C driver shutdown.
337     ///
338     /// Called by the kernel during system reboot or power-off to allow the [`Driver`] to bring the
339     /// [`I2cClient`] into a safe state. Implementing this callback is optional.
340     ///
341     /// Typical actions include stopping transfers, disabling interrupts, or resetting the hardware
342     /// to prevent undesired behavior during shutdown.
343     ///
344     /// This callback is distinct from final resource cleanup, as the driver instance remains valid
345     /// after it returns. Any deallocation or teardown of driver-owned resources should instead be
346     /// handled in `Drop`.
347     fn shutdown<'bound>(dev: &'bound I2cClient<device::Core<'_>>, this: Pin<&Self::Data<'bound>>) {
348         let _ = (dev, this);
349     }
350 
351     /// I2C driver unbind.
352     ///
353     /// Called when the [`I2cClient`] is unbound from its bound [`Driver`]. Implementing this
354     /// callback is optional.
355     ///
356     /// This callback serves as a place for drivers to perform teardown operations that require a
357     /// `&Device<Core>` or `&Device<Bound>` reference. For instance, drivers may try to perform I/O
358     /// operations to gracefully tear down the device.
359     ///
360     /// Otherwise, release operations for driver resources should be performed in `Drop`.
361     fn unbind<'bound>(dev: &'bound I2cClient<device::Core<'_>>, this: Pin<&Self::Data<'bound>>) {
362         let _ = (dev, this);
363     }
364 }
365 
366 /// The i2c adapter representation.
367 ///
368 /// This structure represents the Rust abstraction for a C `struct i2c_adapter`. The
369 /// implementation abstracts the usage of an existing C `struct i2c_adapter` that
370 /// gets passed from the C side
371 ///
372 /// # Invariants
373 ///
374 /// A [`I2cAdapter`] instance represents a valid `struct i2c_adapter` created by the C portion of
375 /// the kernel.
376 #[repr(transparent)]
377 pub struct I2cAdapter<Ctx: device::DeviceContext = device::Normal>(
378     Opaque<bindings::i2c_adapter>,
379     PhantomData<Ctx>,
380 );
381 
382 impl<Ctx: device::DeviceContext> I2cAdapter<Ctx> {
383     fn as_raw(&self) -> *mut bindings::i2c_adapter {
384         self.0.get()
385     }
386 }
387 
388 impl I2cAdapter {
389     /// Returns the I2C Adapter index.
390     #[inline]
391     pub fn index(&self) -> i32 {
392         // SAFETY: `self.as_raw` is a valid pointer to a `struct i2c_adapter`.
393         unsafe { (*self.as_raw()).nr }
394     }
395 
396     /// Gets pointer to an `i2c_adapter` by index.
397     pub fn get(index: i32) -> Result<ARef<Self>> {
398         // SAFETY: `index` must refer to a valid I2C adapter; the kernel
399         // guarantees that `i2c_get_adapter(index)` returns either a valid
400         // pointer or NULL. `NonNull::new` guarantees the correct check.
401         let adapter = NonNull::new(unsafe { bindings::i2c_get_adapter(index) }).ok_or(ENODEV)?;
402 
403         // SAFETY: `adapter` is non-null and points to a live `i2c_adapter`.
404         // `I2cAdapter` is #[repr(transparent)], so this cast is valid.
405         // `i2c_get_adapter` returned the adapter with an incremented refcount, which we pass to
406         // the `ARef`.
407         Ok(unsafe { ARef::from_raw(adapter.cast::<I2cAdapter<device::Normal>>()) })
408     }
409 }
410 
411 // SAFETY: `I2cAdapter` is a transparent wrapper of a type that doesn't depend on
412 // `I2cAdapter`'s generic argument.
413 kernel::impl_device_context_deref!(unsafe { I2cAdapter });
414 kernel::impl_device_context_into_aref!(I2cAdapter);
415 
416 // SAFETY: Instances of `I2cAdapter` are always reference-counted.
417 unsafe impl AlwaysRefCounted for I2cAdapter {
418     fn inc_ref(&self) {
419         // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
420         unsafe { bindings::i2c_get_adapter(self.index()) };
421     }
422 
423     unsafe fn dec_ref(obj: NonNull<Self>) {
424         // SAFETY: The safety requirements guarantee that the refcount is non-zero.
425         unsafe { bindings::i2c_put_adapter(obj.as_ref().as_raw()) }
426     }
427 }
428 
429 /// The i2c board info representation
430 ///
431 /// This structure represents the Rust abstraction for a C `struct i2c_board_info` structure,
432 /// which is used for manual I2C client creation.
433 #[repr(transparent)]
434 pub struct I2cBoardInfo(bindings::i2c_board_info);
435 
436 impl I2cBoardInfo {
437     const I2C_TYPE_SIZE: usize = 20;
438     /// Create a new [`I2cBoardInfo`] for a kernel driver.
439     #[inline(always)]
440     pub const fn new(type_: &'static CStr, addr: u16) -> Self {
441         let src = type_.to_bytes_with_nul();
442         build_assert!(src.len() <= Self::I2C_TYPE_SIZE, "Type exceeds 20 bytes");
443         let mut i2c_board_info: bindings::i2c_board_info = pin_init::zeroed();
444         let mut i: usize = 0;
445         while i < src.len() {
446             i2c_board_info.type_[i] = src[i];
447             i += 1;
448         }
449 
450         i2c_board_info.addr = addr;
451         Self(i2c_board_info)
452     }
453 
454     fn as_raw(&self) -> *const bindings::i2c_board_info {
455         from_ref(&self.0)
456     }
457 }
458 
459 /// The i2c client representation.
460 ///
461 /// This structure represents the Rust abstraction for a C `struct i2c_client`. The
462 /// implementation abstracts the usage of an existing C `struct i2c_client` that
463 /// gets passed from the C side
464 ///
465 /// # Invariants
466 ///
467 /// A [`I2cClient`] instance represents a valid `struct i2c_client` created by the C portion of
468 /// the kernel.
469 #[repr(transparent)]
470 pub struct I2cClient<Ctx: device::DeviceContext = device::Normal>(
471     Opaque<bindings::i2c_client>,
472     PhantomData<Ctx>,
473 );
474 
475 impl<Ctx: device::DeviceContext> I2cClient<Ctx> {
476     fn as_raw(&self) -> *mut bindings::i2c_client {
477         self.0.get()
478     }
479 }
480 
481 // SAFETY: `I2cClient` is a transparent wrapper of `struct i2c_client`.
482 // The offset is guaranteed to point to a valid device field inside `I2cClient`.
483 unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for I2cClient<Ctx> {
484     const OFFSET: usize = offset_of!(bindings::i2c_client, dev);
485 }
486 
487 // SAFETY: `I2cClient` is a transparent wrapper of a type that doesn't depend on
488 // `I2cClient`'s generic argument.
489 kernel::impl_device_context_deref!(unsafe { I2cClient });
490 kernel::impl_device_context_into_aref!(I2cClient);
491 
492 // SAFETY: Instances of `I2cClient` are always reference-counted.
493 unsafe impl AlwaysRefCounted for I2cClient {
494     fn inc_ref(&self) {
495         // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
496         unsafe { bindings::get_device(self.as_ref().as_raw()) };
497     }
498 
499     unsafe fn dec_ref(obj: NonNull<Self>) {
500         // SAFETY: The safety requirements guarantee that the refcount is non-zero.
501         unsafe { bindings::put_device(&raw mut (*obj.as_ref().as_raw()).dev) }
502     }
503 }
504 
505 impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for I2cClient<Ctx> {
506     fn as_ref(&self) -> &device::Device<Ctx> {
507         let raw = self.as_raw();
508         // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
509         // `struct i2c_client`.
510         let dev = unsafe { &raw mut (*raw).dev };
511 
512         // SAFETY: `dev` points to a valid `struct device`.
513         unsafe { device::Device::from_raw(dev) }
514     }
515 }
516 
517 impl<Ctx: device::DeviceContext> TryFrom<&device::Device<Ctx>> for &I2cClient<Ctx> {
518     type Error = kernel::error::Error;
519 
520     fn try_from(dev: &device::Device<Ctx>) -> Result<Self, Self::Error> {
521         // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a
522         // `struct device`.
523         if unsafe { bindings::i2c_verify_client(dev.as_raw()).is_null() } {
524             return Err(EINVAL);
525         }
526 
527         // SAFETY: We've just verified that the type of `dev` equals to
528         // `bindings::i2c_client_type`, hence `dev` must be embedded in a valid
529         // `struct i2c_client` as guaranteed by the corresponding C code.
530         let idev = unsafe { container_of!(dev.as_raw(), bindings::i2c_client, dev) };
531 
532         // SAFETY: `idev` is a valid pointer to a `struct i2c_client`.
533         Ok(unsafe { &*idev.cast() })
534     }
535 }
536 
537 // SAFETY: A `I2cClient` is always reference-counted and can be released from any thread.
538 unsafe impl Send for I2cClient {}
539 
540 // SAFETY: `I2cClient` can be shared among threads because all methods of `I2cClient`
541 // (i.e. `I2cClient<Normal>) are thread safe.
542 unsafe impl Sync for I2cClient {}
543 
544 /// The registration of an i2c client device.
545 ///
546 /// This type represents the registration of a [`struct i2c_client`]. When an instance of this
547 /// type is dropped, its respective i2c client device will be unregistered from the system.
548 ///
549 /// # Invariants
550 ///
551 /// `self.0` always holds a valid pointer to an initialized and registered
552 /// [`struct i2c_client`].
553 #[repr(transparent)]
554 pub struct Registration(NonNull<bindings::i2c_client>);
555 
556 impl Registration {
557     /// The C `i2c_new_client_device` function wrapper for manual I2C client creation.
558     pub fn new<'a>(
559         i2c_adapter: &I2cAdapter,
560         i2c_board_info: &I2cBoardInfo,
561         parent_dev: &'a device::Device<device::Bound>,
562     ) -> impl PinInit<Devres<Self>, Error> + 'a {
563         Devres::new(parent_dev, Self::try_new(i2c_adapter, i2c_board_info))
564     }
565 
566     fn try_new(i2c_adapter: &I2cAdapter, i2c_board_info: &I2cBoardInfo) -> Result<Self> {
567         // SAFETY: the kernel guarantees that `i2c_new_client_device()` returns either a valid
568         // pointer or NULL. `from_err_ptr` separates errors. Following `NonNull::new`
569         // checks for NULL.
570         let raw_dev = from_err_ptr(unsafe {
571             bindings::i2c_new_client_device(i2c_adapter.as_raw(), i2c_board_info.as_raw())
572         })?;
573 
574         let dev_ptr = NonNull::new(raw_dev).ok_or(ENODEV)?;
575 
576         Ok(Self(dev_ptr))
577     }
578 }
579 
580 impl Drop for Registration {
581     fn drop(&mut self) {
582         // SAFETY: `Drop` is only called for a valid `Registration`, which by invariant
583         // always contains a non-null pointer to an `i2c_client`.
584         unsafe { bindings::i2c_unregister_device(self.0.as_ptr()) }
585     }
586 }
587 
588 // SAFETY: A `Registration` of a `struct i2c_client` can be released from any thread.
589 unsafe impl Send for Registration {}
590 
591 // SAFETY: `Registration` offers no interior mutability (no mutation through &self
592 // and no mutable access is exposed)
593 unsafe impl Sync for Registration {}
594