Skip to main content

usb_stack/host/
device.rs

1//! Enumeration and control transfers.
2//!
3//! A [`Device`] owns the control channel of an enumerated device: the address,
4//! the control packet size and the descriptors that were read while
5//! enumerating. Endpoints are turned into [`Pipe`]s on demand.
6
7use crate::descriptor::{descriptor_type, lang_id};
8use crate::endpoint::{Direction, EndpointAddress, EndpointType};
9use crate::host::controller::{
10    Channel, DeviceAddress, EndpointConfig, HostController, Speed, Toggle,
11};
12use crate::host::descriptor::{Configuration, DeviceDescriptor, EndpointDescriptor};
13use crate::host::error::{HostError, HostResult};
14use crate::host::pipe::Pipe;
15use crate::request::Request;
16
17/// Size of the control endpoint before the device reported its own.
18const EP0_MIN_PACKET: u16 = 8;
19
20/// Largest configuration descriptor the stack accepts.
21///
22/// The buffer lives inside [`Device`], so an application pays for it whether or
23/// not the device has a large configuration. 256 bytes hold every HID, CDC-ACM
24/// and audio control configuration; raise this when enumerating a composite
25/// device fails with [`HostError::Overflow`].
26pub const CONFIG_MAX: usize = 256;
27
28/// Room for a string descriptor: thirty-two UTF-16 code units plus the header.
29const STRING_BUFFER: usize = 2 + 2 * 32;
30
31/// An enumerated device.
32pub struct Device<'a, C: HostController> {
33    controller: &'a C,
34    control: Channel,
35    address: DeviceAddress,
36    speed: Speed,
37    max_packet0: u16,
38    descriptor: DeviceDescriptor,
39    raw_config: [u8; CONFIG_MAX],
40    config_length: usize,
41}
42
43impl<'a, C: HostController> Device<'a, C> {
44    /// Reset the port and enumerate whatever is attached.
45    pub(crate) fn enumerate(
46        controller: &'a C,
47        address: DeviceAddress,
48        speed: Speed,
49    ) -> HostResult<Self> {
50        let control = controller.alloc_channel()?;
51        let mut device = Self {
52            controller,
53            control,
54            address: DeviceAddress::ZERO,
55            speed,
56            max_packet0: EP0_MIN_PACKET,
57            descriptor: DeviceDescriptor::default(),
58            raw_config: [0; CONFIG_MAX],
59            config_length: 0,
60        };
61        device.configure_control()?;
62
63        // The first eight bytes of the device descriptor also carry
64        // bMaxPacketSize0, which every later request depends on.
65        let mut head = [0u8; EP0_MIN_PACKET as usize];
66        let request = Request::get_descriptor(descriptor_type::DEVICE, 0, 0, head.len() as u16);
67        if device.control(&request, &mut head)? < head.len() {
68            return Err(HostError::Malformed);
69        }
70        device.max_packet0 = match head[7] {
71            8 | 16 | 32 | 64 => head[7] as u16,
72            _ => return Err(HostError::Malformed),
73        };
74        device.configure_control()?;
75
76        // From the status stage of SET_ADDRESS on, the device answers to its
77        // new address.
78        device.control(&Request::set_address(address.raw()), &mut [])?;
79        device.address = address;
80        controller.wait_millis(2);
81        device.configure_control()?;
82
83        let mut raw = [0u8; DeviceDescriptor::LEN];
84        let request = Request::get_descriptor(descriptor_type::DEVICE, 0, 0, raw.len() as u16);
85        device.control(&request, &mut raw)?;
86        device.descriptor = DeviceDescriptor::parse(&raw)?;
87
88        // The configuration is a linked list flattened into one reply: read its
89        // header first to learn how long the whole thing is.
90        let mut header = [0u8; Configuration::HEADER_LEN];
91        let request =
92            Request::get_descriptor(descriptor_type::CONFIGURATION, 0, 0, header.len() as u16);
93        device.control(&request, &mut header)?;
94        let total = u16::from_le_bytes([header[2], header[3]]) as usize;
95        if total < Configuration::HEADER_LEN {
96            return Err(HostError::Malformed);
97        }
98        if total > CONFIG_MAX {
99            return Err(HostError::Overflow);
100        }
101
102        let mut raw_config = [0u8; CONFIG_MAX];
103        let request = Request::get_descriptor(descriptor_type::CONFIGURATION, 0, 0, total as u16);
104        let length = device.control(&request, &mut raw_config[..total])?;
105        Configuration::parse(&raw_config[..length])?;
106        device.raw_config = raw_config;
107        device.config_length = length;
108
109        Ok(device)
110    }
111
112    /// The address the device answers to.
113    #[inline]
114    pub fn address(&self) -> DeviceAddress {
115        self.address
116    }
117
118    /// The speed the device negotiated.
119    #[inline]
120    pub fn speed(&self) -> Speed {
121        self.speed
122    }
123
124    /// The device descriptor read while enumerating.
125    #[inline]
126    pub fn descriptor(&self) -> &DeviceDescriptor {
127        &self.descriptor
128    }
129
130    /// The configuration descriptor together with its interface and endpoint
131    /// descriptors.
132    #[inline]
133    pub fn configuration(&self) -> Configuration<'_> {
134        // `enumerate` validated the bytes and `raw_config` is never modified
135        // afterwards, so there is nothing left to check.
136        Configuration::validated(&self.raw_config[..self.config_length])
137    }
138
139    /// Run one control transfer.
140    ///
141    /// `buffer` must hold `request.length` bytes. The returned count is the
142    /// number of bytes the device actually sent, which may be less than
143    /// requested.
144    pub fn control(&self, request: &Request, buffer: &mut [u8]) -> HostResult<usize> {
145        if (buffer.len() as u16) < request.length {
146            return Err(HostError::Overflow);
147        }
148        control_transfer(
149            self.controller,
150            self.control,
151            self.max_packet0,
152            request,
153            buffer,
154        )
155    }
156
157    /// Select a configuration.
158    ///
159    /// The endpoints of the device are only usable after this request succeeded.
160    pub fn set_configuration(&self, value: u8) -> HostResult<()> {
161        self.control(&Request::set_configuration(value), &mut [])?;
162        Ok(())
163    }
164
165    /// Read a string descriptor and convert it to UTF-8.
166    ///
167    /// Returns the number of bytes written to `out`. Strings longer than
168    /// thirty-two characters and output that does not fit are truncated at a
169    /// character boundary.
170    pub fn read_string(&self, index: u8, out: &mut [u8]) -> HostResult<usize> {
171        if index == 0 {
172            return Err(HostError::Protocol);
173        }
174        let mut raw = [0u8; STRING_BUFFER];
175        let request = Request::get_descriptor(
176            descriptor_type::STRING,
177            index,
178            lang_id::EN_US,
179            STRING_BUFFER as u16,
180        );
181        let length = self.control(&request, &mut raw)?;
182
183        if length < 2 || raw[0] as usize > length || raw[1] != descriptor_type::STRING {
184            return Err(HostError::Malformed);
185        }
186        Ok(utf16le_to_utf8(&raw[2..raw[0] as usize], out))
187    }
188
189    /// Open the endpoint described by `endpoint`.
190    pub fn open(&self, endpoint: &EndpointDescriptor) -> HostResult<Pipe<'a, C>> {
191        let config = EndpointConfig {
192            address: endpoint.address,
193            transfer: endpoint.transfer_type(),
194            max_packet: endpoint.max_packet,
195            interval: endpoint.interval,
196        };
197        let channel = self.controller.alloc_channel()?;
198        let result = self.controller.configure(channel, self.address, &config);
199        match result {
200            Ok(()) => Ok(Pipe::new(self.controller, channel, config)),
201            Err(error) => {
202                self.controller.free_channel(channel);
203                Err(error)
204            }
205        }
206    }
207
208    /// Clear the halt condition of `pipe` and restart its data toggle.
209    ///
210    /// Called after a transfer failed with [`HostError::Stall`].
211    pub fn clear_halt(&self, pipe: &Pipe<'a, C>) -> HostResult<()> {
212        self.control(&Request::clear_halt(pipe.address().raw()), &mut [])?;
213        pipe.reset_toggle();
214        Ok(())
215    }
216
217    fn configure_control(&self) -> HostResult<()> {
218        let endpoint = EndpointConfig {
219            address: EndpointAddress::EP0_OUT,
220            transfer: EndpointType::Control,
221            max_packet: self.max_packet0,
222            interval: 0,
223        };
224        self.controller
225            .configure(self.control, self.address, &endpoint)
226    }
227}
228
229impl<C: HostController> Drop for Device<'_, C> {
230    fn drop(&mut self) {
231        self.controller.free_channel(self.control);
232    }
233}
234
235// ─── Control transfers ───────────────────────────────────────────────────────
236
237/// The data toggle of the `packet`-th packet of a control data stage.
238///
239/// The data stage always starts at DATA1; the status stage is DATA1 again, and
240/// is programmed by the caller.
241#[inline]
242fn data_stage_toggle(packet: usize) -> Toggle {
243    if packet.is_multiple_of(2) {
244        Toggle::Data1
245    } else {
246        Toggle::Data0
247    }
248}
249
250fn control_transfer<C: HostController>(
251    controller: &C,
252    channel: Channel,
253    max_packet0: u16,
254    request: &Request,
255    buffer: &mut [u8],
256) -> HostResult<usize> {
257    let max_packet = max_packet0.max(EP0_MIN_PACKET) as usize;
258    controller.setup(channel, &request.to_bytes())?;
259
260    if request.length == 0 {
261        // Without a data stage the status stage is the only one left, and it
262        // always goes from the device to the host.
263        controller.transfer_in(channel, Toggle::Data1, &mut [])?;
264        return Ok(0);
265    }
266
267    let length = request.length as usize;
268    let mut done = 0;
269
270    match request.direction {
271        Direction::In => {
272            while done < length {
273                let chunk = (length - done).min(max_packet);
274                let received = controller.transfer_in(
275                    channel,
276                    data_stage_toggle(done / max_packet),
277                    &mut buffer[done..done + chunk],
278                )?;
279                done += received;
280                if received < chunk {
281                    break;
282                }
283            }
284            controller.transfer_out(channel, Toggle::Data1, &[])?;
285        }
286        Direction::Out => {
287            while done < length {
288                let chunk = (length - done).min(max_packet);
289                controller.transfer_out(
290                    channel,
291                    data_stage_toggle(done / max_packet),
292                    &buffer[done..done + chunk],
293                )?;
294                done += chunk;
295            }
296            controller.transfer_in(channel, Toggle::Data1, &mut [])?;
297        }
298    }
299    Ok(done)
300}
301
302// ─── Strings ─────────────────────────────────────────────────────────────────
303
304/// Convert UTF-16LE units to UTF-8, truncating at a character boundary.
305fn utf16le_to_utf8(units: &[u8], out: &mut [u8]) -> usize {
306    let mut written = 0;
307    for pair in units.as_chunks::<2>().0 {
308        // Surrogates and values above U+FFFF are not part of a USB string
309        // descriptor's BMP subset; skip them rather than emit broken UTF-8.
310        let code = u16::from_le_bytes([pair[0], pair[1]]);
311        let decoded = match code {
312            0x0000..=0x007f => [code as u8, 0, 0, 1],
313            0x0080..=0x07ff => [
314                0b1100_0000 | (code >> 6) as u8,
315                0b1000_0000 | (code & 0x3f) as u8,
316                0,
317                2,
318            ],
319            0x0800..=0xd7ff | 0xe000..=0xffff => [
320                0b1110_0000 | (code >> 12) as u8,
321                0b1000_0000 | ((code >> 6) & 0x3f) as u8,
322                0b1000_0000 | (code & 0x3f) as u8,
323                3,
324            ],
325            _ => [0b1111_1101, 0, 0, 1],
326        };
327        let length = decoded[3] as usize;
328        if written + length > out.len() {
329            break;
330        }
331        out[written..written + length].copy_from_slice(&decoded[..length]);
332        written += length;
333    }
334    written
335}