aboutsummaryrefslogtreecommitdiffstats
path: root/usbh/src/device.rs
blob: aba3919ebca458ca725a7d85b216555c3bd5f364 (plain)
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
use super::pipe::{PipeErr, PipeTable, NO_DATA_STAGE};
use super::usbproto::*;

use core::convert::TryInto;
use log::{debug, error, info, trace};

// TODO: impl Drop for Device/Endpoint cleanup if any ends up being
// required.

// FIXME: once again, this doesn't belong here. The issue is that
// we're using `pipe_for`, which requires it.
use atsamd_hal::target_device::usb;

const MAX_DEVICES: usize = 16;

// TODO:
// This may be wrong. It may be 15 additional input + 15 additional
// output! cf §5.3.1.2 of USB 2.0.
const MAX_ENDPOINTS: usize = 16;

// How long to wait before talking to the device again after setting
// its address. cf §9.2.6.3 of USB 2.0
const SETTLE_DELAY: usize = 2;

#[derive(Copy, Clone, Debug, PartialEq)]
pub(crate) enum Error {
    PipeErr(PipeErr),
}
impl From<PipeErr> for Error {
    fn from(e: PipeErr) -> Self {
        Self::PipeErr(e)
    }
}

enum FSM {
    AddressSet,
    WaitForSettle(usize),
    GetConfigDescriptor,
    SetConfig,
    GetReport(usize),
    Steady,
}

pub(crate) struct DeviceTable {
    devices: [Option<Device>; MAX_DEVICES],
}
// TODO: Untie device address from table index. Right now it's wasting
// a table slot because addr 0 isn't used here. And rather than just
// putting in an offset, which can be forgotten, it's better to let
// something else handle address assignment.
impl DeviceTable {
    pub(crate) fn new<F>(millis: &'static F) -> Self
    where
        F: Fn() -> usize + 'static,
    {
        let mut devices: [Option<Device>; MAX_DEVICES] = {
            let mut devs: [core::mem::MaybeUninit<Option<Device>>; MAX_DEVICES] =
                unsafe { core::mem::MaybeUninit::uninit().assume_init() };
            for d in &mut devs[..] {
                unsafe { core::ptr::write(d.as_mut_ptr(), None) }
            }
            unsafe { core::mem::transmute(devs) }
        };
        devices[0] = Some(Device::new(0, 8, millis));
        Self { devices: devices }
    }

    /// Return the device at address `addr`.
    pub(crate) fn device_for(&mut self, addr: u8) -> Option<&mut Device> {
        if let Some(ref mut d) = self.devices[addr as usize] {
            Some(d)
        } else {
            None
        }
    }

    /// Allocate a device with the next available address.
    // TODO: get rid of the millis argument somehow, but the device
    // does need a way of tracking time for Settle reasons.
    pub(crate) fn next(
        &mut self,
        max_packet_size: u8,
        millis: &'static dyn Fn() -> usize,
    ) -> Option<&mut Device> {
        for i in 1..self.devices.len() {
            if self.devices[i].is_none() {
                let a = i.try_into().unwrap();
                let d = Device::new(a, max_packet_size, millis);
                self.devices[i] = Some(d);
                return self.device_for(a);
            }
        }
        None
    }

    /// Remove the device at address `addr`.
    pub(crate) fn remove(&mut self, addr: u8) -> Option<Device> {
        let v = core::mem::replace(&mut self.devices[addr as usize], None);
        v
    }

    pub(crate) fn run(&mut self, pipe_table: &mut PipeTable, host: &mut usb::HOST) {
        for i in 1..self.devices.len() {
            // TODO: Woof, this is ugly, but I'm not sure of a better
            // way to avoid mutably borrowing self twice.
            let mut remove_addr: Option<u8> = None;
            if let Some(ref mut d) = self.devices[i] {
                if let Err(e) = d.fsm(pipe_table, host) {
                    error!("Removing device {}: {:?}", d.addr, e);
                    remove_addr = Some(d.addr);
                } else {
                    remove_addr = None;
                }
            }

            if let Some(addr) = remove_addr {
                self.remove(addr);
            }
        }
    }
}

pub struct Device {
    pub addr: u8,
    pub max_packet_size: u8,
    pub endpoints: [Option<Endpoint>; MAX_ENDPOINTS],
    pub ep0: Endpoint,

    state: FSM,
    millis: &'static dyn Fn() -> usize,
}
impl Device {
    // TODO: get max packet size from device descriptor.
    pub fn new(addr: u8, max_packet_size: u8, millis: &'static dyn Fn() -> usize) -> Self {
        // Set up endpoints array with 0 as default control endpoint.
        let endpoints: [Option<Endpoint>; MAX_ENDPOINTS] = {
            let mut eps: [core::mem::MaybeUninit<Option<Endpoint>>; MAX_ENDPOINTS] =
                unsafe { core::mem::MaybeUninit::uninit().assume_init() };
            for ep in &mut eps[..] {
                unsafe { core::ptr::write(ep.as_mut_ptr(), None) }
            }
            unsafe { core::mem::transmute(eps) }
        };

        Self {
            addr: addr,
            max_packet_size: max_packet_size,
            endpoints: endpoints,
            ep0: Endpoint::new(
                addr,
                0,
                TransferType::Control,
                TransferDirection::In,
                max_packet_size,
            ),

            state: FSM::AddressSet,

            // TODO: This doesn't belong here. Ideally the current
            // time is passed in to the FSM routine.
            millis: millis,
        }
    }
}

impl Device {
    pub(crate) fn fsm(
        &mut self,
        pipe_table: &mut PipeTable,
        host: &mut usb::HOST,
    ) -> Result<(), Error> {
        match self.state {
            FSM::AddressSet => self.state = FSM::WaitForSettle((self.millis)() + SETTLE_DELAY),

            FSM::WaitForSettle(until) => {
                if (self.millis)() >= until {
                    // Dunno why we get the device descriptor a second time.
                    let mut pipe = pipe_table.pipe_for(host, &self.ep0);

                    let mut vol_descr =
                        ::vcell::VolatileCell::<DeviceDescriptor>::new(Default::default());
                    pipe.control_transfer(
                        &mut self.ep0,
                        RequestType::get_descr(),
                        RequestCode::GetDescriptor,
                        WValue::from((0, DescriptorType::Device as u8)),
                        0,
                        Some(&mut vol_descr),
                        self.millis,
                    )?;

                    let desc = vol_descr.get();
                    trace!(" -- devDesc: {:?}", desc);

                    self.state = FSM::GetConfigDescriptor
                }
            }

            FSM::GetConfigDescriptor => {
                // Get config descriptor with minimal data, to see how much we need to allocate for the full descriptor.
                let mut pipe = pipe_table.pipe_for(host, &self.ep0);

                let mut vol_descr =
                    ::vcell::VolatileCell::<ConfigurationDescriptor>::new(Default::default());
                pipe.control_transfer(
                    &mut self.ep0,
                    RequestType::get_descr(),
                    RequestCode::GetDescriptor,
                    WValue::from((0, DescriptorType::Configuration as u8)),
                    0,
                    Some(&mut vol_descr),
                    self.millis,
                )?;
                let desc = vol_descr.get();
                debug!("config: {:?}", desc);

                // TODO: do real allocation later.
                assert!(desc.w_total_length < 64);
                let buf: [u8; 64] = [0; 64];
                let mut tmp = &buf[..desc.w_total_length as usize];
                pipe.control_transfer(
                    &mut self.ep0,
                    RequestType::get_descr(),
                    RequestCode::GetDescriptor,
                    WValue::from((0, DescriptorType::Configuration as u8)),
                    0,
                    Some(&mut tmp),
                    self.millis,
                )?;

                self.state = FSM::SetConfig
            }

            FSM::SetConfig => {
                let mut pipe = pipe_table.pipe_for(host, &self.ep0);

                debug!("+++ setting configuration");
                let conf: u8 = 1;
                pipe.control_transfer(
                    &mut self.ep0,
                    RequestType::set(),
                    RequestCode::SetConfiguration,
                    WValue::from((conf, 0)),
                    0,
                    NO_DATA_STAGE,
                    self.millis,
                )?;
                debug!(" -- configuration set");

                debug!("+++ setting idle");
                pipe.control_transfer(
                    &mut self.ep0,
                    RequestType::from((
                        RequestDirection::HostToDevice,
                        RequestKind::Class,
                        RequestRecipient::Interface,
                    )),
                    RequestCode::GetInterface, // This is also idle, but can't have two enums with the same value.
                    WValue::from((0, 0)),
                    0,
                    NO_DATA_STAGE,
                    self.millis,
                )?;
                debug!(" -- idle set");

                debug!("+++ setting report");
                let mut report: u8 = 0;
                pipe.control_transfer(
                    &mut self.ep0,
                    RequestType::from((
                        RequestDirection::HostToDevice,
                        RequestKind::Class,
                        RequestRecipient::Interface,
                    )),
                    RequestCode::SetConfiguration,
                    WValue::from((0, 2)),
                    0,
                    Some(&mut report),
                    self.millis,
                )?;
                debug!(" -- report set");

                // Stub in some endpoints until we can parse the
                // configuration descriptor.
                self.endpoints[1] = Some(Endpoint::new(
                    self.addr,
                    1,
                    TransferType::Interrupt,
                    TransferDirection::In,
                    8,
                ));
                self.endpoints[2] = Some(Endpoint::new(
                    self.addr,
                    2,
                    TransferType::Interrupt,
                    TransferDirection::In,
                    8,
                ));
                self.state = FSM::GetReport(2)
            }

            FSM::GetReport(0) => self.state = FSM::Steady,

            FSM::GetReport(count) => {
                info!("+++ getting report {}", count);

                // For now, just do an IN transfer to see if we can
                // get some keyboard reports without further setup.

                // EP 1 is boot proto keyboard.
                self.read_report(pipe_table, host, 1);

                // EP 2 is consumer control keys.
                self.read_report(pipe_table, host, 2);

                self.state = FSM::GetReport(count)
            }

            FSM::Steady => {}
        }
        Ok(())
    }

    fn read_report(&mut self, pipe_table: &mut PipeTable, host: &mut usb::HOST, id: u8) {
        if let Some(ref mut ep) = self.endpoints[id as usize] {
            let mut pipe = pipe_table.pipe_for(host, ep);
            let mut buf: core::mem::MaybeUninit<[u8; 8]> = core::mem::MaybeUninit::uninit();
            match pipe.in_transfer(ep, &mut buf, 15, self.millis) {
                Ok(bytes_received) => {
                    let tmp = unsafe { &(buf.assume_init())[..bytes_received] };
                    info!("report {}: {:?}", id, tmp);
                }

                Err(e) => trace!("error {}: {:?}", id, e),
            }
        } else {
            error!("endpoint {} doesn't exist!", id)
        }
    }
}

// TransferType (INTERRUPT)
// Direction (IN)
pub struct Endpoint {
    // This just points back to the address because we need to know it
    // for all endpoint operations, but we don't want to pass the
    // address struct (which contains all endpoints) around.
    pub addr: u8,
    pub num: u8,
    pub transfer_type: TransferType,
    pub direction: TransferDirection,
    pub in_toggle: bool,
    pub out_toggle: bool,
    pub max_packet_size: u8,
}

// cf §9.6.6 of USB 2.0
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum TransferDirection {
    Out,
    In,
}

// ibid
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum TransferType {
    Control = 0,
    Isochronous = 1,
    Bulk = 2,
    Interrupt = 3,
}

impl Endpoint {
    // TODO: direction is ignored on control endpoints. Try to remove
    // it from the API in those cases as well.
    pub fn new(
        addr: u8,
        num: u8,
        transfer_type: TransferType,
        direction: TransferDirection,
        max_packet_size: u8,
    ) -> Self {
        Self {
            addr: addr,
            num: num,
            transfer_type: transfer_type,
            direction: direction,
            in_toggle: false,
            out_toggle: false,
            max_packet_size: max_packet_size,
        }
    }
}