aboutsummaryrefslogtreecommitdiffstats
path: root/samd21-host
diff options
context:
space:
mode:
authorBrian Cully <bjc@kublai.com>2019-08-04 14:19:25 -0400
committerBrian Cully <bjc@kublai.com>2019-08-04 14:19:25 -0400
commite405c474f5e0e94288191223de7ae0f31ae0b15f (patch)
tree4ca89a92f0c868eb8feae272513c1e924b834adc /samd21-host
parentabd478d9425dd2d4acd5b58202b1a95b73ff217b (diff)
downloadsamd21-demo-e405c474f5e0e94288191223de7ae0f31ae0b15f.tar.gz
samd21-demo-e405c474f5e0e94288191223de7ae0f31ae0b15f.zip
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.
Diffstat (limited to 'samd21-host')
-rw-r--r--samd21-host/.cargo/config6
-rw-r--r--samd21-host/Cargo.lock358
-rw-r--r--samd21-host/Cargo.toml24
-rw-r--r--samd21-host/Makefile38
-rw-r--r--samd21-host/examples/simple/logger.rs139
-rw-r--r--samd21-host/examples/simple/macros.rs15
-rwxr-xr-xsamd21-host/examples/simple/main.rs192
-rw-r--r--samd21-host/examples/simple/rtc.rs74
-rwxr-xr-xsamd21-host/find-serial-port16
-rwxr-xr-xsamd21-host/simple.binbin0 -> 123568 bytes
-rw-r--r--samd21-host/simple.uf2bin0 -> 247296 bytes
-rwxr-xr-xsamd21-host/src/lib.rs645
-rw-r--r--samd21-host/src/pipe.rs809
-rw-r--r--samd21-host/src/pipe/addr.rs98
-rw-r--r--samd21-host/src/pipe/ctrl_pipe.rs177
-rw-r--r--samd21-host/src/pipe/ext_reg.rs156
-rw-r--r--samd21-host/src/pipe/pck_size.rs368
-rw-r--r--samd21-host/src/pipe/status_bk.rs170
-rw-r--r--samd21-host/src/pipe/status_pipe.rs407
19 files changed, 3692 insertions, 0 deletions
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 <bjc@kublai.com>"]
+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<u8>) -> 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<u8> = RingBuffer::<u8>::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: W,
+}
+impl<W> WriteWrapper<W>
+where
+ W: serial::Write<u8>,
+{
+ pub const fn new(writer: W) -> Self {
+ Self { w: writer }
+ }
+}
+unsafe impl<W> Sync for WriteWrapper<W> {}
+
+pub struct SerialLogger<W, L> {
+ writer: UnsafeCell<WriteWrapper<W>>,
+ led: UnsafeCell<L>,
+}
+
+impl<W, L> SerialLogger<W, L>
+where
+ W: serial::Write<u8>,
+ L: OutputPin + Send + Sync,
+{
+ pub fn new(writer: WriteWrapper<W>, 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<W, L> Send for SerialLogger<W, L> {}
+unsafe impl<W, L> Sync for SerialLogger<W, L> {}
+
+impl<W, L> log::Log for SerialLogger<W, L>
+where
+ W: serial::Write<u8>,
+ 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<Sercom0Pad3<Pa7<PfD>>, Sercom0Pad2<Pa6<PfD>>, (), ()> =
+ 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::Sercom0Pad3<Pa7<PfD>>, sercom::Sercom0Pad2<Pa6<PfD>>, (), ()>,
+ Pa10<Output<OpenDrain>>,
+ > = 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<Output<OpenDrain>> = 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<Output<OpenDrain>> = 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<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) };
+ red_led.set_high().ok();
+
+ debug!("*** Default Handler: {} ***", interrupt);
+}
+
+#[exception]
+fn NonMaskableInt() {
+ let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) };
+ red_led.set_high().ok();
+
+ debug!("+++ NonMaskableInt +++");
+}
+
+#[exception]
+fn SVCall() {
+ let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) };
+ red_led.set_high().ok();
+
+ debug!("+++ SVCall +++");
+}
+
+#[exception]
+fn PendSV() {
+ let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) };
+ red_led.set_high().ok();
+
+ debug!("+++ PendSV +++");
+}
+
+#[exception]
+fn SysTick() {
+ let red_led: &mut Pa10<Output<OpenDrain>> = 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
--- /dev/null
+++ b/samd21-host/simple.bin
Binary files differ
diff --git a/samd21-host/simple.uf2 b/samd21-host/simple.uf2
new file mode 100644
index 0000000..817dcb3
--- /dev/null
+++ b/samd21-host/simple.uf2
Binary files 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<Event>;
+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<Device>; MAX_DEVICES],
+}
+impl DeviceTable {
+ fn new() -> Self {
+ let tbl = {
+ let mut devs: [MaybeUninit<Option<Device>>; 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<Device> {
+ 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<gpio::PfG>,
+ _dm_pad: gpio::Pa24<gpio::PfG>,
+ _dp_pad: gpio::Pa25<gpio::PfG>,
+ host_enable_pin: Option<gpio::Pa28<Output<OpenDrain>>>,
+
+ // 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<Input<Floating>>,
+ dm_pin: gpio::Pa24<Input<Floating>>,
+ dp_pin: gpio::Pa25<Input<Floating>>,
+ host_enable_pin: Option<gpio::Pa28<Input<Floating>>>,
+ 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::<DeviceDescriptor>::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<PipeErr> 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<F> 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<usize, TransferError> {
+ 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<usize, TransferError> {
+ 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<usize, TransferError> {
+ 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<T>(v: &mut T) -> &mut [u8] {
+ let ptr = v as *mut T as *mut u8;
+ let len = mem::size_of::<T>();
+ 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<PipeDesc>; 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<usize, PipeErr> {
+ /*
+ * 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<usize, PipeErr> {
+ // 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<usize, PipeErr> {
+ 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<bool, PipeErr> {
+ 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<bool, PipeErr> {
+ 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<TransferType> 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::<T>(),
+ _marker: core::marker::PhantomData,
+ }
+ }
+}
+
+pub(crate) struct PipeRegs<'a> {
+ pub(crate) cfg: &'a mut PCFG,
+ pub(crate) binterval: &'a mut BINTERVAL,
+ pub(crate) statusclr: &'a mut PSTATUSCLR,
+ pub(crate) statusset: &'a mut PSTATUSSET,
+ pub(crate) status: &'a mut PSTATUS,
+ pub(crate) intflag: &'a mut PINTFLAG,
+}
+impl<'a> PipeRegs<'a> {
+ pub(crate) fn from(host: &'a mut usb::HOST, i: usize) -> PipeRegs {
+ assert!(i < MAX_PIPES);
+ match i {
+ 0 => Self {
+ cfg: &mut host.pcfg0,
+ binterval: &mut host.binterval0,
+ statusclr: &mut host.pstatusclr0,
+ statusset: &mut host.pstatusset0,
+ status: &mut host.pstatus0,
+ intflag: &mut host.pintflag0,
+ },
+ 1 => Self {
+ cfg: &mut host.pcfg1,
+ binterval: &mut host.binterval1,
+ statusclr: &mut host.pstatusclr1,
+ statusset: &mut host.pstatusset1,
+ status: &mut host.pstatus1,
+ intflag: &mut host.pintflag1,
+ },
+ 2 => Self {
+ cfg: &mut host.pcfg2,
+ binterval: &mut host.binterval2,
+ statusclr: &mut host.pstatusclr2,
+ statusset: &mut host.pstatusset2,
+ status: &mut host.pstatus2,
+ intflag: &mut host.pintflag2,
+ },
+ 3 => Self {
+ cfg: &mut host.pcfg3,
+ binterval: &mut host.binterval3,
+ statusclr: &mut host.pstatusclr3,
+ statusset: &mut host.pstatusset3,
+ status: &mut host.pstatus3,
+ intflag: &mut host.pintflag3,
+ },
+ 4 => Self {
+ cfg: &mut host.pcfg4,
+ binterval: &mut host.binterval4,
+ statusclr: &mut host.pstatusclr4,
+ statusset: &mut host.pstatusset4,
+ status: &mut host.pstatus4,
+ intflag: &mut host.pintflag4,
+ },
+ 5 => Self {
+ cfg: &mut host.pcfg5,
+ binterval: &mut host.binterval5,
+ statusclr: &mut host.pstatusclr5,
+ statusset: &mut host.pstatusset5,
+ status: &mut host.pstatus5,
+ intflag: &mut host.pintflag5,
+ },
+ 6 => Self {
+ cfg: &mut host.pcfg6,
+ binterval: &mut host.binterval6,
+ statusclr: &mut host.pstatusclr6,
+ statusset: &mut host.pstatusset6,
+ status: &mut host.pstatus6,
+ intflag: &mut host.pintflag6,
+ },
+ 7 => Self {
+ cfg: &mut host.pcfg7,
+ binterval: &mut host.binterval7,
+ statusclr: &mut host.pstatusclr7,
+ statusset: &mut host.pstatusset7,
+ status: &mut host.pstatus7,
+ intflag: &mut host.pintflag7,
+ },
+ _ => unreachable!(),
+ }
+ }
+}
+
+// §32.8.7.1
+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::<Addr>(), 4, "Addr register size.");
+ assert_eq!(core::mem::size_of::<PckSize>(), 4, "PckSize register size.");
+ assert_eq!(core::mem::size_of::<ExtReg>(), 2, "ExtReg register size.");
+ assert_eq!(
+ core::mem::size_of::<StatusBk>(),
+ 1,
+ "StatusBk register size."
+ );
+ assert_eq!(
+ core::mem::size_of::<CtrlPipe>(),
+ 2,
+ "CtrlPipe register size."
+ );
+ assert_eq!(
+ core::mem::size_of::<StatusPipe>(),
+ 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::<BankDesc>(),
+ 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::<PipeDesc>(), 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<T>(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<F>(&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<F>(&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<u32> 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<F>(&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<u16> 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<F>(&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<u16> 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<F>(&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<u32> 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<u8> 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<F>(&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<u8> 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<F>(&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<u8> 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)
+ }
+}