smolusb 0.2.2

An experimental lightweight library for implementing USB on embedded systems.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use core::marker::PhantomData;

use log::{error, info, trace, warn};

use crate::descriptor::microsoft10;
use crate::device::Descriptors;
use crate::event::UsbEvent;
use crate::setup::{Direction, Feature, Recipient, Request, RequestType, SetupPacket};
use crate::traits::{AsByteSliceIterator, UsbDriver};

// - State --------------------------------------------------------------------

/// Represents the current state of the Control interface.
#[derive(Clone, Copy, Debug)]
pub enum State {
    Idle,
    Send,
    WaitForZlp,
    SetAddress(u8),
    ReceiveHostData(SetupPacket),
    FinishHostData(SetupPacket),
    Complete,
    Stall,
}

// - Control ------------------------------------------------------------------

/// Implements a USB Control endpoint.
pub struct Control<'a, D, const RX_BUFFER_SIZE: usize> {
    endpoint_number: u8,
    descriptors: Descriptors<'a>,

    next: State,
    configuration: Option<u8>,
    feature_remote_wakeup: bool,

    rx_buffer: [u8; RX_BUFFER_SIZE],
    rx_buffer_position: usize,

    _marker: PhantomData<&'a D>,
}

impl<'a, D, const RX_BUFFER_SIZE: usize> Control<'a, D, RX_BUFFER_SIZE>
where
    D: UsbDriver,
{
    /// Returns the last received control data from the host.
    #[must_use]
    pub fn data(&'a self) -> &'a [u8] {
        &self.rx_buffer[..self.rx_buffer_position]
    }

    fn write_zlp(&self, usb: &D) {
        usb.write(self.endpoint_number, [].into_iter());
    }

    fn read_zlp(&self, usb: &D) -> bool {
        usb.read(self.endpoint_number, &mut [0; crate::EP_MAX_PACKET_SIZE]) == 0
    }
}

impl<'a, D, const RX_BUFFER_SIZE: usize> Control<'a, D, RX_BUFFER_SIZE>
where
    D: UsbDriver,
{
    #[must_use]
    pub fn new(endpoint_number: u8, descriptors: Descriptors<'a>) -> Self {
        Self {
            endpoint_number,
            descriptors: descriptors.set_total_lengths(), // TODO figure out a better solution
            next: State::Idle,
            configuration: None,
            feature_remote_wakeup: false,
            rx_buffer: [0; RX_BUFFER_SIZE],
            rx_buffer_position: 0,
            _marker: PhantomData,
        }
    }

    /// Dispatches an interrupt event generated by the USB peripheral
    /// for handling by the [`Control`] interface.
    ///
    /// Returns the last [`SetupPacket`] received if it could not be
    /// handled by the [`Control`] interface.  (e.g. if it was a
    /// [`RequestType::Class`] or [`RequestType::Vendor`] request)
    #[allow(clippy::too_many_lines)] // sometimes you can't have too much of a good thing!
    pub fn dispatch_event(&mut self, usb: &D, event: UsbEvent) -> Option<SetupPacket> {
        // The Control interface state machine operates on the latest
        // receive event and the current state of the interface.
        match (event, &self.next.clone()) {
            (UsbEvent::BusReset, _state) => {
                // reset
                self.next = State::Idle;
                // self.bus_reset(); - irq handler is doing the reset for us
            }

            (
                UsbEvent::ReceiveSetupPacket(endpoint_number, setup_packet),
                State::Idle | State::Stall,
            ) if endpoint_number == self.endpoint_number => {
                if matches!(self.next, State::Stall) {
                    // clear State::Stall
                    self.next = State::Idle;
                }

                let requested_length = setup_packet.length as usize;

                match (
                    setup_packet.direction(),
                    setup_packet.request_type(),
                    setup_packet.request(),
                ) {
                    // handle microsoft os 1.0 descriptor requests
                    //
                    // reg entries are:
                    //
                    //   Microsoft OS 1.0 String Descriptor: <VID><PID><bcdDevice> => 1d50615b0104
                    //     HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\usbflags\1D50615B0104
                    //     HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\usbflags\1D50615B0104
                    //
                    //   Compatible ID Feature Descriptor:   VID_<VID>&PID_<PID>   => VID_1d50&PID_615b
                    //     HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB\VID_1d50&PID_615b
                    //
                    (
                        Direction::DeviceToHost,
                        RequestType::Vendor,
                        Request::ClassOrVendor(microsoft10::VendorRequest::Microsoft),
                    ) => {
                        let recipient = setup_packet.recipient();
                        let vendor_index = microsoft10::VendorIndex::from(setup_packet.index);

                        match (&recipient, &vendor_index, &self.descriptors.microsoft10) {
                            (
                                Recipient::Device,
                                microsoft10::VendorIndex::CompatibleIdFeatureDescriptor,
                                Some(descriptors),
                            ) => {
                                self.next = State::Send;
                                usb.write_requested(
                                    self.endpoint_number,
                                    requested_length,
                                    descriptors
                                        .compat_id_feature_descriptor
                                        .iter()
                                        .copied()
                                        .take(requested_length),
                                );
                            }
                            (
                                Recipient::Interface,
                                microsoft10::VendorIndex::ExtendedPropertiesFeatureDescriptor,
                                Some(descriptors),
                            ) => {
                                self.next = State::Send;
                                usb.write_requested(
                                    self.endpoint_number,
                                    requested_length,
                                    descriptors
                                        .extended_properties_feature_descriptor
                                        .as_iter()
                                        .copied()
                                        .take(requested_length),
                                );
                            }
                            _ => {
                                self.next = State::Stall;
                                error!(
                                    "Control error. Could not handle Microsoft OS 1.0 Request: '{:?}'.",
                                    setup_packet
                                );
                                usb.stall_endpoint_in(self.endpoint_number);
                            }
                        }
                    }

                    // - standard requests
                    (Direction::DeviceToHost, RequestType::Standard, Request::GetDescriptor) => {
                        self.next = State::Send;
                        return self
                            .descriptors
                            .write(usb, self.endpoint_number, setup_packet);
                    }
                    (Direction::HostToDevice, RequestType::Standard, Request::SetAddress) => {
                        let address: u8 = (setup_packet.value & 0x7f) as u8;
                        self.next = State::SetAddress(address);
                        self.write_zlp(usb);
                    }
                    (Direction::HostToDevice, RequestType::Standard, Request::SetConfiguration) => {
                        let configuration: u8 = (setup_packet.value & 0xff) as u8;
                        // check whether this is a valid configuration
                        // TODO support multiple configurations
                        if configuration > 1 {
                            warn!("Control stall - unknown configuration {}", configuration);
                            self.configuration = None;
                            self.next = State::Stall;
                            usb.stall_endpoint_out(self.endpoint_number);
                            return None;
                        }
                        self.configuration = Some(configuration);
                        self.next = State::Complete;
                        self.write_zlp(usb);
                    }
                    (Direction::DeviceToHost, RequestType::Standard, Request::GetConfiguration) => {
                        self.next = State::Send;
                        if let Some(configuration) = self.configuration {
                            usb.write(self.endpoint_number, [configuration].into_iter());
                        } else {
                            usb.write(self.endpoint_number, [0].into_iter());
                        }
                    }
                    (Direction::DeviceToHost, RequestType::Standard, Request::GetStatus) => {
                        let status: u16 = 0b01; // bit 1:remote-wakeup bit 0:self-powered
                        let status = status | u16::from(self.feature_remote_wakeup) << 1;
                        self.next = State::Send;
                        usb.write(0, status.to_le_bytes().into_iter());
                    }
                    (direction, RequestType::Standard, Request::ClearFeature) => {
                        info!("  TODO Request::ClearFeature {:?}", direction);
                        let recipient = setup_packet.recipient();
                        let feature = Feature::from(setup_packet.value);
                        match (&recipient, &feature) {
                            (Recipient::Endpoint, Feature::EndpointHalt) => {
                                let endpoint_address = (setup_packet.index & 0xff) as u8;
                                let endpoint_number = endpoint_address & 0x7f;
                                let direction = Direction::from(endpoint_address);
                                usb.clear_feature_endpoint_halt(endpoint_number, direction);
                                self.next = State::Complete;
                                self.write_zlp(usb);
                            }
                            (Recipient::Device, Feature::DeviceRemoteWakeup) => {
                                self.feature_remote_wakeup = false;
                                self.next = State::Complete;
                                self.write_zlp(usb);
                            }
                            _ => {
                                warn!(
                                    "SETUP stall: unhandled clear feature {:?}, {:?}",
                                    recipient, feature
                                );
                                self.next = State::Stall;
                                usb.stall_endpoint_in(self.endpoint_number);
                            }
                        }
                    }
                    (direction, RequestType::Standard, Request::SetFeature) => {
                        info!("  TODO Request::SetFeature {:?}", direction);
                        let recipient = setup_packet.recipient();
                        let feature = Feature::from(setup_packet.value);
                        self.next = State::Complete;
                        match (&recipient, &feature) {
                            (Recipient::Device, Feature::DeviceRemoteWakeup) => {
                                self.feature_remote_wakeup = true;
                                self.write_zlp(usb);
                            }
                            _ => {
                                warn!(
                                    "SETUP stall: unhandled set feature {:?}, {:?}",
                                    recipient, feature
                                );
                                usb.stall_endpoint_in(self.endpoint_number);
                                self.next = State::Stall;
                            }
                        }
                    }

                    // - unsupported requests with host data we need to read
                    (Direction::HostToDevice, _, _) if setup_packet.length > 0 => {
                        self.rx_buffer_position = 0;
                        self.next = State::ReceiveHostData(setup_packet);
                        usb.ep_out_prime_receive(self.endpoint_number); // prime to receive data from host
                    }

                    // - unsupported requests
                    (direction, request_type, request) => {
                        trace!(
                            "Unhandled request direction:{:?} request_type:{:?} request:{:?}",
                            direction,
                            request_type,
                            request
                        );
                        self.next = State::Idle;
                        return Some(setup_packet);
                    }
                }
            }

            // - handle states ------------------------------------------------
            (UsbEvent::SendComplete(endpoint_number), State::Send)
                if endpoint_number == self.endpoint_number =>
            {
                self.next = State::WaitForZlp;
                // prime to receive zlp from host
                usb.ep_out_prime_receive(self.endpoint_number);
            }

            (UsbEvent::SendComplete(endpoint_number), State::WaitForZlp)
                if endpoint_number == self.endpoint_number =>
            {
                // it's part of a multi-packet send, we can safely ignore this
            }

            (UsbEvent::ReceivePacket(endpoint_number), State::WaitForZlp)
                if endpoint_number == self.endpoint_number =>
            {
                self.next = State::Idle;
                if !self.read_zlp(usb) {
                    warn!(
                        "Control {:?} {:?} expected a ZLP but received data instead.",
                        event, self.next
                    );
                }
            }

            (UsbEvent::SendComplete(endpoint_number), &State::SetAddress(address))
                if endpoint_number == self.endpoint_number =>
            {
                self.next = State::Idle;
                usb.set_address(address); // set address
            }

            (UsbEvent::SendComplete(endpoint_number), State::Complete)
                if endpoint_number == self.endpoint_number =>
            {
                self.next = State::Idle;
            }

            (UsbEvent::ReceivePacket(endpoint_number), &State::ReceiveHostData(setup_packet))
                if endpoint_number == self.endpoint_number =>
            {
                let mut packet_buffer: [u8; crate::EP_MAX_PACKET_SIZE] =
                    [0; crate::EP_MAX_PACKET_SIZE];
                let bytes_read = usb.read(self.endpoint_number, &mut packet_buffer);

                // handle early abort
                if bytes_read == 0 {
                    warn!("Control receive early abort");
                    // we're done
                    self.next = State::FinishHostData(setup_packet);
                    self.write_zlp(usb);
                    return None;
                }

                // handle buffer overflow
                if self.rx_buffer_position + bytes_read > RX_BUFFER_SIZE {
                    error!("Control receive buffer overflow, truncating.");
                    // keep reading until the host has no more data to send
                    self.next = State::ReceiveHostData(setup_packet);
                    usb.ep_out_prime_receive(self.endpoint_number);
                    return None;
                }

                // append packet to rx_buffer
                let offset = self.rx_buffer_position;
                self.rx_buffer[offset..offset + bytes_read]
                    .copy_from_slice(&packet_buffer[..bytes_read]);
                self.rx_buffer_position += bytes_read;

                // are we done yet?
                if self.rx_buffer_position >= usize::from(setup_packet.length) {
                    // we're done
                    self.next = State::FinishHostData(setup_packet);
                    self.write_zlp(usb);
                } else {
                    // get ready to receive more data
                    self.next = State::ReceiveHostData(setup_packet);
                    // prime to receive next block of data from host
                    usb.ep_out_prime_receive(self.endpoint_number);
                }
            }

            (UsbEvent::SendComplete(endpoint_number), &State::FinishHostData(setup_packet))
                if endpoint_number == self.endpoint_number =>
            {
                // we've sent our zlp and now we are done
                self.next = State::Idle;

                // check for length mismatch
                if self.rx_buffer_position != usize::from(setup_packet.length) {
                    warn!(
                        "Control expected {} bytes of data from the host, but received {} bytes.",
                        setup_packet.length, self.rx_buffer_position,
                    );
                }

                return Some(setup_packet);
            }

            // we'll get these if someone is writing directly to usb1 outside control
            (UsbEvent::ReceivePacket(endpoint_number), State::Idle)
                if endpoint_number == self.endpoint_number =>
            {
                if !self.read_zlp(usb) {
                    warn!("Control expected a ZLP but received data instead.");
                }
            }
            (UsbEvent::SendComplete(endpoint_number), State::Idle)
                if endpoint_number == self.endpoint_number =>
            {
                // do nothing
            }

            (event, state) => {
                self.next = State::Idle;
                error!(
                    "Control state error. Received event '{:?}' while in state '{:?}'.",
                    event, state
                );
            }
        }

        None
    }
}