Files
linux/rust/kernel/serdev.rs
Linus Torvalds 59e6295fac Merge tag 'driver-core-7.3-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core
Pull driver core updates from Danilo Krummrich:
 "container_of:

   - Apply typeof_member(), remove the local __mptr variable to
     eliminate variable shadowing warnings on nested container_of()
     calls, and remove unnecessary parentheses

  core:

   - Add driver name to probe debug print for initcall_debug

   - Avoid repeatedly printing the same 'Fixed dependency cycle' log

   - Unwind device_add() on attribute creation failure in
     attribute_container_add_class_device()

   - Remove statistics group if encryption group creation fails in
     transport_add_class_device()

  debugfs:

   - Fix lockdown check for mmap_prepare()

   - Warn if file creation failed due to uninitialized debugfs

  device property:

   - Implement fw_devlink support for software nodes by adding
     software_node_add_links(), which creates fwnode links from
     DEV_PROP_REF properties to enable automatic probe ordering. Add
     kunit-managed fwnode helpers and test coverage

   - Fix infinite loop in fwnode_for_each_child_node() when the
     secondary fwnode has more than one child. Add test cases

   - Fix out-of-bounds access in software_node_get_reference_args() when
     called with index -1 (UINT_MAX)

   - Refactor to use RAII approach with __free()

   - Add Bartosz Golaszewski as software node reviewer

  firmware loader:

   - Fix race where a sysfs fallback request can complete before being
     queued as pending, leading to a use-after-free on the next fallback
     request

   - Reject 0-size built-in firmware and fail the build on empty
     firmware files in CONFIG_EXTRA_FIRMWARE

  kobject:

   - Provide __KOBJ_ATTR() and __KOBJ_ATTR_RO/WO() initialization macros
     and allow the constification of kobject attributes, enabling them
     to reside in read-only memory

  platform:

   - Provide platform_device_set_of_node(), platform_device_set_fwnode(),
     and platform_device_set_of_node_from_dev() helpers that encapsulate
     firmware node reference counting for dynamically allocated platform
     devices

     Convert all in-tree users that manually assigned dev.of_node or
     dev.fwnode, fixing a pre-existing refcount bug in powermac. Switch
     to counting references of all firmware node types, not only OF
     nodes

   - Unify the release path for dynamically allocated platform devices
     by removing platform_device_release_full(). Amend the fwnode setter
     API contract to warn if a primary software node is overwritten. Add
     KUnit tests for correct software node removal on device
     unregistration

  Rust:

   - Auxiliary:
       - Add registration_data_with() closure-based API for invariant
         ForLt types

   - Debugfs:
       - Migrate BinaryWriter and BinaryReaderMut trait requirements
         from kernel::transmute traits to zerocopy traits

   - Device:
       - Add BoundInternal device context and InternalBoundContext trait
         for bus abstractions that need internal access to a bound
         device.
       - Make the lifetime on Core and CoreInternal invariant to prevent
         coercion to shorter lifetimes

   - Devres:
       - Fix race between concurrent revokers where the losing revoker
         could return before the winning revoker finished dropping the
         inner data, causing use-after-free.
       - Ensure revocation is complete before the device finishes
         unbinding by making the synchronization bidirectional.
       - Add DevresLt<F: ForLt>, a wrapper around Devres that shortens
         'static back to the caller's borrow scope. Implement ForLt and
         CovariantForLt for Bar, IoMem, and ExclusiveIoMem

   - Driver:
       - Switch from index-based to pointer-based device ID info lookup,
         storing static references in driver_data. Centralize device ID
         handling in device_id.rs, removing the open-coded ACPI/OF
         matching logic and duplicate ID table from driver.rs

   - I/O:
       - Make I/O regions typed (with a dynamically-sized Region type
         for the existing untyped case), create view types representing
         subregions of a mapped I/O region, and add io_project!() for
         safely creating subviews.
       - Split Io into a base trait (IoBase) and an extension trait (Io)
         with a blanket implementation, preventing implementers from
         overriding provided methods that unsafe code relies on.
       - Add a SysMem backend for shared system memory with volatile
         access, and make Coherent implement Io via an I/O view type.
         Add IoSysMap as sum type of Mmio and SysMem. Add copying
         methods (memcpy_{from,to}io()) and read_val()/write_val() for
         typed access.
       - Replace dma_read!()/dma_write!() with io_read!()/io_write!()
         for primitives and copying methods for aggregates; drop the old
         macros. Convert nova-core to use I/O projection.
       - Fix internal shortcut rule dispatch in the register!() macro,
         remove unused rule arguments, and use path fragments for alias
         destinations

   - IRQ:
       - Make irq::Registration compatible with lifetime-bound drivers
         by removing the 'static bound on Handler/ThreadedHandler and
         replacing Devres<RegistrationInner> with direct
         request_irq()/free_irq() calls. Handlers can now directly own
         lifetime-bound device resources

   - PCI:
       - Convert IrqVectorRegistration to a lifetime-annotated owning
         type, giving drivers explicit control over the allocation
         lifetime. IrqVector embeds a resolved IrqRequest, making the
         conversion infallible. Remove the redundant
         request_irq()/request_threaded_irq() wrappers from pci::Device.
       - Add pci_irq_type() C helper and expose it via irq_type() on
         IrqVectorRegistration and IrqVector, returning PCI_IRQ_MSIX,
         PCI_IRQ_MSI, or PCI_IRQ_INTX.
       - Mark pci::Device refcount methods inline

   - Serdev:
       - Add Rust abstractions for the serial device bus, including
         serdev::Driver trait, serdev::Device wrapping struct
         serdev_device, and serdev::Adapter implementing
         RegistrationOps. Includes a sample driver. Markus Probst takes
         over as serdev maintainer for both C and Rust code

   - Misc:
       - Split ForLt into a base trait (providing the Of<'a> GAT) and an
         unsafe CovariantForLt subtrait guaranteeing covariance,
         enabling invariant types (e.g. those containing Mutex<&'bound T>)
         to participate in the ForLt abstraction.
       - Fix Coherent read past EOF returning -ERANGE instead of zero.
       - Fix firmware example UB by avoiding null-pointer ARef

  misc:
   - Avoid iattr allocation in kernfs listxattr by using
     kernfs_iattrs_noalloc().
   - Unregister SoC bus on early device registration failure.
   - Remove unused DMA_FENCE_TRACE Kconfig symbol.
   - Fix /sys/module path in comment.
   - Refactor ISA bus init to remove nested blocks.
   - Remove redundant nodemask clears in numa_init().
   - Add kernel-doc for fwnode_operations and sys_soc.h, mark
     internal property data as private for kernel-doc, and add
     property.h/fwnode.h to driver-api infrastructure docs.
   - Add MAINTAINERS entry for sys_soc.h"

* tag 'driver-core-7.3-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core: (129 commits)
  rust: pci: expose the allocated interrupt type
  PCI: Add pci_irq_type() to query the allocated interrupt type
  rust: pci: remove request_irq() and request_threaded_irq() from Device
  rust: pci: resolve IRQ in index() and embed IrqRequest in IrqVector
  rust: pci: convert IrqVectorRegistration to a lifetime-managed owning type
  kernfs: avoid iattr allocation in listxattr
  rust: serdev: use ThisModule::as_ptr() instead of field access
  ACPI/IORT: use platform_device_set_fwnode()
  ACPI/APMT: use platform_device_set_fwnode()
  firmware_loader: do not queue completed sysfs fallback requests
  rust: pci: Mark Device refcount methods inline
  rust: irq: make Registration compatible with lifetime-bound drivers
  rust: net/phy: remove expansion from doc
  rust: dma: return zero for Coherent reads past EOF
  rust: io: register: use path fragment for alias destination
  rust: io: register: remove unused rule arguments
  rust: io: register: dispatch shortcut rules internally
  MAINTAINERS: add sys_soc.h to DRIVER CORE
  rust: debugfs: remove unsafe blocks from traits impl for Vec
  rust: debugfs: migrate debugfs traits requirements to zerocopy
  ...
2026-08-19 10:42:18 -07:00

605 lines
22 KiB
Rust

// SPDX-License-Identifier: GPL-2.0
//! Abstractions for the serial device bus.
//!
//! C header: [`include/linux/serdev.h`](srctree/include/linux/serdev.h)
use crate::{
acpi,
device,
driver,
error::{
from_result,
to_result,
VTABLE_DEFAULT_ERROR, //
},
new_mutex,
of,
prelude::*,
sync::{
aref::AlwaysRefCounted,
Mutex, //
},
time::Jiffies,
types::{
Opaque,
ScopeGuard, //
}, //
};
use core::{
cell::UnsafeCell,
marker::PhantomData,
mem::{offset_of, MaybeUninit},
ptr::NonNull, //
};
/// Parity bit to use with a serial device.
#[repr(u32)]
pub enum Parity {
/// No parity bit.
None = bindings::serdev_parity_SERDEV_PARITY_NONE,
/// Even partiy.
Even = bindings::serdev_parity_SERDEV_PARITY_EVEN,
/// Odd parity.
Odd = bindings::serdev_parity_SERDEV_PARITY_ODD,
}
/// An adapter for the registration of serial device bus device drivers.
pub struct Adapter<T: Driver>(T);
// SAFETY:
// - `bindings::serdev_device_driver` is a C type declared as `repr(C)`.
// - `PrivateData<'bound, T>` is the type of the driver's device private data.
// - `struct serdev_device_driver` embeds a `struct device_driver`.
// - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`.
unsafe impl<T: Driver> driver::DriverLayout for Adapter<T> {
type DriverType = bindings::serdev_device_driver;
type DriverData<'bound> = PrivateData<'bound, T>;
const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver);
}
// SAFETY: A call to `unregister` for a given instance of `DriverType` is guaranteed to be valid if
// a preceding call to `register` has been successful.
unsafe impl<T: Driver> driver::RegistrationOps for Adapter<T> {
unsafe fn register(
sdrv: &Opaque<Self::DriverType>,
name: &'static CStr,
module: &'static ThisModule,
) -> Result {
let of_table = match T::OF_ID_TABLE {
Some(table) => table.as_ptr(),
None => core::ptr::null(),
};
let acpi_table = match T::ACPI_ID_TABLE {
Some(table) => table.as_ptr(),
None => core::ptr::null(),
};
// SAFETY: It's safe to set the fields of `struct serdev_device_driver` on initialization.
unsafe {
(*sdrv.get()).driver.name = name.as_char_ptr();
(*sdrv.get()).probe = Some(Self::probe_callback);
(*sdrv.get()).remove = Some(Self::remove_callback);
(*sdrv.get()).driver.of_match_table = of_table;
(*sdrv.get()).driver.acpi_match_table = acpi_table;
}
// SAFETY: `sdrv` is guaranteed to be a valid `DriverType`.
to_result(unsafe { bindings::__serdev_device_driver_register(sdrv.get(), module.as_ptr()) })
}
unsafe fn unregister(sdrv: &Opaque<Self::DriverType>) {
// SAFETY: `sdrv` is guaranteed to be a valid `DriverType`.
unsafe { bindings::serdev_device_driver_unregister(sdrv.get()) };
}
}
#[doc(hidden)]
#[pin_data(PinnedDrop)]
pub struct PrivateData<'bound, T: Driver> {
sdev: &'bound Device<device::Bound>,
#[pin]
driver: UnsafeCell<MaybeUninit<T::Data<'bound>>>,
open: UnsafeCell<bool>,
/// Whether `receive_buf_callback` is allowed to call `Driver::receive`.
///
/// If locked, the receive_buf_callback will be blocked on data reception.
/// This is the case while the driver is being probed or while [`PrivateData`] is being dropped.
/// This is necessary, because we need to open the serdev device before the driver has been
/// probed in order to allow it to be configured, which allows `receive_buf_callback` to be
/// called. Thus we need to block data until probe completes and the driver data becomes
/// initialized.
///
/// If unlocked and true, the receive_buf_callback will forward the data to
/// `Driver::receive`. This is the normal state of operation.
///
/// If unlocked and false, the receive_buf_callback will throw away the data.
/// This is only the case, if the serdev device is open and
/// - the driver returned an error in probe
/// or
/// - the driver data already has been dropped, because it was unbound.
#[pin]
active: Mutex<bool>,
}
#[pinned_drop]
impl<T: Driver> PinnedDrop for PrivateData<'_, T> {
fn drop(self: Pin<&mut Self>) {
let mut active = self.active.lock();
if *active {
// SAFETY:
// - We have exclusive access to `self.driver`.
// - `self.driver` is guaranteed to be initialized.
unsafe { (*self.driver.get()).assume_init_drop() };
*active = false;
}
drop(active);
// SAFETY: We have exclusive access to `self.open`.
if unsafe { *self.open.get() } {
// SAFETY: `self.sdev.as_raw()` is guaranteed to be a pointer to a valid
// `struct serdev_device`.
unsafe { bindings::serdev_device_close(self.sdev.as_raw()) };
}
}
}
impl<T: Driver> Adapter<T> {
const OPS: &'static bindings::serdev_device_ops = &bindings::serdev_device_ops {
receive_buf: if T::HAS_RECEIVE {
Some(Self::receive_buf_callback)
} else {
None
},
write_wakeup: Some(bindings::serdev_device_write_wakeup),
};
extern "C" fn probe_callback(sdev: *mut bindings::serdev_device) -> kernel::ffi::c_int {
// SAFETY: The serial device bus only ever calls the probe callback with a valid pointer to
// a `struct serdev_device`.
//
// INVARIANT: `sdev` is valid for the duration of `probe_callback()`.
let sdev = unsafe { &*sdev.cast::<Device<device::CoreInternal<'_>>>() };
// SAFETY: `sdev` matched data is of type `Self::IdInfo`.
let info = unsafe { <Self as driver::Adapter>::id_info(sdev.as_ref()) };
from_result(|| {
sdev.as_ref().set_drvdata(try_pin_init!(PrivateData::<T> {
sdev: &**sdev,
driver: MaybeUninit::<T::Data<'_>>::zeroed().into(),
open: false.into(),
active <- new_mutex!(false),
}))?;
// SAFETY: We just set drvdata to `PrivateData<'_, T>`.
let private_data = unsafe { sdev.as_ref().drvdata_borrow::<PrivateData<'_, T>>() };
let private_data = ScopeGuard::new_with_data(private_data, |_| {
// SAFETY: We just set drvdata to `PrivateData<'_, T>`.
drop(unsafe { sdev.as_ref().drvdata_obtain::<PrivateData<'_, T>>() });
});
let mut active = private_data.active.lock();
// SAFETY: `sdev.as_raw()` is guaranteed to be a valid pointer to `serdev_device`.
unsafe { bindings::serdev_device_set_client_ops(sdev.as_raw(), Self::OPS) };
// SAFETY: The serial device bus only ever calls the probe callback with a valid pointer
// to a `serdev_device`.
to_result(unsafe { bindings::serdev_device_open(sdev.as_raw()) })?;
// SAFETY: We have exclusive access to `private_data.open`.
unsafe { *private_data.open.get() = true };
let data = T::probe(sdev, info);
// SAFETY: We have exclusive access to `private_data.driver`.
let driver = unsafe { &mut *private_data.driver.get() };
// SAFETY:
// - `driver.as_mut_ptr()` is a valid pointer to uninitialized data.
// - `private_data.driver` is pinned.
let result = unsafe { pin_init::raw_try_init(driver.as_mut_ptr(), data) };
*active = result.is_ok();
drop(active);
result.map(|()| {
private_data.dismiss();
0
})
})
}
extern "C" fn remove_callback(sdev: *mut bindings::serdev_device) {
// SAFETY: The serial device bus only ever calls the remove callback with a valid pointer
// to a `struct serdev_device`.
//
// INVARIANT: `sdev` is valid for the duration of `remove_callback()`.
let sdev = unsafe { &*sdev.cast::<Device<device::CoreInternal<'_>>>() };
// SAFETY: `remove_callback` is only ever called after a successful call to
// `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
// and stored a `Pin<KBox<PrivateData<'_, T>>>`.
let private_data = unsafe { sdev.as_ref().drvdata_borrow::<PrivateData<'_, T>>() };
// SAFETY: No one has exclusive access to `private_data.driver`.
let data = unsafe { &*private_data.driver.get() };
// SAFETY:
// - `private_data.driver` is pinned.
// - `remove_callback` is only ever called after a successful call to `probe_callback`,
// hence it's guaranteed that `private_data.driver` was initialized.
let data_pinned = unsafe { Pin::new_unchecked(data.assume_init_ref()) };
T::unbind(sdev, data_pinned);
}
extern "C" fn receive_buf_callback(
sdev: *mut bindings::serdev_device,
buf: *const u8,
length: usize,
) -> usize {
// SAFETY: The serial device bus only ever calls the receive buf callback with a valid
// pointer to a `struct serdev_device`.
//
// INVARIANT: `sdev` is valid for the duration of `receive_buf_callback()`.
let sdev = unsafe { &*sdev.cast::<Device<device::BoundInternal>>() };
// SAFETY: `receive_buf_callback` is only ever called after a successful call to
// `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
// and stored a `Pin<KBox<PrivateData<'_, T>>>`.
let private_data = unsafe { sdev.as_ref().drvdata_borrow::<PrivateData<'_, T>>() };
let active = private_data.active.lock();
if !*active {
return length;
}
// SAFETY: No one has exclusive access to `private_data.driver`.
let data = unsafe { &*private_data.driver.get() };
// SAFETY:
// - `private_data.driver` is pinned.
// - `receive_buf_callback` is only ever called after a successful call to `probe_callback`,
// hence it's guaranteed that `private_data.driver` was initialized.
let data_pinned = unsafe { Pin::new_unchecked(data.assume_init_ref()) };
// SAFETY: `buf` is guaranteed to be non-null and has the size of `length`.
let buf = unsafe { core::slice::from_raw_parts(buf, length) };
T::receive(sdev, data_pinned, buf)
}
}
impl<T: Driver> driver::Adapter for Adapter<T> {
type IdInfo = T::IdInfo;
fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {
T::OF_ID_TABLE
}
fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>> {
T::ACPI_ID_TABLE
}
}
/// Declares a kernel module that exposes a single serial device bus device driver.
///
/// # Examples
///
/// ```ignore
/// kernel::module_serdev_device_driver! {
/// type: MyDriver,
/// name: "Module name",
/// authors: ["Author name"],
/// description: "Description",
/// license: "GPL v2",
/// }
/// ```
#[macro_export]
macro_rules! module_serdev_device_driver {
($($f:tt)*) => {
$crate::module_driver!(<T>, $crate::serdev::Adapter<T>, { $($f)* });
};
}
/// The serial device bus device driver trait.
///
/// Drivers must implement this trait in order to get a serial device bus device driver registered.
///
/// # Examples
///
///```
/// # use kernel::{
/// acpi,
/// bindings,
/// device::{
/// Bound,
/// Core, //
/// },
/// of,
/// serdev, //
/// };
///
/// struct MyDriver;
///
/// kernel::of_device_table!(
/// OF_TABLE,
/// <MyDriver as serdev::Driver>::IdInfo,
/// [
/// (of::DeviceId::new(c"test,device"), ())
/// ]
/// );
///
/// kernel::acpi_device_table!(
/// ACPI_TABLE,
/// <MyDriver as serdev::Driver>::IdInfo,
/// [
/// (acpi::DeviceId::new(c"LNUXBEEF"), ())
/// ]
/// );
///
/// #[vtable]
/// impl serdev::Driver for MyDriver {
/// type IdInfo = ();
/// type Data<'bound> = Self;
/// const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
/// const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
///
/// fn probe<'bound>(
/// sdev: &'bound serdev::Device<Core<'_>>,
/// _id_info: Option<&'bound Self::IdInfo>,
/// ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
/// sdev.set_baudrate(115200);
/// sdev.write_all(b"Hello\n", 0)?;
/// Ok(MyDriver)
/// }
/// }
///```
#[vtable]
pub trait Driver {
/// The type holding driver private data about each device id supported by the driver.
// TODO: Use associated_type_defaults once stabilized:
//
// ```
// type IdInfo: 'static = ();
// ```
type IdInfo: 'static;
/// The type of the driver's bus device private data.
type Data<'bound>: Send + Sync + 'bound;
/// The table of OF device ids supported by the driver.
const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;
/// The table of ACPI device ids supported by the driver.
const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = None;
/// Serial device bus device driver probe.
///
/// Called when a new serial device bus device is added or discovered.
/// Implementers should attempt to initialize the device here.
fn probe<'bound>(
sdev: &'bound Device<device::Core<'_>>,
id_info: Option<&'bound Self::IdInfo>,
) -> impl PinInit<Self::Data<'bound>, Error> + 'bound;
/// Serial device bus device driver unbind.
///
/// Called when a [`Device`] is unbound from its bound [`Driver`]. Implementing this callback
/// is optional.
///
/// This callback serves as a place for drivers to perform teardown operations that require a
/// `&Device<Core>` or `&Device<Bound>` reference. For instance.
///
/// Otherwise, release operations for driver resources should be performed in `Drop`.
fn unbind<'bound>(sdev: &'bound Device<device::Core<'_>>, this: Pin<&Self::Data<'bound>>) {
let _ = (sdev, this);
}
/// Serial device bus device data receive callback.
///
/// Called when data got received from device.
///
/// Returns the number of bytes accepted.
fn receive<'bound>(
sdev: &'bound Device<device::Bound>,
this: Pin<&Self::Data<'bound>>,
data: &[u8],
) -> usize {
let _ = (sdev, this, data);
build_error!(VTABLE_DEFAULT_ERROR)
}
}
/// The serial device bus device representation.
///
/// This structure represents the Rust abstraction for a C `struct serdev_device`. The
/// implementation abstracts the usage of an already existing C `struct serdev_device` within Rust
/// code that we get passed from the C side.
///
/// # Invariants
///
/// A [`Device`] instance represents a valid `struct serdev_device` created by the C portion of
/// the kernel.
#[repr(transparent)]
pub struct Device<Ctx: device::DeviceContext = device::Normal>(
Opaque<bindings::serdev_device>,
PhantomData<Ctx>,
);
impl<Ctx: device::DeviceContext> Device<Ctx> {
#[inline]
fn as_raw(&self) -> *mut bindings::serdev_device {
self.0.get()
}
}
impl Device<device::Bound> {
/// Set the baudrate in bits per second.
///
/// Common baudrates are 115200, 9600, 19200, 57600, 4800.
///
/// Use [`Device::write_flush`] before calling this if you have written data prior to this call.
#[inline]
pub fn set_baudrate(&self, speed: u32) -> Result<(), u32> {
// SAFETY: `self.as_raw()` is guaranteed to be a pointer to a valid `serdev_device`.
let ret = unsafe { bindings::serdev_device_set_baudrate(self.as_raw(), speed) };
if ret == speed {
Ok(())
} else {
Err(ret)
}
}
/// Set if flow control should be enabled.
///
/// Use [`Device::write_flush`] before calling this if you have written data prior to this call.
#[inline]
pub fn set_flow_control(&self, enable: bool) {
// SAFETY: `self.as_raw()` is guaranteed to be a pointer to a valid `serdev_device`.
unsafe { bindings::serdev_device_set_flow_control(self.as_raw(), enable) };
}
/// Set parity to use.
///
/// Use [`Device::write_flush`] before calling this if you have written data prior to this call.
#[inline]
pub fn set_parity(&self, parity: Parity) -> Result {
// SAFETY: `self.as_raw()` is guaranteed to be a pointer to a valid `serdev_device`.
to_result(unsafe { bindings::serdev_device_set_parity(self.as_raw(), parity as u32) })
}
/// Write data to the serial device until the controller has accepted all the data or has
/// been interrupted by a timeout or signal.
///
/// Note that any accepted data has only been buffered by the controller. Use
/// [`Device::wait_until_sent`] to make sure the controller write buffer has actually been
/// emptied.
///
/// Use a timeout of 0 to wait indefinitely.
///
/// Returns the number of bytes written (less than `data.len()` if interrupted).
/// [`kernel::error::code::ETIMEDOUT`] or [`kernel::error::code::ERESTARTSYS`] if interrupted
/// before any bytes were written. [`kernel::error::code::EINVAL`] if `data.len() > i32::MAX`.
#[inline]
pub fn write_all(&self, data: &[u8], timeout: Jiffies) -> Result<usize> {
if data.len() > i32::MAX as usize {
return Err(EINVAL);
}
// SAFETY:
// - `self.as_raw()` is guaranteed to be a pointer to a valid `serdev_device`.
// - `data.as_ptr()` is guaranteed to be a valid array pointer with the size of
// `data.len()`.
let ret = unsafe {
bindings::serdev_device_write(
self.as_raw(),
data.as_ptr(),
data.len(),
isize::try_from(timeout).unwrap_or_default(),
)
};
// CAST: negative return values are guaranteed to be between `-MAX_ERRNO` and `-1`,
// which always fit into a `i32`.
to_result(ret as i32).map(|()| ret.unsigned_abs())
}
/// Write data to the serial device.
///
/// If you want to write until the controller has accepted all the data, use
/// [`Device::write_all`].
///
/// Note that any accepted data has only been buffered by the controller. Use
/// [`Device::wait_until_sent`] to make sure the controller write buffer has actually been
/// emptied.
///
/// Returns the number of bytes written (less than `data.len()` if not enough room in the
/// write buffer).
#[inline]
pub fn write(&self, data: &[u8]) -> Result<u32> {
if data.len() > i32::MAX as usize {
return Err(EINVAL);
}
// SAFETY:
// - `self.as_raw()` is guaranteed to be a pointer to a valid `serdev_device`.
// - `data.as_ptr()` is guaranteed to be a valid array pointer with the size of
// `data.len()`.
let ret =
unsafe { bindings::serdev_device_write_buf(self.as_raw(), data.as_ptr(), data.len()) };
to_result(ret as i32).map(|()| ret.unsigned_abs())
}
/// Send data to the serial device immediately.
///
/// Note that this doesn't guarantee that the data has been transmitted.
/// Use [`Device::wait_until_sent`] for this purpose.
#[inline]
pub fn write_flush(&self) {
// SAFETY: `self.as_raw()` is guaranteed to be a pointer to a valid `serdev_device`.
unsafe { bindings::serdev_device_write_flush(self.as_raw()) };
}
/// Wait for the data to be sent.
///
/// After this function, the write buffer of the controller should be empty or the timeout
/// elapsed.
///
/// Use a timeout of 0 to wait indefinitely.
#[inline]
pub fn wait_until_sent(&self, timeout: Jiffies) {
// SAFETY: `self.as_raw()` is guaranteed to be a pointer to a valid `serdev_device`.
unsafe {
bindings::serdev_device_wait_until_sent(
self.as_raw(),
isize::try_from(timeout).unwrap_or_default(),
)
};
}
}
// SAFETY: `serdev::Device` is a transparent wrapper of `struct serdev_device`.
// The offset is guaranteed to point to a valid device field inside `serdev::Device`.
unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx> {
const OFFSET: usize = offset_of!(bindings::serdev_device, dev);
}
// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
// argument.
kernel::impl_device_context_deref!(unsafe { Device });
kernel::impl_device_context_into_aref!(Device);
// SAFETY: Instances of `Device` are always reference-counted.
unsafe impl AlwaysRefCounted for Device {
fn inc_ref(&self) {
self.as_ref().inc_ref();
}
unsafe fn dec_ref(obj: NonNull<Self>) {
// SAFETY: The safety requirements guarantee that the refcount is non-zero.
unsafe { bindings::serdev_device_put(obj.cast().as_ptr()) }
}
}
impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
fn as_ref(&self) -> &device::Device<Ctx> {
// SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
// `struct serdev_device`.
let dev = unsafe { &raw mut (*self.as_raw()).dev };
// SAFETY: `dev` points to a valid `struct device`.
unsafe { device::Device::from_raw(dev) }
}
}
// SAFETY: A `Device` is always reference-counted and can be released from any thread.
unsafe impl Send for Device {}
// SAFETY: `Device` can be shared among threads because all methods of `Device`
// (i.e. `Device<Normal>) are thread safe.
unsafe impl Sync for Device {}
// SAFETY: Same as `Device<Normal>` -- the underlying `struct serdev_device` is the same;
// `Bound` is a zero-sized type-state marker that does not affect thread safety.
unsafe impl Sync for Device<device::Bound> {}