Skip to content

Commit

Permalink
macos: cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinmehall committed Dec 4, 2023
1 parent 2b64b70 commit 5dfd387
Show file tree
Hide file tree
Showing 6 changed files with 62 additions and 46 deletions.
1 change: 1 addition & 0 deletions src/enumeration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ pub enum Speed {
}

impl Speed {
#[allow(dead_code)] // not used on all platforms
pub(crate) fn from_str(s: &str) -> Option<Self> {
match s {
"low" | "1.5" => Some(Speed::Low),
Expand Down
2 changes: 1 addition & 1 deletion src/platform/macos_iokit/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub(crate) struct MacDevice {
impl MacDevice {
pub(crate) fn from_device_info(d: &DeviceInfo) -> Result<Arc<MacDevice>, Error> {
let service = service_by_location_id(d.location_id)?;
let mut device = IoKitDevice::new(service)?;
let device = IoKitDevice::new(service)?;
let _event_registration = add_event_source(device.create_async_event_source()?);

Ok(Arc::new(MacDevice {
Expand Down
2 changes: 1 addition & 1 deletion src/platform/macos_iokit/iokit.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! Utilities for using IOKit APIs.
//!
//!
//! Based on Kate Temkin's [usrs](https://github.com/ktemkin/usrs)
//! licensed under MIT OR Apache-2.0.
Expand Down
56 changes: 26 additions & 30 deletions src/platform/macos_iokit/iokit_usb.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
/// Wrappers for IOKit USB device and interface
///
/// Based on Kate Temkin's [usrs](https://github.com/ktemkin/usrs)
/// licensed under MIT OR Apache-2.0.
//! Wrappers for IOKit USB device and interface
//!
//! Based on Kate Temkin's [usrs](https://github.com/ktemkin/usrs)
//! licensed under MIT OR Apache-2.0.
use std::{collections::BTreeMap, io::ErrorKind, time::Duration};

use core_foundation::{base::TCFType, runloop::CFRunLoopSource};
Expand Down Expand Up @@ -114,14 +115,6 @@ impl IoKitDevice {
}
}

pub(crate) fn open(&mut self) -> Result<(), Error> {
unsafe { check_iokit_return(call_iokit_function!(self.raw, USBDeviceOpen())) }
}

pub(crate) fn close(&mut self) -> Result<(), Error> {
unsafe { check_iokit_return(call_iokit_function!(self.raw, USBDeviceClose())) }
}

pub(crate) fn create_async_event_source(&self) -> Result<CFRunLoopSource, Error> {
unsafe {
let mut raw_source: CFRunLoopSourceRef = std::ptr::null_mut();
Expand Down Expand Up @@ -180,6 +173,16 @@ pub(crate) struct EndpointInfo {
pub(crate) bytes_per_interval: u16,
}

impl EndpointInfo {
pub(crate) fn address(&self) -> u8 {
if self.direction == 0 {
self.number
} else {
self.number | 0x80
}
}
}

/// Wrapper around an IOKit UsbInterface
pub(crate) struct IoKitInterface {
pub(crate) raw: *mut *mut iokit::UsbInterface,
Expand Down Expand Up @@ -284,26 +287,19 @@ impl IoKitInterface {
)
))?;

let address = if direction == 0 {
number
} else {
number | 0x80
let endpoint = EndpointInfo {
pipe_ref,
direction,
number,
transfer_type,
max_packet_size,
interval,
max_burst,
mult,
bytes_per_interval,
};

endpoints.insert(
address,
EndpointInfo {
pipe_ref,
direction,
number,
transfer_type,
max_packet_size,
interval,
max_burst,
mult,
bytes_per_interval,
},
);
endpoints.insert(endpoint.address(), endpoint);
}
Ok(endpoints)
}
Expand Down
41 changes: 30 additions & 11 deletions src/platform/macos_iokit/transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ use std::{
sync::Arc,
};

use io_kit_sys::ret::{kIOReturnNoDevice, kIOReturnSuccess, kIOReturnAborted, IOReturn };
use io_kit_sys::ret::{
kIOReturnAborted, kIOReturnNoDevice, kIOReturnSuccess, kIOReturnUnderrun, IOReturn,
};
use log::{error, info};

use crate::{
Expand Down Expand Up @@ -36,6 +38,7 @@ extern "C" fn transfer_callback(refcon: *mut c_void, result: IOReturn, len: *mut
}

pub struct TransferData {
endpoint_addr: u8,
pipe_ref: u8,
buf: *mut u8,
capacity: usize,
Expand Down Expand Up @@ -70,6 +73,7 @@ impl TransferData {
endpoint: &EndpointInfo,
) -> TransferData {
TransferData {
endpoint_addr: endpoint.address(),
pipe_ref: endpoint.pipe_ref,
buf: null_mut(),
capacity: 0,
Expand All @@ -85,6 +89,7 @@ impl TransferData {

pub(super) fn new_control(device: Arc<super::Device>) -> TransferData {
TransferData {
endpoint_addr: 0,
pipe_ref: 0,
buf: null_mut(),
capacity: 0,
Expand Down Expand Up @@ -122,7 +127,10 @@ impl TransferData {
/// SAFETY: requires that the transfer is not active, but is fully prepared (as it is when submitting the transfer fails)
unsafe fn check_submit_result(&mut self, res: IOReturn) {
if res != kIOReturnSuccess {
error!("Failed to submit transfer: {res:x}");
error!(
"Failed to submit transfer on endpoint {ep}: {res:x}",
ep = self.endpoint_addr
);
let callback_data = {
let inner = &mut *self.inner;
inner.status = res;
Expand All @@ -141,7 +149,7 @@ impl TransferData {
#[allow(non_upper_case_globals)]
#[deny(unreachable_patterns)]
let status = match inner.status {
kIOReturnSuccess => Ok(()),
kIOReturnSuccess | kIOReturnUnderrun => Ok(()),
kIOReturnNoDevice => Err(TransferError::Disconnected),
kIOReturnAborted => Err(TransferError::Cancelled),
_ => Err(TransferError::Unknown),
Expand All @@ -156,19 +164,23 @@ unsafe impl Send for TransferData {}
impl PlatformTransfer for TransferData {
fn cancel(&self) {
if let Some(intf) = self.interface.as_ref() {
let r = unsafe {call_iokit_function!(intf.interface.raw, AbortPipe(self.pipe_ref)) };
info!("Cancelled all transfers on endpoint {ep}. status={r:x}", ep=self.pipe_ref);
let r = unsafe { call_iokit_function!(intf.interface.raw, AbortPipe(self.pipe_ref)) };
info!(
"Cancelled all transfers on endpoint {ep:02x}. status={r:x}",
ep = self.endpoint_addr
);
} else {
assert!(self.pipe_ref == 0);
let r = unsafe { call_iokit_function!(self.device.device.raw, USBDeviceAbortPipeZero()) };
let r =
unsafe { call_iokit_function!(self.device.device.raw, USBDeviceAbortPipeZero()) };
info!("Cancelled all transfers on control pipe. status={r:x}");
}
}
}

impl PlatformSubmit<Vec<u8>> for TransferData {
unsafe fn submit(&mut self, data: Vec<u8>, callback_data: *mut std::ffi::c_void) {
//assert!(ep & 0x80 == 0);
assert!(self.endpoint_addr & 0x80 == 0);
let len = data.len();
self.fill(data, callback_data);

Expand All @@ -183,7 +195,11 @@ impl PlatformSubmit<Vec<u8>> for TransferData {
self.inner as *mut c_void
)
);
info!("Submitted OUT transfer {inner:?}", inner = self.inner);
info!(
"Submitted OUT transfer {inner:?} on endpoint {ep:02x}",
inner = self.inner,
ep = self.endpoint_addr
);
self.check_submit_result(res);
}

Expand All @@ -198,8 +214,7 @@ impl PlatformSubmit<Vec<u8>> for TransferData {

impl PlatformSubmit<RequestBuffer> for TransferData {
unsafe fn submit(&mut self, data: RequestBuffer, callback_data: *mut std::ffi::c_void) {
//assert!(ep & 0x80 == 0x80);
//assert!(ty == USBDEVFS_URB_TYPE_BULK || ty == USBDEVFS_URB_TYPE_INTERRUPT);
assert!(self.endpoint_addr & 0x80 == 0x80);

let (data, len) = data.into_vec();
self.fill(data, callback_data);
Expand All @@ -215,7 +230,11 @@ impl PlatformSubmit<RequestBuffer> for TransferData {
self.inner as *mut c_void
)
);
info!("Submitted IN transfer {inner:?}", inner = self.inner);
info!(
"Submitted IN transfer {inner:?} on endpoint {ep:02x}",
inner = self.inner,
ep = self.endpoint_addr
);

self.check_submit_result(res);
}
Expand Down
6 changes: 3 additions & 3 deletions src/transfer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ mod buffer;
pub use buffer::{RequestBuffer, ResponseBuffer};

mod control;
pub(crate) use control::SETUP_PACKET_SIZE;
#[allow(unused)] pub(crate) use control::SETUP_PACKET_SIZE;
pub use control::{ControlIn, ControlOut, ControlType, Direction, Recipient};

mod internal;
Expand Down Expand Up @@ -125,7 +125,7 @@ impl TryFrom<Completion<ResponseBuffer>> for ResponseBuffer {
}

/// [`Future`] used to await the completion of a transfer.
///
///
/// Use the methods on [`Interface`][super::Interface] to
/// submit an individual transfer and obtain a `TransferFuture`.
///
Expand All @@ -135,7 +135,7 @@ impl TryFrom<Completion<ResponseBuffer>> for ResponseBuffer {
/// in `select!{}`, When racing a `TransferFuture` with a timeout
/// you cannot tell whether data may have been partially transferred on timeout.
/// Use the [`Queue`] interface if these matter for your application.
///
///
/// [cancel-safe]: https://docs.rs/tokio/latest/tokio/macro.select.html#cancellation-safety
pub struct TransferFuture<D: TransferRequest> {
transfer: TransferHandle<platform::TransferData>,
Expand Down

0 comments on commit 5dfd387

Please sign in to comment.