Debian Codegraph @

src/platform/macos_iokit/device.rs

raw symbols SCIP
1 use std::{
2 collections::BTreeMap,
3 ffi::c_void,
4 io::ErrorKind,
5 sync::{
6 atomic::{AtomicU8, AtomicUsize, Ordering},
7 Arc, Mutex,
8 },
9 time::Duration,
10 };
11
12 use log::{debug, error};
13
14 use crate::{
15 platform::macos_iokit::events::add_event_source,
16 transfer::{Control, Direction, EndpointType, TransferError, TransferHandle},
17 DeviceInfo, Error,
18 };
19
20 use super::{
21 enumeration::service_by_registry_id,
22 events::EventRegistration,
23 iokit::{call_iokit_function, check_iokit_return},
24 iokit_c::IOUSBDevRequestTO,
25 iokit_usb::{EndpointInfo, IoKitDevice, IoKitInterface},
26 status_to_transfer_result,
27 };
28
29 pub(crate) struct MacDevice {
30 _event_registration: EventRegistration,
31 pub(super) device: IoKitDevice,
32 active_config: AtomicU8,
33 is_open_exclusive: Mutex<bool>,
34 claimed_interfaces: AtomicUsize,
35 }
36
37 // `get_configuration` does IO, so avoid it in the common case that:
38 // * the device has a single configuration
39 // * the device has at least one interface, indicating that it is configured
40 fn guess_active_config(dev: &IoKitDevice) -> Option<u8> {
41 if dev.get_number_of_configurations().unwrap_or(0) != 1 {
42 return None;
43 }
44 let mut intf = dev.create_interface_iterator().ok()?;
45 intf.next()?;
46 let config_desc = dev.get_configuration_descriptor(0).ok()?;
47 config_desc.get(5).copied() // get bConfigurationValue from descriptor
48 }
49
50 impl MacDevice {
51 pub(crate) fn from_device_info(d: &DeviceInfo) -> Result<Arc<MacDevice>, Error> {
52 log::debug!("Opening device from registry id {}", d.registry_id);
53 let service = service_by_registry_id(d.registry_id)?;
54 let device = IoKitDevice::new(service)?;
55 let _event_registration = add_event_source(device.create_async_event_source()?);
56
57 let opened = match unsafe { call_iokit_function!(device.raw, USBDeviceOpen()) } {
58 io_kit_sys::ret::kIOReturnSuccess => true,
59 err => {
60 // Most methods don't require USBDeviceOpen() so this can be ignored
61 // to allow different processes to open different interfaces.
62 log::debug!("Could not open device for exclusive access: {err:x}");
63 false
64 }
65 };
66
67 let active_config = if let Some(active_config) = guess_active_config(&device) {
68 log::debug!("Active config from single descriptor is {}", active_config);
69 active_config
70 } else {
71 let res = device.get_configuration();
72 log::debug!("Active config from request is {:?}", res);
73 res.unwrap_or(0)
74 };
75
76 Ok(Arc::new(MacDevice {
77 _event_registration,
78 device,
79 active_config: AtomicU8::new(active_config),
80 is_open_exclusive: Mutex::new(opened),
81 claimed_interfaces: AtomicUsize::new(0),
82 }))
83 }
84
85 pub(crate) fn active_configuration_value(&self) -> u8 {
86 self.active_config.load(Ordering::SeqCst)
87 }
88
89 pub(crate) fn configuration_descriptors(&self) -> impl Iterator<Item = &[u8]> {
90 let num_configs = self.device.get_number_of_configurations().unwrap_or(0);
91 (0..num_configs).flat_map(|i| self.device.get_configuration_descriptor(i).ok())
92 }
93
94 fn require_open_exclusive(&self) -> Result<(), Error> {
95 let mut state = self.is_open_exclusive.lock().unwrap();
96 if *state == false {
97 unsafe { check_iokit_return(call_iokit_function!(self.device.raw, USBDeviceOpen()))? };
98 *state = true;
99 }
100
101 if self.claimed_interfaces.load(Ordering::Relaxed) != 0 {
102 return Err(Error::new(
103 ErrorKind::Other,
104 "cannot perform this operation while interfaces are claimed",
105 ));
106 }
107
108 Ok(())
109 }
110
111 pub(crate) fn set_configuration(&self, configuration: u8) -> Result<(), Error> {
112 self.require_open_exclusive()?;
113 unsafe {
114 check_iokit_return(call_iokit_function!(
115 self.device.raw,
116 SetConfiguration(configuration)
117 ))?
118 }
119 log::debug!("Set configuration {configuration}");
120 self.active_config.store(configuration, Ordering::SeqCst);
121 Ok(())
122 }
123
124 pub(crate) fn reset(&self) -> Result<(), Error> {
125 self.require_open_exclusive()?;
126 unsafe {
127 check_iokit_return(call_iokit_function!(
128 self.device.raw,
129 USBDeviceReEnumerate(0)
130 ))
131 }
132 }
133
134 /// SAFETY: `data` must be valid for `len` bytes to read or write, depending on `Direction`
135 unsafe fn control_blocking(
136 &self,
137 direction: Direction,
138 control: Control,
139 data: *mut u8,
140 len: usize,
141 timeout: Duration,
142 ) -> Result<usize, TransferError> {
143 let timeout_ms = timeout.as_millis().min(u32::MAX as u128) as u32;
144 let mut req = IOUSBDevRequestTO {
145 bmRequestType: control.request_type(direction),
146 bRequest: control.request,
147 wValue: control.value,
148 wIndex: control.index,
149 wLength: len.try_into().expect("length must fit in u16"),
150 pData: data.cast::<c_void>(),
151 wLenDone: 0,
152 noDataTimeout: timeout_ms,
153 completionTimeout: timeout_ms,
154 };
155
156 let r = unsafe { call_iokit_function!(self.device.raw, DeviceRequestTO(&mut req)) };
157
158 status_to_transfer_result(r).map(|()| req.wLenDone as usize)
159 }
160
161 pub fn control_in_blocking(
162 &self,
163 control: Control,
164 data: &mut [u8],
165 timeout: Duration,
166 ) -> Result<usize, TransferError> {
167 unsafe {
168 self.control_blocking(
169 Direction::In,
170 control,
171 data.as_mut_ptr(),
172 data.len(),
173 timeout,
174 )
175 }
176 }
177
178 pub fn control_out_blocking(
179 &self,
180 control: Control,
181 data: &[u8],
182 timeout: Duration,
183 ) -> Result<usize, TransferError> {
184 unsafe {
185 self.control_blocking(
186 Direction::Out,
187 control,
188 data.as_ptr() as *mut u8,
189 data.len(),
190 timeout,
191 )
192 }
193 }
194
195 pub(crate) fn make_control_transfer(self: &Arc<Self>) -> TransferHandle<super::TransferData> {
196 TransferHandle::new(super::TransferData::new_control(self.clone()))
197 }
198
199 pub(crate) fn claim_interface(
200 self: &Arc<Self>,
201 interface_number: u8,
202 ) -> Result<Arc<MacInterface>, Error> {
203 let intf_service = self
204 .device
205 .create_interface_iterator()?
206 .nth(interface_number as usize)
207 .ok_or(Error::new(ErrorKind::NotFound, "interface not found"))?;
208
209 let mut interface = IoKitInterface::new(intf_service)?;
210 let _event_registration = add_event_source(interface.create_async_event_source()?);
211
212 interface.open()?;
213
214 let endpoints = interface.endpoints()?;
215 debug!("Found endpoints: {endpoints:?}");
216
217 self.claimed_interfaces.fetch_add(1, Ordering::Acquire);
218
219 Ok(Arc::new(MacInterface {
220 device: self.clone(),
221 interface_number,
222 interface,
223 endpoints: Mutex::new(endpoints),
224 _event_registration,
225 }))
226 }
227
228 pub(crate) fn detach_and_claim_interface(
229 self: &Arc<Self>,
230 interface: u8,
231 ) -> Result<Arc<MacInterface>, Error> {
232 self.claim_interface(interface)
233 }
234 }
235
236 impl Drop for MacDevice {
237 fn drop(&mut self) {
238 if *self.is_open_exclusive.get_mut().unwrap() {
239 match unsafe { call_iokit_function!(self.device.raw, USBDeviceClose()) } {
240 io_kit_sys::ret::kIOReturnSuccess => {}
241 err => log::debug!("Failed to close device: {err:x}"),
242 };
243 }
244 }
245 }
246
247 pub(crate) struct MacInterface {
248 pub(crate) interface_number: u8,
249 _event_registration: EventRegistration,
250 pub(crate) interface: IoKitInterface,
251 pub(crate) device: Arc<MacDevice>,
252
253 /// Map from address to a structure that contains the `pipe_ref` used by iokit
254 pub(crate) endpoints: Mutex<BTreeMap<u8, EndpointInfo>>,
255 }
256
257 impl MacInterface {
258 pub(crate) fn make_transfer(
259 self: &Arc<Self>,
260 endpoint: u8,
261 ep_type: EndpointType,
262 ) -> TransferHandle<super::TransferData> {
263 if ep_type == EndpointType::Control {
264 assert!(endpoint == 0);
265 TransferHandle::new(super::TransferData::new_control(self.device.clone()))
266 } else {
267 let endpoints = self.endpoints.lock().unwrap();
268
269 // This function can't fail, so if the endpoint is not found, use an invalid
270 // pipe_ref that will fail when submitting the transfer.
271 let pipe_ref = endpoints.get(&endpoint).map(|e| e.pipe_ref).unwrap_or(0);
272
273 TransferHandle::new(super::TransferData::new(
274 self.device.clone(),
275 self.clone(),
276 endpoint,
277 pipe_ref,
278 ))
279 }
280 }
281
282 pub fn control_in_blocking(
283 &self,
284 control: Control,
285 data: &mut [u8],
286 timeout: Duration,
287 ) -> Result<usize, TransferError> {
288 self.device.control_in_blocking(control, data, timeout)
289 }
290
291 pub fn control_out_blocking(
292 &self,
293 control: Control,
294 data: &[u8],
295 timeout: Duration,
296 ) -> Result<usize, TransferError> {
297 self.device.control_out_blocking(control, data, timeout)
298 }
299
300 pub fn set_alt_setting(&self, alt_setting: u8) -> Result<(), Error> {
301 debug!(
302 "Set interface {} alt setting to {alt_setting}",
303 self.interface_number
304 );
305
306 let mut endpoints = self.endpoints.lock().unwrap();
307
308 unsafe {
309 check_iokit_return(call_iokit_function!(
310 self.interface.raw,
311 SetAlternateInterface(alt_setting)
312 ))?;
313 }
314
315 *endpoints = self.interface.endpoints()?;
316 debug!("Found endpoints: {endpoints:?}");
317
318 Ok(())
319 }
320
321 pub fn clear_halt(&self, endpoint: u8) -> Result<(), Error> {
322 debug!("Clear halt, endpoint {endpoint:02x}");
323
324 let pipe_ref = {
325 let endpoints = self.endpoints.lock().unwrap();
326 let ep = endpoints
327 .get(&endpoint)
328 .ok_or_else(|| Error::new(ErrorKind::NotFound, "Endpoint not found"))?;
329 ep.pipe_ref
330 };
331
332 unsafe {
333 check_iokit_return(call_iokit_function!(
334 self.interface.raw,
335 ClearPipeStallBothEnds(pipe_ref)
336 ))
337 }
338 }
339 }
340
341 impl Drop for MacInterface {
342 fn drop(&mut self) {
343 if let Err(err) = self.interface.close() {
344 error!("Failed to close interface: {err}")
345 }
346 self.device
347 .claimed_interfaces
348 .fetch_sub(1, Ordering::Release);
349 }
350 }