aboutsummaryrefslogtreecommitdiffstats
path: root/usbh/src/pipe.rs
blob: 835ba8641a51e990e8f5de73bf9e145ae02fc43c (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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
pub mod addr;
pub mod ctrl_pipe;
pub mod ext_reg;
pub mod pck_size;
pub mod status_bk;
pub mod status_pipe;

use addr::Addr;
use ctrl_pipe::CtrlPipe;
use ext_reg::ExtReg;
use pck_size::PckSize;
use status_bk::StatusBk;
use status_pipe::StatusPipe;

use super::usbproto::*;

use atsamd_hal::target_device::usb::{
    self,
    host::{BINTERVAL, PCFG, PINTFLAG, PSTATUS, PSTATUSCLR, PSTATUSSET},
};
use core::convert::TryInto;
use log::{debug, trace};

// Maximum time to wait for a control request with data to finish. cf
// §9.2.6.1 of USB 2.0.
const USB_TIMEOUT: usize = 5 * 1024; // 5 Seconds

// samd21 only supports 8 pipes.
const MAX_PIPES: usize = 8;

// How many times to retry a transaction that has transient errors.
const NAK_LIMIT: usize = 15;

// For use in control requests that do not require a data stage.
pub(crate) const NO_DATA_STAGE: Option<&mut ()> = None;

#[derive(Copy, Clone, Debug, PartialEq)]
pub(crate) enum PipeErr {
    ShortPacket,
    InvalidPipe,
    InvalidToken,
    Stall,
    TransferFail,
    PipeErr,
    Flow,
    HWTimeout,
    DataToggle,
    SWTimeout,
    Other(&'static str),
}
impl From<&'static str> for PipeErr {
    fn from(v: &'static str) -> Self {
        Self::Other(v)
    }
}

pub(crate) struct PipeTable {
    tbl: [PipeDesc; MAX_PIPES],
}

impl PipeTable {
    pub(crate) fn new() -> Self {
        Self {
            tbl: [PipeDesc::new(); MAX_PIPES],
        }
    }

    pub(crate) fn pipe_for<'a, 'b>(
        &'a mut self,
        host: &'b mut usb::HOST,
        addr: u8,
        ep: u8,
    ) -> Pipe<'a, 'b> {
        // Just use two pipes for now. 0 is always for control
        // endpoints, 1 for everything else.
        //
        // TODO: cache in-use pipes and return them without init if
        // possible.
        let i = if ep == 0 { 0 } else { 1 };

        let pregs = PipeRegs::from(host, i);
        let pdesc = &mut self.tbl[i];

        trace!("setting paddr of pipe {} to {}:{}", i, addr, ep);
        pdesc.bank0.ctrl_pipe.write(|w| {
            w.pdaddr().set_addr(addr);
            w.pepnum().set_epnum(ep)
        });
        Pipe {
            num: i,
            regs: pregs,
            desc: pdesc,
        }
    }
}

// TODO: hide regs/desc fields. Needed right now for init_pipe0.
pub(crate) struct Pipe<'a, 'b> {
    num: usize,
    pub(crate) regs: PipeRegs<'b>,
    pub(crate) desc: &'a mut PipeDesc,
}
impl Pipe<'_, '_> {
    pub(crate) fn control_req<T>(
        &mut self,
        bm_request_type: RequestType,
        b_request: RequestCode,
        w_value: WValue,
        w_index: u16,
        buf: Option<&mut T>,
        millis: &dyn Fn() -> usize,
    ) -> Result<(), PipeErr> {
        // Pipe data toggles for control pipes defined in SAMD21 data
        // sheet §32.6.3.9

        let len = match buf {
            None => 0,
            _ => core::mem::size_of::<T>(),
        };

        /*
         * Setup stage.
         */
        let mut setup_packet = SetupPacket {
            bm_request_type: bm_request_type,
            b_request: b_request,
            w_value: w_value,
            w_index: w_index,
            w_length: len as u16,
        };
        self.dtgl_clear();
        self.send(
            USBToken::Setup,
            &DataBuf::from(&mut setup_packet),
            NAK_LIMIT,
            millis,
        )?;

        /*
         * Data stage.
         */
        self.dtgl_set();
        if let Some(b) = buf {
            // TODO: data stage, has up to 5,000ms (in 500ms
            // per-packet chunks) to complete. cf §9.2.6.4 of USB 2.0.
            match bm_request_type.direction()? {
                RequestDirection::DeviceToHost => {
                    self.in_transfer(b, NAK_LIMIT, millis)?;
                }

                RequestDirection::HostToDevice => {
                    debug!("Should OUT for {}b", len);
                }
            }
        }

        /*
         * Status stage.
         */
        // TODO: status stage has up to 50ms to complete. cf §9.2.6.4
        // of USB 2.0.
        self.dtgl_set();
        self.desc.bank0.pcksize.write(|w| {
            unsafe { w.byte_count().bits(0) };
            unsafe { w.multi_packet_size().bits(0) }
        });

        let token = match bm_request_type.direction()? {
            RequestDirection::DeviceToHost => USBToken::Out,
            RequestDirection::HostToDevice => USBToken::In,
        };

        trace!("dispatching status stage");
        self.dispatch_retries(token, NAK_LIMIT, millis)?;
        Ok(())
    }

    fn send(
        &mut self,
        token: USBToken,
        buf: &DataBuf,
        nak_limit: usize,
        millis: &dyn Fn() -> usize,
    ) -> Result<(), PipeErr> {
        trace!("p{}: sending {:?}", self.num, buf);

        self.desc
            .bank0
            .addr
            .write(|w| unsafe { w.addr().bits(buf.ptr as u32) });
        // configure packet size PCKSIZE.SIZE
        self.desc.bank0.pcksize.write(|w| {
            unsafe { w.byte_count().bits(buf.len as u16) };
            unsafe { w.multi_packet_size().bits(0) }
        });

        self.dispatch_retries(token, nak_limit, millis)
    }

    pub(crate) fn in_transfer<T>(
        &mut self,
        buf: &mut T,
        nak_limit: usize,
        millis: &dyn Fn() -> usize,
    ) -> Result<usize, PipeErr> {
        // TODO: pull this from pipe descriptor for this addr/ep.
        let packet_size = 8;

        let db: DataBuf = buf.into();

        trace!("p{}: Should IN for {}b.", self.num, db.len);
        self.desc.bank0.pcksize.write(|w| {
            unsafe { w.byte_count().bits(db.len as u16) };
            unsafe { w.multi_packet_size().bits(0) }
        });

        // Read until we get a short packet (indicating that there's
        // nothing left for us in this transaction) or the buffer is
        // full.
        //
        // TODO: It is sometimes valid to get a short packet when
        // variable length data is desired by the driver. cf §5.3.2 of
        // USB 2.0.
        let mut bytes_received = 0;
        while bytes_received < db.len {
            // Move the buffer pointer forward as we get data.
            self.desc
                .bank0
                .addr
                .write(|w| unsafe { w.addr().bits(db.ptr as u32 + bytes_received as u32) });
            self.regs.statusclr.write(|w| w.bk0rdy().set_bit());

            self.dispatch_retries(USBToken::In, nak_limit, millis)?;
            let recvd = self.desc.bank0.pcksize.read().byte_count().bits() as usize;
            bytes_received += recvd;
            trace!("!! read {} of {}", bytes_received, db.len);
            if recvd < packet_size {
                break;
            }

            // Don't allow writing past the buffer.
            assert!(bytes_received <= db.len);
        }
        //self.dtgl();

        self.regs.statusset.write(|w| w.pfreeze().set_bit());
        if bytes_received < db.len {
            self.log_regs();
            // TODO: honestly, this is probably a panic condition,
            // since whatever's in DataBuf.ptr is totally
            // invalid. Alternately, this function should be declared
            // `unsafe`.
            Err(PipeErr::ShortPacket)
        } else {
            Ok(bytes_received)
        }
    }

    fn dtgl_set(&mut self) {
        self.regs.statusset.write(|w| w.dtgl().set_bit());
    }

    fn dtgl_clear(&mut self) {
        self.regs.statusclr.write(|w| unsafe {
            // No function for this. FIXME: need to patch the SVD for
            // PSTATUSCLR.DTGL at bit0. No? This is in the SVD, but
            // not the rust output.
            w.bits(1)
        });
    }

    fn dtgl(&mut self) {
        // TODO: this makes no sense to me, and docs are unclear. If
        // the status bit is set, set it again? if it's clear then
        // clear it? This is what I get for having to work from
        // Arduino sources.
        trace!(
            "~~~ curbk: {}, dtgl: {}",
            self.regs.status.read().curbk().bit(),
            self.regs.status.read().dtgl().bit()
        );
        if self.regs.status.read().dtgl().bit_is_set() {
            self.dtgl_set();
        } else {
            self.dtgl_clear();
        }
    }

    // This is the only function that calls `millis`. If we can make
    // this just take the current timestamp, we can make this
    // non-blocking.
    fn dispatch_retries(
        &mut self,
        token: USBToken,
        retries: usize,
        millis: &dyn Fn() -> usize,
    ) -> Result<(), PipeErr> {
        assert!(retries > 0);

        trace!("initial regs");
        self.log_regs();

        self.dispatch_packet(token);

        let until = millis() + USB_TIMEOUT;
        let mut last_err = PipeErr::SWTimeout;
        let mut naks = 0;
        while millis() < until {
            match self.dispatch_result(token) {
                Ok(true) => return Ok(()),
                Ok(false) => continue,

                Err(e) => {
                    last_err = e;
                    match last_err {
                        PipeErr::DataToggle => self.dtgl(),
                        PipeErr::Stall => break,
                        _ => {
                            naks += 1;
                            if naks > retries {
                                break;
                            } else {
                                self.dispatch_packet(token);
                            }
                        }
                    }
                }
            }
        }

        trace!("dispatch err: {:?}", last_err);
        self.log_regs();
        Err(last_err)
    }

    fn dispatch_packet(&mut self, token: USBToken) {
        self.regs
            .cfg
            .modify(|_, w| unsafe { w.ptoken().bits(token as u8) });
        match token {
            USBToken::Setup => {
                self.regs.intflag.write(|w| w.txstp().set_bit());
                self.regs.statusset.write(|w| w.bk0rdy().set_bit());
            }
            USBToken::In => self.regs.statusclr.write(|w| w.bk0rdy().set_bit()),
            USBToken::Out => {
                self.regs.intflag.write(|w| w.trcpt0().set_bit());
                self.regs.statusset.write(|w| w.bk0rdy().set_bit());
            }
            _ => {}
        }
        self.regs.statusclr.write(|w| w.pfreeze().set_bit());
    }

    fn dispatch_result(&mut self, token: USBToken) -> Result<bool, PipeErr> {
        if self.is_transfer_complete(token)? {
            Ok(true)
        } else if self.regs.intflag.read().stall().bit_is_set() {
            self.regs.intflag.write(|w| w.stall().set_bit());
            Err(PipeErr::Stall)
        } else if self.regs.intflag.read().trfail().bit_is_set() {
            self.regs.intflag.write(|w| w.trfail().set_bit());
            Err(PipeErr::TransferFail)
        } else if self.regs.intflag.read().perr().bit_is_set() {
            self.regs.intflag.write(|w| w.perr().set_bit());
            Err(PipeErr::PipeErr)
        } else if self.desc.bank0.status_bk.read().errorflow().bit_is_set() {
            self.desc
                .bank0
                .status_bk
                .write(|w| w.errorflow().clear_bit());
            Err(PipeErr::Flow)
        } else if self.desc.bank0.status_pipe.read().touter().bit_is_set() {
            self.desc
                .bank0
                .status_pipe
                .write(|w| w.touter().clear_bit());
            Err(PipeErr::HWTimeout)
        } else if self.desc.bank0.status_pipe.read().dtgler().bit_is_set() {
            self.desc
                .bank0
                .status_pipe
                .write(|w| w.dtgler().clear_bit());
            Err(PipeErr::DataToggle)
        } else {
            // Nothing wrong, but not done yet.
            Ok(false)
        }
    }

    fn is_transfer_complete(&mut self, token: USBToken) -> Result<bool, PipeErr> {
        match token {
            USBToken::Setup => {
                if self.regs.intflag.read().txstp().bit_is_set() {
                    self.regs.intflag.write(|w| w.txstp().set_bit());
                    self.regs.statusset.write(|w| w.pfreeze().set_bit());
                    Ok(true)
                } else {
                    Ok(false)
                }
            }
            USBToken::In => {
                if self.regs.intflag.read().trcpt0().bit_is_set() {
                    self.regs.intflag.write(|w| w.trcpt0().set_bit());
                    self.regs.statusset.write(|w| w.pfreeze().set_bit());
                    Ok(true)
                } else {
                    Ok(false)
                }
            }
            USBToken::Out => {
                if self.regs.intflag.read().trcpt0().bit_is_set() {
                    self.regs.intflag.write(|w| w.trcpt0().set_bit());
                    self.regs.statusset.write(|w| w.pfreeze().set_bit());
                    Ok(true)
                } else {
                    Ok(false)
                }
            }
            _ => Err(PipeErr::InvalidToken),
        }
    }

    fn log_regs(&self) {
        // Pipe regs
        let cfg = self.regs.cfg.read().bits();
        let bin = self.regs.binterval.read().bits();
        let sts = self.regs.status.read().bits();
        let ifl = self.regs.intflag.read().bits();
        trace!(
            "p{}: cfg: {:x}, bin: {:x}, sts: {:x}, ifl: {:x}",
            self.num,
            cfg,
            bin,
            sts,
            ifl
        );

        // Pipe RAM regs
        let adr = self.desc.bank0.addr.read().bits();
        let pks = self.desc.bank0.pcksize.read().bits();
        let ext = self.desc.bank0.extreg.read().bits();
        let sbk = self.desc.bank0.status_bk.read().bits();
        let hcp = self.desc.bank0.ctrl_pipe.read().bits();
        let spi = self.desc.bank0.status_pipe.read().bits();
        trace!(
            "p{}: adr: {:x}, pks: {:x}, ext: {:x}, sbk: {:x}, hcp: {:x}, spi: {:x}",
            self.num,
            adr,
            pks,
            ext,
            sbk,
            hcp,
            spi
        );
    }
}

#[derive(Copy, Clone, Debug, PartialEq)]
pub(crate) enum USBToken {
    Setup = 0,
    In = 1,
    Out = 2,
    Reserved = 3,
}

#[derive(Copy, Clone, Debug, PartialEq)]
pub(crate) enum USBPipeType {
    Disabled = 0x0,
    Control = 0x1,
    ISO = 0x2,
    Bulk = 0x3,
    Interrupt = 0x4,
    Extended = 0x5,
    _Reserved0 = 0x06,
    _Reserved1 = 0x07,
}

pub(crate) struct DataBuf<'a> {
    pub(crate) ptr: *mut u8,
    pub(crate) len: usize,
    _marker: core::marker::PhantomData<&'a ()>,
}
impl DataBuf<'_> {}

impl core::fmt::Debug for DataBuf<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        write!(f, "DataBuf {{ len: {}, ptr: [", self.len)?;
        for i in 0..self.len {
            write!(f, " {:x}", unsafe {
                *self.ptr.offset(i.try_into().unwrap())
            })?;
        }
        write!(f, " ] }}")
    }
}

impl<'a, T> From<&'a mut T> for DataBuf<'a> {
    fn from(v: &'a mut T) -> Self {
        Self {
            ptr: v as *mut T as *mut u8,
            len: core::mem::size_of::<T>(),
            _marker: core::marker::PhantomData,
        }
    }
}

pub(crate) struct PipeRegs<'a> {
    pub(crate) cfg: &'a mut PCFG,
    pub(crate) binterval: &'a mut BINTERVAL,
    pub(crate) statusclr: &'a mut PSTATUSCLR,
    pub(crate) statusset: &'a mut PSTATUSSET,
    pub(crate) status: &'a mut PSTATUS,
    pub(crate) intflag: &'a mut PINTFLAG,
}
impl<'a> PipeRegs<'a> {
    pub(crate) fn from(host: &'a mut usb::HOST, i: usize) -> PipeRegs {
        assert!(i < MAX_PIPES);
        match i {
            0 => Self {
                cfg: &mut host.pcfg0,
                binterval: &mut host.binterval0,
                statusclr: &mut host.pstatusclr0,
                statusset: &mut host.pstatusset0,
                status: &mut host.pstatus0,
                intflag: &mut host.pintflag0,
            },
            1 => Self {
                cfg: &mut host.pcfg1,
                binterval: &mut host.binterval1,
                statusclr: &mut host.pstatusclr1,
                statusset: &mut host.pstatusset1,
                status: &mut host.pstatus1,
                intflag: &mut host.pintflag1,
            },
            2 => Self {
                cfg: &mut host.pcfg2,
                binterval: &mut host.binterval2,
                statusclr: &mut host.pstatusclr2,
                statusset: &mut host.pstatusset2,
                status: &mut host.pstatus2,
                intflag: &mut host.pintflag2,
            },
            3 => Self {
                cfg: &mut host.pcfg3,
                binterval: &mut host.binterval3,
                statusclr: &mut host.pstatusclr3,
                statusset: &mut host.pstatusset3,
                status: &mut host.pstatus3,
                intflag: &mut host.pintflag3,
            },
            4 => Self {
                cfg: &mut host.pcfg4,
                binterval: &mut host.binterval4,
                statusclr: &mut host.pstatusclr4,
                statusset: &mut host.pstatusset4,
                status: &mut host.pstatus4,
                intflag: &mut host.pintflag4,
            },
            5 => Self {
                cfg: &mut host.pcfg5,
                binterval: &mut host.binterval5,
                statusclr: &mut host.pstatusclr5,
                statusset: &mut host.pstatusset5,
                status: &mut host.pstatus5,
                intflag: &mut host.pintflag5,
            },
            6 => Self {
                cfg: &mut host.pcfg6,
                binterval: &mut host.binterval6,
                statusclr: &mut host.pstatusclr6,
                statusset: &mut host.pstatusset6,
                status: &mut host.pstatus6,
                intflag: &mut host.pintflag6,
            },
            7 => Self {
                cfg: &mut host.pcfg7,
                binterval: &mut host.binterval7,
                statusclr: &mut host.pstatusclr7,
                statusset: &mut host.pstatusset7,
                status: &mut host.pstatus7,
                intflag: &mut host.pintflag7,
            },
            _ => unreachable!(),
        }
    }
}

// §32.8.7.1
#[derive(Clone, Copy, Debug)]
pub(crate) struct PipeDesc {
    pub bank0: BankDesc,
    pub bank1: BankDesc,
}

// 2 banks: 32 bytes per pipe.
impl PipeDesc {
    pub fn new() -> Self {
        Self {
            bank0: BankDesc::new(),
            bank1: BankDesc::new(),
        }
    }
}

#[derive(Clone, Copy, Debug)]
#[repr(C)]
// 16 bytes per bank.
pub(crate) struct BankDesc {
    pub addr: Addr,
    pub pcksize: PckSize,
    pub extreg: ExtReg,
    pub status_bk: StatusBk,
    pub ctrl_pipe: CtrlPipe,
    pub status_pipe: StatusPipe,

    _reserved: u8,
}

impl BankDesc {
    fn new() -> Self {
        Self {
            addr: Addr::from(0),
            pcksize: PckSize::from(0),
            extreg: ExtReg::from(0),
            status_bk: StatusBk::from(0),
            ctrl_pipe: CtrlPipe::from(0),
            status_pipe: StatusPipe::from(0),
            _reserved: 0,
        }
    }
}