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