Skip to main content

capsules_extra/usb/
usbc_client.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 bare-bones client of the USB hardware interface.
6//!
7//! It responds to standard device requests and can be enumerated.
8
9use core::cell::Cell;
10
11use super::descriptors::{
12    self, Buffer8, DeviceDescriptor, EndpointAddress, EndpointDescriptor, TransferDirection,
13};
14use super::usbc_client_ctrl::ClientCtrl;
15
16use kernel::debug;
17use kernel::hil;
18use kernel::hil::usb::TransferType;
19use tock_registers_v0::interfaces::{Readable, Writeable};
20use tock_registers_v0::registers::InMemoryRegister;
21
22const VENDOR_ID: u16 = 0x6667;
23const PRODUCT_ID: u16 = 0xabcd;
24
25static LANGUAGES: &[u16; 1] = &[
26    0x0409, // English (United States)
27];
28
29static STRINGS: &[&str] = &[
30    "XYZ Corp.",      // Manufacturer
31    "The Zorpinator", // Product
32    "Serial No. 5",   // Serial number
33];
34
35/// Platform-specific packet length for the `SAM4L` USB hardware.
36pub const MAX_CTRL_PACKET_SIZE_SAM4L: u8 = 8;
37/// Platform-specific packet length for the `nRF52` USB hardware.
38pub const MAX_CTRL_PACKET_SIZE_NRF52840: u8 = 64;
39/// Platform-specific packet length for the `earlgrey` USB hardware.
40pub const MAX_CTRL_PACKET_SIZE_EARLGREY: u8 = 64;
41
42const N_ENDPOINTS: usize = 2;
43
44pub struct Client<'a, C: 'a> {
45    client_ctrl: ClientCtrl<'a, 'static, C>,
46
47    // An eight-byte buffer for each endpoint
48    buffers: [Buffer8; N_ENDPOINTS],
49
50    // State for a debugging feature: A buffer for echoing bulk data
51    // from an OUT endpoint back to an IN endpoint
52    echo_buf: [Cell<u8>; 8], // Must be no larger than endpoint packet buffer
53    echo_len: Cell<usize>,
54    delayed_out: Cell<bool>,
55}
56
57impl<'a, C: hil::usb::UsbController<'a>> Client<'a, C> {
58    pub fn new(controller: &'a C, max_ctrl_packet_size: u8) -> Self {
59        let interfaces: &mut [descriptors::InterfaceDescriptor] =
60            &mut [descriptors::InterfaceDescriptor {
61                interface_number: 0,
62                alternate_setting: 0,
63                num_endpoints: 0,      // (excluding default control endpoint)
64                interface_class: 0xff, // vendor_specific
65                interface_subclass: 0xab,
66                interface_protocol: 0,
67                string_index: 0,
68            }];
69
70        let endpoints: &[&[EndpointDescriptor]] = &mut [&[
71            EndpointDescriptor {
72                endpoint_address: EndpointAddress::new_const(1, TransferDirection::DeviceToHost),
73                transfer_type: TransferType::Bulk,
74                max_packet_size: 8,
75                interval: 0,
76            },
77            EndpointDescriptor {
78                endpoint_address: EndpointAddress::new_const(2, TransferDirection::HostToDevice),
79                transfer_type: TransferType::Bulk,
80                max_packet_size: 8,
81                interval: 0,
82            },
83        ]];
84
85        let (device_descriptor_buffer, other_descriptor_buffer) =
86            descriptors::create_descriptor_buffers(
87                DeviceDescriptor {
88                    vendor_id: VENDOR_ID,
89                    product_id: PRODUCT_ID,
90                    manufacturer_string: 1,
91                    product_string: 2,
92                    serial_number_string: 3,
93                    max_packet_size_ep0: max_ctrl_packet_size,
94                    ..DeviceDescriptor::default()
95                },
96                descriptors::ConfigurationDescriptor::default(),
97                interfaces,
98                endpoints,
99                None, // No HID descriptor
100                None, // No CDC descriptor array
101            );
102
103        Client {
104            client_ctrl: ClientCtrl::new(
105                controller,
106                device_descriptor_buffer,
107                other_descriptor_buffer,
108                None, // No HID descriptor
109                None, // No report descriptor
110                LANGUAGES,
111                STRINGS,
112            ),
113            buffers: Default::default(),
114            echo_buf: Default::default(),
115            echo_len: Cell::new(0),
116            delayed_out: Cell::new(false),
117        }
118    }
119
120    fn alert_full(&'a self) {
121        // Alert the controller that we now have data to send on the Bulk IN endpoint 1
122        self.controller().endpoint_resume_in(1);
123    }
124
125    fn alert_empty(&'a self) {
126        // In case we reported Delay before, alert the controller
127        // that we can now receive data on the Bulk OUT endpoint 2
128        if self.delayed_out.take() {
129            self.controller().endpoint_resume_out(2);
130        }
131    }
132
133    #[inline]
134    fn controller(&'a self) -> &'a C {
135        self.client_ctrl.controller()
136    }
137
138    #[inline]
139    fn buffer(&'a self, i: usize) -> &'a [InMemoryRegister<u8>; 8] {
140        &self.buffers[i - 1].buf
141    }
142}
143
144impl<'a, C: hil::usb::UsbController<'a>> hil::usb::Client<'a> for Client<'a, C> {
145    fn enable(&'a self) {
146        // Set up the default control endpoint
147        self.client_ctrl.enable();
148
149        // Set up a bulk-in endpoint for debugging
150        self.controller().endpoint_set_in_buffer(1, self.buffer(1));
151        self.controller().endpoint_in_enable(TransferType::Bulk, 1);
152
153        // Set up a bulk-out endpoint for debugging
154        self.controller().endpoint_set_out_buffer(2, self.buffer(2));
155        self.controller().endpoint_out_enable(TransferType::Bulk, 2);
156    }
157
158    fn attach(&'a self) {
159        self.client_ctrl.attach();
160    }
161
162    fn bus_reset(&'a self) {
163        // Should the client initiate reconfiguration here?
164        // For now, the hardware layer does it.
165
166        debug!("Bus reset");
167
168        // Reset the state for our pair of debugging endpoints
169        self.echo_len.set(0);
170        self.delayed_out.set(false);
171    }
172
173    /// Handle a Control Setup transaction
174    fn ctrl_setup(&'a self, endpoint: usize) -> hil::usb::CtrlSetupResult {
175        self.client_ctrl.ctrl_setup(endpoint)
176    }
177
178    /// Handle a Control In transaction
179    fn ctrl_in(&'a self, endpoint: usize) -> hil::usb::CtrlInResult {
180        self.client_ctrl.ctrl_in(endpoint)
181    }
182
183    /// Handle a Control Out transaction
184    fn ctrl_out(&'a self, endpoint: usize, packet_bytes: u32) -> hil::usb::CtrlOutResult {
185        self.client_ctrl.ctrl_out(endpoint, packet_bytes)
186    }
187
188    fn ctrl_status(&'a self, endpoint: usize) {
189        self.client_ctrl.ctrl_status(endpoint)
190    }
191
192    /// Handle the completion of a Control transfer
193    fn ctrl_status_complete(&'a self, endpoint: usize) {
194        self.client_ctrl.ctrl_status_complete(endpoint)
195    }
196
197    /// Handle a Bulk/Interrupt IN transaction
198    fn packet_in(&'a self, transfer_type: TransferType, endpoint: usize) -> hil::usb::InResult {
199        match transfer_type {
200            TransferType::Interrupt => {
201                debug!("interrupt_in({}) not implemented", endpoint);
202                hil::usb::InResult::Error
203            }
204            TransferType::Bulk => {
205                // Write a packet into the endpoint buffer
206                let packet_bytes = self.echo_len.get();
207                if packet_bytes > 0 {
208                    // Copy the entire echo buffer into the packet
209                    let packet = self.buffer(endpoint);
210                    for i in 0..packet_bytes {
211                        packet[i].set(self.echo_buf[i].get());
212                    }
213                    self.echo_len.set(0);
214
215                    // We can receive more now
216                    self.alert_empty();
217
218                    hil::usb::InResult::Packet(packet_bytes)
219                } else {
220                    // Nothing to send
221                    hil::usb::InResult::Delay
222                }
223            }
224            TransferType::Control | TransferType::Isochronous => unreachable!(),
225        }
226    }
227
228    /// Handle a Bulk/Interrupt OUT transaction
229    fn packet_out(
230        &'a self,
231        transfer_type: TransferType,
232        endpoint: usize,
233        packet_bytes: u32,
234    ) -> hil::usb::OutResult {
235        match transfer_type {
236            TransferType::Interrupt => {
237                debug!("interrupt_out({}) not implemented", endpoint);
238                hil::usb::OutResult::Error
239            }
240            TransferType::Bulk => {
241                // Consume a packet from the endpoint buffer
242                let new_len = packet_bytes as usize;
243                let current_len = self.echo_len.get();
244                let total_len = current_len + new_len;
245
246                if total_len > self.echo_buf.len() {
247                    // The packet won't fit in our little buffer.  We'll have
248                    // to wait until it is drained
249                    self.delayed_out.set(true);
250                    hil::usb::OutResult::Delay
251                } else if new_len > 0 {
252                    // Copy the packet into our echo buffer
253                    let packet = self.buffer(endpoint);
254                    for i in 0..new_len {
255                        self.echo_buf[current_len + i].set(packet[i].get());
256                    }
257                    self.echo_len.set(total_len);
258
259                    // We can start sending again
260                    self.alert_full();
261                    hil::usb::OutResult::Ok
262                } else {
263                    debug!("Ignoring zero-length OUT packet");
264                    hil::usb::OutResult::Ok
265                }
266            }
267            TransferType::Control | TransferType::Isochronous => unreachable!(),
268        }
269    }
270
271    fn packet_transmitted(&'a self, _endpoint: usize) {
272        // Nothing to do.
273    }
274}