From e405c474f5e0e94288191223de7ae0f31ae0b15f Mon Sep 17 00:00:00 2001 From: Brian Cully Date: Sun, 4 Aug 2019 14:19:25 -0400 Subject: Migrate everything over to separate libraries. * `usb-host` is the crate containing the HAL traits. * `bootkbd` is a crate for a bare-bones boot protocol keyboard driver. * `samd21-host` is a crate with an implementation of `usb-host` for a SAMD21 platform, with an example for the trinket-m0 which uses the `bootkbd` driver to print keyboard reports. --- app/.cargo/config | 6 - app/Cargo.lock | 399 ----------------- app/Cargo.toml | 27 -- app/Makefile | 38 -- app/find-serial-port | 16 - app/logitech-kb-start.pcapng | Bin 8616 -> 0 bytes app/src/dotstar.rs | 42 -- app/src/logger.rs | 139 ------ app/src/macros.rs | 15 - app/src/main.rs | 227 ---------- app/src/rtc.rs | 74 ---- bootkbd/Cargo.toml | 1 - bootkbd/src/lib.rs | 40 +- samd21-host/.cargo/config | 6 + samd21-host/Cargo.lock | 358 +++++++++++++++ samd21-host/Cargo.toml | 24 + samd21-host/Makefile | 38 ++ samd21-host/examples/simple/logger.rs | 139 ++++++ samd21-host/examples/simple/macros.rs | 15 + samd21-host/examples/simple/main.rs | 192 ++++++++ samd21-host/examples/simple/rtc.rs | 74 ++++ samd21-host/find-serial-port | 16 + samd21-host/simple.bin | Bin 0 -> 123568 bytes samd21-host/simple.uf2 | Bin 0 -> 247296 bytes samd21-host/src/lib.rs | 645 +++++++++++++++++++++++++++ samd21-host/src/pipe.rs | 809 ++++++++++++++++++++++++++++++++++ samd21-host/src/pipe/addr.rs | 98 ++++ samd21-host/src/pipe/ctrl_pipe.rs | 177 ++++++++ samd21-host/src/pipe/ext_reg.rs | 156 +++++++ samd21-host/src/pipe/pck_size.rs | 368 ++++++++++++++++ samd21-host/src/pipe/status_bk.rs | 170 +++++++ samd21-host/src/pipe/status_pipe.rs | 407 +++++++++++++++++ usb-host/src/lib.rs | 38 +- usbh/Cargo.lock | 269 ----------- usbh/Cargo.toml | 16 - usbh/src/device.rs | 392 ---------------- usbh/src/lib.rs | 474 -------------------- usbh/src/pipe.rs | 800 --------------------------------- usbh/src/pipe/addr.rs | 98 ---- usbh/src/pipe/ctrl_pipe.rs | 177 -------- usbh/src/pipe/ext_reg.rs | 156 ------- usbh/src/pipe/pck_size.rs | 368 ---------------- usbh/src/pipe/status_bk.rs | 170 ------- usbh/src/pipe/status_pipe.rs | 407 ----------------- usbh/src/usbproto.rs | 438 ------------------ 45 files changed, 3739 insertions(+), 4780 deletions(-) delete mode 100644 app/.cargo/config delete mode 100644 app/Cargo.lock delete mode 100644 app/Cargo.toml delete mode 100644 app/Makefile delete mode 100755 app/find-serial-port delete mode 100644 app/logitech-kb-start.pcapng delete mode 100644 app/src/dotstar.rs delete mode 100644 app/src/logger.rs delete mode 100644 app/src/macros.rs delete mode 100755 app/src/main.rs delete mode 100644 app/src/rtc.rs mode change 100644 => 100755 bootkbd/src/lib.rs create mode 100644 samd21-host/.cargo/config create mode 100644 samd21-host/Cargo.lock create mode 100644 samd21-host/Cargo.toml create mode 100644 samd21-host/Makefile create mode 100644 samd21-host/examples/simple/logger.rs create mode 100644 samd21-host/examples/simple/macros.rs create mode 100755 samd21-host/examples/simple/main.rs create mode 100644 samd21-host/examples/simple/rtc.rs create mode 100755 samd21-host/find-serial-port create mode 100755 samd21-host/simple.bin create mode 100644 samd21-host/simple.uf2 create mode 100755 samd21-host/src/lib.rs create mode 100644 samd21-host/src/pipe.rs create mode 100644 samd21-host/src/pipe/addr.rs create mode 100644 samd21-host/src/pipe/ctrl_pipe.rs create mode 100644 samd21-host/src/pipe/ext_reg.rs create mode 100644 samd21-host/src/pipe/pck_size.rs create mode 100644 samd21-host/src/pipe/status_bk.rs create mode 100644 samd21-host/src/pipe/status_pipe.rs mode change 100644 => 100755 usb-host/src/lib.rs delete mode 100644 usbh/Cargo.lock delete mode 100644 usbh/Cargo.toml delete mode 100644 usbh/src/device.rs delete mode 100755 usbh/src/lib.rs delete mode 100644 usbh/src/pipe.rs delete mode 100644 usbh/src/pipe/addr.rs delete mode 100644 usbh/src/pipe/ctrl_pipe.rs delete mode 100644 usbh/src/pipe/ext_reg.rs delete mode 100644 usbh/src/pipe/pck_size.rs delete mode 100644 usbh/src/pipe/status_bk.rs delete mode 100644 usbh/src/pipe/status_pipe.rs delete mode 100644 usbh/src/usbproto.rs diff --git a/app/.cargo/config b/app/.cargo/config deleted file mode 100644 index b6cdff0..0000000 --- a/app/.cargo/config +++ /dev/null @@ -1,6 +0,0 @@ -[build] -target = "thumbv6m-none-eabi" - -[target.thumbv6m-none-eabi] -rustflags = ["-C", "link-arg=-Tlink.x"] -runner = "qemu-system-arm -pidfile qemu.pid -cpu cortex-m0 -machine lm3s6965evb -nographic -semihosting-config enable=on,target=native -gdb tcp::3333 -S -kernel" diff --git a/app/Cargo.lock b/app/Cargo.lock deleted file mode 100644 index 599825f..0000000 --- a/app/Cargo.lock +++ /dev/null @@ -1,399 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -[[package]] -name = "aligned" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "aligned" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "as-slice 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "apa102-spi" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "smart-leds-trait 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "as-slice" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "generic-array 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)", - "stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "atsamd-hal" -version = "0.5.0" -dependencies = [ - "atsamd21e18a 0.4.0", - "bitfield 0.13.2 (registry+https://github.com/rust-lang/crates.io-index)", - "cortex-m 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)", - "embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "paste 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", - "vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "atsamd21e18a" -version = "0.4.0" -dependencies = [ - "bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", - "cortex-m 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)", - "cortex-m-rt 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)", - "vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "bare-metal" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "bitfield" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "cfg-if" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "clint" -version = "0.2.0" -dependencies = [ - "cortex-m 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "cortex-m" -version = "0.5.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "aligned 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", - "cortex-m 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", - "volatile-register 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "cortex-m" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "aligned 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", - "bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", - "volatile-register 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "cortex-m-rt" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cortex-m-rt-macros 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", - "r0 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "cortex-m-rt-macros" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)", - "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 0.15.38 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "embedded-hal" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "generic-array" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "typenum 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "log" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "nb" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "panic-halt" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "paste" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "paste-impl 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", - "proc-macro-hack 0.5.7 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "paste-impl" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro-hack 0.5.7 (registry+https://github.com/rust-lang/crates.io-index)", - "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 0.15.38 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "proc-macro-hack" -version = "0.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 0.15.38 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "proc-macro2" -version = "0.4.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "quote" -version = "0.6.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "r0" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "rand" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "rand_core" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "rand_core" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "rb" -version = "0.1.0" - -[[package]] -name = "rgb" -version = "0.8.13" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "rustc_version" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "samd21-demo" -version = "0.1.0" -dependencies = [ - "apa102-spi 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "clint 0.2.0", - "cortex-m 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", - "cortex-m-rt 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)", - "embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.7 (registry+https://github.com/rust-lang/crates.io-index)", - "nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "panic-halt 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "rb 0.1.0", - "smart-leds 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "smart-leds-trait 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "trinket_m0 0.3.0", - "usbh 0.1.0", -] - -[[package]] -name = "semver" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "semver-parser" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "smart-leds" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "smart-leds-trait 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "smart-leds-trait" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "rgb 0.8.13 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "stable_deref_trait" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "syn" -version = "0.15.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "trinket_m0" -version = "0.3.0" -dependencies = [ - "atsamd-hal 0.5.0", - "cortex-m 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)", - "cortex-m-rt 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)", - "embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "typenum" -version = "1.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "unicode-xid" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "usbh" -version = "0.1.0" -dependencies = [ - "atsamd-hal 0.5.0", - "embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.7 (registry+https://github.com/rust-lang/crates.io-index)", - "rb 0.1.0", - "vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "vcell" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "void" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "volatile-register" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[metadata] -"checksum aligned 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d39da9b88ae1a81c03c9c082b8db83f1d0e93914126041962af61034ab44c4a5" -"checksum aligned 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d3a316c7ea8e1e9ece54862c992def5a7ac14de9f5832b69d71760680efeeefa" -"checksum apa102-spi 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "244c305e53cabeadfce23409fe24bfcedaa20166aa3f16f6c4ab256302158fd5" -"checksum as-slice 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "293dac66b274fab06f95e7efb05ec439a6b70136081ea522d270bc351ae5bb27" -"checksum bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "a3caf393d93b2d453e80638d0674597020cef3382ada454faacd43d1a55a735a" -"checksum bitfield 0.13.2 (registry+https://github.com/rust-lang/crates.io-index)" = "46afbd2983a5d5a7bd740ccb198caf5b82f45c40c09c0eed36052d91cb92e719" -"checksum cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "b486ce3ccf7ffd79fdeb678eac06a9e6c09fc88d33836340becb8fffe87c5e33" -"checksum cortex-m 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)" = "3c0b159a1e8306949579de3698c841dba58058197b65c60807194e4fa1e7a554" -"checksum cortex-m 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f3c18719fdc57db65668bfc977db9a0fa1a41d718c5d9cd4f652c9d4b0e0956a" -"checksum cortex-m-rt 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)" = "7e1ccc9052352415ec4e3f762f4541098d012016f9354a1a5b2dede39b67f426" -"checksum cortex-m-rt-macros 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "d7ae692573e0acccb1579fef1abf5a5bf1d2f3f0149a22b16870ec9309aee25f" -"checksum embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ee4908a155094da7723c2d60d617b820061e3b4efcc3d9e293d206a5a76c170b" -"checksum generic-array 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)" = "c68f0274ae0e023facc3c97b2e00f076be70e254bc851d972503b328db79b2ec" -"checksum log 0.4.7 (registry+https://github.com/rust-lang/crates.io-index)" = "c275b6ad54070ac2d665eef9197db647b32239c9d244bfb6f041a766d00da5b3" -"checksum nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "b1411551beb3c11dedfb0a90a0fa256b47d28b9ec2cdff34c25a2fa59e45dbdc" -"checksum panic-halt 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "de96540e0ebde571dc55c73d60ef407c653844e6f9a1e2fdbd40c07b9252d812" -"checksum paste 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "1f4a4a1c555c6505821f9d58b8779d0f630a6b7e4e1be24ba718610acf01fa79" -"checksum paste-impl 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "26e796e623b8b257215f27e6c80a5478856cae305f5b59810ff9acdaa34570e6" -"checksum proc-macro-hack 0.5.7 (registry+https://github.com/rust-lang/crates.io-index)" = "0c1dd4172a1e1f96f709341418f49b11ea6c2d95d53dca08c0f74cbd332d9cf3" -"checksum proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)" = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" -"checksum quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)" = "faf4799c5d274f3868a4aae320a0a182cbd2baee377b378f080e16a23e9d80db" -"checksum r0 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e2a38df5b15c8d5c7e8654189744d8e396bddc18ad48041a500ce52d6948941f" -"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" -"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" -"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" -"checksum rgb 0.8.13 (registry+https://github.com/rust-lang/crates.io-index)" = "4f089652ca87f5a82a62935ec6172a534066c7b97be003cc8f702ee9a7a59c92" -"checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" -"checksum semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" -"checksum semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" -"checksum smart-leds 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ab0a30e934e60850bfc020d4c2727cc8a3635371f6af2cb3f55f36f0134ed080" -"checksum smart-leds-trait 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fef18e60d41a6fde19e640cd7590c03fb27aa23146bf60e4da85028d7410cee7" -"checksum stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8" -"checksum syn 0.15.38 (registry+https://github.com/rust-lang/crates.io-index)" = "37ea458a750f59ab679b47fef9b6722c586c5742f4cfe18a120bbc807e5e01fd" -"checksum typenum 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "612d636f949607bdf9b123b4a6f6d966dedf3ff669f7f045890d3a4a73948169" -"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" -"checksum vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "45c297f0afb6928cd08ab1ff9d95e99392595ea25ae1b5ecf822ff8764e57a0d" -"checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" -"checksum volatile-register 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0d67cb4616d99b940db1d6bd28844ff97108b498a6ca850e5b6191a532063286" diff --git a/app/Cargo.toml b/app/Cargo.toml deleted file mode 100644 index 1bf5ab8..0000000 --- a/app/Cargo.toml +++ /dev/null @@ -1,27 +0,0 @@ -[package] -name = "samd21-demo" -version = "0.1.0" -authors = ["Brian Cully "] -edition = "2018" -readme = "../README.md" -license = "GPL-3.0-or-later" - -[dependencies] -rb = { path = "../rb" } -usbh = { path = "../usbh" } - -trinket_m0 = { path = "../../atsamd/boards/trinket_m0" } -clint = { path = "../../clint" } - -panic-halt = "~0.2" -smart-leds = "~0.2" -smart-leds-trait = "~0.2" -apa102-spi = "~0.2" # DotStar driver. -nb = "~0.1" -cortex-m = "~0.6" -cortex-m-rt = "~0.6" -embedded-hal = "~0.2" -log = { version = "~0.4", features = ["max_level_trace", "release_max_level_warn"] } - -[features] -default = ["cortex-m/const-fn"] diff --git a/app/Makefile b/app/Makefile deleted file mode 100644 index a5ef39f..0000000 --- a/app/Makefile +++ /dev/null @@ -1,38 +0,0 @@ -APP = samd21-demo - -USBVID = 239a -USBPID = '001e|801e' - -BOSSAC = bossac -SERIAL = $(shell ./find-serial-port $(USBVID) $(USBPID) || echo 'cant-find-serial-port') -OFFSET = 0x2000 - -.PHONY: all clean cargo-build - -all: $(APP).uf2 - -clean: - rm -f $(APP).uf2 - rm -f $(APP).bin - cargo clean - -cargo-build: - cargo build - -target/thumbv6m-none-eabi/debug/$(APP): cargo-build - -$(APP).bin: target/thumbv6m-none-eabi/debug/$(APP) - cargo objcopy --bin $(APP) -- -O binary $(APP).bin - -# Requires https://github.com/sajattack/uf2conv-rs.git -%.uf2: %.bin - uf2conv-rs $< --base $(OFFSET) --output $@ - -flash: $(APP).bin $(SERIAL) - $(BOSSAC) -R -e -w -v -o$(OFFSET) -p$(SERIAL) $< - -qemu: target/thumbv6m-none-eabi/debug/$(APP) - qemu-system-arm -d in_asm,int,exec,cpu,guest_errors,unimp -pidfile qemu.pid -cpu cortex-m0 -machine lm3s6965evb -nographic -semihosting-config enable=on,target=native -s -S -kernel $< - -gdb: target/thumbv6m-none-eabi/debug/$(APP) - gdb-multiarch -ex "target remote localhost:1234" -ex "break main" -ex "continue" $< diff --git a/app/find-serial-port b/app/find-serial-port deleted file mode 100755 index 62e2c0c..0000000 --- a/app/find-serial-port +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/sh - -if [ $# -ne 2 ]; then - echo "Usage: $0 vid pid" >&2 - exit 1 -fi - -prefix=/dev/serial/by-id - -for dev in `ls $prefix`; do - if [ `udevadm info -q property --name $prefix/$dev | egrep -i "ID_VENDOR_ID=($1)|ID_MODEL_ID=($2)" | wc -l` -eq 2 ]; then - echo `readlink -f $prefix/$dev` - exit 0 - fi -done -exit 2 diff --git a/app/logitech-kb-start.pcapng b/app/logitech-kb-start.pcapng deleted file mode 100644 index ab22fd0..0000000 Binary files a/app/logitech-kb-start.pcapng and /dev/null differ diff --git a/app/src/dotstar.rs b/app/src/dotstar.rs deleted file mode 100644 index 8e930d0..0000000 --- a/app/src/dotstar.rs +++ /dev/null @@ -1,42 +0,0 @@ -use trinket_m0::{ - clock::GenericClockController, - gpio::{self, Floating, Input}, - prelude::*, - sercom::{self, PadPin, SPIMaster1}, - PM, SERCOM1, -}; - -use apa102_spi::Apa102; - -pub fn new( - sercom: SERCOM1, - miso: gpio::Pa31>, - mosi: gpio::Pa0>, - sck: gpio::Pa1>, - port: &mut gpio::Port, - pm: &mut PM, - clocks: &mut GenericClockController, -) -> Apa102< - SPIMaster1< - sercom::Sercom1Pad3>, - sercom::Sercom1Pad0>, - sercom::Sercom1Pad1>, - >, -> { - let gclk = clocks.gclk0(); - let miso = miso.into_pad(port); - let mosi = mosi.into_pad(port); - let sck = sck.into_pad(port); - let spi = SPIMaster1::new( - &clocks - .sercom1_core(&gclk) - .expect("setting up sercom1 clock"), - 3.mhz(), - apa102_spi::MODE, - sercom, - pm, - (miso, mosi, sck), - ); - - Apa102::new(spi) -} diff --git a/app/src/logger.rs b/app/src/logger.rs deleted file mode 100644 index 9f9452e..0000000 --- a/app/src/logger.rs +++ /dev/null @@ -1,139 +0,0 @@ -use crate::rtc; -use rb::{Reader, RingBuffer, Writer}; - -use core::cell::UnsafeCell; -use core::fmt::{self, Write}; -use embedded_hal::{digital::v2::OutputPin, serial}; -use log::{Metadata, Record}; -use trinket_m0::{ - gpio::{Pa6, Pa7, PfD}, - sercom::{Sercom0Pad2, Sercom0Pad3, UART0}, -}; - -static mut UART0: usize = 0; - -struct JoinedRingBuffer<'a> { - lbr: Reader<'a, u8>, - lbw: Writer<'a, u8>, -} - -impl<'a> JoinedRingBuffer<'a> { - const fn new(rb: &'a RingBuffer) -> Self { - let (lbr, lbw) = rb.split(); - Self { lbr: lbr, lbw: lbw } - } -} - -impl fmt::Write for JoinedRingBuffer<'_> { - fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { - for b in s.bytes() { - if let Err(_) = self.lbw.unshift(b) { - // Ignore buffer full errors for logging. - return Ok(()); - } - } - Ok(()) - } -} - -static mut LB: RingBuffer = RingBuffer::::new(0); -static mut JRB: JoinedRingBuffer = unsafe { JoinedRingBuffer::new(&LB) }; - -// The UART isn't necessarily Sync, so wrap it in something that -// is. As long as flush() is only called from one thread, we're fine, -// but this is a guarantee that the logger module doesn't make. -pub struct WriteWrapper { - w: W, -} -impl WriteWrapper -where - W: serial::Write, -{ - pub const fn new(writer: W) -> Self { - Self { w: writer } - } -} -unsafe impl Sync for WriteWrapper {} - -pub struct SerialLogger { - writer: UnsafeCell>, - led: UnsafeCell, -} - -impl SerialLogger -where - W: serial::Write, - L: OutputPin + Send + Sync, -{ - pub fn new(writer: WriteWrapper, led: L) -> Self { - // Stash this for unsafe usage in case there's an issue with - // the rest of the logging. - unsafe { UART0 = core::mem::transmute(&writer.w) }; - Self { - writer: UnsafeCell::new(writer), - led: UnsafeCell::new(led), - } - } -} -unsafe impl Send for SerialLogger {} -unsafe impl Sync for SerialLogger {} - -impl log::Log for SerialLogger -where - W: serial::Write, - L: OutputPin + Send + Sync, -{ - fn enabled(&self, metadata: &Metadata) -> bool { - metadata.level() <= log::max_level() - } - - fn log(&self, record: &Record) { - if !self.enabled(record.metadata()) { - return; - } - - let jrb = unsafe { &mut JRB }; - write!( - jrb, - "[{}] {} {} -- {}\r\n", - rtc::millis(), - record.level(), - record.target(), - record.args() - ) - .ok(); - } - - fn flush(&self) { - // Unsafe due to mutable static. We can only deal with the - // tail position of the buffer here to keep things safe. - let jrb = unsafe { &mut JRB }; - if jrb.lbr.is_empty() { - return; - } - - let led = unsafe { &mut (*self.led.get()) }; - let writer = unsafe { &mut (*self.writer.get()) }; - - led.set_high().ok(); - while let Some(b) = jrb.lbr.shift() { - nb::block!(writer.w.write(b)).ok(); - } - led.set_low().ok(); - } -} - -// Write to the UART right now, instead of putting it on a ring -// buffer. This function is a huge hack, and only useful for debugging -// either before the main loop starts or if the ring buffer is broken. -pub unsafe fn write_fmt_now(args: fmt::Arguments, nl: bool) { - if UART0 == 0 { - return; - } - let uart: &mut UART0>, Sercom0Pad2>, (), ()> = - core::mem::transmute(UART0); - fmt::write(uart, args).expect("writing fmt now to uart"); - if nl { - uart.write_str("\r\n").expect("writing nl now to uart"); - } -} diff --git a/app/src/macros.rs b/app/src/macros.rs deleted file mode 100644 index 46d2d07..0000000 --- a/app/src/macros.rs +++ /dev/null @@ -1,15 +0,0 @@ -#[macro_export] -macro_rules! logln_now { - ($($arg:tt)*) => { - unsafe {crate::logger::write_fmt_now(format_args!($($arg)*), true);} - }; - (_) => {}; -} - -#[macro_export] -macro_rules! log_now { - ($($arg:tt)*) => { - unsafe {crate::logger::write_fmt_now(format_args!($($arg)*), false);} - }; - (_) => {}; -} diff --git a/app/src/main.rs b/app/src/main.rs deleted file mode 100755 index 1f8805b..0000000 --- a/app/src/main.rs +++ /dev/null @@ -1,227 +0,0 @@ -#![no_std] -#![no_main] -#![feature(const_fn)] -#![feature(const_transmute)] -#![allow(dead_code)] - -mod dotstar; -mod logger; -mod macros; -mod rtc; - -//#[allow(unused)] -//use panic_halt; - -use clint::HandlerArray; -use cortex_m::asm::wfi; -use cortex_m_rt::{entry, exception, ExceptionFrame}; -use embedded_hal::digital::v2::OutputPin; -use log::{debug, info, LevelFilter}; -use smart_leds::colors; -use smart_leds_trait::SmartLedsWrite; -use trinket_m0::{ - self as hal, - clock::GenericClockController, - gpio::{OpenDrain, Output, Pa10, Pa6, Pa7, PfD}, - sercom, - target_device::{interrupt, Interrupt}, - time::*, - CorePeripherals, Peripherals, -}; -use usbh::USBHost; - -static HANDLERS: HandlerArray = HandlerArray::new(); - -static mut LED: usize = 0; - -#[entry] -fn main() -> ! { - let mut peripherals = Peripherals::take().expect("taking peripherals"); - let mut core = CorePeripherals::take().expect("taking core peripherals"); - - let mut clocks = GenericClockController::with_internal_32kosc( - peripherals.GCLK, - &mut peripherals.PM, - &mut peripherals.SYSCTRL, - &mut peripherals.NVMCTRL, - ); - - let mut pins = hal::Pins::new(peripherals.PORT); - - let uart = hal::uart( - &mut clocks, - 115_200.hz(), - peripherals.SERCOM0, - &mut core.NVIC, - &mut peripherals.PM, - pins.d3, - pins.d4, - &mut pins.port, - ); - - let mut red_led = pins.d13.into_open_drain_output(&mut pins.port); - red_led.set_low().expect("turning off red LED"); - unsafe { LED = core::mem::transmute(&red_led) } - - // We do the transmute because, while all the underlying data is - // static, we're unable to get a referecence to the UART or LED - // until run-time. Another option would be to use Option in the - // SerialLogger definition, but that requires a check every time - // they might be used. - let uart_wrapped = logger::WriteWrapper::new(uart); - let logger = logger::SerialLogger::new(uart_wrapped, red_led); - - // Wow, would I love to not be annotating this type. - let logger_ref: &'static logger::SerialLogger< - sercom::UART0>, sercom::Sercom0Pad2>, (), ()>, - Pa10>, - > = unsafe { core::mem::transmute(&logger) }; - unsafe { log::set_logger_racy(logger_ref).expect("couldn't set logger") }; - log::set_max_level(LevelFilter::Info); - - info!("setting up dotstar"); - - let mut dotstar = dotstar::new( - peripherals.SERCOM1, - pins.swdio, - pins.dotstar_di, - pins.dotstar_ci, - &mut pins.port, - &mut peripherals.PM, - &mut clocks, - ); - - let black = [colors::BLACK]; - let blue = [colors::DARK_MAGENTA]; - - info!("setting up timer"); - let mut rtc_handler = rtc::setup(peripherals.RTC, &mut clocks); - - info!("setting up usb host"); - let (mut usb_host, mut usb_handler) = USBHost::new( - peripherals.USB, - pins.usb_sof, - pins.usb_dm, - pins.usb_dp, - Some(pins.usb_host_enable), - &mut pins.port, - &mut clocks, - &mut peripherals.PM, - &rtc::millis, - ); - - info!("setting up handlers"); - HANDLERS.with_overrides(|hs| { - hs.register(0, &mut rtc_handler); - core.NVIC.enable(Interrupt::RTC); - - hs.register(1, &mut usb_handler); - unsafe { core.NVIC.set_priority(Interrupt::USB, 0) }; - core.NVIC.enable(Interrupt::USB); - - info!("Boot up complete."); - - let mut last_tick = 0; - loop { - cortex_m::interrupt::free(|_cs| { - dotstar - .write(black.iter().cloned()) - .expect("turning off dotstar"); - }); - - let tick = rtc::millis(); - if tick >= last_tick + 1_024 { - last_tick = tick; - // trace!("{}: tick\r\n", rtc::millis()); - } - - usb_host.task(); - - cortex_m::interrupt::free(|_cs| { - dotstar - .write(blue.iter().cloned()) - .expect("turning on dotstar"); - }); - wfi(); - } - }); - unreachable!(); -} - -#[panic_handler] -fn panic_handler(pi: &core::panic::PanicInfo) -> ! { - let red_led: &mut Pa10> = unsafe { core::mem::transmute(LED) }; - red_led.set_high().ok(); - - logln_now!("~~~ PANIC ~~~"); - logln_now!("{}", pi); - logln_now!("flushing log"); - loop { - log::logger().flush(); - wfi() - } -} - -#[exception] -fn HardFault(ef: &ExceptionFrame) -> ! { - let red_led: &mut Pa10> = unsafe { core::mem::transmute(LED) }; - red_led.set_high().ok(); - - log::logger().flush(); - logln_now!("!!! Hard Fault - ef: {:?} !!!", ef); - logln_now!("flushing log"); - loop { - log::logger().flush(); - wfi() - } -} - -#[exception] -fn DefaultHandler(interrupt: i16) { - let red_led: &mut Pa10> = unsafe { core::mem::transmute(LED) }; - red_led.set_high().ok(); - - debug!("*** Default Handler: {} ***", interrupt); -} - -#[exception] -fn NonMaskableInt() { - let red_led: &mut Pa10> = unsafe { core::mem::transmute(LED) }; - red_led.set_high().ok(); - - debug!("+++ NonMaskableInt +++"); -} - -#[exception] -fn SVCall() { - let red_led: &mut Pa10> = unsafe { core::mem::transmute(LED) }; - red_led.set_high().ok(); - - debug!("+++ SVCall +++"); -} - -#[exception] -fn PendSV() { - let red_led: &mut Pa10> = unsafe { core::mem::transmute(LED) }; - red_led.set_high().ok(); - - debug!("+++ PendSV +++"); -} - -#[exception] -fn SysTick() { - let red_led: &mut Pa10> = unsafe { core::mem::transmute(LED) }; - red_led.set_high().ok(); - - debug!("+++ SysTick +++"); -} - -#[interrupt] -fn RTC() { - HANDLERS.call(0); -} - -#[interrupt] -fn USB() { - HANDLERS.call(1); -} diff --git a/app/src/rtc.rs b/app/src/rtc.rs deleted file mode 100644 index 79e450a..0000000 --- a/app/src/rtc.rs +++ /dev/null @@ -1,74 +0,0 @@ -use core::sync::atomic::{AtomicUsize, Ordering}; -use log; -use trinket_m0::{clock::GenericClockController, RTC}; - -struct Clock(AtomicUsize); -impl Clock { - const fn new() -> Self { - Self(AtomicUsize::new(0)) - } - - fn set(&self, millis: usize) { - self.0.store(millis, Ordering::SeqCst) - } - - // Slightly less than 1ms, due to using a 32,768Hz clock, we can't - // hit exactly 1ms, so we shoot for a bit under. - fn millis(&self) -> usize { - self.0.load(Ordering::SeqCst) - } -} - -static CLOCK: Clock = Clock::new(); - -// Set to run every ~500µs. -static COUNTER: u32 = 16; // 32 ticks requires 1024 cycles at 32,768Hz for 1 second. - -pub fn setup(mut rtc: RTC, clocks: &mut GenericClockController) -> impl FnMut() { - let rtc_clock = &clocks.gclk1(); - clocks.rtc(&rtc_clock); - - rtc.mode0().ctrl.write(|w| w.swrst().set_bit()); - while rtc.mode0().status.read().syncbusy().bit_is_set() {} - - rtc.mode0().ctrl.write(|w| { - w.mode().count32(); - - // Neither the prescaler nor matchlr values seem to work. Not - // sure why. - //w.prescaler().div1024(); - w.matchclr().set_bit() // Reset on match for periodic - }); - - rtc.mode0().comp[0].write(|w| unsafe { w.bits(COUNTER) }); - rtc.mode0().intflag.write(|w| w.cmp0().set_bit()); - rtc.mode0().intenset.write(|w| w.cmp0().set_bit()); - - // Enable the RTC and wait for sync. - rtc.mode0().ctrl.write(|w| w.enable().set_bit()); - while rtc.mode0().status.read().syncbusy().bit_is_set() {} - - move || handler(&mut rtc) -} - -pub fn millis() -> usize { - CLOCK.millis() -} - -fn handler(rtc: &mut RTC) { - // FIXME: matchclr doesn't seem to work to reset the counter? - rtc.mode0().count.write(|w| unsafe { w.bits(0) }); - rtc.mode0().intflag.write(|w| w.cmp0().set_bit()); - - static mut TICKS: usize = 0; - static mut ADD: bool = false; - unsafe { - if ADD { - TICKS += 1; - CLOCK.set(TICKS); - } - ADD = !ADD; - - log::logger().flush(); - } -} diff --git a/bootkbd/Cargo.toml b/bootkbd/Cargo.toml index 7b1b02d..5ae7bd4 100644 --- a/bootkbd/Cargo.toml +++ b/bootkbd/Cargo.toml @@ -8,4 +8,3 @@ license = "GPL-3.0-or-later" [dependencies] usb-host = { path = "../usb-host" } log = "~0.4" - diff --git a/bootkbd/src/lib.rs b/bootkbd/src/lib.rs old mode 100644 new mode 100755 index c143512..dde9e71 --- a/bootkbd/src/lib.rs +++ b/bootkbd/src/lib.rs @@ -1,8 +1,10 @@ +#![no_std] + use log::{debug, error, info}; use usb_host::{ - ConfigurationDescriptor, DescriptorType, DeviceDescriptor, Direction, Driver, Endpoint, - Error as USBError, RequestCode, RequestDirection, RequestKind, RequestRecipient, RequestType, - TransferType, USBHost, WValue, + ConfigurationDescriptor, DescriptorType, DeviceDescriptor, Direction, Driver, DriverError, + Endpoint, RequestCode, RequestDirection, RequestKind, RequestRecipient, RequestType, + TransferError, TransferType, USBHost, WValue, }; use core::mem::{self, MaybeUninit}; @@ -21,6 +23,11 @@ const MAX_ENDPOINTS: usize = 2; pub struct BootKeyboard { devices: [Option; MAX_DEVICES], } +impl core::fmt::Debug for BootKeyboard { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "BootKeyboard") + } +} impl BootKeyboard { pub fn new() -> Self { @@ -35,14 +42,14 @@ impl Driver for BootKeyboard { true } - fn add_device(&mut self, _device: DeviceDescriptor, address: u8) -> Result<(), USBError> { + fn add_device(&mut self, _device: DeviceDescriptor, address: u8) -> Result<(), DriverError> { for i in 0..self.devices.len() { if self.devices[i].is_none() { self.devices[i] = Some(Device::new(address)); return Ok(()); } } - Err(USBError::Permanent("out of devices")) + Err(DriverError::Permanent(address, "out of devices")) } fn remove_device(&mut self, address: u8) { @@ -56,20 +63,15 @@ impl Driver for BootKeyboard { } } - fn tick_device( - &mut self, - address: u8, - millis: usize, - host: &mut dyn USBHost, - ) -> Result<(), USBError> { - for i in 0..self.devices.len() { - if let Some(ref mut dev) = self.devices[i] { - if dev.addr == address { - return dev.fsm(millis, host); + fn tick(&mut self, millis: usize, host: &mut dyn USBHost) -> Result<(), DriverError> { + for d in &mut self.devices[..] { + if let Some(ref mut dev) = d { + if let Err(TransferError::Permanent(e)) = dev.fsm(millis, host) { + return Err(DriverError::Permanent(dev.addr, e)); } } } - Err(USBError::Permanent("no device at address")) + Ok(()) } } @@ -110,7 +112,7 @@ impl Device { } } - fn fsm(&mut self, millis: usize, host: &mut dyn USBHost) -> Result<(), USBError> { + fn fsm(&mut self, millis: usize, host: &mut dyn USBHost) -> Result<(), TransferError> { // TODO: either we need another `control_transfer` that // doesn't take data, or this `none` value needs to be put in // the usb-host layer. None of these options are good. @@ -252,8 +254,8 @@ impl Device { let mut buf: [u8; 8] = [0; 8]; if let Some(ref mut ep) = self.endpoints[0] { match host.in_transfer(ep, &mut buf) { - Err(USBError::Permanent(msg)) => error!("reading report: {}", msg), - Err(USBError::Retry(_)) => return Ok(()), + Err(TransferError::Permanent(msg)) => error!("reading report: {}", msg), + Err(TransferError::Retry(_)) => return Ok(()), Ok(len) => info!("report: {} - {:?}", len, buf), } } diff --git a/samd21-host/.cargo/config b/samd21-host/.cargo/config new file mode 100644 index 0000000..b6cdff0 --- /dev/null +++ b/samd21-host/.cargo/config @@ -0,0 +1,6 @@ +[build] +target = "thumbv6m-none-eabi" + +[target.thumbv6m-none-eabi] +rustflags = ["-C", "link-arg=-Tlink.x"] +runner = "qemu-system-arm -pidfile qemu.pid -cpu cortex-m0 -machine lm3s6965evb -nographic -semihosting-config enable=on,target=native -gdb tcp::3333 -S -kernel" diff --git a/samd21-host/Cargo.lock b/samd21-host/Cargo.lock new file mode 100644 index 0000000..7c24483 --- /dev/null +++ b/samd21-host/Cargo.lock @@ -0,0 +1,358 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "aligned" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "aligned" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "as-slice 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "as-slice" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "generic-array 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)", + "stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "atsamd-hal" +version = "0.5.0" +dependencies = [ + "atsamd21e18a 0.4.0", + "bitfield 0.13.2 (registry+https://github.com/rust-lang/crates.io-index)", + "cortex-m 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)", + "embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", + "nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "paste 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", + "vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "atsamd21e18a" +version = "0.4.0" +dependencies = [ + "bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", + "cortex-m 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)", + "cortex-m-rt 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)", + "vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "bare-metal" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "bitfield" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "bootkbd" +version = "0.1.0" +dependencies = [ + "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", + "usb-host 0.1.0", +] + +[[package]] +name = "cfg-if" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "clint" +version = "0.2.0" +dependencies = [ + "cortex-m 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "cortex-m" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "aligned 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", + "cortex-m 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", + "volatile-register 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "cortex-m" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "aligned 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", + "volatile-register 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "cortex-m-rt" +version = "0.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cortex-m-rt-macros 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", + "r0 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "cortex-m-rt-macros" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.15.42 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "embedded-hal" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "generic-array" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "typenum 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "log" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "nb" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "paste" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "paste-impl 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro-hack 0.5.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "paste-impl" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro-hack 0.5.8 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.15.42 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "proc-macro-hack" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.15.42 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "proc-macro2" +version = "0.4.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "quote" +version = "0.6.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "r0" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rb" +version = "0.1.0" + +[[package]] +name = "rustc_version" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "samd21-host" +version = "0.1.0" +dependencies = [ + "atsamd-hal 0.5.0", + "bootkbd 0.1.0", + "clint 0.2.0", + "cortex-m 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cortex-m-rt 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)", + "embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", + "nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "rb 0.1.0", + "trinket_m0 0.3.0", + "usb-host 0.1.0", +] + +[[package]] +name = "semver" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "semver-parser" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "stable_deref_trait" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "syn" +version = "0.15.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "trinket_m0" +version = "0.3.0" +dependencies = [ + "atsamd-hal 0.5.0", + "cortex-m 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)", + "cortex-m-rt 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)", + "embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", + "nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "typenum" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "unicode-xid" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "usb-host" +version = "0.1.0" + +[[package]] +name = "vcell" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "void" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "volatile-register" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[metadata] +"checksum aligned 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d39da9b88ae1a81c03c9c082b8db83f1d0e93914126041962af61034ab44c4a5" +"checksum aligned 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d3a316c7ea8e1e9ece54862c992def5a7ac14de9f5832b69d71760680efeeefa" +"checksum as-slice 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "293dac66b274fab06f95e7efb05ec439a6b70136081ea522d270bc351ae5bb27" +"checksum bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "a3caf393d93b2d453e80638d0674597020cef3382ada454faacd43d1a55a735a" +"checksum bitfield 0.13.2 (registry+https://github.com/rust-lang/crates.io-index)" = "46afbd2983a5d5a7bd740ccb198caf5b82f45c40c09c0eed36052d91cb92e719" +"checksum cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "b486ce3ccf7ffd79fdeb678eac06a9e6c09fc88d33836340becb8fffe87c5e33" +"checksum cortex-m 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)" = "3c0b159a1e8306949579de3698c841dba58058197b65c60807194e4fa1e7a554" +"checksum cortex-m 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f3c18719fdc57db65668bfc977db9a0fa1a41d718c5d9cd4f652c9d4b0e0956a" +"checksum cortex-m-rt 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)" = "17805910e3ecf029bdbfcc42b7384d9e3d9e5626153fa810002c1ef9839338ac" +"checksum cortex-m-rt-macros 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "d7ae692573e0acccb1579fef1abf5a5bf1d2f3f0149a22b16870ec9309aee25f" +"checksum embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ee4908a155094da7723c2d60d617b820061e3b4efcc3d9e293d206a5a76c170b" +"checksum generic-array 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)" = "c68f0274ae0e023facc3c97b2e00f076be70e254bc851d972503b328db79b2ec" +"checksum log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" +"checksum nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "b1411551beb3c11dedfb0a90a0fa256b47d28b9ec2cdff34c25a2fa59e45dbdc" +"checksum paste 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "1f4a4a1c555c6505821f9d58b8779d0f630a6b7e4e1be24ba718610acf01fa79" +"checksum paste-impl 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "26e796e623b8b257215f27e6c80a5478856cae305f5b59810ff9acdaa34570e6" +"checksum proc-macro-hack 0.5.8 (registry+https://github.com/rust-lang/crates.io-index)" = "982a35d1194084ba319d65c4a68d24ca28f5fdb5b8bc20899e4eef8641ea5178" +"checksum proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)" = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" +"checksum quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)" = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1" +"checksum r0 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e2a38df5b15c8d5c7e8654189744d8e396bddc18ad48041a500ce52d6948941f" +"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" +"checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" +"checksum semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" +"checksum semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" +"checksum stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8" +"checksum syn 0.15.42 (registry+https://github.com/rust-lang/crates.io-index)" = "eadc09306ca51a40555dd6fc2b415538e9e18bc9f870e47b1a524a79fe2dcf5e" +"checksum typenum 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "612d636f949607bdf9b123b4a6f6d966dedf3ff669f7f045890d3a4a73948169" +"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" +"checksum vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "45c297f0afb6928cd08ab1ff9d95e99392595ea25ae1b5ecf822ff8764e57a0d" +"checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" +"checksum volatile-register 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0d67cb4616d99b940db1d6bd28844ff97108b498a6ca850e5b6191a532063286" diff --git a/samd21-host/Cargo.toml b/samd21-host/Cargo.toml new file mode 100644 index 0000000..446bf1d --- /dev/null +++ b/samd21-host/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "samd21-host" +version = "0.1.0" +authors = ["Brian Cully "] +edition = "2018" +license = "GPL-3.0-or-later" + +[dependencies] +usb-host = { path = "../usb-host" } +rb = { path = "../rb" } +log = "~0.4" +embedded-hal = "~0.2" +atsamd-hal = { path = "../../atsamd/hal" } + +[dev-dependencies] +bootkbd = { path = "../bootkbd" } +clint = { path = "../../clint" } +cortex-m = "~0.6" +cortex-m-rt = "~0.6" +nb = "~0.1" +trinket_m0 = { path = "../../atsamd/boards/trinket_m0" } + +[features] +default = ["atsamd-hal/samd21e18a"] diff --git a/samd21-host/Makefile b/samd21-host/Makefile new file mode 100644 index 0000000..87fbc8d --- /dev/null +++ b/samd21-host/Makefile @@ -0,0 +1,38 @@ +APP = simple + +USBVID = 239a +USBPID = '001e|801e' + +BOSSAC = bossac +SERIAL = $(shell ./find-serial-port $(USBVID) $(USBPID) || echo 'cant-find-serial-port') +OFFSET = 0x2000 + +.PHONY: all clean cargo-build target/thumbv6m-none-eabi/debug/examples/$(APP) + +all: $(APP).uf2 + +clean: + rm -f $(APP).uf2 + rm -f $(APP).bin + cargo clean + +cargo-build: + cargo build --example $(APP) + +target/thumbv6m-none-eabi/debug/examples/$(APP): cargo-build + +$(APP).bin: target/thumbv6m-none-eabi/debug/examples/$(APP) + cargo objcopy --example $(APP) -- -O binary $(APP).bin + +# Requires https://github.com/sajattack/uf2conv-rs.git +%.uf2: %.bin + uf2conv-rs $< --base $(OFFSET) --output $@ + +flash: $(APP).bin $(SERIAL) + $(BOSSAC) -R -e -w -v -o$(OFFSET) -p$(SERIAL) $< + +qemu: target/thumbv6m-none-eabi/debug/$(APP) + qemu-system-arm -d in_asm,int,exec,cpu,guest_errors,unimp -pidfile qemu.pid -cpu cortex-m0 -machine lm3s6965evb -nographic -semihosting-config enable=on,target=native -s -S -kernel $< + +gdb: target/thumbv6m-none-eabi/debug/$(APP) + gdb-multiarch -ex "target remote localhost:1234" -ex "break main" -ex "continue" $< diff --git a/samd21-host/examples/simple/logger.rs b/samd21-host/examples/simple/logger.rs new file mode 100644 index 0000000..9f9452e --- /dev/null +++ b/samd21-host/examples/simple/logger.rs @@ -0,0 +1,139 @@ +use crate::rtc; +use rb::{Reader, RingBuffer, Writer}; + +use core::cell::UnsafeCell; +use core::fmt::{self, Write}; +use embedded_hal::{digital::v2::OutputPin, serial}; +use log::{Metadata, Record}; +use trinket_m0::{ + gpio::{Pa6, Pa7, PfD}, + sercom::{Sercom0Pad2, Sercom0Pad3, UART0}, +}; + +static mut UART0: usize = 0; + +struct JoinedRingBuffer<'a> { + lbr: Reader<'a, u8>, + lbw: Writer<'a, u8>, +} + +impl<'a> JoinedRingBuffer<'a> { + const fn new(rb: &'a RingBuffer) -> Self { + let (lbr, lbw) = rb.split(); + Self { lbr: lbr, lbw: lbw } + } +} + +impl fmt::Write for JoinedRingBuffer<'_> { + fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { + for b in s.bytes() { + if let Err(_) = self.lbw.unshift(b) { + // Ignore buffer full errors for logging. + return Ok(()); + } + } + Ok(()) + } +} + +static mut LB: RingBuffer = RingBuffer::::new(0); +static mut JRB: JoinedRingBuffer = unsafe { JoinedRingBuffer::new(&LB) }; + +// The UART isn't necessarily Sync, so wrap it in something that +// is. As long as flush() is only called from one thread, we're fine, +// but this is a guarantee that the logger module doesn't make. +pub struct WriteWrapper { + w: W, +} +impl WriteWrapper +where + W: serial::Write, +{ + pub const fn new(writer: W) -> Self { + Self { w: writer } + } +} +unsafe impl Sync for WriteWrapper {} + +pub struct SerialLogger { + writer: UnsafeCell>, + led: UnsafeCell, +} + +impl SerialLogger +where + W: serial::Write, + L: OutputPin + Send + Sync, +{ + pub fn new(writer: WriteWrapper, led: L) -> Self { + // Stash this for unsafe usage in case there's an issue with + // the rest of the logging. + unsafe { UART0 = core::mem::transmute(&writer.w) }; + Self { + writer: UnsafeCell::new(writer), + led: UnsafeCell::new(led), + } + } +} +unsafe impl Send for SerialLogger {} +unsafe impl Sync for SerialLogger {} + +impl log::Log for SerialLogger +where + W: serial::Write, + L: OutputPin + Send + Sync, +{ + fn enabled(&self, metadata: &Metadata) -> bool { + metadata.level() <= log::max_level() + } + + fn log(&self, record: &Record) { + if !self.enabled(record.metadata()) { + return; + } + + let jrb = unsafe { &mut JRB }; + write!( + jrb, + "[{}] {} {} -- {}\r\n", + rtc::millis(), + record.level(), + record.target(), + record.args() + ) + .ok(); + } + + fn flush(&self) { + // Unsafe due to mutable static. We can only deal with the + // tail position of the buffer here to keep things safe. + let jrb = unsafe { &mut JRB }; + if jrb.lbr.is_empty() { + return; + } + + let led = unsafe { &mut (*self.led.get()) }; + let writer = unsafe { &mut (*self.writer.get()) }; + + led.set_high().ok(); + while let Some(b) = jrb.lbr.shift() { + nb::block!(writer.w.write(b)).ok(); + } + led.set_low().ok(); + } +} + +// Write to the UART right now, instead of putting it on a ring +// buffer. This function is a huge hack, and only useful for debugging +// either before the main loop starts or if the ring buffer is broken. +pub unsafe fn write_fmt_now(args: fmt::Arguments, nl: bool) { + if UART0 == 0 { + return; + } + let uart: &mut UART0>, Sercom0Pad2>, (), ()> = + core::mem::transmute(UART0); + fmt::write(uart, args).expect("writing fmt now to uart"); + if nl { + uart.write_str("\r\n").expect("writing nl now to uart"); + } +} diff --git a/samd21-host/examples/simple/macros.rs b/samd21-host/examples/simple/macros.rs new file mode 100644 index 0000000..46d2d07 --- /dev/null +++ b/samd21-host/examples/simple/macros.rs @@ -0,0 +1,15 @@ +#[macro_export] +macro_rules! logln_now { + ($($arg:tt)*) => { + unsafe {crate::logger::write_fmt_now(format_args!($($arg)*), true);} + }; + (_) => {}; +} + +#[macro_export] +macro_rules! log_now { + ($($arg:tt)*) => { + unsafe {crate::logger::write_fmt_now(format_args!($($arg)*), false);} + }; + (_) => {}; +} diff --git a/samd21-host/examples/simple/main.rs b/samd21-host/examples/simple/main.rs new file mode 100755 index 0000000..c262905 --- /dev/null +++ b/samd21-host/examples/simple/main.rs @@ -0,0 +1,192 @@ +#![no_std] +#![no_main] +#![feature(const_fn)] +#![feature(const_transmute)] +#![allow(dead_code)] + +mod logger; +mod macros; +mod rtc; + +use bootkbd::BootKeyboard; +use clint::HandlerArray; +use cortex_m::asm::wfi; +use cortex_m_rt::{entry, exception, ExceptionFrame}; +use embedded_hal::digital::v2::OutputPin; +use log::{debug, info, LevelFilter}; +use samd21_host::SAMDHost; +use trinket_m0::{ + self as hal, + clock::GenericClockController, + gpio::{OpenDrain, Output, Pa10, Pa6, Pa7, PfD}, + sercom, + target_device::{interrupt, Interrupt}, + time::*, + CorePeripherals, Peripherals, +}; +use usb_host::Driver; + +static HANDLERS: HandlerArray = HandlerArray::new(); + +static mut LED: usize = 0; + +#[entry] +fn main() -> ! { + let mut peripherals = Peripherals::take().expect("taking peripherals"); + let mut core = CorePeripherals::take().expect("taking core peripherals"); + + let mut clocks = GenericClockController::with_internal_32kosc( + peripherals.GCLK, + &mut peripherals.PM, + &mut peripherals.SYSCTRL, + &mut peripherals.NVMCTRL, + ); + + let mut pins = hal::Pins::new(peripherals.PORT); + + let uart = hal::uart( + &mut clocks, + 115_200.hz(), + peripherals.SERCOM0, + &mut core.NVIC, + &mut peripherals.PM, + pins.d3, + pins.d4, + &mut pins.port, + ); + + let mut red_led = pins.d13.into_open_drain_output(&mut pins.port); + red_led.set_low().expect("turning off red LED"); + unsafe { LED = core::mem::transmute(&red_led) } + + // We do the transmute because, while all the underlying data is + // static, we're unable to get a referecence to the UART or LED + // until run-time. Another option would be to use Option in the + // SerialLogger definition, but that requires a check every time + // they might be used. + let uart_wrapped = logger::WriteWrapper::new(uart); + let logger = logger::SerialLogger::new(uart_wrapped, red_led); + + // Wow, would I love to not be annotating this type. + let logger_ref: &'static logger::SerialLogger< + sercom::UART0>, sercom::Sercom0Pad2>, (), ()>, + Pa10>, + > = unsafe { core::mem::transmute(&logger) }; + unsafe { log::set_logger_racy(logger_ref).expect("couldn't set logger") }; + log::set_max_level(LevelFilter::Info); + + info!("setting up timer"); + let mut rtc_handler = rtc::setup(peripherals.RTC, &mut clocks); + + info!("setting up usb host"); + let (mut usb_host, mut usb_handler) = SAMDHost::new( + peripherals.USB, + pins.usb_sof, + pins.usb_dm, + pins.usb_dp, + Some(pins.usb_host_enable), + &mut pins.port, + &mut clocks, + &mut peripherals.PM, + &rtc::millis, + ); + + let mut bootkbd = BootKeyboard::new(); + let mut drivers: [&mut dyn Driver; 1] = [&mut bootkbd]; + + info!("setting up handlers"); + HANDLERS.with_overrides(|hs| { + hs.register(0, &mut rtc_handler); + core.NVIC.enable(Interrupt::RTC); + + hs.register(1, &mut usb_handler); + unsafe { core.NVIC.set_priority(Interrupt::USB, 0) }; + core.NVIC.enable(Interrupt::USB); + + info!("Boot up complete."); + + loop { + usb_host.task(&mut drivers[..]); + wfi(); + } + }); + unreachable!(); +} + +#[panic_handler] +fn panic_handler(pi: &core::panic::PanicInfo) -> ! { + let red_led: &mut Pa10> = unsafe { core::mem::transmute(LED) }; + red_led.set_high().ok(); + + logln_now!("~~~ PANIC ~~~"); + logln_now!("{}", pi); + logln_now!("flushing log"); + loop { + log::logger().flush(); + wfi() + } +} + +#[exception] +fn HardFault(ef: &ExceptionFrame) -> ! { + let red_led: &mut Pa10> = unsafe { core::mem::transmute(LED) }; + red_led.set_high().ok(); + + log::logger().flush(); + logln_now!("!!! Hard Fault - ef: {:?} !!!", ef); + logln_now!("flushing log"); + loop { + log::logger().flush(); + wfi() + } +} + +#[exception] +fn DefaultHandler(interrupt: i16) { + let red_led: &mut Pa10> = unsafe { core::mem::transmute(LED) }; + red_led.set_high().ok(); + + debug!("*** Default Handler: {} ***", interrupt); +} + +#[exception] +fn NonMaskableInt() { + let red_led: &mut Pa10> = unsafe { core::mem::transmute(LED) }; + red_led.set_high().ok(); + + debug!("+++ NonMaskableInt +++"); +} + +#[exception] +fn SVCall() { + let red_led: &mut Pa10> = unsafe { core::mem::transmute(LED) }; + red_led.set_high().ok(); + + debug!("+++ SVCall +++"); +} + +#[exception] +fn PendSV() { + let red_led: &mut Pa10> = unsafe { core::mem::transmute(LED) }; + red_led.set_high().ok(); + + debug!("+++ PendSV +++"); +} + +#[exception] +fn SysTick() { + let red_led: &mut Pa10> = unsafe { core::mem::transmute(LED) }; + red_led.set_high().ok(); + + debug!("+++ SysTick +++"); +} + +#[interrupt] +fn RTC() { + HANDLERS.call(0); +} + +#[interrupt] +fn USB() { + HANDLERS.call(1); +} diff --git a/samd21-host/examples/simple/rtc.rs b/samd21-host/examples/simple/rtc.rs new file mode 100644 index 0000000..79e450a --- /dev/null +++ b/samd21-host/examples/simple/rtc.rs @@ -0,0 +1,74 @@ +use core::sync::atomic::{AtomicUsize, Ordering}; +use log; +use trinket_m0::{clock::GenericClockController, RTC}; + +struct Clock(AtomicUsize); +impl Clock { + const fn new() -> Self { + Self(AtomicUsize::new(0)) + } + + fn set(&self, millis: usize) { + self.0.store(millis, Ordering::SeqCst) + } + + // Slightly less than 1ms, due to using a 32,768Hz clock, we can't + // hit exactly 1ms, so we shoot for a bit under. + fn millis(&self) -> usize { + self.0.load(Ordering::SeqCst) + } +} + +static CLOCK: Clock = Clock::new(); + +// Set to run every ~500µs. +static COUNTER: u32 = 16; // 32 ticks requires 1024 cycles at 32,768Hz for 1 second. + +pub fn setup(mut rtc: RTC, clocks: &mut GenericClockController) -> impl FnMut() { + let rtc_clock = &clocks.gclk1(); + clocks.rtc(&rtc_clock); + + rtc.mode0().ctrl.write(|w| w.swrst().set_bit()); + while rtc.mode0().status.read().syncbusy().bit_is_set() {} + + rtc.mode0().ctrl.write(|w| { + w.mode().count32(); + + // Neither the prescaler nor matchlr values seem to work. Not + // sure why. + //w.prescaler().div1024(); + w.matchclr().set_bit() // Reset on match for periodic + }); + + rtc.mode0().comp[0].write(|w| unsafe { w.bits(COUNTER) }); + rtc.mode0().intflag.write(|w| w.cmp0().set_bit()); + rtc.mode0().intenset.write(|w| w.cmp0().set_bit()); + + // Enable the RTC and wait for sync. + rtc.mode0().ctrl.write(|w| w.enable().set_bit()); + while rtc.mode0().status.read().syncbusy().bit_is_set() {} + + move || handler(&mut rtc) +} + +pub fn millis() -> usize { + CLOCK.millis() +} + +fn handler(rtc: &mut RTC) { + // FIXME: matchclr doesn't seem to work to reset the counter? + rtc.mode0().count.write(|w| unsafe { w.bits(0) }); + rtc.mode0().intflag.write(|w| w.cmp0().set_bit()); + + static mut TICKS: usize = 0; + static mut ADD: bool = false; + unsafe { + if ADD { + TICKS += 1; + CLOCK.set(TICKS); + } + ADD = !ADD; + + log::logger().flush(); + } +} diff --git a/samd21-host/find-serial-port b/samd21-host/find-serial-port new file mode 100755 index 0000000..62e2c0c --- /dev/null +++ b/samd21-host/find-serial-port @@ -0,0 +1,16 @@ +#!/bin/sh + +if [ $# -ne 2 ]; then + echo "Usage: $0 vid pid" >&2 + exit 1 +fi + +prefix=/dev/serial/by-id + +for dev in `ls $prefix`; do + if [ `udevadm info -q property --name $prefix/$dev | egrep -i "ID_VENDOR_ID=($1)|ID_MODEL_ID=($2)" | wc -l` -eq 2 ]; then + echo `readlink -f $prefix/$dev` + exit 0 + fi +done +exit 2 diff --git a/samd21-host/simple.bin b/samd21-host/simple.bin new file mode 100755 index 0000000..26b330f Binary files /dev/null and b/samd21-host/simple.bin differ diff --git a/samd21-host/simple.uf2 b/samd21-host/simple.uf2 new file mode 100644 index 0000000..817dcb3 Binary files /dev/null and b/samd21-host/simple.uf2 differ diff --git a/samd21-host/src/lib.rs b/samd21-host/src/lib.rs new file mode 100755 index 0000000..98ebcff --- /dev/null +++ b/samd21-host/src/lib.rs @@ -0,0 +1,645 @@ +#![no_std] +mod pipe; + +use pipe::{PipeErr, PipeTable}; + +use usb_host::{ + DescriptorType, DeviceDescriptor, Direction, Driver, DriverError, Endpoint, RequestCode, + RequestDirection, RequestKind, RequestRecipient, RequestType, TransferError, TransferType, + USBHost, WValue, +}; + +use atsamd_hal::{ + calibration::{usb_transn_cal, usb_transp_cal, usb_trim_cal}, + clock::{ClockGenId, ClockSource, GenericClockController}, + gpio::{self, Floating, Input, OpenDrain, Output}, + target_device::{PM, USB}, +}; +use embedded_hal::digital::v2::OutputPin; +use log::{debug, error, trace, warn}; +use rb::{Reader, RingBuffer, Writer}; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Event { + Error, + Detached, + Attached, +} +type Events = RingBuffer; +type EventReader = Reader<'static, Event>; +type EventWriter = Writer<'static, Event>; + +const NAK_LIMIT: usize = 15; + +// Must be at least 100ms. cf §9.1.2 of USB 2.0. +const SETTLE_DELAY: usize = 205; // Delay in sec/1024 + +// Ring buffer for sharing events from interrupt context. +static mut EVENTS: Events = Events::new(Event::Error); +// FIXME: this is just for testing. The enum needs to be +// thread-safe if this is the way we're going. +static mut LATEST_EVENT: Event = Event::Detached; + +#[derive(Clone, Copy, Debug, PartialEq)] +enum DetachedState { + Initialize, + WaitForDevice, + Illegal, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum AttachedState { + WaitForSettle(usize), + WaitResetComplete, + WaitSOF(usize), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum SteadyState { + Configuring, + Running, + Error, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum TaskState { + Detached(DetachedState), + Attached(AttachedState), + Steady(SteadyState), +} + +use core::mem::{self, MaybeUninit}; +use core::ptr; + +const MAX_DEVICES: usize = 4; +struct DeviceTable { + tbl: [Option; MAX_DEVICES], +} +impl DeviceTable { + fn new() -> Self { + let tbl = { + let mut devs: [MaybeUninit>; MAX_DEVICES] = + unsafe { MaybeUninit::uninit().assume_init() }; + for d in &mut devs[..] { + unsafe { ptr::write(d.as_mut_ptr(), None) } + } + unsafe { mem::transmute(devs) } + }; + + Self { tbl: tbl } + } + + /// 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. + fn next(&mut self) -> Option<&mut Device> { + for i in 1..self.tbl.len() { + if self.tbl[i].is_none() { + let d = Device { addr: i as u8 }; + self.tbl[i] = Some(d); + return self.tbl[i].as_mut(); + } + } + None + } + + /// Remove the device at address `addr`. + fn remove(&mut self, addr: u8) -> Option { + let v = core::mem::replace(&mut self.tbl[addr as usize], None); + v + } +} + +struct Device { + addr: u8, +} + +pub struct SAMDHost<'a, F> { + usb: USB, + + events: EventReader, + task_state: TaskState, + + // Need chunk of RAM for USB pipes, which gets used with DESCADD + // register. + pipe_table: PipeTable, + + devices: DeviceTable, + + // need sof 1kHz pad? + _sof_pad: gpio::Pa23, + _dm_pad: gpio::Pa24, + _dp_pad: gpio::Pa25, + host_enable_pin: Option>>, + + // To get current milliseconds. + millis: &'a F, +} + +impl<'a, F> SAMDHost<'a, F> +where + F: Fn() -> usize, +{ + pub fn new( + usb: USB, + sof_pin: gpio::Pa23>, + dm_pin: gpio::Pa24>, + dp_pin: gpio::Pa25>, + host_enable_pin: Option>>, + port: &mut gpio::Port, + clocks: &mut GenericClockController, + pm: &mut PM, + millis: &'a F, + ) -> (Self, impl FnMut()) { + let (eventr, mut eventw) = unsafe { EVENTS.split() }; + + let mut rc = Self { + usb: usb, + + events: eventr, + task_state: TaskState::Detached(DetachedState::Initialize), + + pipe_table: PipeTable::new(), + + devices: DeviceTable::new(), + + _sof_pad: sof_pin.into_function_g(port), + _dm_pad: dm_pin.into_function_g(port), + _dp_pad: dp_pin.into_function_g(port), + host_enable_pin: None, + + millis: millis, + }; + + if let Some(he_pin) = host_enable_pin { + rc.host_enable_pin = Some(he_pin.into_open_drain_output(port)); + } + + pm.apbbmask.modify(|_, w| w.usb_().set_bit()); + + // Set up USB clock from 48MHz source on generic clock 6. + clocks.configure_gclk_divider_and_source(ClockGenId::GCLK6, 1, ClockSource::DFLL48M, false); + let gclk6 = clocks + .get_gclk(ClockGenId::GCLK6) + .expect("Could not get clock 6"); + clocks.usb(&gclk6); + + let usbp = &rc.usb as *const _ as usize; + (rc, move || handler(usbp, &mut eventw)) + } + + pub fn reset_periph(&mut self) { + debug!("resetting usb"); + // Reset the USB peripheral and wait for sync. + self.usb.host().ctrla.write(|w| w.swrst().set_bit()); + while self.usb.host().syncbusy.read().swrst().bit_is_set() {} + + // Specify host mode. + self.usb.host().ctrla.modify(|_, w| w.mode().host()); + + // Unsafe due to use of raw bits method. + unsafe { + self.usb.host().padcal.write(|w| { + w.transn().bits(usb_transn_cal()); + w.transp().bits(usb_transp_cal()); + w.trim().bits(usb_trim_cal()) + }); + } + + // Use normal, which is 0 and apparently means low-and-full capable + self.usb.host().ctrlb.modify(|_, w| w.spdconf().normal()); + // According to docs, 1,2,3 are reserved, but .fs returns 3 + //self.usb.host().ctrlb.modify(|_, w| w.spdconf().fs()); + + self.usb.host().ctrla.modify(|_, w| w.runstdby().set_bit()); // keep usb clock running in standby. + + // Set address of USB SRAM. + // Unsafe due to use of raw bits method. + unsafe { + self.usb + .host() + .descadd + .write(|w| w.bits(&self.pipe_table as *const _ as u32)); + } + + if let Some(he_pin) = &mut self.host_enable_pin { + he_pin.set_high().expect("turning on usb host enable pin"); + } + + self.usb.host().intenset.write(|w| { + w.wakeup().set_bit(); + w.dconn().set_bit(); + w.ddisc().set_bit() + }); + + self.usb.host().ctrla.modify(|_, w| w.enable().set_bit()); + while self.usb.host().syncbusy.read().enable().bit_is_set() {} + + // Set VBUS OK to allow host operation. + self.usb.host().ctrlb.modify(|_, w| w.vbusok().set_bit()); + debug!("...done"); + } + + pub fn task(&mut self, drivers: &mut [&mut dyn Driver]) { + static mut LAST_EVENT: Event = Event::Error; + unsafe { + if LAST_EVENT != LATEST_EVENT { + trace!("new event: {:?}", LATEST_EVENT); + } + } + + static mut LAST_TASK_STATE: TaskState = TaskState::Detached(DetachedState::Illegal); + self.task_state = match unsafe { LATEST_EVENT } { + Event::Error => TaskState::Detached(DetachedState::Illegal), + Event::Detached => { + if let TaskState::Detached(_) = self.task_state { + self.task_state + } else { + TaskState::Detached(DetachedState::Initialize) + } + } + Event::Attached => { + if let TaskState::Detached(_) = self.task_state { + TaskState::Attached(AttachedState::WaitForSettle( + (self.millis)() + SETTLE_DELAY, + )) + } else { + self.task_state + } + } + }; + + static mut LAST_CBITS: u16 = 0; + static mut LAST_FLAGS: u16 = 0; + let cbits = self.usb.host().ctrlb.read().bits(); + let bits = self.usb.host().intflag.read().bits(); + unsafe { + if LAST_CBITS != cbits || LAST_FLAGS != bits || LAST_TASK_STATE != self.task_state { + trace!( + "cb: {:x}, f: {:x} changing state {:?} -> {:?}", + cbits, + bits, + LAST_TASK_STATE, + self.task_state, + ); + } + LAST_CBITS = cbits; + LAST_FLAGS = bits; + LAST_TASK_STATE = self.task_state + }; + + if let Some(_event) = self.events.shift() { + // trace!("Found event: {:?}", event); + // self.task_state = match event { + // Event::None => TaskState::Detached(DetachedState::Illegal), + // Event::Detached => { + // if let TaskState::Detached(_) = self.task_state { + // self.task_state + // } else { + // TaskState::Detached(DetachedState::Initialize) + // } + // } + // Event::Attached => { + // if let TaskState::Detached(_) = self.task_state { + // self.delay = self.millis() + SETTLE_DELAY; + // TaskState::Attached(AttachedState::WaitForSettle) + // } else { + // self.task_state + // } + // } + // }; + } + + self.fsm(drivers); + + unsafe { + LAST_EVENT = LATEST_EVENT; + } + } + fn fsm(&mut self, drivers: &mut [&mut dyn Driver]) { + // respond to events from interrupt. + match self.task_state { + TaskState::Detached(s) => self.detached_fsm(s), + TaskState::Attached(s) => self.attached_fsm(s), + TaskState::Steady(s) => self.steady_fsm(s, drivers), + }; + } + + fn detached_fsm(&mut self, s: DetachedState) { + match s { + DetachedState::Initialize => { + self.reset_periph(); + // TODO: Free resources. + + self.task_state = TaskState::Detached(DetachedState::WaitForDevice); + } + + // Do nothing state. Just wait for an interrupt to come in + // saying we have a device attached. + DetachedState::WaitForDevice => {} + + // TODO: should probably reset everything if we end up here somehow. + DetachedState::Illegal => {} + } + } + + fn attached_fsm(&mut self, s: AttachedState) { + match s { + AttachedState::WaitForSettle(until) => { + if (self.millis)() >= until { + self.usb.host().ctrlb.modify(|_, w| w.busreset().set_bit()); + self.task_state = TaskState::Attached(AttachedState::WaitResetComplete); + } + } + + AttachedState::WaitResetComplete => { + if self.usb.host().intflag.read().rst().bit_is_set() { + trace!("reset was sent"); + self.usb.host().intflag.write(|w| w.rst().set_bit()); + + // Seems unneccesary, since SOFE will be set + // immediately after reset according to §32.6.3.3. + self.usb.host().ctrlb.modify(|_, w| w.sofe().set_bit()); + // USB spec requires 20ms of SOF after bus reset. + self.task_state = + TaskState::Attached(AttachedState::WaitSOF((self.millis)() + 20)); + } + } + + AttachedState::WaitSOF(until) => { + if self.usb.host().intflag.read().hsof().bit_is_set() { + self.usb.host().intflag.write(|w| w.hsof().set_bit()); + if (self.millis)() >= until { + self.task_state = TaskState::Steady(SteadyState::Configuring); + } + } + } + } + } + + fn steady_fsm(&mut self, s: SteadyState, drivers: &mut [&mut dyn Driver]) { + match s { + SteadyState::Configuring => { + self.task_state = match self.configure_dev(drivers) { + Ok(_) => TaskState::Steady(SteadyState::Running), + Err(e) => { + warn!("Enumeration error: {:?}", e); + TaskState::Steady(SteadyState::Error) + } + } + } + + SteadyState::Running => { + for d in &mut drivers[..] { + if let Err(e) = d.tick((self.millis)(), self) { + warn!("running driver {:?}: {:?}", d, e); + if let DriverError::Permanent(a, _) = e { + self.devices.remove(a); + } + } + } + } + + SteadyState::Error => {} + } + } + + fn configure_dev(&mut self, drivers: &mut [&mut dyn Driver]) -> Result<(), TransferError> { + let none: Option<&mut [u8]> = None; + let mut a0ep0 = Addr0EP0 { + in_toggle: true, + out_toggle: true, + }; + let mut dev_desc: DeviceDescriptor = + unsafe { MaybeUninit::::uninit().assume_init() }; + self.control_transfer( + &mut a0ep0, + RequestType::from(( + RequestDirection::DeviceToHost, + RequestKind::Standard, + RequestRecipient::Device, + )), + RequestCode::GetDescriptor, + WValue::from((0, DescriptorType::Device as u8)), + 0, + Some(unsafe { to_slice_mut(&mut dev_desc) }), + )?; + + trace!(" -- dev_desc: {:?}", dev_desc); + + // TODO: new error for being out of devices. + let addr = self + .devices + .next() + .ok_or(TransferError::Permanent("out of devices"))? + .addr; + debug!("Setting address to {}.", addr); + self.control_transfer( + &mut a0ep0, + RequestType::from(( + RequestDirection::HostToDevice, + RequestKind::Standard, + RequestRecipient::Device, + )), + RequestCode::SetAddress, + WValue::from((addr, 0)), + 0, + none, + )?; + + // Now that the device is addressed, see if any drivers want + // it. + for d in &mut drivers[..] { + if d.want_device(&dev_desc) { + let res = d.add_device(dev_desc, addr); + match res { + Ok(_) => return Ok(()), + Err(_) => return Err(TransferError::Permanent("out of addresses")), + } + } + } + Ok(()) + } +} + +struct Addr0EP0 { + in_toggle: bool, + out_toggle: bool, +} +impl Endpoint for Addr0EP0 { + fn address(&self) -> u8 { + 0 + } + + fn endpoint_num(&self) -> u8 { + 0 + } + + fn transfer_type(&self) -> TransferType { + TransferType::Control + } + + fn direction(&self) -> Direction { + Direction::In + } + + fn max_packet_size(&self) -> u16 { + 8 + } + + fn in_toggle(&self) -> bool { + self.in_toggle + } + + fn set_in_toggle(&mut self, toggle: bool) { + self.in_toggle = toggle; + } + + fn out_toggle(&self) -> bool { + self.out_toggle + } + + fn set_out_toggle(&mut self, toggle: bool) { + self.out_toggle = toggle; + } +} + +pub fn handler(usbp: usize, events: &mut EventWriter) { + let usb: &mut USB = unsafe { core::mem::transmute(usbp) }; + let flags = usb.host().intflag.read(); + + trace!("USB - {:x}", flags.bits()); + + let mut unshift_event = |e: Event| { + unsafe { LATEST_EVENT = e }; + if let Err(_) = events.unshift(e) { + error!("Couldn't write USB event to queue."); + } + }; + + if flags.hsof().bit_is_set() { + trace!(" +hsof"); + usb.host().intflag.write(|w| w.hsof().set_bit()); + unshift_event(Event::Attached); + } + + if flags.rst().bit_is_set() { + // We seem to get this whenever a device attaches/detaches. + trace!(" +rst"); + usb.host().intflag.write(|w| w.rst().set_bit()); + unshift_event(Event::Detached); + } + + if flags.uprsm().bit_is_set() { + trace!(" +uprsm"); + usb.host().intflag.write(|w| w.uprsm().set_bit()); + unshift_event(Event::Detached); + } + + if flags.dnrsm().bit_is_set() { + trace!(" +dnrsm"); + usb.host().intflag.write(|w| w.dnrsm().set_bit()); + unshift_event(Event::Detached); + } + + if flags.wakeup().bit_is_set() { + // §32.8.5.8 - since VBUSOK is set, then this happens when a + // device is connected. + trace!(" +wakeup"); + usb.host().intflag.write(|w| w.wakeup().set_bit()); + unshift_event(Event::Attached); + } + + if flags.ramacer().bit_is_set() { + trace!(" +ramacer"); + usb.host().intflag.write(|w| w.ramacer().set_bit()); + unshift_event(Event::Detached); + } + + if flags.dconn().bit_is_set() { + trace!(" +dconn"); + usb.host().intflag.write(|w| w.dconn().set_bit()); + usb.host().intenclr.write(|w| w.dconn().set_bit()); + usb.host().intflag.write(|w| w.ddisc().set_bit()); + usb.host().intenset.write(|w| w.ddisc().set_bit()); + usb.host().intflag.write(|w| w.dconn().set_bit()); + unshift_event(Event::Attached); + } + + if flags.ddisc().bit_is_set() { + trace!(" +ddisc"); + usb.host().intflag.write(|w| w.ddisc().set_bit()); + usb.host().intenclr.write(|w| w.ddisc().set_bit()); + usb.host().intflag.write(|w| w.dconn().set_bit()); + usb.host().intenset.write(|w| w.dconn().set_bit()); + usb.host().intflag.write(|w| w.ddisc().set_bit()); + unshift_event(Event::Detached); + } +} + +impl From for TransferError { + fn from(v: PipeErr) -> Self { + match v { + PipeErr::TransferFail => Self::Retry("transfer failed"), + PipeErr::Flow => Self::Retry("data flow"), + PipeErr::DataToggle => Self::Retry("toggle sequence"), + PipeErr::ShortPacket => Self::Permanent("short packet"), + PipeErr::InvalidPipe => Self::Permanent("invalid pipe"), + PipeErr::InvalidToken => Self::Permanent("invalid token"), + PipeErr::Stall => Self::Permanent("stall"), + PipeErr::PipeErr => Self::Permanent("pipe error"), + PipeErr::HWTimeout => Self::Permanent("hardware timeout"), + PipeErr::SWTimeout => Self::Permanent("software timeout"), + PipeErr::Other(s) => Self::Permanent(s), + } + } +} + +impl USBHost for SAMDHost<'_, F> +where + F: Fn() -> usize, +{ + fn control_transfer( + &mut self, + ep: &mut dyn Endpoint, + bm_request_type: RequestType, + b_request: RequestCode, + w_value: WValue, + w_index: u16, + buf: Option<&mut [u8]>, + ) -> Result { + let mut pipe = self.pipe_table.pipe_for(self.usb.host_mut(), ep); + let len = pipe.control_transfer( + ep, + bm_request_type, + b_request, + w_value, + w_index, + buf, + self.millis, + )?; + Ok(len) + } + + fn in_transfer( + &mut self, + ep: &mut dyn Endpoint, + buf: &mut [u8], + ) -> Result { + let mut pipe = self.pipe_table.pipe_for(self.usb.host_mut(), ep); + let len = pipe.in_transfer(ep, buf, NAK_LIMIT, self.millis)?; + Ok(len) + } + + fn out_transfer(&mut self, ep: &mut dyn Endpoint, buf: &[u8]) -> Result { + let mut pipe = self.pipe_table.pipe_for(self.usb.host_mut(), ep); + let len = pipe.out_transfer(ep, buf, NAK_LIMIT, self.millis)?; + Ok(len) + } +} + +unsafe fn to_slice_mut(v: &mut T) -> &mut [u8] { + let ptr = v as *mut T as *mut u8; + let len = mem::size_of::(); + core::slice::from_raw_parts_mut(ptr, len) +} diff --git a/samd21-host/src/pipe.rs b/samd21-host/src/pipe.rs new file mode 100644 index 0000000..0da0e7f --- /dev/null +++ b/samd21-host/src/pipe.rs @@ -0,0 +1,809 @@ +#[allow(unused)] +pub mod addr; +#[allow(unused)] +pub mod ctrl_pipe; +#[allow(unused)] +pub mod ext_reg; +#[allow(unused)] +pub mod pck_size; +#[allow(unused)] +pub mod status_bk; +#[allow(unused)] +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 usb_host::{ + Endpoint, RequestCode, RequestDirection, RequestType, SetupPacket, TransferType, WValue, +}; + +use atsamd_hal::target_device::usb::{ + self, + host::{BINTERVAL, PCFG, PINTFLAG, PSTATUS, PSTATUSCLR, PSTATUSSET}, +}; +use core::convert::TryInto; +use log::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; + +#[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 { + let tbl = { + let mut tbl: [core::mem::MaybeUninit; MAX_PIPES] = + unsafe { core::mem::MaybeUninit::uninit().assume_init() }; + + for e in &mut tbl[..] { + unsafe { core::ptr::write(e.as_mut_ptr(), PipeDesc::new()) } + } + + unsafe { core::mem::transmute(tbl) } + }; + Self { tbl: tbl } + } + + pub(crate) fn pipe_for<'a, 'b>( + &'a mut self, + host: &'b mut usb::HOST, + endpoint: &dyn Endpoint, + ) -> 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 endpoint.endpoint_num() == 0 { 0 } else { 1 }; + + let pregs = PipeRegs::from(host, i); + let pdesc = &mut self.tbl[i]; + + pregs.cfg.write(|w| { + let ptype = PType::from(endpoint.transfer_type()) as u8; + unsafe { w.ptype().bits(ptype) } + }); + trace!( + "setting paddr of pipe {} to {}:{}", + i, + endpoint.address(), + endpoint.endpoint_num() + ); + pdesc.bank0.ctrl_pipe.write(|w| { + w.pdaddr().set_addr(endpoint.address()); + w.pepnum().set_epnum(endpoint.endpoint_num()) + }); + 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_transfer( + &mut self, + ep: &mut dyn Endpoint, + bm_request_type: RequestType, + b_request: RequestCode, + w_value: WValue, + w_index: u16, + buf: Option<&mut [u8]>, + millis: &dyn Fn() -> usize, + ) -> Result { + /* + * Setup stage. + */ + let buflen = buf.as_ref().map_or(0, |b| b.len() as u16); + 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: buflen, + }; + self.send( + ep, + PToken::Setup, + &DataBuf::from(&mut setup_packet), + NAK_LIMIT, + millis, + )?; + + /* + * Data stage. + */ + let mut transfer_len = 0; + 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 => { + transfer_len = self.in_transfer(ep, b, NAK_LIMIT, millis)?; + } + + RequestDirection::HostToDevice => { + transfer_len = self.out_transfer(ep, b, NAK_LIMIT, millis)?; + } + } + } + + /* + * Status stage. + */ + // TODO: status stage has up to 50ms to complete. cf §9.2.6.4 + // of USB 2.0. + 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 => PToken::Out, + RequestDirection::HostToDevice => PToken::In, + }; + + trace!("dispatching status stage"); + self.dispatch_retries(ep, token, NAK_LIMIT, millis)?; + + Ok(transfer_len) + } + + fn send( + &mut self, + ep: &mut dyn Endpoint, + token: PToken, + 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(ep, token, nak_limit, millis) + } + + pub(crate) fn in_transfer( + &mut self, + ep: &mut dyn Endpoint, + buf: &mut [u8], + nak_limit: usize, + millis: &dyn Fn() -> usize, + ) -> Result { + // TODO: pull this from pipe descriptor for this addr/ep. + let packet_size = 8; + + trace!("p{}: Should IN for {}b.", self.num, buf.len()); + self.desc.bank0.pcksize.write(|w| { + unsafe { w.byte_count().bits(buf.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 < buf.len() { + // Move the buffer pointer forward as we get data. + self.desc.bank0.addr.write(|w| unsafe { + w.addr() + .bits(buf.as_mut_ptr() as u32 + bytes_received as u32) + }); + self.regs.statusclr.write(|w| w.bk0rdy().set_bit()); + trace!("--- !!! regs-pre-dispatch !!! ---"); + self.log_regs(); + + self.dispatch_retries(ep, PToken::In, nak_limit, millis)?; + let recvd = self.desc.bank0.pcksize.read().byte_count().bits() as usize; + bytes_received += recvd; + trace!("!! read {} of {}", bytes_received, buf.len()); + if recvd < packet_size { + break; + } + + // Don't allow writing past the buffer. + assert!(bytes_received <= buf.len()); + } + + self.regs.statusset.write(|w| w.pfreeze().set_bit()); + if bytes_received < buf.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`. OR! Make the function take a mutable slice of + // u8, and leave it up to the caller to figure out how to + // deal with short packets. + Err(PipeErr::ShortPacket) + } else { + Ok(bytes_received) + } + } + + pub(crate) fn out_transfer( + &mut self, + ep: &mut dyn Endpoint, + buf: &[u8], + nak_limit: usize, + millis: &dyn Fn() -> usize, + ) -> Result { + trace!("p{}: Should OUT for {}b.", self.num, buf.len()); + self.desc.bank0.pcksize.write(|w| { + unsafe { w.byte_count().bits(buf.len() as u16) }; + unsafe { w.multi_packet_size().bits(0) } + }); + + let mut bytes_sent = 0; + while bytes_sent < buf.len() { + self.desc + .bank0 + .addr + .write(|w| unsafe { w.addr().bits(buf.as_ptr() as u32 + bytes_sent as u32) }); + self.dispatch_retries(ep, PToken::Out, nak_limit, millis)?; + + let sent = self.desc.bank0.pcksize.read().byte_count().bits() as usize; + bytes_sent += sent; + trace!("!! wrote {} of {}", bytes_sent, buf.len()); + } + + Ok(bytes_sent) + } + + fn dtgl(&mut self, ep: &mut dyn Endpoint, token: PToken) { + // 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!( + "~~~ tok: {:?}, dtgl: {}, i: {}, o: {}", + token, + self.regs.status.read().dtgl().bit(), + ep.in_toggle(), + ep.out_toggle(), + ); + + let toggle = match token { + PToken::In => { + let t = !ep.in_toggle(); + ep.set_in_toggle(t); + t + } + + PToken::Out => { + let t = !ep.out_toggle(); + ep.set_out_toggle(t); + t + } + + _ => !self.regs.status.read().dtgl().bit_is_set(), + }; + + if toggle { + self.dtgl_set(); + } else { + self.dtgl_clear(); + } + } + + 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 { + // 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) + }); + } + + // 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, + ep: &mut dyn Endpoint, + token: PToken, + retries: usize, + millis: &dyn Fn() -> usize, + ) -> Result<(), PipeErr> { + self.dispatch_packet(ep, token); + + let until = millis() + USB_TIMEOUT; + let mut last_err = PipeErr::SWTimeout; + let mut naks = 0; + while millis() < until { + let res = self.dispatch_result(token); + match res { + Ok(true) => { + if token == PToken::In { + ep.set_in_toggle(self.regs.status.read().dtgl().bit_is_set()); + } else if token == PToken::Out { + ep.set_out_toggle(self.regs.status.read().dtgl().bit_is_set()); + } + return Ok(()); + } + Ok(false) => continue, + + Err(e) => { + last_err = e; + match last_err { + PipeErr::DataToggle => self.dtgl(ep, token), + + // Flow error on interrupt pipes means we got + // a NAK, which in this context means there's + // no data. cf §32.8.7.5 of SAM D21 data + // sheet. + PipeErr::Flow if ep.transfer_type() == TransferType::Interrupt => break, + + PipeErr::Stall => break, + _ => { + naks += 1; + if naks > retries { + break; + } else { + self.dispatch_packet(ep, token); + } + } + } + } + } + } + + Err(last_err) + } + + fn dispatch_packet(&mut self, ep: &mut dyn Endpoint, token: PToken) { + self.regs + .cfg + .modify(|_, w| unsafe { w.ptoken().bits(token as u8) }); + self.regs.intflag.modify(|_, w| w.trfail().set_bit()); + self.regs.intflag.modify(|_, w| w.perr().set_bit()); + + match token { + PToken::Setup => { + self.regs.intflag.write(|w| w.txstp().set_bit()); + self.regs.statusset.write(|w| w.bk0rdy().set_bit()); + + // Toggles should be 1 for host and function's + // sequence at end of setup transaction. cf §8.6.1 of + // USB 2.0. + self.dtgl_clear(); + ep.set_in_toggle(true); + ep.set_out_toggle(true); + } + PToken::In => { + self.regs.statusclr.write(|w| w.bk0rdy().set_bit()); + if ep.in_toggle() { + self.dtgl_set(); + } else { + self.dtgl_clear(); + } + } + PToken::Out => { + self.regs.intflag.write(|w| w.trcpt0().set_bit()); + self.regs.statusset.write(|w| w.bk0rdy().set_bit()); + if ep.out_toggle() { + self.dtgl_set(); + } else { + self.dtgl_clear(); + } + } + _ => {} + } + + trace!("initial regs"); + self.log_regs(); + + self.regs.statusclr.write(|w| w.pfreeze().set_bit()); + } + + fn dispatch_result(&mut self, token: PToken) -> Result { + if self.is_transfer_complete(token)? { + self.regs.statusset.write(|w| w.pfreeze().set_bit()); + Ok(true) + } else if self.regs.intflag.read().trfail().bit_is_set() { + self.regs.intflag.write(|w| w.trfail().set_bit()); + trace!("trfail"); + self.regs.statusset.write(|w| w.pfreeze().set_bit()); + self.log_regs(); + Err(PipeErr::TransferFail) + } else if self.desc.bank0.status_bk.read().errorflow().bit_is_set() { + trace!("errorflow"); + self.regs.statusset.write(|w| w.pfreeze().set_bit()); + self.log_regs(); + Err(PipeErr::Flow) + } else if self.desc.bank0.status_pipe.read().touter().bit_is_set() { + trace!("touter"); + self.regs.statusset.write(|w| w.pfreeze().set_bit()); + self.log_regs(); + Err(PipeErr::HWTimeout) + } else if self.desc.bank0.status_pipe.read().dtgler().bit_is_set() { + trace!("dtgler"); + self.regs.statusset.write(|w| w.pfreeze().set_bit()); + self.log_regs(); + Err(PipeErr::DataToggle) + } else { + // Nothing wrong, but not done yet. + Ok(false) + } + } + + fn is_transfer_complete(&mut self, token: PToken) -> Result { + match token { + PToken::Setup => { + if self.regs.intflag.read().txstp().bit_is_set() { + self.regs.intflag.write(|w| w.txstp().set_bit()); + Ok(true) + } else { + Ok(false) + } + } + PToken::In => { + if self.regs.intflag.read().trcpt0().bit_is_set() { + self.regs.intflag.write(|w| w.trcpt0().set_bit()); + Ok(true) + } else { + Ok(false) + } + } + PToken::Out => { + if self.regs.intflag.read().trcpt0().bit_is_set() { + self.regs.intflag.write(|w| w.trcpt0().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 + ); + } +} + +// TODO: merge into SVD for pipe cfg register. +#[derive(Copy, Clone, Debug, PartialEq)] +pub(crate) enum PToken { + Setup = 0x0, + In = 0x1, + Out = 0x2, + _Reserved = 0x3, +} + +// TODO: merge into SVD for pipe cfg register. +#[allow(unused)] +#[derive(Copy, Clone, Debug, PartialEq)] +pub(crate) enum PType { + Disabled = 0x0, + Control = 0x1, + ISO = 0x2, + Bulk = 0x3, + Interrupt = 0x4, + Extended = 0x5, + _Reserved0 = 0x06, + _Reserved1 = 0x07, +} +impl From for PType { + fn from(v: TransferType) -> Self { + match v { + TransferType::Control => Self::Control, + TransferType::Isochronous => Self::ISO, + TransferType::Bulk => Self::Bulk, + TransferType::Interrupt => Self::Interrupt, + } + } +} + +struct DataBuf<'a> { + ptr: *mut u8, + 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::(), + _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 +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(), + } + } +} + +#[repr(C, packed)] +// 16 bytes per bank. +pub(crate) struct BankDesc { + pub addr: Addr, + pub pcksize: PckSize, + pub extreg: ExtReg, + pub status_bk: StatusBk, + _reserved0: u8, + pub ctrl_pipe: CtrlPipe, + pub status_pipe: StatusPipe, + _reserved1: u8, +} + +impl BankDesc { + fn new() -> Self { + Self { + addr: Addr::from(0), + pcksize: PckSize::from(0), + extreg: ExtReg::from(0), + status_bk: StatusBk::from(0), + _reserved0: 0, + ctrl_pipe: CtrlPipe::from(0), + status_pipe: StatusPipe::from(0), + _reserved1: 0, + } + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn bank_desc_sizes() { + assert_eq!(core::mem::size_of::(), 4, "Addr register size."); + assert_eq!(core::mem::size_of::(), 4, "PckSize register size."); + assert_eq!(core::mem::size_of::(), 2, "ExtReg register size."); + assert_eq!( + core::mem::size_of::(), + 1, + "StatusBk register size." + ); + assert_eq!( + core::mem::size_of::(), + 2, + "CtrlPipe register size." + ); + assert_eq!( + core::mem::size_of::(), + 1, + "StatusPipe register size." + ); + + // addr at 0x00 for 4 + // pcksize at 0x04 for 4 + // extreg at 0x08 for 2 + // status_bk at 0x0a for 2 + // ctrl_pipe at 0x0c for 2 + // status_pipe at 0x0e for 1 + assert_eq!( + core::mem::size_of::(), + 16, + "Bank descriptor size." + ); + } + + #[test] + fn bank_desc_offsets() { + let bd = BankDesc::new(); + let base = &bd as *const _ as usize; + + assert_offset("Addr", &bd.addr, base, 0x00); + assert_offset("PckSize", &bd.pcksize, base, 0x04); + assert_offset("ExtReg", &bd.extreg, base, 0x08); + assert_offset("StatusBk", &bd.status_bk, base, 0x0a); + assert_offset("CtrlPipe", &bd.ctrl_pipe, base, 0x0c); + assert_offset("StatusPipe", &bd.status_pipe, base, 0x0e); + } + + #[test] + fn pipe_desc_size() { + assert_eq!(core::mem::size_of::(), 32); + } + + #[test] + fn pipe_desc_offsets() { + let pd = PipeDesc::new(); + let base = &pd as *const _ as usize; + + assert_offset("Bank0", &pd.bank0, base, 0x00); + assert_offset("Bank1", &pd.bank1, base, 0x10); + } + + fn assert_offset(name: &str, field: &T, base: usize, offset: usize) { + let ptr = field as *const _ as usize; + assert_eq!(ptr - base, offset, "{} register offset.", name); + } +} diff --git a/samd21-host/src/pipe/addr.rs b/samd21-host/src/pipe/addr.rs new file mode 100644 index 0000000..b3548cf --- /dev/null +++ b/samd21-host/src/pipe/addr.rs @@ -0,0 +1,98 @@ +/// § 32.8.7.2 +/// Address of the Data Buffer. +/// +/// Offset: 0x00 & 0x10 +/// Reset: 0xxxxxxxxx +/// Property: NA +#[derive(Clone, Copy, Debug)] +#[repr(C, packed)] +pub struct Addr(u32); + +pub struct R { + bits: u32, +} + +pub struct W { + bits: u32, +} + +impl Addr { + pub fn read(&self) -> R { + R { bits: self.0 } + } + + pub fn write(&mut self, f: F) + where + F: FnOnce(&mut W) -> &mut W, + { + let mut w = W { bits: self.0 }; + f(&mut w); + self.0 = w.bits; + } + + pub fn modify(&mut self, f: F) + where + for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, + { + let r = R { bits: self.0 }; + let mut w = W { bits: self.0 }; + f(&r, &mut w); + self.0 = w.bits; + } +} + +impl From for Addr { + fn from(v: u32) -> Self { + Self(v) + } +} + +impl R { + /// Value in raw bits. + pub fn bits(&self) -> u32 { + self.bits + } + + pub fn addr(&self) -> AddrR { + AddrR(self.bits) + } +} + +/// Data Pointer Address Value +/// +/// These bits define the data pointer address as an absolute double +/// word address in RAM. The two least significant bits must be zero +/// to ensure the descriptor is 32-bit aligned. +pub struct AddrR(u32); +impl AddrR { + pub fn bits(&self) -> u32 { + self.0 + } +} + +impl W { + /// Write raw bits. + pub unsafe fn bits(&mut self, v: u32) -> &mut Self { + self.bits = v; + self + } + + pub fn addr(&mut self) -> AddrW { + AddrW { w: self } + } +} + +pub struct AddrW<'a> { + w: &'a mut W, +} +impl<'a> AddrW<'a> { + pub unsafe fn bits(self, v: u32) -> &'a mut W { + // Address must be 32-bit aligned. cf §32.8.7.2 of SAMD21 data + // sheet. + assert!((v & 0x3) == 0); + self.w.bits = v; + self.w + } + + // TODO: "safe" method take a pointer instead of raw u32 +} diff --git a/samd21-host/src/pipe/ctrl_pipe.rs b/samd21-host/src/pipe/ctrl_pipe.rs new file mode 100644 index 0000000..9301d51 --- /dev/null +++ b/samd21-host/src/pipe/ctrl_pipe.rs @@ -0,0 +1,177 @@ +/// Host Control Pipe. +/// +/// Offset: 0x0c +/// Reset: 0xXXXX +/// Property: PAC Write-Protection, Write-Synchronized, Read-Synchronized +#[derive(Clone, Copy, Debug)] +#[repr(C, packed)] +pub struct CtrlPipe(u16); + +pub struct R { + bits: u16, +} + +pub struct W { + bits: u16, +} + +impl CtrlPipe { + pub fn read(&self) -> R { + R { bits: self.0 } + } + + pub fn write(&mut self, f: F) + where + F: FnOnce(&mut W) -> &mut W, + { + let mut w = W { bits: self.0 }; + f(&mut w); + self.0 = w.bits; + } +} + +impl From for CtrlPipe { + fn from(v: u16) -> Self { + Self(v) + } +} + +impl R { + /// Value in raw bits. + pub fn bits(&self) -> u16 { + self.bits + } + + pub fn permax(&self) -> PErMaxR { + let bits = { + const POS: u8 = 12; + const MASK: u16 = 0xf; + ((self.bits >> POS) & MASK) as u8 + }; + + PErMaxR(bits) + } + + pub fn pepnum(&self) -> PEpNumR { + let bits = { + const POS: u8 = 8; + const MASK: u16 = 0xf; + ((self.bits >> POS) & MASK) as u8 + }; + + PEpNumR(bits) + } + + pub fn pdaddr(&self) -> PDAddrR { + let bits = { + const POS: u8 = 0; + const MASK: u16 = 0x3f; + ((self.bits >> POS) & MASK) as u8 + }; + + PDAddrR(bits) + } +} + +/// Pipe Error Max Number +/// +/// These bits define the maximum number of error for this Pipe before +/// freezing the pipe automatically. +pub struct PErMaxR(u8); +impl PErMaxR { + pub fn max(&self) -> u8 { + self.0 + } +} + +/// Pipe EndPoint Number +/// +/// These bits define the number of endpoint for this Pipe. +pub struct PEpNumR(u8); +impl PEpNumR { + pub fn epnum(&self) -> u8 { + self.0 + } +} + +/// Pipe Device Address +/// +/// These bits define the Device Address for this pipe. +pub struct PDAddrR(u8); +impl PDAddrR { + pub fn addr(&self) -> u8 { + self.0 + } +} + +impl W { + /// Write raw bits. + + pub unsafe fn bits(&mut self, v: u16) -> &mut Self { + self.bits = v; + self + } + + pub fn permax(&mut self) -> PErMaxW { + PErMaxW { w: self } + } + + pub fn pepnum(&mut self) -> PEpNumW { + PEpNumW { w: self } + } + + pub fn pdaddr(&mut self) -> PDAddrW { + PDAddrW { w: self } + } +} + +pub struct PErMaxW<'a> { + w: &'a mut W, +} +impl<'a> PErMaxW<'a> { + pub unsafe fn bits(self, v: u8) -> &'a mut W { + const POS: u8 = 12; + const MASK: u8 = 0xf; + self.w.bits &= !((MASK as u16) << POS); + self.w.bits |= ((v & MASK) as u16) << POS; + self.w + } + + pub fn set_max(self, v: u8) -> &'a mut W { + unsafe { self.bits(v) } + } +} + +pub struct PEpNumW<'a> { + w: &'a mut W, +} +impl<'a> PEpNumW<'a> { + pub unsafe fn bits(self, v: u8) -> &'a mut W { + const POS: u8 = 8; + const MASK: u8 = 0xf; + self.w.bits &= !((MASK as u16) << POS); + self.w.bits |= ((v & MASK) as u16) << POS; + self.w + } + + pub fn set_epnum(self, v: u8) -> &'a mut W { + unsafe { self.bits(v) } + } +} + +pub struct PDAddrW<'a> { + w: &'a mut W, +} +impl<'a> PDAddrW<'a> { + pub unsafe fn bits(self, v: u8) -> &'a mut W { + const POS: u8 = 0; + const MASK: u8 = 0x3f; + self.w.bits &= !((MASK as u16) << POS); + self.w.bits |= ((v & MASK) as u16) << POS; + self.w + } + + pub fn set_addr(self, v: u8) -> &'a mut W { + unsafe { self.bits(v) } + } +} diff --git a/samd21-host/src/pipe/ext_reg.rs b/samd21-host/src/pipe/ext_reg.rs new file mode 100644 index 0000000..9778f1b --- /dev/null +++ b/samd21-host/src/pipe/ext_reg.rs @@ -0,0 +1,156 @@ +/// §32.8.7.4 +/// Extended Register. +/// +/// Offset: 0x08 +/// Reset: 0xxxxxxxx +/// Property: NA +#[derive(Clone, Copy, Debug)] +#[repr(C, packed)] +pub(crate) struct ExtReg(u16); + +pub(crate) struct R { + bits: u16, +} + +pub(crate) struct W { + bits: u16, +} + +impl ExtReg { + pub fn read(&self) -> R { + R { bits: self.0 } + } + + pub fn write(&mut self, f: F) + where + F: FnOnce(&mut W) -> &mut W, + { + let mut w = W { bits: self.0 }; + f(&mut w); + self.0 = w.bits; + } +} + +impl From for ExtReg { + fn from(v: u16) -> Self { + Self(v) + } +} + +impl R { + /// Value in raw bits. + pub fn bits(&self) -> u16 { + self.bits + } + + pub fn variable(&self) -> VariableR { + let bits = { + const POS: u8 = 4; + const MASK: u16 = 0x7ff; + (self.bits >> POS) & MASK + }; + + VariableR(bits) + } + + pub fn subpid(&self) -> SubPIDR { + let bits = { + const POS: u8 = 0; + const MASK: u16 = 0xf; + ((self.bits >> POS) & MASK) as u8 + }; + + SubPIDR(bits) + } +} + +/// Variable field send with extended token +/// +/// These bits define the VARIABLE field sent with extended token. See +/// “Section 2.1.1 Protocol Extension Token in the reference document +/// ENGINEERING CHANGE NOTICE, USB 2.0 Link Power Management +/// Addendum.” +/// +/// To support the USB2.0 Link Power Management addition the VARIABLE +/// field should be set as described below. +/// +/// | VARIABLE | Description | +/// +----------------+-----------------------+ +/// | VARIABLE[3:0] | bLinkState[1] | +/// | VARIABLE[7:4] | BESL (See LPM ECN)[2] | +/// | VARIABLE[8] | bRemoteWake[1] | +/// | VARIABLE[10:9] | Reserved | +/// +/// [1] for a definition of LPM Token bRemoteWake and bLinkState +/// fields, refer to "Table 2-3 in the reference document ENGINEERING +/// CHANGE NOTICE, USB 2.0 Link Power Management Addendum" +/// +/// [2] for a definition of LPM Token BESL field, refer to "Table 2-3 +/// in the reference document ENGINEERING CHANGE NOTICE, USB 2.0 Link +/// Power Management Addendum" and "Table X-X1 in Errata for ECN USB +/// 2.0 Link Power Management. +pub(crate) struct VariableR(u16); +impl VariableR { + pub fn bits(&self) -> u16 { + self.0 + } +} + +/// SUBPID field with extended token +/// +/// These bits define the SUBPID field sent with extended token. See +/// “Section 2.1.1 Protocol Extension Token in the reference document +/// ENGINEERING CHANGE NOTICE, USB 2.0 Link Power Management +/// Addendum”. +/// +/// To support the USB2.0 Link Power Management addition the SUBPID +/// field should be set as described in “Table 2.2 SubPID Types in the +/// reference document ENGINEERING CHANGE NOTICE, USB 2.0 Link Power +/// Management Addendum”. +pub(crate) struct SubPIDR(u8); +impl SubPIDR { + pub fn bits(&self) -> u8 { + self.0 + } +} + +impl W { + /// Write raw bits. + pub unsafe fn bits(&mut self, v: u16) -> &mut Self { + self.bits = v; + self + } + + pub fn variable(&mut self) -> VariableW { + VariableW { w: self } + } + pub fn subpid(&mut self) -> SubPIDW { + SubPIDW { w: self } + } +} + +pub(crate) struct VariableW<'a> { + w: &'a mut W, +} +impl<'a> VariableW<'a> { + pub unsafe fn bits(self, v: u16) -> &'a mut W { + const POS: u8 = 4; + const MASK: u16 = 0x7ff; + self.w.bits &= !((MASK as u16) << POS); + self.w.bits |= ((v & MASK) as u16) << POS; + self.w + } +} + +pub(crate) struct SubPIDW<'a> { + w: &'a mut W, +} +impl<'a> SubPIDW<'a> { + pub unsafe fn bits(self, v: u16) -> &'a mut W { + const POS: u8 = 0; + const MASK: u16 = 0xf; + self.w.bits &= !((MASK as u16) << POS); + self.w.bits |= ((v & MASK) as u16) << POS; + self.w + } +} diff --git a/samd21-host/src/pipe/pck_size.rs b/samd21-host/src/pipe/pck_size.rs new file mode 100644 index 0000000..acc499f --- /dev/null +++ b/samd21-host/src/pipe/pck_size.rs @@ -0,0 +1,368 @@ +/// § 32.8.7.3 +/// Packet Size. +/// +/// Offset: 0x04 & 0x14 +/// Reset: 0xxxxxxxxx +/// Property: NA +#[derive(Clone, Copy, Debug)] +#[repr(C, packed)] +pub(crate) struct PckSize(u32); + +pub(crate) struct R { + bits: u32, +} + +pub(crate) struct W { + bits: u32, +} + +impl PckSize { + pub fn read(&self) -> R { + R { bits: self.0 } + } + + pub fn write(&mut self, f: F) + where + F: FnOnce(&mut W) -> &mut W, + { + let mut w = W { bits: self.0 }; + f(&mut w); + self.0 = w.bits; + } +} + +impl From for PckSize { + fn from(v: u32) -> Self { + Self(v) + } +} + +impl R { + /// Value in raw bits. + pub fn bits(&self) -> u32 { + self.bits + } + + pub fn auto_zlp(&self) -> AutoZLPR { + let bits = { + const POS: u8 = 31; + const MASK: u32 = 1; + ((self.bits >> POS) & MASK) == 1 + }; + + AutoZLPR(bits) + } + + pub fn size(&self) -> SizeR { + let bits = { + const POS: u8 = 28; + const MASK: u32 = 0x7; + ((self.bits >> POS) & MASK) as u8 + }; + + SizeR::from(bits) + } + + pub fn multi_packet_size(&self) -> MultiPacketSizeR { + let bits = { + const POS: u8 = 14; + const MASK: u32 = 0x3fff; + ((self.bits >> POS) & MASK) as u16 + }; + + MultiPacketSizeR(bits) + } + + // Documentation is wrong on this field. Actually 14 bits from + // offset 0. + pub fn byte_count(&self) -> ByteCountR { + let bits = { + const POS: u8 = 0; + const MASK: u32 = 0x3fff; + ((self.bits >> POS) & MASK) as u16 + }; + + ByteCountR(bits) + } +} + +/// Automatic Zero Length Packet +/// +/// This bit defines the automatic Zero Length Packet mode of the +/// pipe. +/// +/// When enabled, the USB module will manage the ZLP handshake by +/// hardware. This bit is for OUT pipes only. When disabled the +/// handshake should be managed by firmware. +pub(crate) struct AutoZLPR(bool); +impl AutoZLPR { + pub fn bit(&self) -> bool { + self.0 + } + + pub fn bit_is_set(&self) -> bool { + self.bit() + } + + pub fn bit_is_clear(&self) -> bool { + !self.bit() + } +} + +/// Pipe size +/// +/// These bits contains the size of the pipe. +/// +/// These bits are cleared upon sending a USB reset. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum SizeR { + Bytes8, + Bytes16, + Bytes32, + Bytes64, + Bytes128, + Bytes256, + Bytes512, + Bytes1024, +} + +impl SizeR { + pub fn bits(&self) -> u8 { + match *self { + Self::Bytes8 => 0x0, + Self::Bytes16 => 0x1, + Self::Bytes32 => 0x2, + Self::Bytes64 => 0x3, + Self::Bytes128 => 0x4, + Self::Bytes256 => 0x5, + Self::Bytes512 => 0x6, + Self::Bytes1024 => 0x7, + } + } + + fn is_bytes8(&self) -> bool { + *self == Self::Bytes8 + } + fn is_bytes16(&self) -> bool { + *self == Self::Bytes16 + } + fn is_bytes32(&self) -> bool { + *self == Self::Bytes32 + } + fn is_bytes64(&self) -> bool { + *self == Self::Bytes64 + } + fn is_bytes128(&self) -> bool { + *self == Self::Bytes128 + } + fn is_bytes256(&self) -> bool { + *self == Self::Bytes256 + } + fn is_bytes512(&self) -> bool { + *self == Self::Bytes512 + } + fn is_bytes1024(&self) -> bool { + *self == Self::Bytes1024 + } +} + +impl From for SizeR { + fn from(v: u8) -> Self { + match v { + 0x0 => Self::Bytes8, + 0x1 => Self::Bytes16, + 0x2 => Self::Bytes32, + 0x3 => Self::Bytes64, + 0x4 => Self::Bytes128, + 0x5 => Self::Bytes256, + 0x6 => Self::Bytes512, + 0x7 => Self::Bytes1024, + _ => panic!("pcksize between 0 and 7 only"), + } + } +} + +/// Multi Packet IN or OUT size +/// +/// These bits define the 14-bit value that is used for multi-packet +/// transfers. +/// +/// For IN pipes, MULTI_PACKET_SIZE holds the total number of bytes +/// sent. MULTI_PACKET_SIZE should be written to zero when setting up +/// a new transfer. +/// +/// For OUT pipes, MULTI_PACKET_SIZE holds the total data size for the +/// complete transfer. This value must be a multiple of the maximum +/// packet size. +pub(crate) struct MultiPacketSizeR(u16); +impl MultiPacketSizeR { + pub fn bits(&self) -> u16 { + self.0 + } +} + +/// Byte Count +/// +/// These bits define the 14-bit value that contains number of bytes +/// sent in the last OUT or SETUP transaction for an OUT pipe, or of +/// the number of bytes to be received in the next IN transaction for +/// an input pipe. +pub(crate) struct ByteCountR(u16); +impl ByteCountR { + pub fn bits(&self) -> u16 { + self.0 + } +} + +impl W { + /// Write raw bits. + pub unsafe fn bits(&mut self, v: u32) -> &mut Self { + self.bits = v; + self + } + + pub fn auto_zlp(&mut self) -> AutoZLPW { + AutoZLPW { w: self } + } + + pub fn size(&mut self) -> _SizeW { + _SizeW { w: self } + } + + pub fn multi_packet_size(&mut self) -> MultiPacketSizeW { + MultiPacketSizeW { w: self } + } + + pub fn byte_count(&mut self) -> ByteCountW { + ByteCountW { w: self } + } +} + +pub(crate) struct AutoZLPW<'a> { + w: &'a mut W, +} +impl<'a> AutoZLPW<'a> { + pub fn bit(self, v: bool) -> &'a mut W { + const POS: u8 = 31; + const MASK: bool = true; + self.w.bits &= !((MASK as u32) << POS); + self.w.bits |= ((v & MASK) as u32) << POS; + self.w + } + + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } +} + +#[derive(Copy, Clone, Debug, PartialEq)] +pub(crate) enum SizeW { + Bytes8, + Bytes16, + Bytes32, + Bytes64, + Bytes128, + Bytes256, + Bytes512, + Bytes1024, +} +impl SizeW { + pub fn bits(&self) -> u8 { + match *self { + Self::Bytes8 => 0, + Self::Bytes16 => 1, + Self::Bytes32 => 2, + Self::Bytes64 => 3, + Self::Bytes128 => 4, + Self::Bytes256 => 5, + Self::Bytes512 => 6, + Self::Bytes1024 => 7, + } + } +} + +/// Proxy for `SizeW` +pub(crate) struct _SizeW<'a> { + w: &'a mut W, +} +impl<'a> _SizeW<'a> { + pub unsafe fn bits(self, v: u8) -> &'a mut W { + const POS: u8 = 28; + const MASK: u8 = 0x7; + self.w.bits &= !((MASK as u32) << POS); + self.w.bits |= ((v & MASK) as u32) << POS; + self.w + } + + pub fn variant(self, v: SizeW) -> &'a mut W { + unsafe { self.bits(v.bits()) } + } + + pub fn bytes8(self) -> &'a mut W { + self.variant(SizeW::Bytes8) + } + + pub fn bytes16(self) -> &'a mut W { + self.variant(SizeW::Bytes16) + } + + pub fn bytes32(self) -> &'a mut W { + self.variant(SizeW::Bytes32) + } + + pub fn bytes64(self) -> &'a mut W { + self.variant(SizeW::Bytes64) + } + + pub fn bytes128(self) -> &'a mut W { + self.variant(SizeW::Bytes128) + } + + pub fn bytes256(self) -> &'a mut W { + self.variant(SizeW::Bytes256) + } + + pub fn bytes512(self) -> &'a mut W { + self.variant(SizeW::Bytes512) + } + + pub fn bytes1024(self) -> &'a mut W { + self.variant(SizeW::Bytes1024) + } +} + +pub(crate) struct MultiPacketSizeW<'a> { + w: &'a mut W, +} +impl<'a> MultiPacketSizeW<'a> { + pub unsafe fn bits(self, v: u16) -> &'a mut W { + assert!(v < 16_384); + + const POS: u8 = 14; + const MASK: u16 = 0x3fff; + self.w.bits &= !((MASK as u32) << POS); + self.w.bits |= ((v & MASK) as u32) << POS; + self.w + } +} + +pub(crate) struct ByteCountW<'a> { + w: &'a mut W, +} +impl<'a> ByteCountW<'a> { + // Documentation is wrong on this field. Actually 14 bits from + // offset 0. + pub unsafe fn bits(self, v: u16) -> &'a mut W { + assert!(v < 16_384); + + const POS: u8 = 0; + const MASK: u16 = 0x3fff; + self.w.bits &= !((MASK as u32) << POS); + self.w.bits |= ((v & MASK) as u32) << POS; + self.w + } +} diff --git a/samd21-host/src/pipe/status_bk.rs b/samd21-host/src/pipe/status_bk.rs new file mode 100644 index 0000000..489fc62 --- /dev/null +++ b/samd21-host/src/pipe/status_bk.rs @@ -0,0 +1,170 @@ +/// §32.8.7.5 +/// Host Status Bank. +/// +/// Offset: 0x0a & 0x1a +/// Reset: 0xxxxxxx +/// Property: NA +#[derive(Clone, Copy, Debug)] +#[repr(C, packed)] +pub(crate) struct StatusBk(u8); + +pub(crate) struct R { + bits: u8, +} + +pub(crate) struct W { + bits: u8, +} + +impl StatusBk { + pub fn read(&self) -> R { + R { bits: self.0 } + } + + pub fn write(&mut self, f: F) + where + F: FnOnce(&mut W) -> &mut W, + { + let mut w = W { bits: self.0 }; + f(&mut w); + self.0 = w.bits; + } +} + +impl From for StatusBk { + fn from(v: u8) -> Self { + Self(v) + } +} + +impl R { + /// Value in raw bits. + pub fn bits(&self) -> u8 { + self.bits + } + + pub fn errorflow(&self) -> ErrorFlowR { + let bits = { + const POS: u8 = 1; + const MASK: u8 = 1; + ((self.bits >> POS) & MASK) == 1 + }; + + ErrorFlowR(bits) + } + + pub fn crcerr(&self) -> CRCErrR { + let bits = { + const POS: u8 = 0; + const MASK: u8 = 1; + ((self.bits >> POS) & MASK) == 1 + }; + + CRCErrR(bits) + } +} + +/// Error Flow Status +/// +/// This bit defines the Error Flow Status. +/// +/// This bit is set when a Error Flow has been detected during +/// transfer from/towards this bank. +/// +/// For IN transfer, a NAK handshake has been received. For OUT +/// transfer, a NAK handshake has been received. For Isochronous IN +/// transfer, an overrun condition has occurred. For Isochronous OUT +/// transfer, an underflow condition has occurred. +pub(crate) struct ErrorFlowR(bool); +impl ErrorFlowR { + pub fn bit(&self) -> bool { + self.0 + } + + pub fn bit_is_set(&self) -> bool { + self.bit() + } + + pub fn bit_is_clear(&self) -> bool { + !self.bit_is_set() + } +} + +/// CRC Error +/// +/// This bit defines the CRC Error Status. +/// +/// This bit is set when a CRC error has been detected in an +/// isochronous IN endpoint bank. +pub(crate) struct CRCErrR(bool); +impl CRCErrR { + pub fn bit(&self) -> bool { + self.0 + } + + pub fn bit_is_set(&self) -> bool { + self.bit() + } + + pub fn bit_is_clear(&self) -> bool { + !self.bit_is_set() + } +} + +impl W { + /// Write raw bits. + pub unsafe fn bits(&mut self, v: u8) -> &mut Self { + self.bits = v; + self + } + + pub fn errorflow(&mut self) -> ErrorFlowW { + ErrorFlowW { w: self } + } + + pub fn crcerr(&mut self) -> CRCErrW { + CRCErrW { w: self } + } +} + +pub(crate) struct ErrorFlowW<'a> { + w: &'a mut W, +} +impl<'a> ErrorFlowW<'a> { + pub fn bit(self, v: bool) -> &'a mut W { + const POS: u8 = 1; + const MASK: bool = true; + self.w.bits &= !((MASK as u8) << POS); + self.w.bits |= ((v & MASK) as u8) << POS; + self.w + } + + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } +} + +pub(crate) struct CRCErrW<'a> { + w: &'a mut W, +} +impl<'a> CRCErrW<'a> { + pub fn bit(self, v: bool) -> &'a mut W { + const POS: u8 = 0; + const MASK: bool = true; + self.w.bits &= !((MASK as u8) << POS); + self.w.bits |= ((v & MASK) as u8) << POS; + self.w + } + + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } +} diff --git a/samd21-host/src/pipe/status_pipe.rs b/samd21-host/src/pipe/status_pipe.rs new file mode 100644 index 0000000..be135c5 --- /dev/null +++ b/samd21-host/src/pipe/status_pipe.rs @@ -0,0 +1,407 @@ +/// Host Status Pipe. +/// +/// Offset: 0x0e & 0x1e +/// Reset: 0xxxxxx +/// Property: PAC Write-Protection, Write-Synchronized, Read-Synchronized +#[derive(Clone, Copy, Debug)] +#[repr(C, packed)] +pub(crate) struct StatusPipe(u8); + +pub(crate) struct R { + bits: u8, +} +pub(crate) struct W { + bits: u8, +} + +impl StatusPipe { + pub fn read(&self) -> R { + R { bits: self.0 } + } + + pub fn write(&mut self, f: F) + where + F: FnOnce(&mut W) -> &mut W, + { + let mut w = W { bits: self.0 }; + f(&mut w); + self.0 = w.bits; + } +} + +impl From for StatusPipe { + fn from(v: u8) -> Self { + Self(v) + } +} + +impl R { + /// Value in raw bits. + pub fn bits(&self) -> u8 { + self.bits + } + + pub fn ercnt(&self) -> ErCntR { + let bits = { + const POS: u8 = 5; + const MASK: u8 = 0x7; + ((self.bits >> POS) & MASK) as u8 + }; + + ErCntR(bits) + } + + pub fn crc16er(&self) -> CRC16ErR { + let bits = { + const POS: u8 = 4; + const MASK: u8 = 1; + ((self.bits >> POS) & MASK) == 1 + }; + + CRC16ErR(bits) + } + + pub fn touter(&self) -> TOutErrR { + let bits = { + const POS: u8 = 3; + const MASK: u8 = 1; + + ((self.bits >> POS) & MASK) == 1 + }; + + TOutErrR(bits) + } + + pub fn pider(&self) -> PIDErR { + let bits = { + const POS: u8 = 2; + const MASK: u8 = 1; + + ((self.bits >> POS) & MASK) == 1 + }; + + PIDErR(bits) + } + + pub fn dapider(&self) -> DaPIDErR { + let bits = { + const POS: u8 = 1; + const MASK: u8 = 1; + + ((self.bits >> POS) & MASK) == 1 + }; + + DaPIDErR(bits) + } + + pub fn dtgler(&self) -> DTglErR { + let bits = { + const POS: u8 = 0; + const MASK: u8 = 1; + + ((self.bits >> POS) & MASK) == 1 + }; + + DTglErR(bits) + } +} + +/// Pipe Error Counter +/// +/// The number of errors detected on the pipe. +pub(crate) struct ErCntR(u8); +impl ErCntR { + pub fn bits(&self) -> u8 { + self.0 + } +} + +/// CRC16 ERROR +/// +/// This bit defines the CRC16 Error Status. +/// +/// This bit is set when a CRC 16 error has been detected during a IN +/// transactions. +pub(crate) struct CRC16ErR(bool); +impl CRC16ErR { + pub fn bit(&self) -> bool { + self.0 + } + + pub fn bit_is_set(&self) -> bool { + self.bit() + } + + pub fn bit_is_clear(&self) -> bool { + !self.bit_is_set() + } +} + +/// TIME OUT ERROR +/// +/// This bit defines the Time Out Error Status. +/// +/// This bit is set when a Time Out error has been detected during a +/// USB transaction. +pub(crate) struct TOutErrR(bool); +impl TOutErrR { + pub fn bit(&self) -> bool { + self.0 + } + + pub fn bit_is_set(&self) -> bool { + self.bit() + } + + pub fn bit_is_clear(&self) -> bool { + !self.bit_is_set() + } +} + +/// PID ERROR +/// +/// This bit defines the PID Error Status. +/// +/// This bit is set when a PID error has been detected during a USB +/// transaction. +pub(crate) struct PIDErR(bool); +impl PIDErR { + pub fn bit(&self) -> bool { + self.0 + } + + pub fn bit_is_set(&self) -> bool { + self.bit() + } + + pub fn bit_is_clear(&self) -> bool { + !self.bit_is_set() + } +} + +/// Data PID ERROR +/// +/// This bit defines the PID Error Status. +/// +/// This bit is set when a Data PID error has been detected during a +/// USB transaction. +pub(crate) struct DaPIDErR(bool); +impl DaPIDErR { + pub fn bit(&self) -> bool { + self.0 + } + + pub fn bit_is_set(&self) -> bool { + self.bit() + } + + pub fn bit_is_clear(&self) -> bool { + !self.bit_is_set() + } +} + +/// Data Toggle Error +/// +/// This bit defines the Data Toggle Error Status. +/// +/// This bit is set when a Data Toggle Error has been detected. +pub(crate) struct DTglErR(bool); +impl DTglErR { + pub fn bit(&self) -> bool { + self.0 + } + + pub fn bit_is_set(&self) -> bool { + self.bit() + } + + pub fn bit_is_clear(&self) -> bool { + !self.bit_is_set() + } +} + +impl W { + /// Write raw bits. + pub unsafe fn bits(&mut self, v: u8) -> &mut Self { + self.bits = v; + self + } + + pub fn ercnt(&mut self) -> ErCntW { + ErCntW { w: self } + } + + pub fn crc16er(&mut self) -> CRC16ErW { + CRC16ErW { w: self } + } + + pub fn touter(&mut self) -> TOutErW { + TOutErW { w: self } + } + + pub fn pider(&mut self) -> PIDErW { + PIDErW { w: self } + } + + pub fn dapider(&mut self) -> DaPIDErW { + DaPIDErW { w: self } + } + + pub fn dtgler(&mut self) -> DTglErW { + DTglErW { w: self } + } +} + +/// Pipe Error Counter +/// +/// The number of errors detected on the pipe. +pub(crate) struct ErCntW<'a> { + w: &'a mut W, +} +impl<'a> ErCntW<'a> { + pub unsafe fn bits(self, v: u8) -> &'a mut W { + const POS: u8 = 5; + const MASK: u8 = 0x7; + self.w.bits &= !((MASK as u8) << POS); + self.w.bits |= ((v & MASK) as u8) << POS; + self.w + } + + pub fn set_count(self, v: u8) -> &'a mut W { + unsafe { self.bits(v) } + } +} + +/// CRC16 ERROR +/// +/// This bit defines the CRC16 Error Status. +/// +/// This bit is set when a CRC 16 error has been detected during a IN +/// transactions. +pub(crate) struct CRC16ErW<'a> { + w: &'a mut W, +} +impl<'a> CRC16ErW<'a> { + pub fn bit(self, v: bool) -> &'a mut W { + const POS: u8 = 4; + const MASK: bool = true; + self.w.bits &= !((MASK as u8) << POS); + self.w.bits |= ((v & MASK) as u8) << POS; + self.w + } + + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } +} + +/// TIME OUT ERROR +/// +/// This bit defines the Time Out Error Status. +/// +/// This bit is set when a Time Out error has been detected during a +/// USB transaction. +pub(crate) struct TOutErW<'a> { + w: &'a mut W, +} +impl<'a> TOutErW<'a> { + pub fn bit(self, v: bool) -> &'a mut W { + const POS: u8 = 3; + const MASK: bool = true; + self.w.bits &= !((MASK as u8) << POS); + self.w.bits |= ((v & MASK) as u8) << POS; + self.w + } + + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } +} + +/// PID ERROR +/// +/// This bit defines the PID Error Status. +/// +/// This bit is set when a PID error has been detected during a USB +/// transaction. +pub(crate) struct PIDErW<'a> { + w: &'a mut W, +} +impl<'a> PIDErW<'a> { + pub fn bit(self, v: bool) -> &'a mut W { + const POS: u8 = 2; + const MASK: bool = true; + self.w.bits &= !((MASK as u8) << POS); + self.w.bits |= ((v & MASK) as u8) << POS; + self.w + } + + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } +} + +/// Data PID ERROR +/// +/// This bit defines the PID Error Status. +/// +/// This bit is set when a Data PID error has been detected during a +/// USB transaction. +pub(crate) struct DaPIDErW<'a> { + w: &'a mut W, +} +impl<'a> DaPIDErW<'a> { + pub fn bit(self, v: bool) -> &'a mut W { + const POS: u8 = 1; + const MASK: bool = true; + self.w.bits &= !((MASK as u8) << POS); + self.w.bits |= ((v & MASK) as u8) << POS; + self.w + } + + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } +} + +/// Data Toggle Error +/// +/// This bit defines the Data Toggle Error Status. +/// +/// This bit is set when a Data Toggle Error has been detected. +pub(crate) struct DTglErW<'a> { + w: &'a mut W, +} +impl<'a> DTglErW<'a> { + pub fn bit(self, v: bool) -> &'a mut W { + const POS: u8 = 0; + const MASK: bool = true; + self.w.bits &= !((MASK as u8) << POS); + self.w.bits |= ((v & MASK) as u8) << POS; + self.w + } + + pub fn set_bit(self) -> &'a mut W { + self.bit(true) + } + + pub fn clear_bit(self) -> &'a mut W { + self.bit(false) + } +} diff --git a/usb-host/src/lib.rs b/usb-host/src/lib.rs old mode 100644 new mode 100755 index 831a67c..551824a --- a/usb-host/src/lib.rs +++ b/usb-host/src/lib.rs @@ -1,10 +1,13 @@ +#![no_std] + mod descriptor; mod setup; pub use descriptor::*; pub use setup::*; -pub enum Error { +#[derive(Debug)] +pub enum TransferError { Retry(&'static str), Permanent(&'static str), } @@ -18,11 +21,15 @@ pub trait USBHost { w_value: WValue, w_index: u16, buf: Option<&mut [u8]>, - ) -> Result; + ) -> Result; - fn in_transfer(&mut self, ep: &mut dyn Endpoint, buf: &mut [u8]) -> Result; + fn in_transfer( + &mut self, + ep: &mut dyn Endpoint, + buf: &mut [u8], + ) -> Result; - fn out_transfer(&mut self, ep: &mut dyn Endpoint, buf: &[u8]) -> Result; + fn out_transfer(&mut self, ep: &mut dyn Endpoint, buf: &[u8]) -> Result; } // cf §9.6.6 of USB 2.0 @@ -40,6 +47,7 @@ pub enum Direction { Out, In, } + pub trait Endpoint { fn address(&self) -> u8; @@ -60,17 +68,23 @@ pub trait Endpoint { fn set_out_toggle(&mut self, toggle: bool); } -pub trait Driver { +#[derive(Copy, Clone, Debug)] +pub enum DriverError { + Retry(u8, &'static str), + Permanent(u8, &'static str), +} +pub trait Driver: core::fmt::Debug { fn want_device(&self, device: &DeviceDescriptor) -> bool; - fn add_device(&mut self, device: DeviceDescriptor, address: u8) -> Result<(), Error>; + fn add_device(&mut self, device: DeviceDescriptor, address: u8) -> Result<(), DriverError>; fn remove_device(&mut self, address: u8); - fn tick_device( - &mut self, - address: u8, - millis: usize, - usbhost: &mut dyn USBHost, - ) -> Result<(), Error>; + fn tick(&mut self, millis: usize, usbhost: &mut dyn USBHost) -> Result<(), DriverError>; } + +// TODO: There needs to be a per-interface/function driver trait, as +// well, since that's how most drivers will actually work. +// +// As a result, the host driver has to at least get the full +// configuration. diff --git a/usbh/Cargo.lock b/usbh/Cargo.lock deleted file mode 100644 index 5b973da..0000000 --- a/usbh/Cargo.lock +++ /dev/null @@ -1,269 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -[[package]] -name = "aligned" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "aligned" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "as-slice 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "as-slice" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "generic-array 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)", - "stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "atsamd-hal" -version = "0.5.0" -dependencies = [ - "atsamd21e18a 0.4.0", - "bitfield 0.13.2 (registry+https://github.com/rust-lang/crates.io-index)", - "cortex-m 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)", - "embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "paste 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", - "vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "atsamd21e18a" -version = "0.4.0" -dependencies = [ - "bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", - "cortex-m 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)", - "vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "bare-metal" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "bitfield" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "cfg-if" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "cortex-m" -version = "0.5.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "aligned 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", - "cortex-m 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", - "volatile-register 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "cortex-m" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "aligned 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", - "bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", - "volatile-register 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "embedded-hal" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "generic-array" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "typenum 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "log" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "nb" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "paste" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "paste-impl 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", - "proc-macro-hack 0.5.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "paste-impl" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro-hack 0.5.8 (registry+https://github.com/rust-lang/crates.io-index)", - "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 0.15.42 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "proc-macro-hack" -version = "0.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 0.15.42 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "proc-macro2" -version = "0.4.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "quote" -version = "0.6.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "rb" -version = "0.1.0" - -[[package]] -name = "rustc_version" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "semver" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "semver-parser" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "stable_deref_trait" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "syn" -version = "0.15.42" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "typenum" -version = "1.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "unicode-xid" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "usbh" -version = "0.1.0" -dependencies = [ - "atsamd-hal 0.5.0", - "embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.7 (registry+https://github.com/rust-lang/crates.io-index)", - "rb 0.1.0", - "vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "vcell" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "void" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "volatile-register" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[metadata] -"checksum aligned 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d39da9b88ae1a81c03c9c082b8db83f1d0e93914126041962af61034ab44c4a5" -"checksum aligned 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d3a316c7ea8e1e9ece54862c992def5a7ac14de9f5832b69d71760680efeeefa" -"checksum as-slice 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "293dac66b274fab06f95e7efb05ec439a6b70136081ea522d270bc351ae5bb27" -"checksum bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "a3caf393d93b2d453e80638d0674597020cef3382ada454faacd43d1a55a735a" -"checksum bitfield 0.13.2 (registry+https://github.com/rust-lang/crates.io-index)" = "46afbd2983a5d5a7bd740ccb198caf5b82f45c40c09c0eed36052d91cb92e719" -"checksum cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "b486ce3ccf7ffd79fdeb678eac06a9e6c09fc88d33836340becb8fffe87c5e33" -"checksum cortex-m 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)" = "3c0b159a1e8306949579de3698c841dba58058197b65c60807194e4fa1e7a554" -"checksum cortex-m 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f3c18719fdc57db65668bfc977db9a0fa1a41d718c5d9cd4f652c9d4b0e0956a" -"checksum embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ee4908a155094da7723c2d60d617b820061e3b4efcc3d9e293d206a5a76c170b" -"checksum generic-array 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)" = "c68f0274ae0e023facc3c97b2e00f076be70e254bc851d972503b328db79b2ec" -"checksum log 0.4.7 (registry+https://github.com/rust-lang/crates.io-index)" = "c275b6ad54070ac2d665eef9197db647b32239c9d244bfb6f041a766d00da5b3" -"checksum nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "b1411551beb3c11dedfb0a90a0fa256b47d28b9ec2cdff34c25a2fa59e45dbdc" -"checksum paste 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "1f4a4a1c555c6505821f9d58b8779d0f630a6b7e4e1be24ba718610acf01fa79" -"checksum paste-impl 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "26e796e623b8b257215f27e6c80a5478856cae305f5b59810ff9acdaa34570e6" -"checksum proc-macro-hack 0.5.8 (registry+https://github.com/rust-lang/crates.io-index)" = "982a35d1194084ba319d65c4a68d24ca28f5fdb5b8bc20899e4eef8641ea5178" -"checksum proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)" = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" -"checksum quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)" = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1" -"checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" -"checksum semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" -"checksum semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" -"checksum stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8" -"checksum syn 0.15.42 (registry+https://github.com/rust-lang/crates.io-index)" = "eadc09306ca51a40555dd6fc2b415538e9e18bc9f870e47b1a524a79fe2dcf5e" -"checksum typenum 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "612d636f949607bdf9b123b4a6f6d966dedf3ff669f7f045890d3a4a73948169" -"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" -"checksum vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "45c297f0afb6928cd08ab1ff9d95e99392595ea25ae1b5ecf822ff8764e57a0d" -"checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" -"checksum volatile-register 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0d67cb4616d99b940db1d6bd28844ff97108b498a6ca850e5b6191a532063286" diff --git a/usbh/Cargo.toml b/usbh/Cargo.toml deleted file mode 100644 index ecbd6c5..0000000 --- a/usbh/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "usbh" -version = "0.1.0" -authors = ["Brian Cully "] -edition = "2018" -license = "GPL-3.0-or-later" - -[dependencies] -rb = { path = "../rb" } -atsamd-hal = { path = "../../atsamd/hal" } -embedded-hal = "~0.2" -log = "~0.4" -vcell = "~0.1" - -[features] -default = ["atsamd-hal/samd21e18a"] diff --git a/usbh/src/device.rs b/usbh/src/device.rs deleted file mode 100644 index fd5c1a1..0000000 --- a/usbh/src/device.rs +++ /dev/null @@ -1,392 +0,0 @@ -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 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; 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(millis: &'static F) -> Self - where - F: Fn() -> usize + 'static, - { - let mut devices: [Option; MAX_DEVICES] = { - let mut devs: [core::mem::MaybeUninit>; 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 { - 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 = 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; 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; MAX_ENDPOINTS] = { - let mut eps: [core::mem::MaybeUninit>; 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::::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::::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) => { - debug!("+++ 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: [u8; 8] = [0; 8]; - match pipe.in_transfer(ep, &mut buf, 15, self.millis) { - Ok(bytes_received) => info!("report {}: {} - {:?}", id, bytes_received, buf), - - Err(PipeErr::Flow) => return, - - 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, - } - } -} diff --git a/usbh/src/lib.rs b/usbh/src/lib.rs deleted file mode 100755 index 1ed414c..0000000 --- a/usbh/src/lib.rs +++ /dev/null @@ -1,474 +0,0 @@ -#![no_std] -#![allow(dead_code)] - -mod device; -mod pipe; -mod usbproto; - -use device::{Device, DeviceTable}; -use pipe::{PipeErr, PipeTable, NO_DATA_STAGE}; -use rb::{Reader, RingBuffer, Writer}; -use usbproto::*; - -use atsamd_hal::{ - calibration::{usb_transn_cal, usb_transp_cal, usb_trim_cal}, - clock::{ClockGenId, ClockSource, GenericClockController}, - gpio::{self, Floating, Input, OpenDrain, Output}, - target_device::{PM, USB}, -}; -use embedded_hal::digital::v2::OutputPin; -use log::{debug, error, trace, warn}; - -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum Event { - Error, - Detached, - Attached, -} -type Events = RingBuffer; -type EventReader = Reader<'static, Event>; -type EventWriter = Writer<'static, Event>; - -#[derive(Clone, Copy, Debug, PartialEq)] -enum DetachedState { - Initialize, - WaitForDevice, - Illegal, -} - -#[derive(Clone, Copy, Debug, PartialEq)] -enum AttachedState { - WaitForSettle(usize), - WaitResetComplete, - WaitSOF(usize), -} - -#[derive(Clone, Copy, Debug, PartialEq)] -enum SteadyState { - Configuring, - Running, - Error, -} - -#[derive(Clone, Copy, Debug, PartialEq)] -enum TaskState { - Detached(DetachedState), - Attached(AttachedState), - Steady(SteadyState), -} - -// Must be at least 100ms. cf §9.1.2 of USB 2.0. -const SETTLE_DELAY: usize = 205; // Delay in sec/1024 -const NAK_LIMIT: usize = 15; - -static mut EVENTS: Events = Events::new(Event::Error); -// FIXME: this is just for testing. The enum needs to be -// thread-safe if this is the way we're going. -static mut LATEST_EVENT: Event = Event::Detached; - -pub struct USBHost -where - F: Fn() -> usize + 'static, -{ - usb: USB, - - events: EventReader, - task_state: TaskState, - - // Need chunk of RAM for USB pipes, which gets used with DESCADD - // register. - pipe_table: PipeTable, - - devices: DeviceTable, - addr0: Device, - - // need sof 1kHz pad? - _sof_pad: gpio::Pa23, - _dm_pad: gpio::Pa24, - _dp_pad: gpio::Pa25, - host_enable_pin: Option>>, - - // To get current milliseconds. - millis: &'static F, -} - -impl USBHost -where - F: Fn() -> usize + 'static, -{ - pub fn new( - usb: USB, - sof_pin: gpio::Pa23>, - dm_pin: gpio::Pa24>, - dp_pin: gpio::Pa25>, - host_enable_pin: Option>>, - port: &mut gpio::Port, - clocks: &mut GenericClockController, - pm: &mut PM, - millis: &'static F, - ) -> (Self, impl FnMut()) { - let (eventr, mut eventw) = unsafe { EVENTS.split() }; - - let mut rc = Self { - usb: usb, - - events: eventr, - task_state: TaskState::Detached(DetachedState::Initialize), - - pipe_table: PipeTable::new(), - - devices: DeviceTable::new(millis), - addr0: Device::new(0, 8, millis), - - _sof_pad: sof_pin.into_function_g(port), - _dm_pad: dm_pin.into_function_g(port), - _dp_pad: dp_pin.into_function_g(port), - host_enable_pin: None, - - millis: millis, - }; - - if let Some(he_pin) = host_enable_pin { - rc.host_enable_pin = Some(he_pin.into_open_drain_output(port)); - } - - pm.apbbmask.modify(|_, w| w.usb_().set_bit()); - - // Set up USB clock from 48MHz source on generic clock 6. - clocks.configure_gclk_divider_and_source(ClockGenId::GCLK6, 1, ClockSource::DFLL48M, false); - let gclk6 = clocks - .get_gclk(ClockGenId::GCLK6) - .expect("Could not get clock 6"); - clocks.usb(&gclk6); - - let usbp = &rc.usb as *const _ as usize; - (rc, move || handler(usbp, &mut eventw)) - } - - pub fn reset_periph(&mut self) { - debug!("resetting usb"); - // Reset the USB peripheral and wait for sync. - self.usb.host().ctrla.write(|w| w.swrst().set_bit()); - while self.usb.host().syncbusy.read().swrst().bit_is_set() {} - - // Specify host mode. - self.usb.host().ctrla.modify(|_, w| w.mode().host()); - - // Unsafe due to use of raw bits method. - unsafe { - self.usb.host().padcal.write(|w| { - w.transn().bits(usb_transn_cal()); - w.transp().bits(usb_transp_cal()); - w.trim().bits(usb_trim_cal()) - }); - } - - // Use normal, which is 0 and apparently means low-and-full capable - self.usb.host().ctrlb.modify(|_, w| w.spdconf().normal()); - // According to docs, 1,2,3 are reserved, but .fs returns 3 - //self.usb.host().ctrlb.modify(|_, w| w.spdconf().fs()); - - self.usb.host().ctrla.modify(|_, w| w.runstdby().set_bit()); // keep usb clock running in standby. - - // Set address of USB SRAM. - // Unsafe due to use of raw bits method. - unsafe { - self.usb - .host() - .descadd - .write(|w| w.bits(&self.pipe_table as *const _ as u32)); - } - - if let Some(he_pin) = &mut self.host_enable_pin { - he_pin.set_high().expect("turning on usb host enable pin"); - } - - self.usb.host().intenset.write(|w| { - w.wakeup().set_bit(); - w.dconn().set_bit(); - w.ddisc().set_bit() - }); - - self.usb.host().ctrla.modify(|_, w| w.enable().set_bit()); - while self.usb.host().syncbusy.read().enable().bit_is_set() {} - - // Set VBUS OK to allow host operation. - self.usb.host().ctrlb.modify(|_, w| w.vbusok().set_bit()); - debug!("...done"); - } - - pub fn task(&mut self) { - static mut LAST_EVENT: Event = Event::Error; - unsafe { - if LAST_EVENT != LATEST_EVENT { - trace!("new event: {:?}", LATEST_EVENT); - } - } - - static mut LAST_TASK_STATE: TaskState = TaskState::Detached(DetachedState::Illegal); - self.task_state = match unsafe { LATEST_EVENT } { - Event::Error => TaskState::Detached(DetachedState::Illegal), - Event::Detached => { - if let TaskState::Detached(_) = self.task_state { - self.task_state - } else { - TaskState::Detached(DetachedState::Initialize) - } - } - Event::Attached => { - if let TaskState::Detached(_) = self.task_state { - TaskState::Attached(AttachedState::WaitForSettle( - (self.millis)() + SETTLE_DELAY, - )) - } else { - self.task_state - } - } - }; - - static mut LAST_CBITS: u16 = 0; - static mut LAST_FLAGS: u16 = 0; - let cbits = self.usb.host().ctrlb.read().bits(); - let bits = self.usb.host().intflag.read().bits(); - unsafe { - if LAST_CBITS != cbits || LAST_FLAGS != bits || LAST_TASK_STATE != self.task_state { - trace!( - "cb: {:x}, f: {:x} changing state {:?} -> {:?}", - cbits, - bits, - LAST_TASK_STATE, - self.task_state, - ); - } - LAST_CBITS = cbits; - LAST_FLAGS = bits; - LAST_TASK_STATE = self.task_state - }; - - if let Some(_event) = self.events.shift() { - // trace!("Found event: {:?}", event); - // self.task_state = match event { - // Event::None => TaskState::Detached(DetachedState::Illegal), - // Event::Detached => { - // if let TaskState::Detached(_) = self.task_state { - // self.task_state - // } else { - // TaskState::Detached(DetachedState::Initialize) - // } - // } - // Event::Attached => { - // if let TaskState::Detached(_) = self.task_state { - // self.delay = self.millis() + SETTLE_DELAY; - // TaskState::Attached(AttachedState::WaitForSettle) - // } else { - // self.task_state - // } - // } - // }; - } - - self.fsm(); - - unsafe { - LAST_EVENT = LATEST_EVENT; - } - } - - fn poll_devices(&mut self) {} - - fn fsm(&mut self) { - // respond to events from interrupt. - match self.task_state { - TaskState::Detached(s) => self.detached_fsm(s), - TaskState::Attached(s) => self.attached_fsm(s), - TaskState::Steady(s) => self.steady_fsm(s), - }; - } - - fn detached_fsm(&mut self, s: DetachedState) { - match s { - DetachedState::Initialize => { - self.reset_periph(); - // TODO: Free resources. - - self.task_state = TaskState::Detached(DetachedState::WaitForDevice); - } - - // Do nothing state. Just wait for an interrupt to come in - // saying we have a device attached. - DetachedState::WaitForDevice => {} - - // TODO: should probably reset everything if we end up here somehow. - DetachedState::Illegal => {} - } - } - - fn attached_fsm(&mut self, s: AttachedState) { - match s { - AttachedState::WaitForSettle(until) => { - if (self.millis)() >= until { - self.usb.host().ctrlb.modify(|_, w| w.busreset().set_bit()); - self.task_state = TaskState::Attached(AttachedState::WaitResetComplete); - } - } - - AttachedState::WaitResetComplete => { - if self.usb.host().intflag.read().rst().bit_is_set() { - trace!("reset was sent"); - self.usb.host().intflag.write(|w| w.rst().set_bit()); - - // Seems unneccesary, since SOFE will be set - // immediately after reset according to §32.6.3.3. - self.usb.host().ctrlb.modify(|_, w| w.sofe().set_bit()); - // USB spec requires 20ms of SOF after bus reset. - self.task_state = - TaskState::Attached(AttachedState::WaitSOF((self.millis)() + 20)); - } - } - - AttachedState::WaitSOF(until) => { - if self.usb.host().intflag.read().hsof().bit_is_set() { - self.usb.host().intflag.write(|w| w.hsof().set_bit()); - if (self.millis)() >= until { - self.task_state = TaskState::Steady(SteadyState::Configuring); - } - } - } - } - } - - fn steady_fsm(&mut self, s: SteadyState) { - match s { - SteadyState::Configuring => { - self.task_state = match self.configure_dev() { - Ok(_) => TaskState::Steady(SteadyState::Running), - Err(e) => { - warn!("Enumeration error: {:?}", e); - TaskState::Steady(SteadyState::Error) - } - } - } - - SteadyState::Running => { - self.devices.run(&mut self.pipe_table, self.usb.host_mut()); - } - - SteadyState::Error => {} - } - } - - fn configure_dev(&mut self) -> Result<(), PipeErr> { - let mut pipe = self - .pipe_table - .pipe_for(self.usb.host_mut(), &self.addr0.ep0); - let mut vol_descr = ::vcell::VolatileCell::::new(Default::default()); - pipe.control_transfer( - &mut self.addr0.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); - - match self.devices.next(desc.b_max_packet_size, self.millis) { - // TODO: new error for being out of devices. - None => Err(PipeErr::Other("out of devices")), - Some(device) => { - debug!("Setting address to {}.", device.addr); - pipe.control_transfer( - &mut self.addr0.ep0, - RequestType::set(), - RequestCode::SetAddress, - WValue::from((device.addr, 0)), - 0, - NO_DATA_STAGE, - self.millis, - )?; - - // Now that the device is addressed, `Device` can handle the - // rest of the setup in its FSM. - Ok(()) - } - } - } -} - -pub fn handler(usbp: usize, events: &mut EventWriter) { - let usb: &mut USB = unsafe { core::mem::transmute(usbp) }; - let flags = usb.host().intflag.read(); - - trace!("USB - {:x}", flags.bits()); - - let mut unshift_event = |e: Event| { - unsafe { LATEST_EVENT = e }; - if let Err(_) = events.unshift(e) { - error!("Couldn't write USB event to queue."); - } - }; - - if flags.hsof().bit_is_set() { - trace!(" +hsof"); - usb.host().intflag.write(|w| w.hsof().set_bit()); - unshift_event(Event::Attached); - } - - if flags.rst().bit_is_set() { - // We seem to get this whenever a device attaches/detaches. - trace!(" +rst"); - usb.host().intflag.write(|w| w.rst().set_bit()); - unshift_event(Event::Detached); - } - - if flags.uprsm().bit_is_set() { - trace!(" +uprsm"); - usb.host().intflag.write(|w| w.uprsm().set_bit()); - unshift_event(Event::Detached); - } - - if flags.dnrsm().bit_is_set() { - trace!(" +dnrsm"); - usb.host().intflag.write(|w| w.dnrsm().set_bit()); - unshift_event(Event::Detached); - } - - if flags.wakeup().bit_is_set() { - // §32.8.5.8 - since VBUSOK is set, then this happens when a - // device is connected. - trace!(" +wakeup"); - usb.host().intflag.write(|w| w.wakeup().set_bit()); - unshift_event(Event::Attached); - } - - if flags.ramacer().bit_is_set() { - trace!(" +ramacer"); - usb.host().intflag.write(|w| w.ramacer().set_bit()); - unshift_event(Event::Detached); - } - - if flags.dconn().bit_is_set() { - trace!(" +dconn"); - usb.host().intflag.write(|w| w.dconn().set_bit()); - usb.host().intenclr.write(|w| w.dconn().set_bit()); - usb.host().intflag.write(|w| w.ddisc().set_bit()); - usb.host().intenset.write(|w| w.ddisc().set_bit()); - usb.host().intflag.write(|w| w.dconn().set_bit()); - unshift_event(Event::Attached); - } - - if flags.ddisc().bit_is_set() { - trace!(" +ddisc"); - usb.host().intflag.write(|w| w.ddisc().set_bit()); - usb.host().intenclr.write(|w| w.ddisc().set_bit()); - // // Stop reset signal, in case of disconnection during reset - // uhd_stop_reset(); // nothing on samd21 - usb.host().intflag.write(|w| w.dconn().set_bit()); - usb.host().intenset.write(|w| w.dconn().set_bit()); - usb.host().intflag.write(|w| w.ddisc().set_bit()); - unshift_event(Event::Detached); - } -} diff --git a/usbh/src/pipe.rs b/usbh/src/pipe.rs deleted file mode 100644 index 80ebe11..0000000 --- a/usbh/src/pipe.rs +++ /dev/null @@ -1,800 +0,0 @@ -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::device::{Endpoint, TransferType}; - -use super::usbproto::*; - -use atsamd_hal::target_device::usb::{ - self, - host::{BINTERVAL, PCFG, PINTFLAG, PSTATUS, PSTATUSCLR, PSTATUSSET}, -}; -use core::convert::TryInto; -use log::{trace, warn}; - -// 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 { - let tbl = { - let mut tbl: [core::mem::MaybeUninit; MAX_PIPES] = - unsafe { core::mem::MaybeUninit::uninit().assume_init() }; - - for e in &mut tbl[..] { - unsafe { core::ptr::write(e.as_mut_ptr(), PipeDesc::new()) } - } - - unsafe { core::mem::transmute(tbl) } - }; - Self { tbl: tbl } - } - - pub(crate) fn pipe_for<'a, 'b>( - &'a mut self, - host: &'b mut usb::HOST, - endpoint: &Endpoint, - ) -> 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 endpoint.num == 0 { 0 } else { 1 }; - - let pregs = PipeRegs::from(host, i); - let pdesc = &mut self.tbl[i]; - - pregs.cfg.write(|w| { - let ptype = PType::from(endpoint.transfer_type) as u8; - unsafe { w.ptype().bits(ptype) } - }); - trace!( - "setting paddr of pipe {} to {}:{}", - i, - endpoint.addr, - endpoint.num - ); - pdesc.bank0.ctrl_pipe.write(|w| { - w.pdaddr().set_addr(endpoint.addr); - w.pepnum().set_epnum(endpoint.num) - }); - 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_transfer( - &mut self, - ep: &mut Endpoint, - bm_request_type: RequestType, - b_request: RequestCode, - w_value: WValue, - w_index: u16, - buf: Option<&mut T>, - millis: &dyn Fn() -> usize, - ) -> Result<(), PipeErr> { - let len = match buf { - None => 0, - _ => core::mem::size_of::(), - }; - - /* - * 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.send( - ep, - PToken::Setup, - &DataBuf::from(&mut setup_packet), - NAK_LIMIT, - millis, - )?; - - /* - * Data stage. - */ - 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(ep, b, NAK_LIMIT, millis)?; - } - - RequestDirection::HostToDevice => { - self.out_transfer(ep, b, NAK_LIMIT, millis)?; - } - } - } - - /* - * Status stage. - */ - // TODO: status stage has up to 50ms to complete. cf §9.2.6.4 - // of USB 2.0. - 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 => PToken::Out, - RequestDirection::HostToDevice => PToken::In, - }; - - trace!("dispatching status stage"); - self.dispatch_retries(ep, token, NAK_LIMIT, millis)?; - - Ok(()) - } - - fn send( - &mut self, - ep: &mut Endpoint, - token: PToken, - 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(ep, token, nak_limit, millis) - } - - pub(crate) fn in_transfer( - &mut self, - ep: &mut Endpoint, - buf: &mut T, - nak_limit: usize, - millis: &dyn Fn() -> usize, - ) -> Result { - // 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()); - trace!("--- !!! regs-pre-dispatch !!! ---"); - self.log_regs(); - - self.dispatch_retries(ep, PToken::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.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`. OR! Make the function take a mutable slice of - // u8, and leave it up to the caller to figure out how to - // deal with short packets. - Err(PipeErr::ShortPacket) - } else { - Ok(bytes_received) - } - } - - pub(crate) fn out_transfer( - &mut self, - ep: &mut Endpoint, - buf: &mut T, - nak_limit: usize, - millis: &dyn Fn() -> usize, - ) -> Result { - let db: DataBuf = buf.into(); - - trace!("p{}: Should OUT 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) } - }); - - let mut bytes_sent = 0; - while bytes_sent < db.len { - self.desc - .bank0 - .addr - .write(|w| unsafe { w.addr().bits(db.ptr as u32 + bytes_sent as u32) }); - self.dispatch_retries(ep, PToken::Out, nak_limit, millis)?; - - let sent = self.desc.bank0.pcksize.read().byte_count().bits() as usize; - bytes_sent += sent; - trace!("!! wrote {} of {}", bytes_sent, db.len); - } - - Ok(bytes_sent) - } - - pub(crate) fn dtgl(&mut self, ep: &mut Endpoint, token: PToken) { - // 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!( - "~~~ tok: {:?}, dtgl: {}, i: {}, o: {}", - token, - self.regs.status.read().dtgl().bit(), - ep.in_toggle, - ep.out_toggle, - ); - if self.regs.status.read().dtgl().bit_is_set() { - self.dtgl_set(); - } else { - self.dtgl_clear(); - } - if token == PToken::In { - ep.in_toggle = self.regs.status.read().dtgl().bit_is_set() - } else { - ep.out_toggle = self.regs.status.read().dtgl().bit_is_set() - } - } - - pub(crate) fn dtgl_set(&mut self) { - self.regs.statusset.write(|w| w.dtgl().set_bit()); - } - - pub(crate) 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) - }); - } - - // 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, - ep: &mut Endpoint, - token: PToken, - retries: usize, - millis: &dyn Fn() -> usize, - ) -> Result<(), PipeErr> { - self.dispatch_packet(ep, token); - - let until = millis() + USB_TIMEOUT; - let mut last_err = PipeErr::SWTimeout; - let mut naks = 0; - while millis() < until { - let res = self.dispatch_result(token); - match res { - Ok(true) => { - if token == PToken::In { - ep.in_toggle = self.regs.status.read().dtgl().bit_is_set(); - } else if token == PToken::Out { - ep.out_toggle = self.regs.status.read().dtgl().bit_is_set(); - } - return Ok(()); - } - Ok(false) => continue, - - Err(e) => { - last_err = e; - match last_err { - PipeErr::DataToggle => self.dtgl(ep, token), - - // Flow error on interrupt pipes means we got - // a NAK, which in this context means there's - // no data. cf §32.8.7.5 of SAM D21 data - // sheet. - PipeErr::Flow if ep.transfer_type == TransferType::Interrupt => break, - - PipeErr::Stall => break, - _ => { - naks += 1; - if naks > retries { - break; - } else { - self.dispatch_packet(ep, token); - } - } - } - } - } - } - - Err(last_err) - } - - fn dispatch_packet(&mut self, ep: &mut Endpoint, token: PToken) { - self.regs - .cfg - .modify(|_, w| unsafe { w.ptoken().bits(token as u8) }); - self.regs.intflag.modify(|_, w| w.trfail().set_bit()); - self.regs.intflag.modify(|_, w| w.perr().set_bit()); - - match token { - PToken::Setup => { - self.regs.intflag.write(|w| w.txstp().set_bit()); - self.regs.statusset.write(|w| w.bk0rdy().set_bit()); - - // Toggles should be 1 for host and function's - // sequence at end of setup transaction. cf §8.6.1 of - // USB 2.0. - self.dtgl_clear(); - ep.in_toggle = true; - ep.out_toggle = true; - } - PToken::In => { - self.regs.statusclr.write(|w| w.bk0rdy().set_bit()); - if ep.in_toggle { - self.dtgl_set(); - } else { - self.dtgl_clear(); - } - } - PToken::Out => { - self.regs.intflag.write(|w| w.trcpt0().set_bit()); - self.regs.statusset.write(|w| w.bk0rdy().set_bit()); - if ep.out_toggle { - self.dtgl_set(); - } else { - self.dtgl_clear(); - } - } - _ => {} - } - - trace!("initial regs"); - self.log_regs(); - - self.regs.statusclr.write(|w| w.pfreeze().set_bit()); - } - - fn dispatch_result(&mut self, token: PToken) -> Result { - if self.is_transfer_complete(token)? { - self.regs.statusset.write(|w| w.pfreeze().set_bit()); - Ok(true) - } else if self.regs.intflag.read().trfail().bit_is_set() { - self.regs.intflag.write(|w| w.trfail().set_bit()); - trace!("trfail"); - self.regs.statusset.write(|w| w.pfreeze().set_bit()); - self.log_regs(); - Err(PipeErr::TransferFail) - } else if self.desc.bank0.status_bk.read().errorflow().bit_is_set() { - trace!("errorflow"); - self.regs.statusset.write(|w| w.pfreeze().set_bit()); - self.log_regs(); - Err(PipeErr::Flow) - } else if self.desc.bank0.status_pipe.read().touter().bit_is_set() { - trace!("touter"); - self.regs.statusset.write(|w| w.pfreeze().set_bit()); - self.log_regs(); - Err(PipeErr::HWTimeout) - } else if self.desc.bank0.status_pipe.read().dtgler().bit_is_set() { - trace!("dtgler"); - self.regs.statusset.write(|w| w.pfreeze().set_bit()); - self.log_regs(); - Err(PipeErr::DataToggle) - } else { - // Nothing wrong, but not done yet. - Ok(false) - } - } - - fn is_transfer_complete(&mut self, token: PToken) -> Result { - match token { - PToken::Setup => { - if self.regs.intflag.read().txstp().bit_is_set() { - self.regs.intflag.write(|w| w.txstp().set_bit()); - Ok(true) - } else { - Ok(false) - } - } - PToken::In => { - if self.regs.intflag.read().trcpt0().bit_is_set() { - self.regs.intflag.write(|w| w.trcpt0().set_bit()); - Ok(true) - } else { - Ok(false) - } - } - PToken::Out => { - if self.regs.intflag.read().trcpt0().bit_is_set() { - self.regs.intflag.write(|w| w.trcpt0().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 - ); - } -} - -// TODO: merge into SVD for pipe cfg register. -#[derive(Copy, Clone, Debug, PartialEq)] -pub(crate) enum PToken { - Setup = 0x0, - In = 0x1, - Out = 0x2, - _Reserved = 0x3, -} - -// TODO: merge into SVD for pipe cfg register. -#[derive(Copy, Clone, Debug, PartialEq)] -pub(crate) enum PType { - Disabled = 0x0, - Control = 0x1, - ISO = 0x2, - Bulk = 0x3, - Interrupt = 0x4, - Extended = 0x5, - _Reserved0 = 0x06, - _Reserved1 = 0x07, -} -impl From for PType { - fn from(v: TransferType) -> Self { - match v { - TransferType::Control => Self::Control, - TransferType::Isochronous => Self::ISO, - TransferType::Bulk => Self::Bulk, - TransferType::Interrupt => Self::Interrupt, - } - } -} - -struct DataBuf<'a> { - ptr: *mut u8, - 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::(), - _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 -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(), - } - } -} - -#[repr(C, packed)] -// 16 bytes per bank. -pub(crate) struct BankDesc { - pub addr: Addr, - pub pcksize: PckSize, - pub extreg: ExtReg, - pub status_bk: StatusBk, - _reserved0: u8, - pub ctrl_pipe: CtrlPipe, - pub status_pipe: StatusPipe, - _reserved1: u8, -} - -impl BankDesc { - fn new() -> Self { - Self { - addr: Addr::from(0), - pcksize: PckSize::from(0), - extreg: ExtReg::from(0), - status_bk: StatusBk::from(0), - _reserved0: 0, - ctrl_pipe: CtrlPipe::from(0), - status_pipe: StatusPipe::from(0), - _reserved1: 0, - } - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn bank_desc_sizes() { - assert_eq!(core::mem::size_of::(), 4, "Addr register size."); - assert_eq!(core::mem::size_of::(), 4, "PckSize register size."); - assert_eq!(core::mem::size_of::(), 2, "ExtReg register size."); - assert_eq!( - core::mem::size_of::(), - 1, - "StatusBk register size." - ); - assert_eq!( - core::mem::size_of::(), - 2, - "CtrlPipe register size." - ); - assert_eq!( - core::mem::size_of::(), - 1, - "StatusPipe register size." - ); - - // addr at 0x00 for 4 - // pcksize at 0x04 for 4 - // extreg at 0x08 for 2 - // status_bk at 0x0a for 2 - // ctrl_pipe at 0x0c for 2 - // status_pipe at 0x0e for 1 - assert_eq!( - core::mem::size_of::(), - 16, - "Bank descriptor size." - ); - } - - #[test] - fn bank_desc_offsets() { - let bd = BankDesc::new(); - let base = &bd as *const _ as usize; - - assert_offset("Addr", &bd.addr, base, 0x00); - assert_offset("PckSize", &bd.pcksize, base, 0x04); - assert_offset("ExtReg", &bd.extreg, base, 0x08); - assert_offset("StatusBk", &bd.status_bk, base, 0x0a); - assert_offset("CtrlPipe", &bd.ctrl_pipe, base, 0x0c); - assert_offset("StatusPipe", &bd.status_pipe, base, 0x0e); - } - - #[test] - fn pipe_desc_size() { - assert_eq!(core::mem::size_of::(), 32); - } - - #[test] - fn pipe_desc_offsets() { - let pd = PipeDesc::new(); - let base = &pd as *const _ as usize; - - assert_offset("Bank0", &pd.bank0, base, 0x00); - assert_offset("Bank1", &pd.bank1, base, 0x10); - } - - fn assert_offset(name: &str, field: &T, base: usize, offset: usize) { - let ptr = field as *const _ as usize; - assert_eq!(ptr - base, offset, "{} register offset.", name); - } -} diff --git a/usbh/src/pipe/addr.rs b/usbh/src/pipe/addr.rs deleted file mode 100644 index aa26048..0000000 --- a/usbh/src/pipe/addr.rs +++ /dev/null @@ -1,98 +0,0 @@ -/// § 32.8.7.2 -/// Address of the Data Buffer. -/// -/// Offset: 0x00 & 0x10 -/// Reset: 0xxxxxxxxx -/// Property: NA -#[derive(Clone, Copy, Debug)] -#[repr(C, packed)] -pub(crate) struct Addr(u32); - -pub(crate) struct R { - bits: u32, -} - -pub(crate) struct W { - bits: u32, -} - -impl Addr { - pub fn read(&self) -> R { - R { bits: self.0 } - } - - pub fn write(&mut self, f: F) - where - F: FnOnce(&mut W) -> &mut W, - { - let mut w = W { bits: self.0 }; - f(&mut w); - self.0 = w.bits; - } - - pub fn modify(&mut self, f: F) - where - for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, - { - let r = R { bits: self.0 }; - let mut w = W { bits: self.0 }; - f(&r, &mut w); - self.0 = w.bits; - } -} - -impl From for Addr { - fn from(v: u32) -> Self { - Self(v) - } -} - -impl R { - /// Value in raw bits. - pub fn bits(&self) -> u32 { - self.bits - } - - pub fn addr(&self) -> AddrR { - AddrR(self.bits) - } -} - -/// Data Pointer Address Value -/// -/// These bits define the data pointer address as an absolute double -/// word address in RAM. The two least significant bits must be zero -/// to ensure the descriptor is 32-bit aligned. -pub(crate) struct AddrR(u32); -impl AddrR { - pub fn bits(&self) -> u32 { - self.0 - } -} - -impl W { - /// Write raw bits. - pub unsafe fn bits(&mut self, v: u32) -> &mut Self { - self.bits = v; - self - } - - pub fn addr(&mut self) -> AddrW { - AddrW { w: self } - } -} - -pub(crate) struct AddrW<'a> { - w: &'a mut W, -} -impl<'a> AddrW<'a> { - pub unsafe fn bits(self, v: u32) -> &'a mut W { - // Address must be 32-bit aligned. cf §32.8.7.2 of SAMD21 data - // sheet. - assert!((v & 0x3) == 0); - self.w.bits = v; - self.w - } - - // TODO: "safe" method take a pointer instead of raw u32 -} diff --git a/usbh/src/pipe/ctrl_pipe.rs b/usbh/src/pipe/ctrl_pipe.rs deleted file mode 100644 index 179b615..0000000 --- a/usbh/src/pipe/ctrl_pipe.rs +++ /dev/null @@ -1,177 +0,0 @@ -/// Host Control Pipe. -/// -/// Offset: 0x0c -/// Reset: 0xXXXX -/// Property: PAC Write-Protection, Write-Synchronized, Read-Synchronized -#[derive(Clone, Copy, Debug)] -#[repr(C, packed)] -pub(crate) struct CtrlPipe(u16); - -pub(crate) struct R { - bits: u16, -} - -pub(crate) struct W { - bits: u16, -} - -impl CtrlPipe { - pub fn read(&self) -> R { - R { bits: self.0 } - } - - pub fn write(&mut self, f: F) - where - F: FnOnce(&mut W) -> &mut W, - { - let mut w = W { bits: self.0 }; - f(&mut w); - self.0 = w.bits; - } -} - -impl From for CtrlPipe { - fn from(v: u16) -> Self { - Self(v) - } -} - -impl R { - /// Value in raw bits. - pub fn bits(&self) -> u16 { - self.bits - } - - pub fn permax(&self) -> PErMaxR { - let bits = { - const POS: u8 = 12; - const MASK: u16 = 0xf; - ((self.bits >> POS) & MASK) as u8 - }; - - PErMaxR(bits) - } - - pub fn pepnum(&self) -> PEpNumR { - let bits = { - const POS: u8 = 8; - const MASK: u16 = 0xf; - ((self.bits >> POS) & MASK) as u8 - }; - - PEpNumR(bits) - } - - pub fn pdaddr(&self) -> PDAddrR { - let bits = { - const POS: u8 = 0; - const MASK: u16 = 0x3f; - ((self.bits >> POS) & MASK) as u8 - }; - - PDAddrR(bits) - } -} - -/// Pipe Error Max Number -/// -/// These bits define the maximum number of error for this Pipe before -/// freezing the pipe automatically. -pub(crate) struct PErMaxR(u8); -impl PErMaxR { - pub fn max(&self) -> u8 { - self.0 - } -} - -/// Pipe EndPoint Number -/// -/// These bits define the number of endpoint for this Pipe. -pub(crate) struct PEpNumR(u8); -impl PEpNumR { - pub fn epnum(&self) -> u8 { - self.0 - } -} - -/// Pipe Device Address -/// -/// These bits define the Device Address for this pipe. -pub(crate) struct PDAddrR(u8); -impl PDAddrR { - pub fn addr(&self) -> u8 { - self.0 - } -} - -impl W { - /// Write raw bits. - - pub unsafe fn bits(&mut self, v: u16) -> &mut Self { - self.bits = v; - self - } - - pub fn permax(&mut self) -> PErMaxW { - PErMaxW { w: self } - } - - pub fn pepnum(&mut self) -> PEpNumW { - PEpNumW { w: self } - } - - pub fn pdaddr(&mut self) -> PDAddrW { - PDAddrW { w: self } - } -} - -pub(crate) struct PErMaxW<'a> { - w: &'a mut W, -} -impl<'a> PErMaxW<'a> { - pub unsafe fn bits(self, v: u8) -> &'a mut W { - const POS: u8 = 12; - const MASK: u8 = 0xf; - self.w.bits &= !((MASK as u16) << POS); - self.w.bits |= ((v & MASK) as u16) << POS; - self.w - } - - pub fn set_max(self, v: u8) -> &'a mut W { - unsafe { self.bits(v) } - } -} - -pub(crate) struct PEpNumW<'a> { - w: &'a mut W, -} -impl<'a> PEpNumW<'a> { - pub unsafe fn bits(self, v: u8) -> &'a mut W { - const POS: u8 = 8; - const MASK: u8 = 0xf; - self.w.bits &= !((MASK as u16) << POS); - self.w.bits |= ((v & MASK) as u16) << POS; - self.w - } - - pub fn set_epnum(self, v: u8) -> &'a mut W { - unsafe { self.bits(v) } - } -} - -pub(crate) struct PDAddrW<'a> { - w: &'a mut W, -} -impl<'a> PDAddrW<'a> { - pub unsafe fn bits(self, v: u8) -> &'a mut W { - const POS: u8 = 0; - const MASK: u8 = 0x3f; - self.w.bits &= !((MASK as u16) << POS); - self.w.bits |= ((v & MASK) as u16) << POS; - self.w - } - - pub fn set_addr(self, v: u8) -> &'a mut W { - unsafe { self.bits(v) } - } -} diff --git a/usbh/src/pipe/ext_reg.rs b/usbh/src/pipe/ext_reg.rs deleted file mode 100644 index 9778f1b..0000000 --- a/usbh/src/pipe/ext_reg.rs +++ /dev/null @@ -1,156 +0,0 @@ -/// §32.8.7.4 -/// Extended Register. -/// -/// Offset: 0x08 -/// Reset: 0xxxxxxxx -/// Property: NA -#[derive(Clone, Copy, Debug)] -#[repr(C, packed)] -pub(crate) struct ExtReg(u16); - -pub(crate) struct R { - bits: u16, -} - -pub(crate) struct W { - bits: u16, -} - -impl ExtReg { - pub fn read(&self) -> R { - R { bits: self.0 } - } - - pub fn write(&mut self, f: F) - where - F: FnOnce(&mut W) -> &mut W, - { - let mut w = W { bits: self.0 }; - f(&mut w); - self.0 = w.bits; - } -} - -impl From for ExtReg { - fn from(v: u16) -> Self { - Self(v) - } -} - -impl R { - /// Value in raw bits. - pub fn bits(&self) -> u16 { - self.bits - } - - pub fn variable(&self) -> VariableR { - let bits = { - const POS: u8 = 4; - const MASK: u16 = 0x7ff; - (self.bits >> POS) & MASK - }; - - VariableR(bits) - } - - pub fn subpid(&self) -> SubPIDR { - let bits = { - const POS: u8 = 0; - const MASK: u16 = 0xf; - ((self.bits >> POS) & MASK) as u8 - }; - - SubPIDR(bits) - } -} - -/// Variable field send with extended token -/// -/// These bits define the VARIABLE field sent with extended token. See -/// “Section 2.1.1 Protocol Extension Token in the reference document -/// ENGINEERING CHANGE NOTICE, USB 2.0 Link Power Management -/// Addendum.” -/// -/// To support the USB2.0 Link Power Management addition the VARIABLE -/// field should be set as described below. -/// -/// | VARIABLE | Description | -/// +----------------+-----------------------+ -/// | VARIABLE[3:0] | bLinkState[1] | -/// | VARIABLE[7:4] | BESL (See LPM ECN)[2] | -/// | VARIABLE[8] | bRemoteWake[1] | -/// | VARIABLE[10:9] | Reserved | -/// -/// [1] for a definition of LPM Token bRemoteWake and bLinkState -/// fields, refer to "Table 2-3 in the reference document ENGINEERING -/// CHANGE NOTICE, USB 2.0 Link Power Management Addendum" -/// -/// [2] for a definition of LPM Token BESL field, refer to "Table 2-3 -/// in the reference document ENGINEERING CHANGE NOTICE, USB 2.0 Link -/// Power Management Addendum" and "Table X-X1 in Errata for ECN USB -/// 2.0 Link Power Management. -pub(crate) struct VariableR(u16); -impl VariableR { - pub fn bits(&self) -> u16 { - self.0 - } -} - -/// SUBPID field with extended token -/// -/// These bits define the SUBPID field sent with extended token. See -/// “Section 2.1.1 Protocol Extension Token in the reference document -/// ENGINEERING CHANGE NOTICE, USB 2.0 Link Power Management -/// Addendum”. -/// -/// To support the USB2.0 Link Power Management addition the SUBPID -/// field should be set as described in “Table 2.2 SubPID Types in the -/// reference document ENGINEERING CHANGE NOTICE, USB 2.0 Link Power -/// Management Addendum”. -pub(crate) struct SubPIDR(u8); -impl SubPIDR { - pub fn bits(&self) -> u8 { - self.0 - } -} - -impl W { - /// Write raw bits. - pub unsafe fn bits(&mut self, v: u16) -> &mut Self { - self.bits = v; - self - } - - pub fn variable(&mut self) -> VariableW { - VariableW { w: self } - } - pub fn subpid(&mut self) -> SubPIDW { - SubPIDW { w: self } - } -} - -pub(crate) struct VariableW<'a> { - w: &'a mut W, -} -impl<'a> VariableW<'a> { - pub unsafe fn bits(self, v: u16) -> &'a mut W { - const POS: u8 = 4; - const MASK: u16 = 0x7ff; - self.w.bits &= !((MASK as u16) << POS); - self.w.bits |= ((v & MASK) as u16) << POS; - self.w - } -} - -pub(crate) struct SubPIDW<'a> { - w: &'a mut W, -} -impl<'a> SubPIDW<'a> { - pub unsafe fn bits(self, v: u16) -> &'a mut W { - const POS: u8 = 0; - const MASK: u16 = 0xf; - self.w.bits &= !((MASK as u16) << POS); - self.w.bits |= ((v & MASK) as u16) << POS; - self.w - } -} diff --git a/usbh/src/pipe/pck_size.rs b/usbh/src/pipe/pck_size.rs deleted file mode 100644 index acc499f..0000000 --- a/usbh/src/pipe/pck_size.rs +++ /dev/null @@ -1,368 +0,0 @@ -/// § 32.8.7.3 -/// Packet Size. -/// -/// Offset: 0x04 & 0x14 -/// Reset: 0xxxxxxxxx -/// Property: NA -#[derive(Clone, Copy, Debug)] -#[repr(C, packed)] -pub(crate) struct PckSize(u32); - -pub(crate) struct R { - bits: u32, -} - -pub(crate) struct W { - bits: u32, -} - -impl PckSize { - pub fn read(&self) -> R { - R { bits: self.0 } - } - - pub fn write(&mut self, f: F) - where - F: FnOnce(&mut W) -> &mut W, - { - let mut w = W { bits: self.0 }; - f(&mut w); - self.0 = w.bits; - } -} - -impl From for PckSize { - fn from(v: u32) -> Self { - Self(v) - } -} - -impl R { - /// Value in raw bits. - pub fn bits(&self) -> u32 { - self.bits - } - - pub fn auto_zlp(&self) -> AutoZLPR { - let bits = { - const POS: u8 = 31; - const MASK: u32 = 1; - ((self.bits >> POS) & MASK) == 1 - }; - - AutoZLPR(bits) - } - - pub fn size(&self) -> SizeR { - let bits = { - const POS: u8 = 28; - const MASK: u32 = 0x7; - ((self.bits >> POS) & MASK) as u8 - }; - - SizeR::from(bits) - } - - pub fn multi_packet_size(&self) -> MultiPacketSizeR { - let bits = { - const POS: u8 = 14; - const MASK: u32 = 0x3fff; - ((self.bits >> POS) & MASK) as u16 - }; - - MultiPacketSizeR(bits) - } - - // Documentation is wrong on this field. Actually 14 bits from - // offset 0. - pub fn byte_count(&self) -> ByteCountR { - let bits = { - const POS: u8 = 0; - const MASK: u32 = 0x3fff; - ((self.bits >> POS) & MASK) as u16 - }; - - ByteCountR(bits) - } -} - -/// Automatic Zero Length Packet -/// -/// This bit defines the automatic Zero Length Packet mode of the -/// pipe. -/// -/// When enabled, the USB module will manage the ZLP handshake by -/// hardware. This bit is for OUT pipes only. When disabled the -/// handshake should be managed by firmware. -pub(crate) struct AutoZLPR(bool); -impl AutoZLPR { - pub fn bit(&self) -> bool { - self.0 - } - - pub fn bit_is_set(&self) -> bool { - self.bit() - } - - pub fn bit_is_clear(&self) -> bool { - !self.bit() - } -} - -/// Pipe size -/// -/// These bits contains the size of the pipe. -/// -/// These bits are cleared upon sending a USB reset. -#[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) enum SizeR { - Bytes8, - Bytes16, - Bytes32, - Bytes64, - Bytes128, - Bytes256, - Bytes512, - Bytes1024, -} - -impl SizeR { - pub fn bits(&self) -> u8 { - match *self { - Self::Bytes8 => 0x0, - Self::Bytes16 => 0x1, - Self::Bytes32 => 0x2, - Self::Bytes64 => 0x3, - Self::Bytes128 => 0x4, - Self::Bytes256 => 0x5, - Self::Bytes512 => 0x6, - Self::Bytes1024 => 0x7, - } - } - - fn is_bytes8(&self) -> bool { - *self == Self::Bytes8 - } - fn is_bytes16(&self) -> bool { - *self == Self::Bytes16 - } - fn is_bytes32(&self) -> bool { - *self == Self::Bytes32 - } - fn is_bytes64(&self) -> bool { - *self == Self::Bytes64 - } - fn is_bytes128(&self) -> bool { - *self == Self::Bytes128 - } - fn is_bytes256(&self) -> bool { - *self == Self::Bytes256 - } - fn is_bytes512(&self) -> bool { - *self == Self::Bytes512 - } - fn is_bytes1024(&self) -> bool { - *self == Self::Bytes1024 - } -} - -impl From for SizeR { - fn from(v: u8) -> Self { - match v { - 0x0 => Self::Bytes8, - 0x1 => Self::Bytes16, - 0x2 => Self::Bytes32, - 0x3 => Self::Bytes64, - 0x4 => Self::Bytes128, - 0x5 => Self::Bytes256, - 0x6 => Self::Bytes512, - 0x7 => Self::Bytes1024, - _ => panic!("pcksize between 0 and 7 only"), - } - } -} - -/// Multi Packet IN or OUT size -/// -/// These bits define the 14-bit value that is used for multi-packet -/// transfers. -/// -/// For IN pipes, MULTI_PACKET_SIZE holds the total number of bytes -/// sent. MULTI_PACKET_SIZE should be written to zero when setting up -/// a new transfer. -/// -/// For OUT pipes, MULTI_PACKET_SIZE holds the total data size for the -/// complete transfer. This value must be a multiple of the maximum -/// packet size. -pub(crate) struct MultiPacketSizeR(u16); -impl MultiPacketSizeR { - pub fn bits(&self) -> u16 { - self.0 - } -} - -/// Byte Count -/// -/// These bits define the 14-bit value that contains number of bytes -/// sent in the last OUT or SETUP transaction for an OUT pipe, or of -/// the number of bytes to be received in the next IN transaction for -/// an input pipe. -pub(crate) struct ByteCountR(u16); -impl ByteCountR { - pub fn bits(&self) -> u16 { - self.0 - } -} - -impl W { - /// Write raw bits. - pub unsafe fn bits(&mut self, v: u32) -> &mut Self { - self.bits = v; - self - } - - pub fn auto_zlp(&mut self) -> AutoZLPW { - AutoZLPW { w: self } - } - - pub fn size(&mut self) -> _SizeW { - _SizeW { w: self } - } - - pub fn multi_packet_size(&mut self) -> MultiPacketSizeW { - MultiPacketSizeW { w: self } - } - - pub fn byte_count(&mut self) -> ByteCountW { - ByteCountW { w: self } - } -} - -pub(crate) struct AutoZLPW<'a> { - w: &'a mut W, -} -impl<'a> AutoZLPW<'a> { - pub fn bit(self, v: bool) -> &'a mut W { - const POS: u8 = 31; - const MASK: bool = true; - self.w.bits &= !((MASK as u32) << POS); - self.w.bits |= ((v & MASK) as u32) << POS; - self.w - } - - pub fn set_bit(self) -> &'a mut W { - self.bit(true) - } - - pub fn clear_bit(self) -> &'a mut W { - self.bit(false) - } -} - -#[derive(Copy, Clone, Debug, PartialEq)] -pub(crate) enum SizeW { - Bytes8, - Bytes16, - Bytes32, - Bytes64, - Bytes128, - Bytes256, - Bytes512, - Bytes1024, -} -impl SizeW { - pub fn bits(&self) -> u8 { - match *self { - Self::Bytes8 => 0, - Self::Bytes16 => 1, - Self::Bytes32 => 2, - Self::Bytes64 => 3, - Self::Bytes128 => 4, - Self::Bytes256 => 5, - Self::Bytes512 => 6, - Self::Bytes1024 => 7, - } - } -} - -/// Proxy for `SizeW` -pub(crate) struct _SizeW<'a> { - w: &'a mut W, -} -impl<'a> _SizeW<'a> { - pub unsafe fn bits(self, v: u8) -> &'a mut W { - const POS: u8 = 28; - const MASK: u8 = 0x7; - self.w.bits &= !((MASK as u32) << POS); - self.w.bits |= ((v & MASK) as u32) << POS; - self.w - } - - pub fn variant(self, v: SizeW) -> &'a mut W { - unsafe { self.bits(v.bits()) } - } - - pub fn bytes8(self) -> &'a mut W { - self.variant(SizeW::Bytes8) - } - - pub fn bytes16(self) -> &'a mut W { - self.variant(SizeW::Bytes16) - } - - pub fn bytes32(self) -> &'a mut W { - self.variant(SizeW::Bytes32) - } - - pub fn bytes64(self) -> &'a mut W { - self.variant(SizeW::Bytes64) - } - - pub fn bytes128(self) -> &'a mut W { - self.variant(SizeW::Bytes128) - } - - pub fn bytes256(self) -> &'a mut W { - self.variant(SizeW::Bytes256) - } - - pub fn bytes512(self) -> &'a mut W { - self.variant(SizeW::Bytes512) - } - - pub fn bytes1024(self) -> &'a mut W { - self.variant(SizeW::Bytes1024) - } -} - -pub(crate) struct MultiPacketSizeW<'a> { - w: &'a mut W, -} -impl<'a> MultiPacketSizeW<'a> { - pub unsafe fn bits(self, v: u16) -> &'a mut W { - assert!(v < 16_384); - - const POS: u8 = 14; - const MASK: u16 = 0x3fff; - self.w.bits &= !((MASK as u32) << POS); - self.w.bits |= ((v & MASK) as u32) << POS; - self.w - } -} - -pub(crate) struct ByteCountW<'a> { - w: &'a mut W, -} -impl<'a> ByteCountW<'a> { - // Documentation is wrong on this field. Actually 14 bits from - // offset 0. - pub unsafe fn bits(self, v: u16) -> &'a mut W { - assert!(v < 16_384); - - const POS: u8 = 0; - const MASK: u16 = 0x3fff; - self.w.bits &= !((MASK as u32) << POS); - self.w.bits |= ((v & MASK) as u32) << POS; - self.w - } -} diff --git a/usbh/src/pipe/status_bk.rs b/usbh/src/pipe/status_bk.rs deleted file mode 100644 index 489fc62..0000000 --- a/usbh/src/pipe/status_bk.rs +++ /dev/null @@ -1,170 +0,0 @@ -/// §32.8.7.5 -/// Host Status Bank. -/// -/// Offset: 0x0a & 0x1a -/// Reset: 0xxxxxxx -/// Property: NA -#[derive(Clone, Copy, Debug)] -#[repr(C, packed)] -pub(crate) struct StatusBk(u8); - -pub(crate) struct R { - bits: u8, -} - -pub(crate) struct W { - bits: u8, -} - -impl StatusBk { - pub fn read(&self) -> R { - R { bits: self.0 } - } - - pub fn write(&mut self, f: F) - where - F: FnOnce(&mut W) -> &mut W, - { - let mut w = W { bits: self.0 }; - f(&mut w); - self.0 = w.bits; - } -} - -impl From for StatusBk { - fn from(v: u8) -> Self { - Self(v) - } -} - -impl R { - /// Value in raw bits. - pub fn bits(&self) -> u8 { - self.bits - } - - pub fn errorflow(&self) -> ErrorFlowR { - let bits = { - const POS: u8 = 1; - const MASK: u8 = 1; - ((self.bits >> POS) & MASK) == 1 - }; - - ErrorFlowR(bits) - } - - pub fn crcerr(&self) -> CRCErrR { - let bits = { - const POS: u8 = 0; - const MASK: u8 = 1; - ((self.bits >> POS) & MASK) == 1 - }; - - CRCErrR(bits) - } -} - -/// Error Flow Status -/// -/// This bit defines the Error Flow Status. -/// -/// This bit is set when a Error Flow has been detected during -/// transfer from/towards this bank. -/// -/// For IN transfer, a NAK handshake has been received. For OUT -/// transfer, a NAK handshake has been received. For Isochronous IN -/// transfer, an overrun condition has occurred. For Isochronous OUT -/// transfer, an underflow condition has occurred. -pub(crate) struct ErrorFlowR(bool); -impl ErrorFlowR { - pub fn bit(&self) -> bool { - self.0 - } - - pub fn bit_is_set(&self) -> bool { - self.bit() - } - - pub fn bit_is_clear(&self) -> bool { - !self.bit_is_set() - } -} - -/// CRC Error -/// -/// This bit defines the CRC Error Status. -/// -/// This bit is set when a CRC error has been detected in an -/// isochronous IN endpoint bank. -pub(crate) struct CRCErrR(bool); -impl CRCErrR { - pub fn bit(&self) -> bool { - self.0 - } - - pub fn bit_is_set(&self) -> bool { - self.bit() - } - - pub fn bit_is_clear(&self) -> bool { - !self.bit_is_set() - } -} - -impl W { - /// Write raw bits. - pub unsafe fn bits(&mut self, v: u8) -> &mut Self { - self.bits = v; - self - } - - pub fn errorflow(&mut self) -> ErrorFlowW { - ErrorFlowW { w: self } - } - - pub fn crcerr(&mut self) -> CRCErrW { - CRCErrW { w: self } - } -} - -pub(crate) struct ErrorFlowW<'a> { - w: &'a mut W, -} -impl<'a> ErrorFlowW<'a> { - pub fn bit(self, v: bool) -> &'a mut W { - const POS: u8 = 1; - const MASK: bool = true; - self.w.bits &= !((MASK as u8) << POS); - self.w.bits |= ((v & MASK) as u8) << POS; - self.w - } - - pub fn set_bit(self) -> &'a mut W { - self.bit(true) - } - - pub fn clear_bit(self) -> &'a mut W { - self.bit(false) - } -} - -pub(crate) struct CRCErrW<'a> { - w: &'a mut W, -} -impl<'a> CRCErrW<'a> { - pub fn bit(self, v: bool) -> &'a mut W { - const POS: u8 = 0; - const MASK: bool = true; - self.w.bits &= !((MASK as u8) << POS); - self.w.bits |= ((v & MASK) as u8) << POS; - self.w - } - - pub fn set_bit(self) -> &'a mut W { - self.bit(true) - } - - pub fn clear_bit(self) -> &'a mut W { - self.bit(false) - } -} diff --git a/usbh/src/pipe/status_pipe.rs b/usbh/src/pipe/status_pipe.rs deleted file mode 100644 index be135c5..0000000 --- a/usbh/src/pipe/status_pipe.rs +++ /dev/null @@ -1,407 +0,0 @@ -/// Host Status Pipe. -/// -/// Offset: 0x0e & 0x1e -/// Reset: 0xxxxxx -/// Property: PAC Write-Protection, Write-Synchronized, Read-Synchronized -#[derive(Clone, Copy, Debug)] -#[repr(C, packed)] -pub(crate) struct StatusPipe(u8); - -pub(crate) struct R { - bits: u8, -} -pub(crate) struct W { - bits: u8, -} - -impl StatusPipe { - pub fn read(&self) -> R { - R { bits: self.0 } - } - - pub fn write(&mut self, f: F) - where - F: FnOnce(&mut W) -> &mut W, - { - let mut w = W { bits: self.0 }; - f(&mut w); - self.0 = w.bits; - } -} - -impl From for StatusPipe { - fn from(v: u8) -> Self { - Self(v) - } -} - -impl R { - /// Value in raw bits. - pub fn bits(&self) -> u8 { - self.bits - } - - pub fn ercnt(&self) -> ErCntR { - let bits = { - const POS: u8 = 5; - const MASK: u8 = 0x7; - ((self.bits >> POS) & MASK) as u8 - }; - - ErCntR(bits) - } - - pub fn crc16er(&self) -> CRC16ErR { - let bits = { - const POS: u8 = 4; - const MASK: u8 = 1; - ((self.bits >> POS) & MASK) == 1 - }; - - CRC16ErR(bits) - } - - pub fn touter(&self) -> TOutErrR { - let bits = { - const POS: u8 = 3; - const MASK: u8 = 1; - - ((self.bits >> POS) & MASK) == 1 - }; - - TOutErrR(bits) - } - - pub fn pider(&self) -> PIDErR { - let bits = { - const POS: u8 = 2; - const MASK: u8 = 1; - - ((self.bits >> POS) & MASK) == 1 - }; - - PIDErR(bits) - } - - pub fn dapider(&self) -> DaPIDErR { - let bits = { - const POS: u8 = 1; - const MASK: u8 = 1; - - ((self.bits >> POS) & MASK) == 1 - }; - - DaPIDErR(bits) - } - - pub fn dtgler(&self) -> DTglErR { - let bits = { - const POS: u8 = 0; - const MASK: u8 = 1; - - ((self.bits >> POS) & MASK) == 1 - }; - - DTglErR(bits) - } -} - -/// Pipe Error Counter -/// -/// The number of errors detected on the pipe. -pub(crate) struct ErCntR(u8); -impl ErCntR { - pub fn bits(&self) -> u8 { - self.0 - } -} - -/// CRC16 ERROR -/// -/// This bit defines the CRC16 Error Status. -/// -/// This bit is set when a CRC 16 error has been detected during a IN -/// transactions. -pub(crate) struct CRC16ErR(bool); -impl CRC16ErR { - pub fn bit(&self) -> bool { - self.0 - } - - pub fn bit_is_set(&self) -> bool { - self.bit() - } - - pub fn bit_is_clear(&self) -> bool { - !self.bit_is_set() - } -} - -/// TIME OUT ERROR -/// -/// This bit defines the Time Out Error Status. -/// -/// This bit is set when a Time Out error has been detected during a -/// USB transaction. -pub(crate) struct TOutErrR(bool); -impl TOutErrR { - pub fn bit(&self) -> bool { - self.0 - } - - pub fn bit_is_set(&self) -> bool { - self.bit() - } - - pub fn bit_is_clear(&self) -> bool { - !self.bit_is_set() - } -} - -/// PID ERROR -/// -/// This bit defines the PID Error Status. -/// -/// This bit is set when a PID error has been detected during a USB -/// transaction. -pub(crate) struct PIDErR(bool); -impl PIDErR { - pub fn bit(&self) -> bool { - self.0 - } - - pub fn bit_is_set(&self) -> bool { - self.bit() - } - - pub fn bit_is_clear(&self) -> bool { - !self.bit_is_set() - } -} - -/// Data PID ERROR -/// -/// This bit defines the PID Error Status. -/// -/// This bit is set when a Data PID error has been detected during a -/// USB transaction. -pub(crate) struct DaPIDErR(bool); -impl DaPIDErR { - pub fn bit(&self) -> bool { - self.0 - } - - pub fn bit_is_set(&self) -> bool { - self.bit() - } - - pub fn bit_is_clear(&self) -> bool { - !self.bit_is_set() - } -} - -/// Data Toggle Error -/// -/// This bit defines the Data Toggle Error Status. -/// -/// This bit is set when a Data Toggle Error has been detected. -pub(crate) struct DTglErR(bool); -impl DTglErR { - pub fn bit(&self) -> bool { - self.0 - } - - pub fn bit_is_set(&self) -> bool { - self.bit() - } - - pub fn bit_is_clear(&self) -> bool { - !self.bit_is_set() - } -} - -impl W { - /// Write raw bits. - pub unsafe fn bits(&mut self, v: u8) -> &mut Self { - self.bits = v; - self - } - - pub fn ercnt(&mut self) -> ErCntW { - ErCntW { w: self } - } - - pub fn crc16er(&mut self) -> CRC16ErW { - CRC16ErW { w: self } - } - - pub fn touter(&mut self) -> TOutErW { - TOutErW { w: self } - } - - pub fn pider(&mut self) -> PIDErW { - PIDErW { w: self } - } - - pub fn dapider(&mut self) -> DaPIDErW { - DaPIDErW { w: self } - } - - pub fn dtgler(&mut self) -> DTglErW { - DTglErW { w: self } - } -} - -/// Pipe Error Counter -/// -/// The number of errors detected on the pipe. -pub(crate) struct ErCntW<'a> { - w: &'a mut W, -} -impl<'a> ErCntW<'a> { - pub unsafe fn bits(self, v: u8) -> &'a mut W { - const POS: u8 = 5; - const MASK: u8 = 0x7; - self.w.bits &= !((MASK as u8) << POS); - self.w.bits |= ((v & MASK) as u8) << POS; - self.w - } - - pub fn set_count(self, v: u8) -> &'a mut W { - unsafe { self.bits(v) } - } -} - -/// CRC16 ERROR -/// -/// This bit defines the CRC16 Error Status. -/// -/// This bit is set when a CRC 16 error has been detected during a IN -/// transactions. -pub(crate) struct CRC16ErW<'a> { - w: &'a mut W, -} -impl<'a> CRC16ErW<'a> { - pub fn bit(self, v: bool) -> &'a mut W { - const POS: u8 = 4; - const MASK: bool = true; - self.w.bits &= !((MASK as u8) << POS); - self.w.bits |= ((v & MASK) as u8) << POS; - self.w - } - - pub fn set_bit(self) -> &'a mut W { - self.bit(true) - } - - pub fn clear_bit(self) -> &'a mut W { - self.bit(false) - } -} - -/// TIME OUT ERROR -/// -/// This bit defines the Time Out Error Status. -/// -/// This bit is set when a Time Out error has been detected during a -/// USB transaction. -pub(crate) struct TOutErW<'a> { - w: &'a mut W, -} -impl<'a> TOutErW<'a> { - pub fn bit(self, v: bool) -> &'a mut W { - const POS: u8 = 3; - const MASK: bool = true; - self.w.bits &= !((MASK as u8) << POS); - self.w.bits |= ((v & MASK) as u8) << POS; - self.w - } - - pub fn set_bit(self) -> &'a mut W { - self.bit(true) - } - - pub fn clear_bit(self) -> &'a mut W { - self.bit(false) - } -} - -/// PID ERROR -/// -/// This bit defines the PID Error Status. -/// -/// This bit is set when a PID error has been detected during a USB -/// transaction. -pub(crate) struct PIDErW<'a> { - w: &'a mut W, -} -impl<'a> PIDErW<'a> { - pub fn bit(self, v: bool) -> &'a mut W { - const POS: u8 = 2; - const MASK: bool = true; - self.w.bits &= !((MASK as u8) << POS); - self.w.bits |= ((v & MASK) as u8) << POS; - self.w - } - - pub fn set_bit(self) -> &'a mut W { - self.bit(true) - } - - pub fn clear_bit(self) -> &'a mut W { - self.bit(false) - } -} - -/// Data PID ERROR -/// -/// This bit defines the PID Error Status. -/// -/// This bit is set when a Data PID error has been detected during a -/// USB transaction. -pub(crate) struct DaPIDErW<'a> { - w: &'a mut W, -} -impl<'a> DaPIDErW<'a> { - pub fn bit(self, v: bool) -> &'a mut W { - const POS: u8 = 1; - const MASK: bool = true; - self.w.bits &= !((MASK as u8) << POS); - self.w.bits |= ((v & MASK) as u8) << POS; - self.w - } - - pub fn set_bit(self) -> &'a mut W { - self.bit(true) - } - - pub fn clear_bit(self) -> &'a mut W { - self.bit(false) - } -} - -/// Data Toggle Error -/// -/// This bit defines the Data Toggle Error Status. -/// -/// This bit is set when a Data Toggle Error has been detected. -pub(crate) struct DTglErW<'a> { - w: &'a mut W, -} -impl<'a> DTglErW<'a> { - pub fn bit(self, v: bool) -> &'a mut W { - const POS: u8 = 0; - const MASK: bool = true; - self.w.bits &= !((MASK as u8) << POS); - self.w.bits |= ((v & MASK) as u8) << POS; - self.w - } - - pub fn set_bit(self) -> &'a mut W { - self.bit(true) - } - - pub fn clear_bit(self) -> &'a mut W { - self.bit(false) - } -} diff --git a/usbh/src/usbproto.rs b/usbh/src/usbproto.rs deleted file mode 100644 index 33bc28c..0000000 --- a/usbh/src/usbproto.rs +++ /dev/null @@ -1,438 +0,0 @@ -/// USB Protocol level types and functions. -/// -/// Everything in here is defined by the USB specification, and -/// hardware independent. -use core::convert::TryFrom; -use core::convert::TryInto; - -// TODO: Put protocol section references in for types and -// documentation. - -#[derive(Copy, Clone, Debug, Default, PartialEq)] -#[repr(C, packed)] -pub struct DeviceDescriptor { - pub b_length: u8, - pub b_descriptor_type: DescriptorType, - pub bcd_usb: u16, - pub b_device_class: u8, - pub b_device_sub_class: u8, - pub b_device_protocol: u8, - pub b_max_packet_size: u8, - pub id_vendor: u16, - pub id_product: u16, - pub bcd_device: u16, - pub i_manufacturer: u8, - pub i_product: u8, - pub i_serial_number: u8, - pub b_num_configurations: u8, -} - -#[derive(Copy, Clone, Debug, Default, PartialEq)] -#[repr(C, packed)] -pub struct ConfigurationDescriptor { - pub b_length: u8, - pub b_descriptor_type: DescriptorType, - pub w_total_length: u16, - pub b_num_interfaces: u8, - pub b_configuration_value: u8, - pub i_configuration: u8, - pub bm_attributes: u8, - pub b_max_power: u8, -} - -#[derive(Copy, Clone, Debug, Default, PartialEq)] -#[repr(C, packed)] -pub struct InterfaceDescriptor { - pub b_length: u8, - pub b_descriptor_type: DescriptorType, - pub b_interface_number: u8, - pub b_alternate_setting: u8, - pub b_num_endpoints: u8, - pub b_interface_class: u8, - pub b_interface_sub_class: u8, - pub b_interface_protocol: u8, - pub i_interface: u8, -} - -#[derive(Copy, Clone, Debug, Default, PartialEq)] -#[repr(C, packed)] -pub struct EndpointDescriptor { - pub b_length: u8, - pub b_descriptor_type: DescriptorType, - pub b_endpoint_address: u8, - pub bm_attributes: u8, - pub w_max_packet_size: u16, - pub b_interval: u8, -} - -#[derive(Copy, Clone, Debug, Default, PartialEq)] -#[repr(C, packed)] -pub struct SetupPacket { - pub bm_request_type: RequestType, - pub b_request: RequestCode, - pub w_value: WValue, - pub w_index: u16, - pub w_length: u16, -} - -#[derive(Clone, Copy, Debug, Default, PartialEq)] -#[repr(C)] -pub struct RequestType(u8); -impl RequestType { - // Get descriptor request type. - pub fn get_descr() -> Self { - Self::from(( - RequestDirection::DeviceToHost, - RequestKind::Standard, - RequestRecipient::Device, - )) - } - - // Set request type for all but 'set feature' and 'set interface'. - pub fn set() -> Self { - Self::from(( - RequestDirection::HostToDevice, - RequestKind::Standard, - RequestRecipient::Device, - )) - } - - // Get interface request type. - pub fn cl_get_intf() -> Self { - Self::from(( - RequestDirection::DeviceToHost, - RequestKind::Class, - RequestRecipient::Interface, - )) - } - - pub fn recipient(&self) -> Result { - const POS: u8 = 0; - const MASK: u8 = 0x1f; - (self.0 & (MASK << POS)).try_into() - } - - pub fn set_recipient(&mut self, v: RequestRecipient) { - const POS: u8 = 0; - const MASK: u8 = 0x1f; - self.0 &= !(MASK << POS); - self.0 |= v as u8 & MASK; - } - - pub fn kind(&self) -> Result { - const POS: u8 = 5; - const MASK: u8 = 0x3; - (self.0 & (MASK << POS)).try_into() - } - - pub fn set_kind(&mut self, v: RequestKind) { - const POS: u8 = 5; - const MASK: u8 = 0x3; - self.0 &= !(MASK << POS); - self.0 |= v as u8 & MASK; - } - - pub fn direction(&self) -> Result { - const POS: u8 = 7; - const MASK: u8 = 0x1; - (self.0 & (MASK << POS)).try_into() - } - - pub fn set_direction(&mut self, v: RequestDirection) { - const POS: u8 = 7; - const MASK: u8 = 0x1; - self.0 &= !(MASK << POS); - self.0 |= v as u8 & MASK; - } -} -impl From<(RequestDirection, RequestKind, RequestRecipient)> for RequestType { - fn from(v: (RequestDirection, RequestKind, RequestRecipient)) -> Self { - Self(v.0 as u8 | v.1 as u8 | v.2 as u8) - } -} - -#[derive(Copy, Clone, Debug, PartialEq)] -pub enum RequestDirection { - HostToDevice = 0x00, - DeviceToHost = 0x80, -} -impl TryFrom for RequestDirection { - type Error = &'static str; - - fn try_from(v: u8) -> Result { - match v { - 0x00 => Ok(Self::HostToDevice), - 0x80 => Ok(Self::DeviceToHost), - _ => Err("direction can only be 0x00 or 0x80"), - } - } -} - -#[derive(Copy, Clone, Debug, PartialEq)] -pub enum RequestKind { - Standard = 0x00, - Class = 0x20, - Vendor = 0x40, -} -impl TryFrom for RequestKind { - type Error = &'static str; - - fn try_from(v: u8) -> Result { - match v { - 0x00 => Ok(Self::Standard), - 0x20 => Ok(Self::Class), - 0x40 => Ok(Self::Vendor), - _ => Err("type can only be 0x00, 0x20, or 0x40"), - } - } -} - -#[derive(Copy, Clone, Debug, PartialEq)] -pub enum RequestRecipient { - Device = 0x00, - Interface = 0x01, - Endpoint = 0x02, - Other = 0x03, -} -impl TryFrom for RequestRecipient { - type Error = &'static str; - - fn try_from(v: u8) -> Result { - match v { - 0x00 => Ok(Self::Device), - 0x01 => Ok(Self::Interface), - 0x02 => Ok(Self::Endpoint), - 0x03 => Ok(Self::Other), - _ => Err("recipient can only be between 0 and 3"), - } - } -} - -#[derive(Clone, Copy, Debug, Default, PartialEq)] -#[repr(C)] -pub struct WValue(u16); -impl WValue { - pub fn w_value_lo(&self) -> u8 { - const POS: u8 = 0; - const MASK: u16 = 0xff; - ((self.0 >> POS) & MASK) as u8 - } - - pub fn set_w_value_lo(&mut self, v: u8) { - const POS: u8 = 0; - const MASK: u8 = 0xff; - self.0 &= !((MASK as u16) << POS); - self.0 |= ((v & MASK) as u16) << POS; - } - - pub fn w_value_hi(&self) -> u8 { - const POS: u8 = 8; - const MASK: u16 = 0xff; - ((self.0 >> POS) & MASK) as u8 - } - - pub fn set_w_value_hi(&mut self, v: u8) { - const POS: u8 = 8; - const MASK: u8 = 0xff; - self.0 &= !((MASK as u16) << POS); - self.0 |= ((v & MASK) as u16) << POS; - } -} -impl From<(u8, u8)> for WValue { - fn from(v: (u8, u8)) -> Self { - let mut rc = Self(0); - rc.set_w_value_lo(v.0); - rc.set_w_value_hi(v.1); - rc - } -} - -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum RequestCode { - GetStatus = 0, - ClearFeature = 1, - SetFeature = 3, - SetAddress = 5, - GetDescriptor = 6, - SetDescriptor = 7, - GetConfiguration = 8, - SetConfiguration = 9, - GetInterface = 10, - SetInterface = 11, - SynchFrame = 12, -} -impl TryFrom for RequestCode { - type Error = &'static str; - - fn try_from(v: u8) -> Result { - match v { - 0 => Ok(Self::GetStatus), - 1 => Ok(Self::ClearFeature), - 3 => Ok(Self::SetFeature), - 5 => Ok(Self::SetAddress), - 6 => Ok(Self::GetDescriptor), - 7 => Ok(Self::SetDescriptor), - 8 => Ok(Self::GetConfiguration), - 9 => Ok(Self::SetConfiguration), - 10 => Ok(Self::GetInterface), - 11 => Ok(Self::SetInterface), - 12 => Ok(Self::SynchFrame), - _ => Err("invalid request value"), - } - } -} -impl Default for RequestCode { - fn default() -> Self { - Self::GetStatus - } -} - -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum USBFeature { - EndpointHalt = 0, - DeviceRemoteWakeup = 1, - TestMode = 2, -} - -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum DescriptorType { - Device = 1, - Configuration = 2, - String = 3, - Interface = 4, - Endpoint = 5, - DeviceQualifier = 6, - OtherSpeed = 7, - InterfacePower = 8, -} -impl Default for DescriptorType { - fn default() -> Self { - Self::Device - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn dev_desc_serialize() { - let desc = DeviceDescriptor { - b_length: 18, - b_descriptor_type: DescriptorType::Device, - bcd_usb: 0x0110, - b_device_class: 0x02, - b_device_sub_class: 0x03, - b_device_protocol: 0x04, - b_max_packet_size: 64, - id_vendor: 0xdead, - id_product: 0xbeef, - bcd_device: 0x5432, - i_manufacturer: 0xa0, - i_product: 0xa1, - i_serial_number: 0xa2, - b_num_configurations: 1, - }; - let want = [ - 0x12, 0x01, 0x10, 0x01, 0x02, 0x03, 0x04, 64, 0xad, 0xde, 0xef, 0xbe, 0x32, 0x54, 0xa0, - 0xa1, 0xa2, 1, - ]; - - serde_test(&desc, &want); - } - - #[test] - fn config_desc_serialize() { - let desc = ConfigurationDescriptor { - b_length: 18, - b_descriptor_type: DescriptorType::Configuration, - w_total_length: 0x20, - b_num_interfaces: 5, - b_configuration_value: 10, - i_configuration: 1, - bm_attributes: 0x40, - b_max_power: 0xfa, - }; - let want = [0x12, 0x02, 0x20, 0x00, 0x05, 0x0a, 0x01, 0x40, 0xfa]; - - serde_test(&desc, &want); - } - - #[test] - fn interface_desc_serialize() { - let desc = InterfaceDescriptor { - b_length: 18, - b_descriptor_type: DescriptorType::Interface, - b_interface_number: 2, - b_alternate_setting: 0xaa, - b_num_endpoints: 5, - b_interface_class: 0x11, - b_interface_sub_class: 0x22, - b_interface_protocol: 0x33, - i_interface: 10, - }; - let want = [0x12, 0x04, 0x02, 0xaa, 0x05, 0x11, 0x22, 0x33, 0x0a]; - - serde_test(&desc, &want); - } - - #[test] - fn endpoint_desc_serialize() { - let desc = EndpointDescriptor { - b_length: 18, - b_descriptor_type: DescriptorType::Endpoint, - b_endpoint_address: 1, - bm_attributes: 0x22, - w_max_packet_size: 0xdead, - b_interval: 0x33, - }; - let want = [0x12, 0x05, 0x01, 0x22, 0xad, 0xde, 0x33]; - - serde_test(&desc, &want); - } - - #[test] - fn setup_packet_serialize() { - let setup_packet = SetupPacket { - bm_request_type: RequestType::get_descr(), - b_request: RequestCode::GetDescriptor, - w_value: WValue::from((0x00, 0x01)), - w_index: 0xbeef, - w_length: 18, - }; - let want = [0x80, 0x06, 0x00, 0x01, 0xef, 0xbe, 0x012, 0x00]; - - serde_test(&setup_packet, &want); - } - - fn serde_test(native: &T, raw: &[u8]) - where - T: Default + PartialEq + core::fmt::Debug, - { - ser_test(native, raw); - de_test(raw, native); - } - - fn ser_test(native: &T, raw: &[u8]) { - let ptr = native as *const T as *const u8; - let len = core::mem::size_of::(); - assert_eq!(len, raw.len()); - let got_raw = unsafe { core::slice::from_raw_parts(ptr, len) }; - assert_eq!(got_raw, raw); - } - - fn de_test(raw: &[u8], native: &T) - where - T: Default + PartialEq + core::fmt::Debug, - { - let mut got_native: T = Default::default(); - let ptr = &mut got_native as *mut T as *mut u8; - let len = core::mem::size_of::(); - assert_eq!(raw.len(), len); - let dbslice = unsafe { core::slice::from_raw_parts_mut(ptr, len) }; - for i in 0..len { - dbslice[i] = raw[i]; - } - assert_eq!(got_native, *native); - } -} -- cgit v1.2.3