Skip to main content

kernel/
usb.rs

1// SPDX-License-Identifier: GPL-2.0
2// SPDX-FileCopyrightText: Copyright (C) 2025 Collabora Ltd.
3
4//! Abstractions for the USB bus.
5//!
6//! C header: [`include/linux/usb.h`](srctree/include/linux/usb.h)
7
8use crate::{
9    bindings,
10    device,
11    device_id::{
12        RawDeviceId,
13        RawDeviceIdIndex, //
14    },
15    driver,
16    error::{
17        from_result,
18        to_result, //
19    },
20    prelude::*,
21    sync::aref::AlwaysRefCounted,
22    types::Opaque,
23    ThisModule, //
24};
25use core::{
26    marker::PhantomData,
27    mem::offset_of,
28    ptr::NonNull, //
29};
30
31/// An adapter for the registration of USB drivers.
32pub struct Adapter<T: Driver>(T);
33
34// SAFETY:
35// - `bindings::usb_driver` is a C type declared as `repr(C)`.
36// - `T::Data` is the type of the driver's device private data.
37// - `struct usb_driver` embeds a `struct device_driver`.
38// - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`.
39unsafe impl<T: Driver> driver::DriverLayout for Adapter<T> {
40    type DriverType = bindings::usb_driver;
41    type DriverData<'bound> = T::Data<'bound>;
42    const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver);
43}
44
45// SAFETY: A call to `unregister` for a given instance of `DriverType` is guaranteed to be valid if
46// a preceding call to `register` has been successful.
47unsafe impl<T: Driver> driver::RegistrationOps for Adapter<T> {
48    unsafe fn register(
49        udrv: &Opaque<Self::DriverType>,
50        name: &'static CStr,
51        module: &'static ThisModule,
52    ) -> Result {
53        // SAFETY: It's safe to set the fields of `struct usb_driver` on initialization.
54        unsafe {
55            (*udrv.get()).name = name.as_char_ptr();
56            (*udrv.get()).probe = Some(Self::probe_callback);
57            (*udrv.get()).disconnect = Some(Self::disconnect_callback);
58            (*udrv.get()).id_table = T::ID_TABLE.as_ptr();
59        }
60
61        // SAFETY: `udrv` is guaranteed to be a valid `DriverType`.
62        to_result(unsafe {
63            bindings::usb_register_driver(udrv.get(), module.0, name.as_char_ptr())
64        })
65    }
66
67    unsafe fn unregister(udrv: &Opaque<Self::DriverType>) {
68        // SAFETY: `udrv` is guaranteed to be a valid `DriverType`.
69        unsafe { bindings::usb_deregister(udrv.get()) };
70    }
71}
72
73impl<T: Driver> Adapter<T> {
74    extern "C" fn probe_callback(
75        intf: *mut bindings::usb_interface,
76        id: *const bindings::usb_device_id,
77    ) -> kernel::ffi::c_int {
78        // SAFETY: The USB core only ever calls the probe callback with a valid pointer to a
79        // `struct usb_interface` and `struct usb_device_id`.
80        //
81        // INVARIANT: `intf` is valid for the duration of `probe_callback()`.
82        let intf = unsafe { &*intf.cast::<Interface<device::CoreInternal<'_>>>() };
83
84        from_result(|| {
85            // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `struct usb_device_id` and
86            // does not add additional invariants, so it's safe to transmute.
87            let id = unsafe { &*id.cast::<DeviceId>() };
88
89            let info = T::ID_TABLE.info(id.index());
90            let data = T::probe(intf, id, info);
91
92            let dev: &device::Device<device::CoreInternal<'_>> = intf.as_ref();
93            dev.set_drvdata(data)?;
94            Ok(0)
95        })
96    }
97
98    extern "C" fn disconnect_callback(intf: *mut bindings::usb_interface) {
99        // SAFETY: The USB core only ever calls the disconnect callback with a valid pointer to a
100        // `struct usb_interface`.
101        //
102        // INVARIANT: `intf` is valid for the duration of `disconnect_callback()`.
103        let intf = unsafe { &*intf.cast::<Interface<device::CoreInternal<'_>>>() };
104
105        let dev: &device::Device<device::CoreInternal<'_>> = intf.as_ref();
106
107        // SAFETY: `disconnect_callback` is only ever called after a successful call to
108        // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
109        // and stored a `Pin<KBox<T::Data<'_>>>`.
110        let data = unsafe { dev.drvdata_borrow::<T::Data<'_>>() };
111
112        T::disconnect(intf, data);
113    }
114}
115
116/// Abstraction for the USB device ID structure, i.e. [`struct usb_device_id`].
117///
118/// [`struct usb_device_id`]: https://docs.kernel.org/driver-api/basics.html#c.usb_device_id
119#[repr(transparent)]
120#[derive(Clone, Copy)]
121pub struct DeviceId(bindings::usb_device_id);
122
123impl DeviceId {
124    /// Equivalent to C's `USB_DEVICE` macro.
125    pub const fn from_id(vendor: u16, product: u16) -> Self {
126        Self(bindings::usb_device_id {
127            match_flags: bindings::USB_DEVICE_ID_MATCH_DEVICE as u16,
128            idVendor: vendor,
129            idProduct: product,
130            ..pin_init::zeroed()
131        })
132    }
133
134    /// Equivalent to C's `USB_DEVICE_VER` macro.
135    pub const fn from_device_ver(vendor: u16, product: u16, bcd_lo: u16, bcd_hi: u16) -> Self {
136        Self(bindings::usb_device_id {
137            match_flags: bindings::USB_DEVICE_ID_MATCH_DEVICE_AND_VERSION as u16,
138            idVendor: vendor,
139            idProduct: product,
140            bcdDevice_lo: bcd_lo,
141            bcdDevice_hi: bcd_hi,
142            ..pin_init::zeroed()
143        })
144    }
145
146    /// Equivalent to C's `USB_DEVICE_INFO` macro.
147    pub const fn from_device_info(class: u8, subclass: u8, protocol: u8) -> Self {
148        Self(bindings::usb_device_id {
149            match_flags: bindings::USB_DEVICE_ID_MATCH_DEV_INFO as u16,
150            bDeviceClass: class,
151            bDeviceSubClass: subclass,
152            bDeviceProtocol: protocol,
153            ..pin_init::zeroed()
154        })
155    }
156
157    /// Equivalent to C's `USB_INTERFACE_INFO` macro.
158    pub const fn from_interface_info(class: u8, subclass: u8, protocol: u8) -> Self {
159        Self(bindings::usb_device_id {
160            match_flags: bindings::USB_DEVICE_ID_MATCH_INT_INFO as u16,
161            bInterfaceClass: class,
162            bInterfaceSubClass: subclass,
163            bInterfaceProtocol: protocol,
164            ..pin_init::zeroed()
165        })
166    }
167
168    /// Equivalent to C's `USB_DEVICE_INTERFACE_CLASS` macro.
169    pub const fn from_device_interface_class(vendor: u16, product: u16, class: u8) -> Self {
170        Self(bindings::usb_device_id {
171            match_flags: (bindings::USB_DEVICE_ID_MATCH_DEVICE
172                | bindings::USB_DEVICE_ID_MATCH_INT_CLASS) as u16,
173            idVendor: vendor,
174            idProduct: product,
175            bInterfaceClass: class,
176            ..pin_init::zeroed()
177        })
178    }
179
180    /// Equivalent to C's `USB_DEVICE_INTERFACE_PROTOCOL` macro.
181    pub const fn from_device_interface_protocol(vendor: u16, product: u16, protocol: u8) -> Self {
182        Self(bindings::usb_device_id {
183            match_flags: (bindings::USB_DEVICE_ID_MATCH_DEVICE
184                | bindings::USB_DEVICE_ID_MATCH_INT_PROTOCOL) as u16,
185            idVendor: vendor,
186            idProduct: product,
187            bInterfaceProtocol: protocol,
188            ..pin_init::zeroed()
189        })
190    }
191
192    /// Equivalent to C's `USB_DEVICE_INTERFACE_NUMBER` macro.
193    pub const fn from_device_interface_number(vendor: u16, product: u16, number: u8) -> Self {
194        Self(bindings::usb_device_id {
195            match_flags: (bindings::USB_DEVICE_ID_MATCH_DEVICE
196                | bindings::USB_DEVICE_ID_MATCH_INT_NUMBER) as u16,
197            idVendor: vendor,
198            idProduct: product,
199            bInterfaceNumber: number,
200            ..pin_init::zeroed()
201        })
202    }
203
204    /// Equivalent to C's `USB_DEVICE_AND_INTERFACE_INFO` macro.
205    pub const fn from_device_and_interface_info(
206        vendor: u16,
207        product: u16,
208        class: u8,
209        subclass: u8,
210        protocol: u8,
211    ) -> Self {
212        Self(bindings::usb_device_id {
213            match_flags: (bindings::USB_DEVICE_ID_MATCH_INT_INFO
214                | bindings::USB_DEVICE_ID_MATCH_DEVICE) as u16,
215            idVendor: vendor,
216            idProduct: product,
217            bInterfaceClass: class,
218            bInterfaceSubClass: subclass,
219            bInterfaceProtocol: protocol,
220            ..pin_init::zeroed()
221        })
222    }
223}
224
225// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `usb_device_id` and does not add
226// additional invariants, so it's safe to transmute to `RawType`.
227unsafe impl RawDeviceId for DeviceId {
228    type RawType = bindings::usb_device_id;
229}
230
231// SAFETY: `DRIVER_DATA_OFFSET` is the offset to the `driver_info` field.
232unsafe impl RawDeviceIdIndex for DeviceId {
233    const DRIVER_DATA_OFFSET: usize = core::mem::offset_of!(bindings::usb_device_id, driver_info);
234
235    fn index(&self) -> usize {
236        self.0.driver_info
237    }
238}
239
240/// [`IdTable`](kernel::device_id::IdTable) type for USB.
241pub type IdTable<T> = &'static dyn kernel::device_id::IdTable<DeviceId, T>;
242
243/// Create a USB `IdTable` with its alias for modpost.
244#[macro_export]
245macro_rules! usb_device_table {
246    ($table_name:ident, $module_table_name:ident, $id_info_type: ty, $table_data: expr) => {
247        const $table_name: $crate::device_id::IdArray<
248            $crate::usb::DeviceId,
249            $id_info_type,
250            { $table_data.len() },
251        > = $crate::device_id::IdArray::new($table_data);
252
253        $crate::module_device_table!("usb", $module_table_name, $table_name);
254    };
255}
256
257/// The USB driver trait.
258///
259/// # Examples
260///
261///```
262/// # use kernel::{bindings, device::Core, usb};
263/// use kernel::prelude::*;
264///
265/// struct MyDriver;
266///
267/// kernel::usb_device_table!(
268///     USB_TABLE,
269///     MODULE_USB_TABLE,
270///     <MyDriver as usb::Driver>::IdInfo,
271///     [
272///         (usb::DeviceId::from_id(0x1234, 0x5678), ()),
273///         (usb::DeviceId::from_id(0xabcd, 0xef01), ()),
274///     ]
275/// );
276///
277/// impl usb::Driver for MyDriver {
278///     type IdInfo = ();
279///     type Data<'bound> = Self;
280///     const ID_TABLE: usb::IdTable<Self::IdInfo> = &USB_TABLE;
281///
282///     fn probe<'bound>(
283///         _interface: &'bound usb::Interface<Core<'_>>,
284///         _id: &usb::DeviceId,
285///         _info: &'bound Self::IdInfo,
286///     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
287///         Err(ENODEV)
288///     }
289///
290///     fn disconnect<'bound>(
291///         _interface: &'bound usb::Interface<Core<'_>>,
292///         _data: Pin<&Self::Data<'bound>>,
293///     ) {
294///     }
295/// }
296///```
297pub trait Driver {
298    /// The type holding information about each one of the device ids supported by the driver.
299    type IdInfo: 'static;
300
301    /// The type of the driver's bus device private data.
302    type Data<'bound>: Send + 'bound;
303
304    /// The table of device ids supported by the driver.
305    const ID_TABLE: IdTable<Self::IdInfo>;
306
307    /// USB driver probe.
308    ///
309    /// Called when a new USB interface is bound to this driver.
310    /// Implementers should attempt to initialize the interface here.
311    fn probe<'bound>(
312        interface: &'bound Interface<device::Core<'_>>,
313        id: &DeviceId,
314        id_info: &'bound Self::IdInfo,
315    ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound;
316
317    /// USB driver disconnect.
318    ///
319    /// Called when the USB interface is about to be unbound from this driver.
320    fn disconnect<'bound>(
321        interface: &'bound Interface<device::Core<'_>>,
322        data: Pin<&Self::Data<'bound>>,
323    );
324}
325
326/// A USB interface.
327///
328/// This structure represents the Rust abstraction for a C [`struct usb_interface`].
329/// The implementation abstracts the usage of a C [`struct usb_interface`] passed
330/// in from the C side.
331///
332/// # Invariants
333///
334/// An [`Interface`] instance represents a valid [`struct usb_interface`] created
335/// by the C portion of the kernel.
336///
337/// [`struct usb_interface`]: https://www.kernel.org/doc/html/latest/driver-api/usb/usb.html#c.usb_interface
338#[repr(transparent)]
339pub struct Interface<Ctx: device::DeviceContext = device::Normal>(
340    Opaque<bindings::usb_interface>,
341    PhantomData<Ctx>,
342);
343
344impl<Ctx: device::DeviceContext> Interface<Ctx> {
345    fn as_raw(&self) -> *mut bindings::usb_interface {
346        self.0.get()
347    }
348}
349
350// SAFETY: `usb::Interface` is a transparent wrapper of `struct usb_interface`.
351// The offset is guaranteed to point to a valid device field inside `usb::Interface`.
352unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Interface<Ctx> {
353    const OFFSET: usize = offset_of!(bindings::usb_interface, dev);
354}
355
356// SAFETY: `Interface` is a transparent wrapper of a type that doesn't depend on
357// `Interface`'s generic argument.
358kernel::impl_device_context_deref!(unsafe { Interface });
359kernel::impl_device_context_into_aref!(Interface);
360
361impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Interface<Ctx> {
362    fn as_ref(&self) -> &device::Device<Ctx> {
363        // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
364        // `struct usb_interface`.
365        let dev = unsafe { &raw mut ((*self.as_raw()).dev) };
366
367        // SAFETY: `dev` points to a valid `struct device`.
368        unsafe { device::Device::from_raw(dev) }
369    }
370}
371
372impl<Ctx: device::DeviceContext> AsRef<Device> for Interface<Ctx> {
373    fn as_ref(&self) -> &Device {
374        // SAFETY: `self.as_raw()` is valid by the type invariants.
375        let usb_dev = unsafe { bindings::interface_to_usbdev(self.as_raw()) };
376
377        // SAFETY: For a valid `struct usb_interface` pointer, the above call to
378        // `interface_to_usbdev()` guarantees to return a valid pointer to a `struct usb_device`.
379        unsafe { &*(usb_dev.cast()) }
380    }
381}
382
383// SAFETY: Instances of `Interface` are always reference-counted.
384unsafe impl AlwaysRefCounted for Interface {
385    #[inline]
386    fn inc_ref(&self) {
387        // SAFETY: The invariants of `Interface` guarantee that `self.as_raw()`
388        // returns a valid `struct usb_interface` pointer, for which we will
389        // acquire a new refcount.
390        unsafe { bindings::usb_get_intf(self.as_raw()) };
391    }
392
393    #[inline]
394    unsafe fn dec_ref(obj: NonNull<Self>) {
395        // SAFETY: The safety requirements guarantee that the refcount is non-zero.
396        unsafe { bindings::usb_put_intf(obj.cast().as_ptr()) }
397    }
398}
399
400// SAFETY: A `Interface` is always reference-counted and can be released from any thread.
401unsafe impl Send for Interface {}
402
403// SAFETY: It is safe to send a &Interface to another thread because we do not
404// allow any mutation through a shared reference.
405unsafe impl Sync for Interface {}
406
407/// A USB device.
408///
409/// This structure represents the Rust abstraction for a C [`struct usb_device`].
410/// The implementation abstracts the usage of a C [`struct usb_device`] passed in
411/// from the C side.
412///
413/// # Invariants
414///
415/// A [`Device`] instance represents a valid [`struct usb_device`] created by the C portion of the
416/// kernel.
417///
418/// [`struct usb_device`]: https://www.kernel.org/doc/html/latest/driver-api/usb/usb.html#c.usb_device
419#[repr(transparent)]
420struct Device<Ctx: device::DeviceContext = device::Normal>(
421    Opaque<bindings::usb_device>,
422    PhantomData<Ctx>,
423);
424
425impl<Ctx: device::DeviceContext> Device<Ctx> {
426    fn as_raw(&self) -> *mut bindings::usb_device {
427        self.0.get()
428    }
429}
430
431// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
432// argument.
433kernel::impl_device_context_deref!(unsafe { Device });
434kernel::impl_device_context_into_aref!(Device);
435
436// SAFETY: Instances of `Device` are always reference-counted.
437unsafe impl AlwaysRefCounted for Device {
438    #[inline]
439    fn inc_ref(&self) {
440        // SAFETY: The invariants of `Device` guarantee that `self.as_raw()`
441        // returns a valid `struct usb_device` pointer, for which we will
442        // acquire a new refcount.
443        unsafe { bindings::usb_get_dev(self.as_raw()) };
444    }
445
446    #[inline]
447    unsafe fn dec_ref(obj: NonNull<Self>) {
448        // SAFETY: The safety requirements guarantee that the refcount is non-zero.
449        unsafe { bindings::usb_put_dev(obj.cast().as_ptr()) }
450    }
451}
452
453impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
454    fn as_ref(&self) -> &device::Device<Ctx> {
455        // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
456        // `struct usb_device`.
457        let dev = unsafe { &raw mut ((*self.as_raw()).dev) };
458
459        // SAFETY: `dev` points to a valid `struct device`.
460        unsafe { device::Device::from_raw(dev) }
461    }
462}
463
464// SAFETY: A `Device` is always reference-counted and can be released from any thread.
465unsafe impl Send for Device {}
466
467// SAFETY: It is safe to send a &Device to another thread because we do not
468// allow any mutation through a shared reference.
469unsafe impl Sync for Device {}
470
471// SAFETY: Same as `Device<Normal>` -- the underlying `struct usb_device` is the same;
472// `Bound` is a zero-sized type-state marker that does not affect thread safety.
473unsafe impl Sync for Device<device::Bound> {}
474
475/// Declares a kernel module that exposes a single USB driver.
476///
477/// # Examples
478///
479/// ```ignore
480/// module_usb_driver! {
481///     type: MyDriver,
482///     name: "Module name",
483///     author: ["Author name"],
484///     description: "Description",
485///     license: "GPL v2",
486/// }
487/// ```
488#[macro_export]
489macro_rules! module_usb_driver {
490    ($($f:tt)*) => {
491        $crate::module_driver!(<T>, $crate::usb::Adapter<T>, { $($f)* });
492    }
493}