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
//! A bare-bones client of the USB hardware interface
//!
//! It responds to standard device requests and can be enumerated.

use core::cell::Cell;
use core::cmp::min;
use core::default::Default;
use kernel::common::VolatileCell;
use kernel::hil;
use kernel::hil::usb::*;
use usb::*;

const VENDOR_ID: u16 = 0x6667;
const PRODUCT_ID: u16 = 0xabcd;

static LANGUAGES: &'static [u16] = &[
    0x0409 // English (United States)
];

static STRINGS: &'static [&'static str] = &[
    "XYZ Corp.",      // Manufacturer
    "The Zorpinator", // Product
    "Serial No. 5",   // Serial number
];

const DESCRIPTOR_BUFLEN: usize = 30;

pub struct Client<'a, C: 'a> {
    controller: &'a C,
    state: Cell<State>,
    ep0_storage: [VolatileCell<u8>; 8],
    descriptor_storage: [Cell<u8>; DESCRIPTOR_BUFLEN],
}

#[derive(Copy, Clone)]
enum State {
    Init,

    /// We are doing a Control In transfer of some data
    /// in self.descriptor_storage, with the given extent
    /// remaining to send
    CtrlIn(usize, usize),

    /// We will accept data from the host
    CtrlOut,

    SetAddress,
}

impl<'a, C: UsbController> Client<'a, C> {
    pub fn new(controller: &'a C) -> Self {
        Client {
            controller: controller,
            state: Cell::new(State::Init),
            ep0_storage: [VolatileCell::new(0); 8],
            descriptor_storage: Default::default(),
        }
    }

    #[inline]
    fn ep0_buf(&self) -> &[VolatileCell<u8>] {
        &self.ep0_storage
    }

    #[inline]
    fn descriptor_buf(&'a self) -> &'a [Cell<u8>] {
        &self.descriptor_storage
    }
}

impl<'a, C: UsbController> hil::usb::Client for Client<'a, C> {
    fn enable(&self) {
        self.controller.endpoint_set_buffer(0, self.ep0_buf());
        self.controller.enable_device(false);
        self.controller.endpoint_ctrl_out_enable(0);

        // XXX
        // static es: C::EndpointState = Default::default();
        // self.controller.endpoint_configure(&es, 0);
    }

    fn attach(&self) {
        self.controller.attach();
    }

    fn bus_reset(&self) {
        // Should the client initiate reconfiguration here?
        // For now, the hardware layer does it.
    }

    /// Handle a Control Setup transaction
    fn ctrl_setup(&self) -> CtrlSetupResult {
        SetupData::get(self.ep0_buf()).map_or(CtrlSetupResult::ErrNoParse, |setup_data| {
            setup_data.get_standard_request().map_or_else(
                || {
                    // XX: CtrlSetupResult::ErrNonstandardRequest

                    // For now, promiscuously accept vendor data and even supply
                    // a few debugging bytes when host does a read

                    match setup_data.request_type.transfer_direction() {
                        TransferDirection::HostToDevice => {
                            self.state.set(State::CtrlOut);
                            CtrlSetupResult::Ok
                        }
                        TransferDirection::DeviceToHost => {
                            // Arrange to some crap back
                            let buf = self.descriptor_buf();
                            buf[0].set(0xa);
                            buf[1].set(0xb);
                            buf[2].set(0xc);
                            self.state.set(State::CtrlIn(0, 3));
                            CtrlSetupResult::Ok
                        }
                    }
                },
                |request| {
                    match request {
                        StandardDeviceRequest::GetDescriptor {
                            descriptor_type,
                            descriptor_index,
                            lang_id,
                            requested_length,
                        } => {
                            match descriptor_type {
                                DescriptorType::Device => match descriptor_index {
                                    0 => {
                                        let buf = self.descriptor_buf();
                                        let d = DeviceDescriptor {
                                            vendor_id: VENDOR_ID,
                                            product_id: PRODUCT_ID,
                                            manufacturer_string: 1,
                                            product_string: 2,
                                            serial_number_string: 3,
                                            ..Default::default()
                                        };
                                        let len = d.write_to(buf);
                                        let end = min(len, requested_length as usize);
                                        self.state.set(State::CtrlIn(0, end));
                                        CtrlSetupResult::Ok
                                    }
                                    _ => CtrlSetupResult::ErrInvalidDeviceIndex,
                                },
                                DescriptorType::Configuration => {
                                    match descriptor_index {
                                        0 => {
                                            // Place all the descriptors
                                            // related to this configuration
                                            // into a buffer contiguously,
                                            // starting with the last

                                            let buf = self.descriptor_buf();
                                            let mut storage_avail = buf.len();

                                            let di = InterfaceDescriptor::default();
                                            storage_avail -=
                                                di.write_to(&buf[storage_avail - di.size()..]);

                                            let dc = ConfigurationDescriptor {
                                                num_interfaces: 1,
                                                related_descriptor_length: di.size(),
                                                ..Default::default()
                                            };
                                            storage_avail -=
                                                dc.write_to(&buf[storage_avail - dc.size()..]);

                                            let request_start = storage_avail;
                                            let request_end = min(
                                                request_start + (requested_length as usize),
                                                buf.len(),
                                            );
                                            self.state
                                                .set(State::CtrlIn(request_start, request_end));
                                            CtrlSetupResult::Ok
                                        }
                                        _ => CtrlSetupResult::ErrInvalidConfigurationIndex,
                                    }
                                }
                                DescriptorType::String => {
                                    if let Some(buf) = match descriptor_index {
                                        0 => {
                                            let buf = self.descriptor_buf();
                                            let d = LanguagesDescriptor { langs: LANGUAGES };
                                            let len = d.write_to(buf);
                                            let end = min(len, requested_length as usize);
                                            Some(&buf[..end])
                                        }
                                        i if i > 0 && (i as usize) <= STRINGS.len()
                                            && lang_id == LANGUAGES[0] =>
                                        {
                                            let buf = self.descriptor_buf();
                                            let d = StringDescriptor {
                                                string: STRINGS[i as usize - 1],
                                            };
                                            let len = d.write_to(buf);
                                            let end = min(len, requested_length as usize);
                                            Some(&buf[..end])
                                        }
                                        _ => None,
                                    } {
                                        self.state.set(State::CtrlIn(0, buf.len()));
                                        CtrlSetupResult::Ok
                                    } else {
                                        CtrlSetupResult::ErrInvalidStringIndex
                                    }
                                }
                                DescriptorType::DeviceQualifier => {
                                    // We are full-speed only, so we must
                                    // respond with a request error
                                    CtrlSetupResult::ErrNoDeviceQualifier
                                }
                                _ => CtrlSetupResult::ErrUnrecognizedDescriptorType,
                            } // match descriptor_type
                        }
                        StandardDeviceRequest::SetAddress { device_address } => {
                            // Load the address we've been assigned ...
                            self.controller.set_address(device_address);

                            // ... and when this request gets to the Status stage
                            // we will actually enable the address.
                            self.state.set(State::SetAddress);
                            CtrlSetupResult::Ok
                        }
                        StandardDeviceRequest::SetConfiguration { .. } => {
                            // We have been assigned a particular configuration: fine!
                            CtrlSetupResult::Ok
                        }
                        _ => CtrlSetupResult::ErrUnrecognizedRequestType,
                    }
                },
            )
        })
    }

    /// Handle a Control In transaction
    fn ctrl_in(&self) -> CtrlInResult {
        match self.state.get() {
            State::CtrlIn(start, end) => {
                let len = end.saturating_sub(start);
                if len > 0 {
                    let packet_bytes = min(8, len);
                    let packet = &self.descriptor_storage[start..start + packet_bytes];
                    let ep0_buf = self.ep0_buf();

                    // Copy a packet into the endpoint buffer
                    for (i, b) in packet.iter().enumerate() {
                        ep0_buf[i].set(b.get());
                    }

                    let start = start + packet_bytes;
                    let len = end.saturating_sub(start);
                    let transfer_complete = len == 0;

                    self.state.set(State::CtrlIn(start, end));

                    CtrlInResult::Packet(packet_bytes, transfer_complete)
                } else {
                    CtrlInResult::Packet(0, true)
                }
            }
            _ => CtrlInResult::Error,
        }
    }

    /// Handle a Control Out transaction
    fn ctrl_out(&self, packet_bytes: u32) -> CtrlOutResult {
        match self.state.get() {
            State::CtrlOut => {
                debug!("Received {} vendor control bytes", packet_bytes);
                // &self.ep0_buf()[0 .. packet_bytes as usize]
                CtrlOutResult::Ok
            }
            _ => {
                // Bad state
                CtrlOutResult::Halted
            }
        }
    }

    fn ctrl_status(&self) {
        // Entered Status stage
    }

    /// Handle the completion of a Control transfer
    fn ctrl_status_complete(&self) {
        // Control Read: IN request acknowledged
        // Control Write: status sent

        match self.state.get() {
            State::SetAddress => {
                self.controller.enable_address();
            }
            _ => {}
        };
        self.state.set(State::Init);
    }
}