Debian Codegraph @

src/platform/linux_usbfs/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 rustix::io::Errno;
9
10 use crate::transfer::{
11 Completion, ControlIn, ControlOut, EndpointType, PlatformSubmit, PlatformTransfer,
12 RequestBuffer, ResponseBuffer, TransferError, SETUP_PACKET_SIZE,
13 };
14
15 use super::{
16 errno_to_transfer_error,
17 usbfs::{
18 Urb, USBDEVFS_URB_TYPE_BULK, USBDEVFS_URB_TYPE_CONTROL, USBDEVFS_URB_TYPE_INTERRUPT,
19 USBDEVFS_URB_TYPE_ISO,
20 },
21 };
22
23 /// Linux-specific transfer state.
24 ///
25 /// This logically contains a `Vec` with urb.buffer and capacity.
26 /// It also owns the `urb` allocation itself, which is stored out-of-line
27 /// to avoid violating noalias when submitting the transfer while holding
28 /// `&mut TransferData`.
29 pub struct TransferData {
30 urb: *mut Urb,
31 capacity: usize,
32 device: Arc<super::Device>,
33
34 /// Not directly used, exists just to keep the interface from being released
35 /// while active.
36 _interface: Option<Arc<super::Interface>>,
37 }
38
39 unsafe impl Send for TransferData {}
40
41 impl TransferData {
42 pub(super) fn new(
43 device: Arc<super::Device>,
44 interface: Option<Arc<super::Interface>>,
45 endpoint: u8,
46 ep_type: EndpointType,
47 ) -> TransferData {
48 let ep_type = match ep_type {
49 EndpointType::Control => USBDEVFS_URB_TYPE_CONTROL,
50 EndpointType::Interrupt => USBDEVFS_URB_TYPE_INTERRUPT,
51 EndpointType::Bulk => USBDEVFS_URB_TYPE_BULK,
52 EndpointType::Isochronous => USBDEVFS_URB_TYPE_ISO,
53 };
54
55 TransferData {
56 urb: Box::into_raw(Box::new(Urb {
57 ep_type,
58 endpoint,
59 status: 0,
60 flags: 0,
61 buffer: null_mut(),
62 buffer_length: 0,
63 actual_length: 0,
64 start_frame: 0,
65 number_of_packets_or_stream_id: 0,
66 error_count: 0,
67 signr: 0,
68 usercontext: null_mut(),
69 })),
70 capacity: 0,
71 device,
72 _interface: interface,
73 }
74 }
75
76 fn urb_mut(&mut self) -> &mut Urb {
77 // SAFETY: if we have `&mut`, the transfer is not pending
78 unsafe { &mut *self.urb }
79 }
80
81 fn fill(&mut self, v: Vec<u8>, len: usize, user_data: *mut c_void) {
82 let mut v = ManuallyDrop::new(v);
83 let urb = self.urb_mut();
84 urb.buffer = v.as_mut_ptr();
85 urb.buffer_length = len.try_into().expect("buffer size should fit in i32");
86 urb.usercontext = user_data;
87 urb.actual_length = 0;
88 self.capacity = v.capacity();
89 }
90
91 /// SAFETY: requires that the transfer has completed and `length` bytes are initialized
92 unsafe fn take_buf(&mut self, length: usize) -> Vec<u8> {
93 let urb = self.urb_mut();
94 assert!(!urb.buffer.is_null());
95 let ptr = mem::replace(&mut urb.buffer, null_mut());
96 let capacity = mem::replace(&mut self.capacity, 0);
97 assert!(length <= capacity);
98 Vec::from_raw_parts(ptr, length, capacity)
99 }
100 }
101
102 impl Drop for TransferData {
103 fn drop(&mut self) {
104 unsafe {
105 if !self.urb_mut().buffer.is_null() {
106 drop(Vec::from_raw_parts(self.urb_mut().buffer, 0, self.capacity));
107 }
108 drop(Box::from_raw(self.urb));
109 }
110 }
111 }
112
113 impl PlatformTransfer for TransferData {
114 fn cancel(&self) {
115 unsafe {
116 self.device.cancel_urb(self.urb);
117 }
118 }
119 }
120
121 impl PlatformSubmit<Vec<u8>> for TransferData {
122 unsafe fn submit(&mut self, data: Vec<u8>, user_data: *mut c_void) {
123 let ep = self.urb_mut().endpoint;
124 assert!(ep & 0x80 == 0);
125 let len = data.len();
126 self.fill(data, len, user_data);
127
128 // SAFETY: we just properly filled the buffer and it is not already pending
129 unsafe { self.device.submit_urb(self.urb) }
130 }
131
132 unsafe fn take_completed(&mut self) -> Completion<ResponseBuffer> {
133 let status = urb_status(self.urb_mut());
134 let len = self.urb_mut().actual_length as usize;
135
136 // SAFETY: self is completed (precondition)
137 let data = ResponseBuffer::from_vec(self.take_buf(0), len);
138 Completion { data, status }
139 }
140 }
141
142 impl PlatformSubmit<RequestBuffer> for TransferData {
143 unsafe fn submit(&mut self, data: RequestBuffer, user_data: *mut c_void) {
144 let ep = self.urb_mut().endpoint;
145 let ty = self.urb_mut().ep_type;
146 assert!(ep & 0x80 == 0x80);
147 assert!(ty == USBDEVFS_URB_TYPE_BULK || ty == USBDEVFS_URB_TYPE_INTERRUPT);
148
149 let (data, len) = data.into_vec();
150 self.fill(data, len, user_data);
151
152 // SAFETY: we just properly filled the buffer and it is not already pending
153 unsafe { self.device.submit_urb(self.urb) }
154 }
155
156 unsafe fn take_completed(&mut self) -> Completion<Vec<u8>> {
157 let status = urb_status(self.urb_mut());
158 let len = self.urb_mut().actual_length as usize;
159
160 // SAFETY: self is completed (precondition) and `actual_length` bytes were initialized.
161 let data = unsafe { self.take_buf(len) };
162 Completion { data, status }
163 }
164 }
165
166 impl PlatformSubmit<ControlIn> for TransferData {
167 unsafe fn submit(&mut self, data: ControlIn, user_data: *mut c_void) {
168 let buf_len = SETUP_PACKET_SIZE + data.length as usize;
169 let mut buf = Vec::with_capacity(buf_len);
170 buf.extend_from_slice(&data.setup_packet());
171 self.fill(buf, buf_len, user_data);
172
173 // SAFETY: we just properly filled the buffer and it is not already pending
174 unsafe { self.device.submit_urb(self.urb) }
175 }
176
177 unsafe fn take_completed(&mut self) -> Completion<Vec<u8>> {
178 let status = urb_status(self.urb_mut());
179 let len = self.urb_mut().actual_length as usize;
180
181 // SAFETY: transfer is completed (precondition) and `actual_length`
182 // bytes were initialized with setup buf in front
183 let mut data = unsafe { self.take_buf(SETUP_PACKET_SIZE + len) };
184 data.splice(0..SETUP_PACKET_SIZE, []);
185 Completion { data, status }
186 }
187 }
188
189 impl PlatformSubmit<ControlOut<'_>> for TransferData {
190 unsafe fn submit(&mut self, data: ControlOut, user_data: *mut c_void) {
191 let buf_len = SETUP_PACKET_SIZE + data.data.len();
192 let mut buf = Vec::with_capacity(buf_len);
193 buf.extend_from_slice(
194 &data
195 .setup_packet()
196 .expect("data length should fit in setup packet's u16"),
197 );
198 buf.extend_from_slice(data.data);
199 self.fill(buf, buf_len, user_data);
200
201 // SAFETY: we just properly filled the buffer and it is not already pending
202 unsafe { self.device.submit_urb(self.urb) }
203 }
204
205 unsafe fn take_completed(&mut self) -> Completion<ResponseBuffer> {
206 let status = urb_status(self.urb_mut());
207 let len = self.urb_mut().actual_length as usize;
208 let data = ResponseBuffer::from_vec(self.take_buf(0), len);
209 Completion { data, status }
210 }
211 }
212
213 fn urb_status(urb: &Urb) -> Result<(), TransferError> {
214 if urb.status == 0 {
215 return Ok(());
216 }
217
218 // It's sometimes positive, sometimes negative, but rustix panics if negative.
219 Err(errno_to_transfer_error(Errno::from_raw_os_error(
220 urb.status.abs(),
221 )))
222 }