Skip to main content

capsules_extra/usb/
usbc_client_ctrl.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! A generic USB client layer managing control requests
6//!
7//! This layer responds to control requests and handles the state machine for
8//! implementing them.
9//!
10//! Right now, the stack looks like this:
11//!
12//! ```text
13//!                  Client
14//!                  |   ^
15//!             |-----   |
16//!             v        |
17//!      ClientCtrl      |
18//!          |           |
19//!          v           |
20//!          UsbController
21//! ```
22
23use super::descriptors::Buffer64;
24use super::descriptors::Descriptor;
25use super::descriptors::DescriptorBuffer;
26use super::descriptors::DescriptorType;
27use super::descriptors::DeviceBuffer;
28use super::descriptors::HIDDescriptor;
29use super::descriptors::LanguagesDescriptor;
30use super::descriptors::Recipient;
31use super::descriptors::ReportDescriptor;
32use super::descriptors::SetupData;
33use super::descriptors::StandardRequest;
34use super::descriptors::StringDescriptor;
35use super::descriptors::TransferDirection;
36
37use core::cell::Cell;
38use core::cmp::min;
39
40use kernel::hil;
41use kernel::hil::usb::TransferType;
42use tock_registers_v0::interfaces::Writeable;
43
44const DESCRIPTOR_BUFLEN: usize = 128;
45
46const N_ENDPOINTS: usize = 3;
47
48/// Handler for USB control endpoint requests.
49pub struct ClientCtrl<'a, 'b, U: 'a> {
50    /// The USB hardware controller.
51    controller: &'a U,
52
53    /// State of each endpoint.
54    state: [Cell<State>; N_ENDPOINTS],
55
56    /// A 64-byte buffer for the control endpoint to be passed to the USB
57    /// driver.
58    pub ctrl_buffer: Buffer64,
59
60    /// Storage for composing responses to device descriptor requests.
61    descriptor_storage: [Cell<u8>; DESCRIPTOR_BUFLEN],
62
63    /// Buffer containing the byte-packed representation of the device
64    /// descriptor. This is expected to be created and passed from the user of
65    /// `ClientCtrl`.
66    device_descriptor_buffer: DeviceBuffer,
67
68    /// Buffer containing the byte-serialized representation of the configuration
69    /// descriptor and all other descriptors for this device.
70    other_descriptor_buffer: DescriptorBuffer,
71
72    /// An optional HID descriptor for the configuration. This can be requested
73    /// separately. It must also be included in `other_descriptor_buffer` if it exists.
74    hid_descriptor: Option<&'b HIDDescriptor<'b>>,
75
76    /// An optional report descriptor for the configuration. This can be
77    /// requested separately. It must also be included in
78    /// `other_descriptor_buffer` if it exists.
79    report_descriptor: Option<&'b ReportDescriptor<'b>>,
80
81    /// Supported language (only one for now).
82    language: &'b [u16; 1],
83
84    /// USB strings to provide human readable descriptions of certain descriptor attributes.
85    strings: &'b [&'b str],
86}
87
88/// States for the individual endpoints.
89#[derive(Copy, Clone, Default)]
90enum State {
91    #[default]
92    Init,
93
94    /// We are doing a Control In transfer of some data in
95    /// self.descriptor_storage, with the given extent remaining to send.
96    CtrlIn(usize, usize),
97
98    /// We will accept data from the host.
99    CtrlOut,
100
101    SetAddress,
102}
103
104impl<'a, 'b, U: hil::usb::UsbController<'a>> ClientCtrl<'a, 'b, U> {
105    pub fn new(
106        controller: &'a U,
107        device_descriptor_buffer: DeviceBuffer,
108        other_descriptor_buffer: DescriptorBuffer,
109        hid_descriptor: Option<&'b HIDDescriptor<'b>>,
110        report_descriptor: Option<&'b ReportDescriptor<'b>>,
111        language: &'b [u16; 1],
112        strings: &'b [&'b str],
113    ) -> Self {
114        ClientCtrl {
115            controller,
116            state: Default::default(),
117            // For the moment, the Default trait is not implemented for arrays
118            // of length > 32, and the Cell type is not Copy, so we have to
119            // initialize each element manually.
120            #[rustfmt::skip]
121            descriptor_storage: [
122                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
123                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
124                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
125                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
126                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
127                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
128                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
129                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
130                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
131                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
132                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
133                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
134                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
135                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
136                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
137                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
138                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
139                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
140                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
141                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
142                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
143                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
144                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
145                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
146                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
147                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
148                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
149                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
150                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
151                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
152                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
153                Cell::default(), Cell::default(), Cell::default(), Cell::default(),
154            ],
155            ctrl_buffer: Buffer64::default(),
156            device_descriptor_buffer,
157            other_descriptor_buffer,
158            hid_descriptor,
159            report_descriptor,
160            language,
161            strings,
162        }
163    }
164
165    #[inline]
166    pub fn controller(&self) -> &'a U {
167        self.controller
168    }
169
170    #[inline]
171    fn descriptor_buf(&'a self) -> &'a [Cell<u8>] {
172        &self.descriptor_storage
173    }
174
175    pub fn enable(&'a self) {
176        // Set up the default control endpoint
177        self.controller
178            .endpoint_set_ctrl_buffer(&self.ctrl_buffer.buf);
179        self.controller
180            .enable_as_device(hil::usb::DeviceSpeed::Full); // must be Full for Bulk transfers
181        self.controller
182            .endpoint_out_enable(TransferType::Control, 0);
183    }
184
185    pub fn attach(&'a self) {
186        self.controller.attach();
187    }
188
189    /// Handle a Control Setup transaction
190    pub fn ctrl_setup(&'a self, endpoint: usize) -> hil::usb::CtrlSetupResult {
191        if endpoint != 0 {
192            // For now we only support the default Control endpoint
193            return hil::usb::CtrlSetupResult::ErrInvalidDeviceIndex;
194        }
195        SetupData::get(&self.ctrl_buffer.buf).map_or(
196            hil::usb::CtrlSetupResult::ErrNoParse,
197            |setup_data| {
198                let transfer_direction = setup_data.request_type.transfer_direction();
199                let recipient = setup_data.request_type.recipient();
200                setup_data.get_standard_request().map_or_else(
201                    || {
202                        // XX: CtrlSetupResult::ErrNonstandardRequest
203
204                        // For now, promiscuously accept vendor data and even supply
205                        // a few debugging bytes when host does a read
206
207                        match transfer_direction {
208                            TransferDirection::HostToDevice => {
209                                self.state[endpoint].set(State::CtrlOut);
210                                hil::usb::CtrlSetupResult::Ok
211                            }
212                            TransferDirection::DeviceToHost => {
213                                // Arrange to send some crap back
214                                let buf = self.descriptor_buf();
215                                buf[0].set(0xa);
216                                buf[1].set(0xb);
217                                buf[2].set(0xc);
218                                self.state[endpoint].set(State::CtrlIn(0, 3));
219                                hil::usb::CtrlSetupResult::Ok
220                            }
221                        }
222                    },
223                    |request| match recipient {
224                        Recipient::Device => self.handle_standard_device_request(endpoint, request),
225                        Recipient::Interface => {
226                            self.handle_standard_interface_request(endpoint, request)
227                        }
228                        _ => hil::usb::CtrlSetupResult::ErrGeneric,
229                    },
230                )
231            },
232        )
233    }
234
235    fn handle_standard_device_request(
236        &'a self,
237        endpoint: usize,
238        request: StandardRequest,
239    ) -> hil::usb::CtrlSetupResult {
240        match request {
241            StandardRequest::GetDescriptor {
242                descriptor_type,
243                descriptor_index,
244                lang_id,
245                requested_length,
246            } => {
247                match descriptor_type {
248                    DescriptorType::Device => match descriptor_index {
249                        0 => {
250                            let buf = self.descriptor_buf();
251                            let len = self.device_descriptor_buffer.write_to(buf);
252
253                            let end = min(len, requested_length as usize);
254
255                            self.state[endpoint].set(State::CtrlIn(0, end));
256                            hil::usb::CtrlSetupResult::Ok
257                        }
258                        _ => hil::usb::CtrlSetupResult::ErrInvalidDeviceIndex,
259                    },
260                    DescriptorType::Configuration => match descriptor_index {
261                        0 => {
262                            let buf = self.descriptor_buf();
263                            let len = self.other_descriptor_buffer.write_to(buf);
264
265                            let end = min(len, requested_length as usize);
266                            self.state[endpoint].set(State::CtrlIn(0, end));
267                            hil::usb::CtrlSetupResult::Ok
268                        }
269                        _ => hil::usb::CtrlSetupResult::ErrInvalidConfigurationIndex,
270                    },
271                    DescriptorType::String => {
272                        if let Some(len) = match descriptor_index {
273                            0 => {
274                                let buf = self.descriptor_buf();
275                                let d = LanguagesDescriptor {
276                                    langs: self.language,
277                                };
278                                let len = d.write_to(buf);
279                                Some(len)
280                            }
281                            i if i > 0
282                                && (i as usize) <= self.strings.len()
283                                && lang_id == self.language[0] =>
284                            {
285                                let buf = self.descriptor_buf();
286                                let d = StringDescriptor {
287                                    string: self.strings[i as usize - 1],
288                                };
289                                let len = d.write_to(buf);
290                                Some(len)
291                            }
292                            _ => None,
293                        } {
294                            let end = min(len, requested_length as usize);
295                            self.state[endpoint].set(State::CtrlIn(0, end));
296                            hil::usb::CtrlSetupResult::Ok
297                        } else {
298                            hil::usb::CtrlSetupResult::ErrInvalidStringIndex
299                        }
300                    }
301                    DescriptorType::DeviceQualifier => {
302                        // We are full-speed only, so we must
303                        // respond with a request error
304                        hil::usb::CtrlSetupResult::ErrNoDeviceQualifier
305                    }
306                    _ => hil::usb::CtrlSetupResult::ErrUnrecognizedDescriptorType,
307                } // match descriptor_type
308            }
309            StandardRequest::SetAddress { device_address } => {
310                // Load the address we've been assigned ...
311                self.controller.set_address(device_address);
312
313                // ... and when this request gets to the Status stage we will actually enable the
314                // address.
315                self.state[endpoint].set(State::SetAddress);
316                hil::usb::CtrlSetupResult::OkSetAddress
317            }
318            StandardRequest::SetConfiguration { .. } => {
319                // We have been assigned a particular configuration: fine!
320                hil::usb::CtrlSetupResult::Ok
321            }
322            _ => hil::usb::CtrlSetupResult::ErrUnrecognizedRequestType,
323        }
324    }
325
326    fn handle_standard_interface_request(
327        &'a self,
328        endpoint: usize,
329        request: StandardRequest,
330    ) -> hil::usb::CtrlSetupResult {
331        match request {
332            StandardRequest::GetDescriptor {
333                descriptor_type,
334                // TODO: use the descriptor index
335                descriptor_index: _,
336                // TODO: use the language ID?
337                lang_id: _,
338                requested_length,
339            } => match descriptor_type {
340                DescriptorType::HID => {
341                    if let Some(desc) = self.hid_descriptor {
342                        let buf = self.descriptor_buf();
343                        let len = desc.write_to(buf);
344                        let end = min(len, requested_length as usize);
345                        self.state[endpoint].set(State::CtrlIn(0, end));
346                        hil::usb::CtrlSetupResult::Ok
347                    } else {
348                        hil::usb::CtrlSetupResult::ErrGeneric
349                    }
350                }
351                DescriptorType::Report => {
352                    if let Some(desc) = self.report_descriptor {
353                        let buf = self.descriptor_buf();
354                        let len = desc.write_to(buf);
355                        let end = min(len, requested_length as usize);
356                        self.state[endpoint].set(State::CtrlIn(0, end));
357                        hil::usb::CtrlSetupResult::Ok
358                    } else {
359                        hil::usb::CtrlSetupResult::ErrGeneric
360                    }
361                }
362                _ => hil::usb::CtrlSetupResult::ErrGeneric,
363            },
364            _ => hil::usb::CtrlSetupResult::ErrGeneric,
365        }
366    }
367
368    /// Allow the upper ctrl layer to set data for a CtrlIn response.
369    pub fn prepare_ctrl_in(&'a self, endpoint: usize, f: fn(&'a [Cell<u8>]) -> usize) {
370        let len = f(self.descriptor_buf());
371        self.state[endpoint].set(State::CtrlIn(0, len));
372    }
373
374    /// Handle a Control In transaction
375    pub fn ctrl_in(&'a self, endpoint: usize) -> hil::usb::CtrlInResult {
376        match self.state[endpoint].get() {
377            State::CtrlIn(start, end) => {
378                let len = end.saturating_sub(start);
379                if len > 0 {
380                    let packet_bytes = min(self.ctrl_buffer.buf.len(), len);
381                    let packet = &self.descriptor_storage[start..start + packet_bytes];
382                    let buf = &self.ctrl_buffer.buf;
383
384                    // Copy a packet into the endpoint buffer
385                    for (i, b) in packet.iter().enumerate() {
386                        buf[i].set(b.get());
387                    }
388
389                    let start = start + packet_bytes;
390                    let len = end.saturating_sub(start);
391                    let transfer_complete = len == 0;
392
393                    self.state[endpoint].set(State::CtrlIn(start, end));
394
395                    hil::usb::CtrlInResult::Packet(packet_bytes, transfer_complete)
396                } else {
397                    hil::usb::CtrlInResult::Packet(0, true)
398                }
399            }
400            _ => hil::usb::CtrlInResult::Error,
401        }
402    }
403
404    /// Handle a Control Out transaction
405    pub fn ctrl_out(&'a self, endpoint: usize, _packet_bytes: u32) -> hil::usb::CtrlOutResult {
406        match self.state[endpoint].get() {
407            State::CtrlOut => {
408                // Gamely accept the data
409                hil::usb::CtrlOutResult::Ok
410            }
411            _ => {
412                // Bad state
413                hil::usb::CtrlOutResult::Halted
414            }
415        }
416    }
417
418    pub fn ctrl_status(&'a self, _endpoint: usize) {
419        // Entered Status stage
420    }
421
422    /// Handle the completion of a Control transfer
423    pub fn ctrl_status_complete(&'a self, endpoint: usize) {
424        // Control Read: IN request acknowledged
425        // Control Write: status sent
426
427        if let State::SetAddress = self.state[endpoint].get() {
428            self.controller.enable_address();
429        }
430        self.state[endpoint].set(State::Init);
431    }
432}