Debian Codegraph @

src/platform/macos_iokit/transfer.rs

raw symbols SCIP
1 use std::{
2 ffi::c_void,
3 mem::{self, ManuallyDrop},
4 ptr::null_mut,
5 sync::Arc,
6 };
7
8 use io_kit_sys::ret::{kIOReturnSuccess, IOReturn};
9 use log::{debug, error};
10
11 use crate::{
12 platform::macos_iokit::iokit_c::IOUSBDevRequest,
13 transfer::{
14 notify_completion, Completion, ControlIn, ControlOut, PlatformSubmit, PlatformTransfer,
15 RequestBuffer, ResponseBuffer, TransferError,
16 },
17 };
18
19 use super::{iokit::call_iokit_function, status_to_transfer_result};
20
21 extern "C" fn transfer_callback(refcon: *mut c_void, result: IOReturn, len: *mut c_void) {
22 debug!(
23 "Completion callback for transfer {refcon:?}, status={result:x}, len={len}",
24 len = len as usize
25 );
26
27 unsafe {
28 let callback_data = {
29 let inner = &mut *(refcon as *mut TransferDataInner);
30 inner.actual_len = len as usize;
31 inner.status = result;
32 inner.callback_data
33 };
34 notify_completion::<super::TransferData>(callback_data)
35 }
36 }
37
38 pub struct TransferData {
39 endpoint_addr: u8,
40 pipe_ref: u8,
41 buf: *mut u8,
42 capacity: usize,
43 inner: *mut TransferDataInner,
44 device: Arc<super::Device>,
45 interface: Option<Arc<super::Interface>>,
46 }
47
48 impl Drop for TransferData {
49 fn drop(&mut self) {
50 if !self.buf.is_null() {
51 unsafe { drop(Vec::from_raw_parts(self.buf, 0, self.capacity)) }
52 }
53 unsafe { drop(Box::from_raw(self.inner)) }
54 }
55 }
56
57 /// Bring the data accessed on the transfer callback out-of-line
58 /// so that we can have a reference to it while the callback may
59 /// write to other fields concurrently. This could be included
60 /// in `TransferData`` with the proposed [`UnsafePinned`](https://github.com/rust-lang/rfcs/pull/3467)
61 pub struct TransferDataInner {
62 actual_len: usize,
63 callback_data: *mut c_void,
64 status: IOReturn,
65 }
66
67 impl TransferData {
68 pub(super) fn new(
69 device: Arc<super::Device>,
70 interface: Arc<super::Interface>,
71 endpoint_addr: u8,
72 pipe_ref: u8,
73 ) -> TransferData {
74 TransferData {
75 endpoint_addr,
76 pipe_ref,
77 buf: null_mut(),
78 capacity: 0,
79 inner: Box::into_raw(Box::new(TransferDataInner {
80 actual_len: 0,
81 callback_data: null_mut(),
82 status: kIOReturnSuccess,
83 })),
84 device,
85 interface: Some(interface),
86 }
87 }
88
89 pub(super) fn new_control(device: Arc<super::Device>) -> TransferData {
90 TransferData {
91 endpoint_addr: 0,
92 pipe_ref: 0,
93 buf: null_mut(),
94 capacity: 0,
95 inner: Box::into_raw(Box::new(TransferDataInner {
96 actual_len: 0,
97 callback_data: null_mut(),
98 status: kIOReturnSuccess,
99 })),
100 device,
101 interface: None,
102 }
103 }
104
105 /// SAFETY: Requires that the transfer is not active
106 unsafe fn fill(&mut self, buf: Vec<u8>, callback_data: *mut c_void) {
107 let mut buf = ManuallyDrop::new(buf);
108 self.buf = buf.as_mut_ptr();
109 self.capacity = buf.capacity();
110
111 let inner = &mut *self.inner;
112 inner.actual_len = 0;
113 inner.status = kIOReturnSuccess;
114 inner.callback_data = callback_data;
115 }
116
117 /// SAFETY: requires that the transfer has completed and `length` bytes are initialized
118 unsafe fn take_buf(&mut self, length: usize) -> Vec<u8> {
119 assert!(!self.buf.is_null());
120 let ptr = mem::replace(&mut self.buf, null_mut());
121 let capacity = mem::replace(&mut self.capacity, 0);
122 assert!(length <= capacity);
123 Vec::from_raw_parts(ptr, length, capacity)
124 }
125
126 /// SAFETY: requires that the transfer is not active, but is fully prepared (as it is when submitting the transfer fails)
127 unsafe fn check_submit_result(&mut self, res: IOReturn) {
128 if res != kIOReturnSuccess {
129 error!(
130 "Failed to submit transfer on endpoint {ep}: {res:x}",
131 ep = self.endpoint_addr
132 );
133 let callback_data = {
134 let inner = &mut *self.inner;
135 inner.status = res;
136 inner.callback_data
137 };
138
139 // Complete the transfer in the place of the callback
140 notify_completion::<super::TransferData>(callback_data)
141 }
142 }
143
144 /// SAFETY: requires that the transfer is in a completed state
145 unsafe fn take_status(&mut self) -> (Result<(), TransferError>, usize) {
146 let inner = unsafe { &*self.inner };
147
148 (status_to_transfer_result(inner.status), inner.actual_len)
149 }
150 }
151
152 unsafe impl Send for TransferData {}
153
154 impl PlatformTransfer for TransferData {
155 fn cancel(&self) {
156 if let Some(intf) = self.interface.as_ref() {
157 let r = unsafe { call_iokit_function!(intf.interface.raw, AbortPipe(self.pipe_ref)) };
158 debug!(
159 "Cancelled all transfers on endpoint {ep:02x}. status={r:x}",
160 ep = self.endpoint_addr
161 );
162 } else {
163 assert!(self.pipe_ref == 0);
164 let r =
165 unsafe { call_iokit_function!(self.device.device.raw, USBDeviceAbortPipeZero()) };
166 debug!("Cancelled all transfers on control pipe. status={r:x}");
167 }
168 }
169 }
170
171 impl PlatformSubmit<Vec<u8>> for TransferData {
172 unsafe fn submit(&mut self, data: Vec<u8>, callback_data: *mut std::ffi::c_void) {
173 assert!(self.endpoint_addr & 0x80 == 0);
174 let len = data.len();
175 self.fill(data, callback_data);
176
177 // SAFETY: we just properly filled the buffer and it is not already pending
178 let res = call_iokit_function!(
179 self.interface.as_ref().unwrap().interface.raw,
180 WritePipeAsync(
181 self.pipe_ref,
182 self.buf as *mut c_void,
183 u32::try_from(len).expect("request too large"),
184 transfer_callback,
185 self.inner as *mut c_void
186 )
187 );
188 debug!(
189 "Submitted OUT transfer {inner:?} on endpoint {ep:02x}",
190 inner = self.inner,
191 ep = self.endpoint_addr
192 );
193 self.check_submit_result(res);
194 }
195
196 unsafe fn take_completed(&mut self) -> crate::transfer::Completion<ResponseBuffer> {
197 let (status, actual_len) = self.take_status();
198
199 // SAFETY: self is completed (precondition) and `actual_length` bytes were initialized.
200 let data = ResponseBuffer::from_vec(unsafe { self.take_buf(0) }, actual_len);
201 Completion { data, status }
202 }
203 }
204
205 impl PlatformSubmit<RequestBuffer> for TransferData {
206 unsafe fn submit(&mut self, data: RequestBuffer, callback_data: *mut std::ffi::c_void) {
207 assert!(self.endpoint_addr & 0x80 == 0x80);
208
209 let (data, len) = data.into_vec();
210 self.fill(data, callback_data);
211
212 // SAFETY: we just properly filled the buffer and it is not already pending
213 let res = call_iokit_function!(
214 self.interface.as_ref().unwrap().interface.raw,
215 ReadPipeAsync(
216 self.pipe_ref,
217 self.buf as *mut c_void,
218 u32::try_from(len).expect("request too large"),
219 transfer_callback,
220 self.inner as *mut c_void
221 )
222 );
223 debug!(
224 "Submitted IN transfer {inner:?} on endpoint {ep:02x}",
225 inner = self.inner,
226 ep = self.endpoint_addr
227 );
228
229 self.check_submit_result(res);
230 }
231
232 unsafe fn take_completed(&mut self) -> crate::transfer::Completion<Vec<u8>> {
233 let (status, actual_len) = self.take_status();
234
235 // SAFETY: self is completed (precondition) and `actual_length` bytes were initialized.
236 let data = unsafe { self.take_buf(actual_len) };
237 Completion { data, status }
238 }
239 }
240
241 impl PlatformSubmit<ControlIn> for TransferData {
242 unsafe fn submit(&mut self, data: ControlIn, callback_data: *mut std::ffi::c_void) {
243 assert!(self.pipe_ref == 0);
244
245 let buf = Vec::with_capacity(data.length as usize);
246 self.fill(buf, callback_data);
247
248 let mut req = IOUSBDevRequest {
249 bmRequestType: data.request_type(),
250 bRequest: data.request,
251 wValue: data.value,
252 wIndex: data.index,
253 wLength: data.length,
254 pData: self.buf as *mut c_void,
255 wLenDone: 0,
256 };
257
258 // SAFETY: we just properly filled the buffer and it is not already pending
259 let res = call_iokit_function!(
260 self.device.device.raw,
261 DeviceRequestAsync(&mut req, transfer_callback, self.inner as *mut c_void)
262 );
263 debug!(
264 "Submitted Control IN transfer {inner:?}",
265 inner = self.inner
266 );
267 self.check_submit_result(res);
268 }
269
270 unsafe fn take_completed(&mut self) -> crate::transfer::Completion<Vec<u8>> {
271 let (status, actual_len) = self.take_status();
272
273 // SAFETY: self is completed (precondition) and `actual_length` bytes were initialized.
274 let data = unsafe { self.take_buf(actual_len) };
275 Completion { data, status }
276 }
277 }
278
279 impl PlatformSubmit<ControlOut<'_>> for TransferData {
280 unsafe fn submit(&mut self, data: ControlOut<'_>, callback_data: *mut std::ffi::c_void) {
281 assert!(self.pipe_ref == 0);
282
283 let buf = data.data.to_vec();
284 let len = buf.len();
285 self.fill(buf, callback_data);
286
287 let mut req = IOUSBDevRequest {
288 bmRequestType: data.request_type(),
289 bRequest: data.request,
290 wValue: data.value,
291 wIndex: data.index,
292 wLength: u16::try_from(len).expect("request too long"),
293 pData: self.buf as *mut c_void,
294 wLenDone: 0,
295 };
296
297 // SAFETY: we just properly filled the buffer and it is not already pending
298 let res = call_iokit_function!(
299 self.device.device.raw,
300 DeviceRequestAsync(&mut req, transfer_callback, self.inner as *mut c_void)
301 );
302 debug!(
303 "Submitted Control OUT transfer {inner:?}",
304 inner = self.inner
305 );
306 self.check_submit_result(res);
307 }
308
309 unsafe fn take_completed(&mut self) -> crate::transfer::Completion<ResponseBuffer> {
310 let (status, actual_len) = self.take_status();
311
312 // SAFETY: self is completed (precondition) and `actual_length` bytes were initialized.
313 let data = ResponseBuffer::from_vec(unsafe { self.take_buf(0) }, actual_len);
314 Completion { data, status }
315 }
316 }