aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorBrian Cully <bjc@kublai.com>2019-06-24 21:14:32 -0400
committerBrian Cully <bjc@kublai.com>2019-07-23 19:55:18 -0400
commit63d4ce8154eb8f6feb67986e98ea9b5007632460 (patch)
tree187e66104eb7c848dcf73a5ee067c5f27235360a
downloadsamd21-demo-63d4ce8154eb8f6feb67986e98ea9b5007632460.tar.gz
samd21-demo-63d4ce8154eb8f6feb67986e98ea9b5007632460.zip
Initial commit.
-rw-r--r--.gitignore6
-rw-r--r--COPYING674
-rw-r--r--README.md33
-rw-r--r--app/.cargo/config6
-rw-r--r--app/Cargo.lock373
-rw-r--r--app/Cargo.toml27
-rw-r--r--app/Makefile38
-rwxr-xr-xapp/find-serial-port16
-rw-r--r--app/samd21-demo.uf2bin0 -> 136704 bytes
-rw-r--r--app/src/dotstar.rs42
-rw-r--r--app/src/log.rs95
-rw-r--r--app/src/macros.rs31
-rwxr-xr-xapp/src/main.rs202
-rw-r--r--app/src/rtc.rs71
-rw-r--r--app/src/usb.rs612
-rw-r--r--app/src/usb/pipe.rs503
-rw-r--r--app/src/usb/pipe/addr.rs87
-rw-r--r--app/src/usb/pipe/ctrl_pipe.rs177
-rw-r--r--app/src/usb/pipe/ext_reg.rs156
-rw-r--r--app/src/usb/pipe/pck_size.rs360
-rw-r--r--app/src/usb/pipe/status_bk.rs170
-rw-r--r--app/src/usb/pipe/status_pipe.rs407
-rw-r--r--app/src/usb/usbproto.rs331
-rw-r--r--rb/Cargo.lock6
-rw-r--r--rb/Cargo.toml5
-rwxr-xr-xrb/src/lib.rs221
26 files changed, 4649 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..c7a8f5f
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,6 @@
+samd21-demo.bin
+.gdb_history
+qemu.pid
+app/*.uf2
+*/target
+**/*.rs.bk
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..1d2d59d
--- /dev/null
+++ b/README.md
@@ -0,0 +1,33 @@
+# SAMD21 demo
+
+This is mostly a proof-of-concept of a USB Host driver on the SAMD21
+platform.
+
+The code is also a complete mess, but is hopefully understandable
+enough. At some point I intend to separate this into architecture
+dependent and independent stuff with a HAL layer. However, right now,
+this is mostly just slapped together as I tried to figure out how to
+get stuff to work at all.
+
+# Features
+
+Basically none. It'll go through enumeration up to the point of
+assigning an address, but that's it right now. Short term priority is
+getting the system to a point where it can host a boot-protocol
+keyboard.
+
+# Board support
+
+Uses trinket-m0, but should be fairly easy to port to other samd
+architectures.
+
+# Building
+
+Normal cargo stuff works. There's a `Makefile` which has a target for
+flashing an Adafruit Trinket M0 on Linux.
+
+You'll need to tweak the atsamd-hal to remove the feature requirements
+for generating the USB padcal code. You'll also need to add
+definitions for the 1kHz SOF pad, and (optionally) the USB Host Enable
+PIN. You can find a version of the HAL that does this [on my github
+branch](https://github.com/bjc/atsamd/tree/unflag-usb-calibration).
diff --git a/app/.cargo/config b/app/.cargo/config
new file mode 100644
index 0000000..b6cdff0
--- /dev/null
+++ b/app/.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/app/Cargo.lock b/app/Cargo.lock
new file mode 100644
index 0000000..ca61229
--- /dev/null
+++ b/app/Cargo.lock
@@ -0,0 +1,373 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+[[package]]
+name = "aligned"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "aligned"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "as-slice 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "apa102-spi"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
+ "smart-leds-trait 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "as-slice"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "generic-array 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)",
+ "stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "atsamd-hal"
+version = "0.5.0"
+dependencies = [
+ "atsamd21e18a 0.4.0",
+ "bitfield 0.13.2 (registry+https://github.com/rust-lang/crates.io-index)",
+ "cortex-m 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)",
+ "embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
+ "nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
+ "paste 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
+ "vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "atsamd21e18a"
+version = "0.4.0"
+dependencies = [
+ "bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)",
+ "cortex-m 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)",
+ "cortex-m-rt 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)",
+ "vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "bare-metal"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "bitfield"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "clint"
+version = "0.2.0"
+dependencies = [
+ "cortex-m 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "cortex-m"
+version = "0.5.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "aligned 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)",
+ "cortex-m 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "volatile-register 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "cortex-m"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "aligned 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
+ "bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)",
+ "volatile-register 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "cortex-m-rt"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "cortex-m-rt-macros 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
+ "r0 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "cortex-m-rt-macros"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)",
+ "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)",
+ "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)",
+ "syn 0.15.38 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "embedded-hal"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
+ "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "typenum 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "nb"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "panic-halt"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "paste"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "paste-impl 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
+ "proc-macro-hack 0.5.7 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "paste-impl"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "proc-macro-hack 0.5.7 (registry+https://github.com/rust-lang/crates.io-index)",
+ "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)",
+ "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)",
+ "syn 0.15.38 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "proc-macro-hack"
+version = "0.5.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)",
+ "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)",
+ "syn 0.15.38 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "0.4.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "quote"
+version = "0.6.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "r0"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "rand"
+version = "0.5.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "rb"
+version = "0.1.0"
+
+[[package]]
+name = "rgb"
+version = "0.8.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "rustc_version"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "samd21-demo"
+version = "0.1.0"
+dependencies = [
+ "apa102-spi 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)",
+ "clint 0.2.0",
+ "cortex-m 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "cortex-m-rt 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)",
+ "embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
+ "nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
+ "panic-halt 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "rb 0.1.0",
+ "smart-leds 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "smart-leds-trait 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "trinket_m0 0.3.0",
+ "vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "semver"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "semver-parser"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "smart-leds"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "smart-leds-trait 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "smart-leds-trait"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "rgb 0.8.13 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "syn"
+version = "0.15.38"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)",
+ "quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)",
+ "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "trinket_m0"
+version = "0.3.0"
+dependencies = [
+ "atsamd-hal 0.5.0",
+ "cortex-m 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)",
+ "cortex-m-rt 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)",
+ "embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
+ "nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "typenum"
+version = "1.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "unicode-xid"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "vcell"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "void"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "volatile-register"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[metadata]
+"checksum aligned 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d39da9b88ae1a81c03c9c082b8db83f1d0e93914126041962af61034ab44c4a5"
+"checksum aligned 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d3a316c7ea8e1e9ece54862c992def5a7ac14de9f5832b69d71760680efeeefa"
+"checksum apa102-spi 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "244c305e53cabeadfce23409fe24bfcedaa20166aa3f16f6c4ab256302158fd5"
+"checksum as-slice 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "293dac66b274fab06f95e7efb05ec439a6b70136081ea522d270bc351ae5bb27"
+"checksum bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "a3caf393d93b2d453e80638d0674597020cef3382ada454faacd43d1a55a735a"
+"checksum bitfield 0.13.2 (registry+https://github.com/rust-lang/crates.io-index)" = "46afbd2983a5d5a7bd740ccb198caf5b82f45c40c09c0eed36052d91cb92e719"
+"checksum cortex-m 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)" = "3c0b159a1e8306949579de3698c841dba58058197b65c60807194e4fa1e7a554"
+"checksum cortex-m 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f3c18719fdc57db65668bfc977db9a0fa1a41d718c5d9cd4f652c9d4b0e0956a"
+"checksum cortex-m-rt 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)" = "7e1ccc9052352415ec4e3f762f4541098d012016f9354a1a5b2dede39b67f426"
+"checksum cortex-m-rt-macros 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "d7ae692573e0acccb1579fef1abf5a5bf1d2f3f0149a22b16870ec9309aee25f"
+"checksum embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ee4908a155094da7723c2d60d617b820061e3b4efcc3d9e293d206a5a76c170b"
+"checksum generic-array 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)" = "c68f0274ae0e023facc3c97b2e00f076be70e254bc851d972503b328db79b2ec"
+"checksum nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "b1411551beb3c11dedfb0a90a0fa256b47d28b9ec2cdff34c25a2fa59e45dbdc"
+"checksum panic-halt 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "de96540e0ebde571dc55c73d60ef407c653844e6f9a1e2fdbd40c07b9252d812"
+"checksum paste 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "1f4a4a1c555c6505821f9d58b8779d0f630a6b7e4e1be24ba718610acf01fa79"
+"checksum paste-impl 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "26e796e623b8b257215f27e6c80a5478856cae305f5b59810ff9acdaa34570e6"
+"checksum proc-macro-hack 0.5.7 (registry+https://github.com/rust-lang/crates.io-index)" = "0c1dd4172a1e1f96f709341418f49b11ea6c2d95d53dca08c0f74cbd332d9cf3"
+"checksum proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)" = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759"
+"checksum quote 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)" = "faf4799c5d274f3868a4aae320a0a182cbd2baee377b378f080e16a23e9d80db"
+"checksum r0 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e2a38df5b15c8d5c7e8654189744d8e396bddc18ad48041a500ce52d6948941f"
+"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9"
+"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b"
+"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0"
+"checksum rgb 0.8.13 (registry+https://github.com/rust-lang/crates.io-index)" = "4f089652ca87f5a82a62935ec6172a534066c7b97be003cc8f702ee9a7a59c92"
+"checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a"
+"checksum semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403"
+"checksum semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3"
+"checksum smart-leds 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ab0a30e934e60850bfc020d4c2727cc8a3635371f6af2cb3f55f36f0134ed080"
+"checksum smart-leds-trait 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fef18e60d41a6fde19e640cd7590c03fb27aa23146bf60e4da85028d7410cee7"
+"checksum stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8"
+"checksum syn 0.15.38 (registry+https://github.com/rust-lang/crates.io-index)" = "37ea458a750f59ab679b47fef9b6722c586c5742f4cfe18a120bbc807e5e01fd"
+"checksum typenum 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "612d636f949607bdf9b123b4a6f6d966dedf3ff669f7f045890d3a4a73948169"
+"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc"
+"checksum vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "45c297f0afb6928cd08ab1ff9d95e99392595ea25ae1b5ecf822ff8764e57a0d"
+"checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d"
+"checksum volatile-register 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0d67cb4616d99b940db1d6bd28844ff97108b498a6ca850e5b6191a532063286"
diff --git a/app/Cargo.toml b/app/Cargo.toml
new file mode 100644
index 0000000..fd96c1a
--- /dev/null
+++ b/app/Cargo.toml
@@ -0,0 +1,27 @@
+[package]
+name = "samd21-demo"
+version = "0.1.0"
+authors = ["Brian Cully <bjc@kublai.com>"]
+edition = "2018"
+readme = "../README.md"
+license = "GPL-3.0-or-later"
+license-file = "../COPYING"
+
+[dependencies]
+trinket_m0 = { path = "../../atsamd/boards/trinket_m0" }
+panic-halt = "~0.2"
+smart-leds = "~0.2"
+smart-leds-trait = "~0.2"
+apa102-spi = "~0.2" # DotStar driver.
+nb = "~0.1"
+cortex-m = "~0.6"
+cortex-m-rt = "~0.6"
+embedded-hal = "~0.2"
+clint = { path = "../../clint" }
+#cortex-m-semihosting = "~0.3"
+bare-metal = "~0.2"
+rb = { path = "../rb" }
+vcell = "~0.1"
+
+[features]
+default = ["cortex-m/const-fn"]
diff --git a/app/Makefile b/app/Makefile
new file mode 100644
index 0000000..a5ef39f
--- /dev/null
+++ b/app/Makefile
@@ -0,0 +1,38 @@
+APP = samd21-demo
+
+USBVID = 239a
+USBPID = '001e|801e'
+
+BOSSAC = bossac
+SERIAL = $(shell ./find-serial-port $(USBVID) $(USBPID) || echo 'cant-find-serial-port')
+OFFSET = 0x2000
+
+.PHONY: all clean cargo-build
+
+all: $(APP).uf2
+
+clean:
+ rm -f $(APP).uf2
+ rm -f $(APP).bin
+ cargo clean
+
+cargo-build:
+ cargo build
+
+target/thumbv6m-none-eabi/debug/$(APP): cargo-build
+
+$(APP).bin: target/thumbv6m-none-eabi/debug/$(APP)
+ cargo objcopy --bin $(APP) -- -O binary $(APP).bin
+
+# Requires https://github.com/sajattack/uf2conv-rs.git
+%.uf2: %.bin
+ uf2conv-rs $< --base $(OFFSET) --output $@
+
+flash: $(APP).bin $(SERIAL)
+ $(BOSSAC) -R -e -w -v -o$(OFFSET) -p$(SERIAL) $<
+
+qemu: target/thumbv6m-none-eabi/debug/$(APP)
+ qemu-system-arm -d in_asm,int,exec,cpu,guest_errors,unimp -pidfile qemu.pid -cpu cortex-m0 -machine lm3s6965evb -nographic -semihosting-config enable=on,target=native -s -S -kernel $<
+
+gdb: target/thumbv6m-none-eabi/debug/$(APP)
+ gdb-multiarch -ex "target remote localhost:1234" -ex "break main" -ex "continue" $<
diff --git a/app/find-serial-port b/app/find-serial-port
new file mode 100755
index 0000000..62e2c0c
--- /dev/null
+++ b/app/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/app/samd21-demo.uf2 b/app/samd21-demo.uf2
new file mode 100644
index 0000000..035b8a5
--- /dev/null
+++ b/app/samd21-demo.uf2
Binary files differ
diff --git a/app/src/dotstar.rs b/app/src/dotstar.rs
new file mode 100644
index 0000000..8e930d0
--- /dev/null
+++ b/app/src/dotstar.rs
@@ -0,0 +1,42 @@
+use trinket_m0::{
+ clock::GenericClockController,
+ gpio::{self, Floating, Input},
+ prelude::*,
+ sercom::{self, PadPin, SPIMaster1},
+ PM, SERCOM1,
+};
+
+use apa102_spi::Apa102;
+
+pub fn new(
+ sercom: SERCOM1,
+ miso: gpio::Pa31<Input<Floating>>,
+ mosi: gpio::Pa0<Input<Floating>>,
+ sck: gpio::Pa1<Input<Floating>>,
+ port: &mut gpio::Port,
+ pm: &mut PM,
+ clocks: &mut GenericClockController,
+) -> Apa102<
+ SPIMaster1<
+ sercom::Sercom1Pad3<gpio::Pa31<gpio::PfD>>,
+ sercom::Sercom1Pad0<gpio::Pa0<gpio::PfD>>,
+ sercom::Sercom1Pad1<gpio::Pa1<gpio::PfD>>,
+ >,
+> {
+ let gclk = clocks.gclk0();
+ let miso = miso.into_pad(port);
+ let mosi = mosi.into_pad(port);
+ let sck = sck.into_pad(port);
+ let spi = SPIMaster1::new(
+ &clocks
+ .sercom1_core(&gclk)
+ .expect("setting up sercom1 clock"),
+ 3.mhz(),
+ apa102_spi::MODE,
+ sercom,
+ pm,
+ (miso, mosi, sck),
+ );
+
+ Apa102::new(spi)
+}
diff --git a/app/src/log.rs b/app/src/log.rs
new file mode 100644
index 0000000..6cfba8f
--- /dev/null
+++ b/app/src/log.rs
@@ -0,0 +1,95 @@
+use rb::{Reader, RingBuffer, Writer};
+
+use core::fmt::{self, Write};
+use embedded_hal::{digital::v2::OutputPin, serial};
+use trinket_m0::{
+ gpio::{Pa6, Pa7, PfD},
+ sercom::{Sercom0Pad2, Sercom0Pad3, UART0},
+};
+
+static mut LB: RingBuffer<u8> = RingBuffer::<u8>::new(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 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 LOGBUF: JoinedRingBuffer = unsafe { JoinedRingBuffer::new(&LB) };
+static mut UART0: usize = 0;
+
+pub struct Processor<W, L> {
+ uart: W,
+ led: L,
+}
+
+impl<W, L> Processor<W, L>
+where
+ W: serial::Write<u8>,
+ L: OutputPin,
+{
+ pub fn new(uart: W, led: L) -> Self {
+ // Unsafe because we're creating a mutable alias.
+ unsafe { UART0 = core::mem::transmute(&uart) };
+ Self {
+ uart: uart,
+ led: led,
+ }
+ }
+
+ pub fn task(&mut self) {
+ // Unsafe due to mutable static.
+ if unsafe { LOGBUF.lbr.is_empty() } {
+ return;
+ }
+ self.led.set_high().ok();
+ // Unsafe due to mutable static.
+ while let Some(b) = unsafe { LOGBUF.lbr.shift() } {
+ nb::block!(self.uart.write(b)).ok();
+ }
+ self.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");
+ }
+}
+
+pub fn write_fmt(args: fmt::Arguments, nl: bool) {
+ // Unsafe due to mutable static.
+ unsafe {
+ fmt::write(&mut LOGBUF, args).expect("writing fmt to log");
+ if nl {
+ LOGBUF.write_str("\r\n").expect("writing nl to log");
+ }
+ }
+}
diff --git a/app/src/macros.rs b/app/src/macros.rs
new file mode 100644
index 0000000..fe262b4
--- /dev/null
+++ b/app/src/macros.rs
@@ -0,0 +1,31 @@
+#[macro_export]
+macro_rules! logln {
+ ($($arg:tt)*) => {
+ crate::log::write_fmt(format_args!($($arg)*), true);
+ };
+ (_) => {};
+}
+
+#[macro_export]
+macro_rules! log {
+ ($($arg:tt)*) => {
+ crate::log::write_fmt(format_args!($($arg)*), false);
+ };
+ (_) => {};
+}
+
+#[macro_export]
+macro_rules! logln_now {
+ ($($arg:tt)*) => {
+ unsafe {crate::log::write_fmt_now(format_args!($($arg)*), true);}
+ };
+ (_) => {};
+}
+
+#[macro_export]
+macro_rules! log_now {
+ ($($arg:tt)*) => {
+ unsafe {crate::log::write_fmt_now(format_args!($($arg)*), false);}
+ };
+ (_) => {};
+}
diff --git a/app/src/main.rs b/app/src/main.rs
new file mode 100755
index 0000000..1025fae
--- /dev/null
+++ b/app/src/main.rs
@@ -0,0 +1,202 @@
+#![no_std]
+#![no_main]
+#![feature(const_fn)]
+#![feature(const_transmute)]
+#![allow(dead_code)]
+
+mod dotstar;
+mod log;
+mod macros;
+mod rtc;
+mod usb;
+
+//#[allow(unused)]
+//use panic_halt;
+
+use clint::HandlerArray;
+use cortex_m::asm::wfi;
+use cortex_m_rt::{entry, exception, ExceptionFrame};
+use embedded_hal::digital::v2::OutputPin;
+use smart_leds::colors;
+use smart_leds_trait::SmartLedsWrite;
+use trinket_m0::{
+ self as hal,
+ clock::GenericClockController,
+ gpio::{OpenDrain, Output, Pa10},
+ target_device::{interrupt, Interrupt},
+ time::*,
+ CorePeripherals, Peripherals,
+};
+
+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) }
+
+ let mut processor = log::Processor::new(uart, red_led);
+ logln_now!("setting up dotstar");
+
+ let mut dotstar = dotstar::new(
+ peripherals.SERCOM1,
+ pins.swdio,
+ pins.dotstar_di,
+ pins.dotstar_ci,
+ &mut pins.port,
+ &mut peripherals.PM,
+ &mut clocks,
+ );
+
+ let black = [colors::BLACK];
+ let blue = [colors::DARK_MAGENTA];
+
+ logln_now!("setting up timer");
+ let mut rtc_handler = rtc::setup(peripherals.RTC, &mut clocks);
+
+ logln_now!("setting up usb host");
+ let (mut usb_host, mut usb_handler) = usb::USBHost::new(
+ peripherals.USB,
+ pins.usb_sof,
+ pins.usb_dm,
+ pins.usb_dp,
+ Some(pins.usb_host_enable),
+ &mut pins.port,
+ &mut clocks,
+ &mut peripherals.PM,
+ );
+
+ logln!("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);
+
+ logln!("Boot up complete.");
+
+ let mut last_tick = 0;
+ loop {
+ dotstar
+ .write(black.iter().cloned())
+ .expect("turning off dotstar");
+
+ let tick = rtc::millis();
+ if tick >= last_tick + 1_024 {
+ last_tick = tick;
+ //logln!("{}: tick", rtc::millis());
+ }
+
+ usb_host.task();
+
+ processor.task();
+
+ dotstar
+ .write(blue.iter().cloned())
+ .expect("turning on dotstar");
+ wfi();
+ }
+ });
+ unreachable!();
+}
+
+#[panic_handler]
+fn panic_handler(pi: &core::panic::PanicInfo) -> ! {
+ let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) };
+ red_led.set_high().ok();
+
+ logln_now!("~~~ PANIC ~~~");
+ logln_now!("{}", pi);
+ loop {
+ wfi()
+ }
+}
+
+#[exception]
+fn HardFault(ef: &ExceptionFrame) -> ! {
+ let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) };
+ red_led.set_high().ok();
+
+ logln_now!("!!! Hard Fault - ef: {:?} !!!", ef);
+ loop {
+ wfi()
+ }
+}
+
+#[exception]
+fn DefaultHandler(interrupt: i16) {
+ let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) };
+ red_led.set_high().ok();
+
+ logln_now!("*** Default Handler: {} ***", interrupt);
+}
+
+#[exception]
+fn NonMaskableInt() {
+ let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) };
+ red_led.set_high().ok();
+
+ logln_now!("+++ NonMaskableInt +++");
+}
+
+#[exception]
+fn SVCall() {
+ let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) };
+ red_led.set_high().ok();
+
+ logln_now!("+++ SVCall +++");
+}
+
+#[exception]
+fn PendSV() {
+ let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) };
+ red_led.set_high().ok();
+
+ logln_now!("+++ PendSV +++");
+}
+
+#[exception]
+fn SysTick() {
+ let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) };
+ red_led.set_high().ok();
+
+ logln_now!("+++ SysTick +++");
+}
+
+#[interrupt]
+fn RTC() {
+ HANDLERS.call(0);
+}
+
+#[interrupt]
+fn USB() {
+ HANDLERS.call(1);
+}
diff --git a/app/src/rtc.rs b/app/src/rtc.rs
new file mode 100644
index 0000000..0d39d31
--- /dev/null
+++ b/app/src/rtc.rs
@@ -0,0 +1,71 @@
+use core::sync::atomic::{AtomicUsize, Ordering};
+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;
+ }
+}
diff --git a/app/src/usb.rs b/app/src/usb.rs
new file mode 100644
index 0000000..c15e1b5
--- /dev/null
+++ b/app/src/usb.rs
@@ -0,0 +1,612 @@
+mod pipe;
+mod usbproto;
+
+use crate::{log, logln, logln_now, rtc};
+use pipe::{DataBuf, PipeErr, PipeTable, USBPipeType, USBToken};
+use rb::{Reader, RingBuffer, Writer};
+use usbproto::*;
+
+use embedded_hal::digital::v2::OutputPin;
+use trinket_m0::{
+ calibration::{usb_transn_cal, usb_transp_cal, usb_trim_cal},
+ clock::{ClockGenId, ClockSource, GenericClockController},
+ gpio::{self, Floating, Input, OpenDrain, Output},
+ PM, USB,
+};
+
+#[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>;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum DetachedState {
+ Initialize,
+ WaitForDevice,
+ Illegal,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum AttachedState {
+ WaitForSettle,
+ WaitResetComplete,
+ WaitSOF,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum SteadyState {
+ Configuring,
+ Running,
+ Error,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum TaskState {
+ Detached(DetachedState),
+ Attached(AttachedState),
+ Steady(SteadyState),
+}
+
+const MAX_DEVICES: usize = 16;
+const SETTLE_DELAY: usize = 205; // Delay in sec/1024
+const NAK_LIMIT: usize = 15;
+
+static mut EVENTS: Events = Events::new(Event::Error);
+// FIXME: this is just for testing. The enum needs to be
+// thread-safe if this is the way we're going.
+static mut LATEST_EVENT: Event = Event::Detached;
+
+#[repr(C)]
+#[derive(Debug)]
+struct EPInfo {
+ ep_addr: u32,
+ mak_pkt_size: u32,
+ ep_attribs: u8,
+}
+
+impl EPInfo {
+ fn bm_snd_toggle(&self) -> bool {
+ const POS: u8 = 0;
+ const MASK: u8 = 0x1;
+ ((self.ep_attribs >> POS) & MASK) == 1
+ }
+ fn bm_rcv_toggle(&self) -> bool {
+ const POS: u8 = 1;
+ const MASK: u8 = 0x1;
+ ((self.ep_attribs >> POS) & MASK) == 1
+ }
+ fn bm_nak_power(&self) -> u8 {
+ const POS: u8 = 2;
+ const MASK: u8 = 0x3f;
+ (self.ep_attribs >> POS) & MASK
+ }
+}
+
+#[derive(Debug)]
+struct USBDeviceAddress(u32);
+
+impl USBDeviceAddress {
+ fn bm_address(&self) -> u8 {
+ const POS: u8 = 0;
+ const MASK: u32 = 0x7;
+ ((self.0 >> POS) & MASK) as u8
+ }
+ fn bm_parent(&self) -> u8 {
+ const POS: u8 = 3;
+ const MASK: u32 = 0x7;
+ ((self.0 >> POS) & MASK) as u8
+ }
+ fn bm_hub(&self) -> bool {
+ const POS: u8 = 6;
+ const MASK: u32 = 0x1;
+ ((self.0 >> POS) & MASK) == 1
+ }
+}
+
+pub struct USBHost {
+ usb: USB,
+
+ events: EventReader,
+ task_state: TaskState,
+ delay: usize,
+
+ // Need chunk of RAM for USB pipes, which gets used with DESCADD
+ // register.
+ pipe_table: PipeTable,
+
+ // 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>>>,
+}
+
+impl USBHost {
+ 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,
+ ) -> (Self, impl FnMut()) {
+ let (eventr, mut eventw) = unsafe { EVENTS.split() };
+ let mut rc = Self {
+ usb: usb,
+ events: eventr,
+ task_state: TaskState::Detached(DetachedState::Initialize),
+ delay: 0,
+ pipe_table: PipeTable::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,
+ };
+
+ if let Some(he_pin) = host_enable_pin {
+ rc.host_enable_pin = Some(he_pin.into_open_drain_output(port));
+ }
+
+ logln_now!("setting up usb clock");
+ 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);
+
+ rc.reset_periph();
+
+ let usbp = &rc.usb as *const _ as usize;
+ (rc, move || handler(usbp, &mut eventw))
+ }
+
+ pub fn reset_periph(&mut self) {
+ log!("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());
+ logln!("...done");
+ }
+
+ pub fn task(&mut self) {
+ static mut LAST_EVENT: Event = Event::Error;
+ unsafe {
+ if LAST_EVENT != LATEST_EVENT {
+ logln!("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 {
+ self.delay = rtc::millis() + SETTLE_DELAY;
+ TaskState::Attached(AttachedState::WaitForSettle)
+ } 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 {
+ logln!(
+ "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() {
+ // logln!("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 = rtc::millis() + SETTLE_DELAY;
+ // TaskState::Attached(AttachedState::WaitForSettle)
+ // } else {
+ // self.task_state
+ // }
+ // }
+ // };
+ }
+
+ self.poll_devices();
+ self.fsm();
+
+ unsafe {
+ LAST_EVENT = LATEST_EVENT;
+ }
+ }
+
+ fn poll_devices(&mut self) {
+ for _ in 0..MAX_DEVICES {}
+ }
+
+ fn fsm(&mut self) {
+ // respond to events from interrupt.
+ match self.task_state {
+ TaskState::Detached(s) => self.detached_fsm(s),
+ TaskState::Attached(s) => self.attached_fsm(s),
+ TaskState::Steady(s) => self.steady_fsm(s),
+ };
+ }
+
+ fn detached_fsm(&mut self, s: DetachedState) {
+ match s {
+ DetachedState::Initialize => {
+ self.reset_periph();
+ // TODO: Free resources.
+
+ self.task_state = TaskState::Detached(DetachedState::WaitForDevice);
+ }
+
+ // Do nothing state. Just wait for an interrupt to come in
+ // saying we have a device attached.
+ DetachedState::WaitForDevice => {}
+
+ // TODO: should probably reset everything if we end up here somehow.
+ DetachedState::Illegal => {}
+ }
+ }
+
+ fn attached_fsm(&mut self, s: AttachedState) {
+ match s {
+ AttachedState::WaitForSettle => {
+ if rtc::millis() >= self.delay {
+ 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() {
+ logln!("reset was sent");
+ self.usb.host().intflag.write(|w| w.rst().set_bit());
+
+ // Make sure we always have a control pipe set up.
+ self.init_pipe0();
+
+ // 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.delay = rtc::millis() + 20;
+ self.task_state = TaskState::Attached(AttachedState::WaitSOF);
+ }
+ }
+
+ AttachedState::WaitSOF => {
+ if self.usb.host().intflag.read().hsof().bit_is_set() {
+ self.usb.host().intflag.write(|w| w.hsof().set_bit());
+ if rtc::millis() >= self.delay {
+ self.task_state = TaskState::Steady(SteadyState::Configuring);
+ }
+ }
+ }
+ }
+ }
+
+ fn steady_fsm(&mut self, s: SteadyState) {
+ match s {
+ SteadyState::Configuring => {
+ let low_speed = 0;
+ self.task_state = match self.configure_dev(0, 0, low_speed) {
+ Ok(_) => TaskState::Steady(SteadyState::Running),
+ Err(e) => {
+ logln!("Enumeration error: {:?}", e);
+ TaskState::Steady(SteadyState::Error)
+ }
+ }
+ }
+
+ SteadyState::Running => {}
+
+ SteadyState::Error => {}
+ }
+ }
+
+ fn configure_dev(&mut self, _parent: u32, _port: u32, _low_speed: u32) -> Result<(), PipeErr> {
+ // addr: 0x20007774
+ let tmp: USBDeviceDescriptor = Default::default();
+ // addr: 0x20007788
+ let vol_descr = ::vcell::VolatileCell::new(tmp);
+ self.control_req(
+ 0,
+ 0,
+ BMRequestType::get_descr(),
+ USBRequest::GetDescriptor,
+ WValue::from((0, USBDescriptor::Device as u8)),
+ 0,
+ Some(DataBuf::from(&vol_descr)),
+ )?;
+
+ let desc = vol_descr.get();
+ logln_now!(
+ " -- len: {}, ver: {:04x}, bMaxPacketSize: {}, bNumConfigurations: {}",
+ desc.b_length,
+ desc.bcd_usb,
+ desc.b_max_packet_size,
+ desc.b_num_configurations
+ );
+ logln_now!(" -- vid: {:x}, pid: {:x}", desc.id_vendor, desc.id_product);
+
+ // Assign address to this device and:
+ // - Stash bMaxPacketSize
+ // Then SET_ADDRESS(newAddr)
+ let new_address: u8 = 1;
+ self.control_req(
+ 0,
+ 0,
+ BMRequestType::set(),
+ USBRequest::SetAddress,
+ WValue::from((new_address, 0)),
+ 0,
+ None,
+ )?;
+ logln_now!(" -- address set");
+ // Delay according to §9.2.6.3 of USB 2.0
+ let until = rtc::millis() + 300;
+ while rtc::millis() < until {}
+
+ // Once addressed, SET_CONFIGURATION(0)
+ logln_now!("+++ setting configuration");
+ let conf: u8 = 0;
+ self.control_req(
+ new_address,
+ 0,
+ BMRequestType::set(),
+ USBRequest::SetConfiguration,
+ WValue::from((conf, 0)),
+ 0,
+ None,
+ )?;
+ logln_now!(" -- configuration set");
+
+ // Now we should be able to access it normally.
+
+ Ok(())
+ }
+
+ fn control_req(
+ &mut self,
+ addr: u8,
+ ep: u8,
+ bm_request_type: BMRequestType,
+ b_request: USBRequest,
+ w_value: WValue,
+ w_index: u16,
+ buf: Option<DataBuf>,
+ ) -> Result<(), PipeErr> {
+ if let Some(ref b) = buf {
+ assert!(b.ptr as usize & 0x3 == 0);
+ assert!(b.len <= 65_535);
+ }
+
+ /*
+ * Setup stage.
+ */
+ let setup_packet = USBSetupPacket {
+ bm_request_type: bm_request_type,
+ b_request: b_request,
+ w_value: w_value,
+ w_index: w_index,
+ w_length: match buf {
+ None => 0,
+ Some(ref b) => b.len as u16,
+ },
+ };
+ let mut pipe = self.pipe_table.pipe_for(self.usb.host_mut(), addr, ep);
+ pipe.send(USBToken::Setup, &DataBuf::from(&setup_packet), NAK_LIMIT)?;
+
+ /*
+ * Data stage.
+ */
+ if let Some(b) = buf {
+ match bm_request_type.direction() {
+ USBSetupDirection::DeviceToHost => {
+ logln_now!("buf0: {:?}", &b);
+ pipe.in_transfer(&b, NAK_LIMIT)?;
+ logln_now!("buf1: {:?}", &b);
+ }
+
+ USBSetupDirection::HostToDevice => {
+ logln_now!("Should OUT for {}b", b.len);
+ }
+ }
+ }
+
+ /*
+ * Status stage.
+ */
+ pipe.desc.bank0.pcksize.write(|w| {
+ // FIXME: see note in `Pipe.send`.
+ unsafe { w.bits(0) }
+ });
+
+ // PSTATUSSET.DTGL set -- TODO: figure out if this is
+ // necessary.
+ pipe.regs.statusset.write(|w| w.dtgl().set_bit());
+
+ let token = match bm_request_type.direction() {
+ USBSetupDirection::DeviceToHost => USBToken::Out,
+ USBSetupDirection::HostToDevice => USBToken::In,
+ };
+
+ // TODO: should probably make `pipe.send` have optional
+ // `DataBuf`, rather than exposing `dispatch_retries`.
+ logln_now!("dispatching status stage");
+ pipe.dispatch_retries(token, NAK_LIMIT)?;
+ Ok(())
+ }
+
+ // Set up a default pipe for the control endpoint 0 on pipe 0.
+ fn init_pipe0(&mut self) {
+ let speed = self.usb.host().status.read().speed().bits();
+ let pipe = self.pipe_table.pipe_for(self.usb.host_mut(), 0, 0);
+ pipe.regs.cfg.write(|w| {
+ unsafe { w.ptype().bits(USBPipeType::Control as u8) };
+ w.bk().clear_bit()
+ });
+ pipe.desc.bank0.pcksize.write(|w| match speed {
+ 0 => w.size().bytes64(),
+ _ => w.size().bytes8(),
+ });
+ }
+}
+
+pub fn handler(usbp: usize, events: &mut EventWriter) {
+ let usb: &mut USB = unsafe { core::mem::transmute(usbp) };
+ let flags = usb.host().intflag.read();
+
+ logln!("USB - {:x}", flags.bits());
+
+ let mut unshift_event = |e: Event| {
+ unsafe { LATEST_EVENT = e };
+ if let Err(_) = events.unshift(e) {
+ logln!("Couldn't write USB event to queue.");
+ }
+ };
+
+ if flags.hsof().bit_is_set() {
+ logln!(" +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.
+ logln!(" +rst");
+ usb.host().intflag.write(|w| w.rst().set_bit());
+ unshift_event(Event::Detached);
+ }
+
+ if flags.uprsm().bit_is_set() {
+ logln!(" +uprsm");
+ usb.host().intflag.write(|w| w.uprsm().set_bit());
+ unshift_event(Event::Detached);
+ }
+
+ if flags.dnrsm().bit_is_set() {
+ logln!(" +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.
+ logln!(" +wakeup");
+ usb.host().intflag.write(|w| w.wakeup().set_bit());
+ unshift_event(Event::Attached);
+ }
+
+ if flags.ramacer().bit_is_set() {
+ logln!(" +ramacer");
+ usb.host().intflag.write(|w| w.ramacer().set_bit());
+ unshift_event(Event::Detached);
+ }
+
+ if flags.dconn().bit_is_set() {
+ logln!(" +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() {
+ logln!(" +ddisc");
+ usb.host().intflag.write(|w| w.ddisc().set_bit());
+ usb.host().intenclr.write(|w| w.ddisc().set_bit());
+ // // Stop reset signal, in case of disconnection during reset
+ // uhd_stop_reset(); // nothing on samd21
+ usb.host().intflag.write(|w| w.dconn().set_bit());
+ usb.host().intenset.write(|w| w.dconn().set_bit());
+ usb.host().intflag.write(|w| w.ddisc().set_bit());
+ unshift_event(Event::Detached);
+ }
+}
diff --git a/app/src/usb/pipe.rs b/app/src/usb/pipe.rs
new file mode 100644
index 0000000..12ca4cb
--- /dev/null
+++ b/app/src/usb/pipe.rs
@@ -0,0 +1,503 @@
+pub mod addr;
+pub mod ctrl_pipe;
+pub mod ext_reg;
+pub mod pck_size;
+pub mod status_bk;
+pub mod status_pipe;
+
+use addr::Addr;
+use ctrl_pipe::CtrlPipe;
+use ext_reg::ExtReg;
+use pck_size::PckSize;
+use status_bk::StatusBk;
+use status_pipe::StatusPipe;
+
+use crate::logln_now;
+use crate::rtc;
+
+use core::convert::TryInto;
+
+// FIXME: this stuff is needed for PipeRegs, and while tied to samd,
+// it shouldn't be tied to trinket_m0. Will need to figure out a
+// better layout for this.
+use trinket_m0::usb::{
+ self,
+ host::{BINTERVAL, PCFG, PINTFLAG, PSTATUS, PSTATUSCLR, PSTATUSSET},
+};
+
+// TODO: verify this timeout against §9.2.6.1 of USB 2.0 spec.
+const USB_TIMEOUT: usize = 5 * 1024; // 5 Seconds
+
+// samd21 only supports 8 pipes.
+const MAX_PIPES: usize = 8;
+
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub(crate) enum PipeErr {
+ InvalidPipe,
+ InvalidToken,
+ Stall,
+ TransferFail,
+ Flow,
+ HWTimeout,
+ DataToggle,
+ SWTimeout,
+ Other,
+}
+pub(crate) struct PipeTable {
+ tbl: [PipeDesc; MAX_PIPES],
+}
+
+impl PipeTable {
+ pub(crate) fn new() -> Self {
+ Self {
+ tbl: [PipeDesc::new(); MAX_PIPES],
+ }
+ }
+
+ pub(crate) fn pipe_for<'a, 'b>(
+ &'a mut self,
+ host: &'b mut usb::HOST,
+ addr: u8,
+ ep: u8,
+ ) -> Pipe<'a, 'b> {
+ // Just use two pipes for now. 0 is always for control
+ // endpoints, 1 for everything else.
+ //
+ // TODO: cache in-use pipes and return them without init if
+ // possible.
+ let i = if ep == 0 { 0 } else { 1 };
+
+ let pregs = PipeRegs::from(host, i);
+ let pdesc = &mut self.tbl[i];
+
+ logln_now!("setting paddr of pipe {} to {}:{}", i, addr, ep);
+ logln_now!("cpipe0: {:x}", pdesc.bank0.ctrl_pipe.read().bits());
+ pdesc.bank0.ctrl_pipe.write(|w| {
+ w.pdaddr().set_addr(addr);
+ w.pepnum().set_epnum(ep)
+ });
+ logln_now!("cpipe1: {:x}", pdesc.bank0.ctrl_pipe.read().bits());
+ 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 send(
+ &mut self,
+ token: USBToken,
+ buf: &DataBuf,
+ nak_limit: usize,
+ ) -> Result<(), PipeErr> {
+ // Data needs to be word aligned.
+ assert!((buf.ptr as u32) & 0x3 == 0);
+ // byte_count section of register is 14 bits.
+ assert!(buf.len < 16_384);
+
+ logln_now!("p{}: sending {:?}", self.num, buf);
+
+ // Equiv to UHD_Pipe_Write(epAddr: 0, sizeof(setup_packet), &setup_packet)
+ 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| {
+ // FIXME: write raw to pcksize, because byte_count offset
+ // may be off? Doc table shows 6 bits, but text says 14,
+ // and arduino shows 14.
+ unsafe { w.bits(buf.len as u32) }
+ //unsafe { w.byte_count().bits(buf.len as u8) };
+ //unsafe { w.multi_packet_size().bits(0) }
+ });
+
+ self.dispatch_retries(token, nak_limit)
+ }
+
+ pub(crate) fn in_transfer(&mut self, buf: &DataBuf, nak_limit: usize) -> Result<(), PipeErr> {
+ // Data needs to be word aligned.
+ assert!((buf.ptr as u32) & 0x3 == 0);
+ // byte_count section of register is 14 bits.
+ assert!(buf.len < 16_384);
+
+ logln_now!("p{}: Should IN for {}b.", self.num, buf.len);
+ // TODO: should just pass pipe and pregs in, probably. TODO:
+ // merge with stuff in `send_to_pipe` that also does this.
+ self.desc
+ .bank0
+ .addr
+ .write(|w| unsafe { w.addr().bits(buf.ptr as u32) });
+ self.desc.bank0.pcksize.write(|w| {
+ // FIXME: see note in `send`.
+ unsafe { w.bits(buf.len as u32) }
+ //unsafe { w.byte_count().bits(buf.len as u8) };
+ //unsafe { w.multi_packet_size().bits(0) }
+ });
+
+ // Possibly set PSTATUS.DTGL? Not sure how this works
+ // yet. Arduino would set it here if dispatchPkt returned USB_ERROR_DATATOGGLE
+ //pregs.statusset.write(|w| w.dtgl().set_bit());
+ //pregs.statusclr.write(|w| unsafe {
+ // No function for this. FIXME: need to patch the SVD for
+ // PSTATUSCLR.DTGL at bit0
+ // w.bits(1)
+ //});
+
+ self.dispatch_retries(USBToken::In, nak_limit)
+ }
+
+ pub(crate) fn dispatch_retries(
+ &mut self,
+ token: USBToken,
+ retries: usize,
+ ) -> Result<(), PipeErr> {
+ assert!(retries > 0);
+
+ logln_now!("initial regs");
+ self.log_regs();
+
+ let until = rtc::millis() + USB_TIMEOUT;
+ let mut last_result: Result<(), PipeErr> = Err(PipeErr::SWTimeout);
+ let mut naks = 0;
+ while naks <= retries {
+ logln_now!("p{}: dispatch {:?} retry {}", self.num, token, naks);
+
+ self.dispatch_packet(token);
+ last_result = self.dispatch_result(token, until);
+ match last_result {
+ Ok(_) => return Ok(()),
+ // FIXME: handle datatoggle
+ Err(PipeErr::DataToggle) => {
+ if self.regs.status.read().dtgl().bit_is_set() {
+ self.regs.statusset.write(|w| w.dtgl().set_bit());
+ } else {
+ self.regs.statusclr.write(|w| unsafe {
+ // No function for this. FIXME: need to patch the SVD for PSTATUSCLR.DTGL at bit0
+ w.bits(1)
+ });
+ }
+ }
+ Err(PipeErr::SWTimeout) => break,
+ Err(PipeErr::Stall) => break,
+ Err(_) => naks += 1,
+ }
+ }
+
+ last_result
+ }
+
+ 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();
+ logln_now!(
+ "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();
+ logln_now!(
+ "p{}: adr: {:x}, pks: {:x}, ext: {:x}, sbk: {:x}, hcp: {:x}, spi: {:x}",
+ self.num,
+ adr,
+ pks,
+ ext,
+ sbk,
+ hcp,
+ spi
+ );
+ }
+
+ fn dispatch_packet(&mut self, token: USBToken) {
+ self.regs
+ .cfg
+ .modify(|_, w| unsafe { w.ptoken().bits(token as u8) });
+ match token {
+ USBToken::Setup => {
+ self.regs.intflag.write(|w| w.txstp().set_bit());
+ self.regs.statusset.write(|w| w.bk0rdy().set_bit());
+ }
+ USBToken::In => self.regs.statusclr.write(|w| w.bk0rdy().set_bit()),
+ USBToken::Out => {
+ self.regs.intflag.write(|w| w.trcpt0().set_bit());
+ self.regs.statusset.write(|w| w.bk0rdy().set_bit());
+ }
+ _ => {}
+ }
+ self.regs.statusclr.write(|w| w.pfreeze().set_bit());
+ }
+
+ fn dispatch_result(&mut self, token: USBToken, until: usize) -> Result<(), PipeErr> {
+ while rtc::millis() <= until {
+ if self.is_transfer_complete(token)? {
+ return Ok(());
+ } else if self.regs.intflag.read().stall().bit_is_set() {
+ logln_now!("stall");
+ self.log_regs();
+ self.regs.intflag.write(|w| w.stall().set_bit());
+ return Err(PipeErr::Stall);
+ } else if self.regs.intflag.read().trfail().bit_is_set() {
+ logln_now!("trfail");
+ self.log_regs();
+ self.regs.intflag.write(|w| w.trfail().set_bit());
+ return Err(PipeErr::TransferFail);
+ } else if self.desc.bank0.status_bk.read().errorflow().bit_is_set() {
+ logln_now!("errorflow");
+ self.log_regs();
+ self.desc
+ .bank0
+ .status_bk
+ .write(|w| w.errorflow().clear_bit());
+ return Err(PipeErr::Flow);
+ } else if self.desc.bank0.status_pipe.read().touter().bit_is_set() {
+ logln_now!("touter");
+ self.log_regs();
+ self.desc
+ .bank0
+ .status_pipe
+ .write(|w| w.touter().clear_bit());
+ return Err(PipeErr::HWTimeout);
+ } else if self.desc.bank0.status_pipe.read().dtgler().bit_is_set() {
+ logln_now!("dtgler");
+ self.log_regs();
+ self.desc
+ .bank0
+ .status_pipe
+ .write(|w| w.dtgler().clear_bit());
+ return Err(PipeErr::DataToggle);
+ }
+ }
+ logln_now!("swtimeout");
+ self.log_regs();
+ Err(PipeErr::SWTimeout)
+ }
+
+ fn is_transfer_complete(&mut self, token: USBToken) -> Result<bool, PipeErr> {
+ match token {
+ USBToken::Setup => {
+ if self.regs.intflag.read().txstp().bit_is_set() {
+ self.regs.intflag.write(|w| w.txstp().set_bit());
+ self.regs.statusset.write(|w| w.pfreeze().set_bit());
+ Ok(true)
+ } else {
+ Ok(false)
+ }
+ }
+ USBToken::In => {
+ if self.regs.intflag.read().trcpt0().bit_is_set() {
+ self.regs.intflag.write(|w| w.trcpt0().set_bit());
+ self.regs.statusset.write(|w| w.pfreeze().set_bit());
+ Ok(true)
+ } else {
+ Ok(false)
+ }
+ }
+ USBToken::Out => {
+ if self.regs.intflag.read().trcpt0().bit_is_set() {
+ self.regs.intflag.write(|w| w.trcpt0().set_bit());
+ self.regs.statusset.write(|w| w.pfreeze().set_bit());
+ Ok(true)
+ } else {
+ Ok(false)
+ }
+ }
+ _ => Err(PipeErr::InvalidToken),
+ }
+ }
+}
+
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub(crate) enum USBToken {
+ Setup = 0,
+ In = 1,
+ Out = 2,
+ Reserved = 3,
+}
+
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub(crate) enum USBPipeType {
+ Disabled = 0x0,
+ Control = 0x1,
+ ISO = 0x2,
+ Bulk = 0x3,
+ Interrupt = 0x4,
+ Extended = 0x5,
+ _Reserved0 = 0x06,
+ _Reserved1 = 0x07,
+}
+
+pub(crate) struct DataBuf<'a> {
+ pub(crate) ptr: *const u8,
+ pub(crate) len: usize,
+ _marker: core::marker::PhantomData<&'a ()>,
+}
+impl DataBuf<'_> {}
+
+impl core::fmt::Debug for DataBuf<'_> {
+ fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
+ write!(f, "DataBuf {{ len: {}, ptr: [", self.len)?;
+ for i in 0..self.len {
+ write!(f, " {:x}", unsafe {
+ *self.ptr.offset(i.try_into().unwrap())
+ })?;
+ }
+ write!(f, " ] }}")
+ }
+}
+
+impl<'a, T> From<&'a T> for DataBuf<'a> {
+ fn from(v: &'a T) -> Self {
+ Self {
+ ptr: v as *const T as *const u8,
+ len: core::mem::size_of::<T>(),
+ _marker: core::marker::PhantomData,
+ }
+ }
+}
+
+pub(crate) struct PipeRegs<'a> {
+ pub(crate) cfg: &'a mut PCFG,
+ pub(crate) binterval: &'a mut BINTERVAL,
+ pub(crate) statusclr: &'a mut PSTATUSCLR,
+ pub(crate) statusset: &'a mut PSTATUSSET,
+ pub(crate) status: &'a mut PSTATUS,
+ pub(crate) intflag: &'a mut PINTFLAG,
+}
+impl<'a> PipeRegs<'a> {
+ pub(crate) fn from(host: &'a mut usb::HOST, i: usize) -> PipeRegs {
+ assert!(i < MAX_PIPES);
+ match i {
+ 0 => Self {
+ cfg: &mut host.pcfg0,
+ binterval: &mut host.binterval0,
+ statusclr: &mut host.pstatusclr0,
+ statusset: &mut host.pstatusset0,
+ status: &mut host.pstatus0,
+ intflag: &mut host.pintflag0,
+ },
+ 1 => Self {
+ cfg: &mut host.pcfg1,
+ binterval: &mut host.binterval1,
+ statusclr: &mut host.pstatusclr1,
+ statusset: &mut host.pstatusset1,
+ status: &mut host.pstatus1,
+ intflag: &mut host.pintflag1,
+ },
+ 2 => Self {
+ cfg: &mut host.pcfg2,
+ binterval: &mut host.binterval2,
+ statusclr: &mut host.pstatusclr2,
+ statusset: &mut host.pstatusset2,
+ status: &mut host.pstatus2,
+ intflag: &mut host.pintflag2,
+ },
+ 3 => Self {
+ cfg: &mut host.pcfg3,
+ binterval: &mut host.binterval3,
+ statusclr: &mut host.pstatusclr3,
+ statusset: &mut host.pstatusset3,
+ status: &mut host.pstatus3,
+ intflag: &mut host.pintflag3,
+ },
+ 4 => Self {
+ cfg: &mut host.pcfg4,
+ binterval: &mut host.binterval4,
+ statusclr: &mut host.pstatusclr4,
+ statusset: &mut host.pstatusset4,
+ status: &mut host.pstatus4,
+ intflag: &mut host.pintflag4,
+ },
+ 5 => Self {
+ cfg: &mut host.pcfg5,
+ binterval: &mut host.binterval5,
+ statusclr: &mut host.pstatusclr5,
+ statusset: &mut host.pstatusset5,
+ status: &mut host.pstatus5,
+ intflag: &mut host.pintflag5,
+ },
+ 6 => Self {
+ cfg: &mut host.pcfg6,
+ binterval: &mut host.binterval6,
+ statusclr: &mut host.pstatusclr6,
+ statusset: &mut host.pstatusset6,
+ status: &mut host.pstatus6,
+ intflag: &mut host.pintflag6,
+ },
+ 7 => Self {
+ cfg: &mut host.pcfg7,
+ binterval: &mut host.binterval7,
+ statusclr: &mut host.pstatusclr7,
+ statusset: &mut host.pstatusset7,
+ status: &mut host.pstatus7,
+ intflag: &mut host.pintflag7,
+ },
+ _ => unreachable!(),
+ }
+ }
+}
+
+// §32.8.7.1
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct PipeDesc {
+ pub bank0: BankDesc,
+ pub bank1: BankDesc,
+}
+
+// 2 banks: 32 bytes per pipe.
+impl PipeDesc {
+ pub fn new() -> Self {
+ Self {
+ bank0: BankDesc::new(),
+ bank1: BankDesc::new(),
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+#[repr(C, packed)]
+// 16 bytes per bank.
+pub(crate) struct BankDesc {
+ pub addr: Addr,
+ pub pcksize: PckSize,
+ pub extreg: ExtReg,
+ pub status_bk: StatusBk,
+ pub ctrl_pipe: CtrlPipe,
+ pub status_pipe: StatusPipe,
+
+ _reserved: u8,
+}
+
+impl BankDesc {
+ fn new() -> Self {
+ Self {
+ addr: Addr::from(0),
+ pcksize: PckSize::from(0),
+ extreg: ExtReg::from(0),
+ status_bk: StatusBk::from(0),
+ ctrl_pipe: CtrlPipe::from(0),
+ status_pipe: StatusPipe::from(0),
+ _reserved: 0,
+ }
+ }
+}
diff --git a/app/src/usb/pipe/addr.rs b/app/src/usb/pipe/addr.rs
new file mode 100644
index 0000000..8b92177
--- /dev/null
+++ b/app/src/usb/pipe/addr.rs
@@ -0,0 +1,87 @@
+/// § 32.8.7.2
+/// Address of the Data Buffer.
+///
+/// Offset: 0x00 & 0x10
+/// Reset: 0xxxxxxxxx
+/// Property: NA
+#[derive(Clone, Copy, Debug)]
+#[repr(C)]
+pub(crate) struct Addr(u32);
+
+pub(crate) struct R {
+ bits: u32,
+}
+
+pub(crate) struct W {
+ bits: u32,
+}
+
+impl Addr {
+ pub fn read(&self) -> R {
+ R { bits: self.0 }
+ }
+
+ pub fn write<F>(&mut self, f: F)
+ where
+ F: FnOnce(&mut W) -> &mut W,
+ {
+ let mut w = W { bits: self.0 };
+ f(&mut w);
+ // Address must be 32-bit aligned.
+ assert!((w.bits & 0x3) == 0);
+ 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(crate) struct AddrR(u32);
+impl AddrR {
+ pub fn bits(&self) -> u32 {
+ self.0
+ }
+}
+
+impl W {
+ /// Write raw bits.
+ pub unsafe fn bits(&mut self, v: u32) -> &mut Self {
+ self.bits = v;
+ self
+ }
+
+ pub fn addr(&mut self) -> AddrW {
+ AddrW { w: self }
+ }
+}
+
+pub(crate) struct AddrW<'a> {
+ w: &'a mut W,
+}
+impl<'a> AddrW<'a> {
+ pub unsafe fn bits(self, v: u32) -> &'a mut W {
+ self.w.bits = v;
+ self.w
+ }
+
+ // TODO: "safe" method take a pointer instead of raw u32
+}
diff --git a/app/src/usb/pipe/ctrl_pipe.rs b/app/src/usb/pipe/ctrl_pipe.rs
new file mode 100644
index 0000000..63390df
--- /dev/null
+++ b/app/src/usb/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)]
+pub(crate) struct CtrlPipe(u16);
+
+pub(crate) struct R {
+ bits: u16,
+}
+
+pub(crate) struct W {
+ bits: u16,
+}
+
+impl CtrlPipe {
+ pub fn read(&self) -> R {
+ R { bits: self.0 }
+ }
+
+ pub fn write<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(crate) struct PErMaxR(u8);
+impl PErMaxR {
+ pub fn max(&self) -> u8 {
+ self.0
+ }
+}
+
+/// Pipe EndPoint Number
+///
+/// These bits define the number of endpoint for this Pipe.
+pub(crate) struct PEpNumR(u8);
+impl PEpNumR {
+ pub fn epnum(&self) -> u8 {
+ self.0
+ }
+}
+
+/// Pipe Device Address
+///
+/// These bits define the Device Address for this pipe.
+pub(crate) struct PDAddrR(u8);
+impl PDAddrR {
+ pub fn addr(&self) -> u8 {
+ self.0
+ }
+}
+
+impl W {
+ /// Write raw bits.
+
+ pub unsafe fn bits(&mut self, v: u16) -> &mut Self {
+ self.bits = v;
+ self
+ }
+
+ pub fn permax(&mut self) -> PErMaxW {
+ PErMaxW { w: self }
+ }
+
+ pub fn pepnum(&mut self) -> PEpNumW {
+ PEpNumW { w: self }
+ }
+
+ pub fn pdaddr(&mut self) -> PDAddrW {
+ PDAddrW { w: self }
+ }
+}
+
+pub(crate) struct PErMaxW<'a> {
+ w: &'a mut W,
+}
+impl<'a> PErMaxW<'a> {
+ pub unsafe fn bits(self, v: u8) -> &'a mut W {
+ const POS: u8 = 12;
+ const MASK: u8 = 0xf;
+ self.w.bits &= !((MASK as u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << POS;
+ self.w
+ }
+
+ pub fn set_max(self, v: u8) -> &'a mut W {
+ unsafe { self.bits(v) }
+ }
+}
+
+pub(crate) struct PEpNumW<'a> {
+ w: &'a mut W,
+}
+impl<'a> PEpNumW<'a> {
+ pub unsafe fn bits(self, v: u8) -> &'a mut W {
+ const POS: u8 = 8;
+ const MASK: u8 = 0xf;
+ self.w.bits &= !((MASK as u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << POS;
+ self.w
+ }
+
+ pub fn set_epnum(self, v: u8) -> &'a mut W {
+ unsafe { self.bits(v) }
+ }
+}
+
+pub(crate) struct PDAddrW<'a> {
+ w: &'a mut W,
+}
+impl<'a> PDAddrW<'a> {
+ pub unsafe fn bits(self, v: u8) -> &'a mut W {
+ const POS: u8 = 0;
+ const MASK: u8 = 0x3f;
+ self.w.bits &= !((MASK as u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << POS;
+ self.w
+ }
+
+ pub fn set_addr(self, v: u8) -> &'a mut W {
+ unsafe { self.bits(v) }
+ }
+}
diff --git a/app/src/usb/pipe/ext_reg.rs b/app/src/usb/pipe/ext_reg.rs
new file mode 100644
index 0000000..023ce9f
--- /dev/null
+++ b/app/src/usb/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)]
+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/app/src/usb/pipe/pck_size.rs b/app/src/usb/pipe/pck_size.rs
new file mode 100644
index 0000000..5133005
--- /dev/null
+++ b/app/src/usb/pipe/pck_size.rs
@@ -0,0 +1,360 @@
+/// § 32.8.7.3
+/// Packet Size.
+///
+/// Offset: 0x04 & 0x14
+/// Reset: 0xxxxxxxxx
+/// Property: NA
+#[derive(Clone, Copy, Debug)]
+#[repr(C)]
+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)
+ }
+
+ pub fn byte_count(&self) -> ByteCountR {
+ let bits = {
+ const POS: u8 = 8;
+ const MASK: u32 = 0x3f;
+ ((self.bits >> POS) & MASK) as u8
+ };
+
+ 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(u8);
+impl ByteCountR {
+ pub fn bits(&self) -> u8 {
+ 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 {
+ 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> {
+ pub unsafe fn bits(self, v: u8) -> &'a mut W {
+ const POS: u8 = 8;
+ const MASK: u8 = 0x3f;
+ self.w.bits &= !((MASK as u32) << POS);
+ self.w.bits |= ((v & MASK) as u32) << POS;
+ self.w
+ }
+}
diff --git a/app/src/usb/pipe/status_bk.rs b/app/src/usb/pipe/status_bk.rs
new file mode 100644
index 0000000..4ddb420
--- /dev/null
+++ b/app/src/usb/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)]
+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/app/src/usb/pipe/status_pipe.rs b/app/src/usb/pipe/status_pipe.rs
new file mode 100644
index 0000000..4f8eb41
--- /dev/null
+++ b/app/src/usb/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)]
+pub(crate) struct StatusPipe(u16);
+
+pub(crate) struct R {
+ bits: u16,
+}
+pub(crate) struct W {
+ bits: u16,
+}
+
+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<u16> for StatusPipe {
+ fn from(v: u16) -> Self {
+ Self(v)
+ }
+}
+
+impl R {
+ /// Value in raw bits.
+ pub fn bits(&self) -> u16 {
+ self.bits
+ }
+
+ pub fn ercnt(&self) -> ErCntR {
+ let bits = {
+ const POS: u8 = 5;
+ const MASK: u16 = 0x7;
+ ((self.bits >> POS) & MASK) as u8
+ };
+
+ ErCntR(bits)
+ }
+
+ pub fn crc16er(&self) -> CRC16ErR {
+ let bits = {
+ const POS: u8 = 4;
+ const MASK: u16 = 1;
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ CRC16ErR(bits)
+ }
+
+ pub fn touter(&self) -> TOutErrR {
+ let bits = {
+ const POS: u8 = 3;
+ const MASK: u16 = 1;
+
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ TOutErrR(bits)
+ }
+
+ pub fn pider(&self) -> PIDErR {
+ let bits = {
+ const POS: u8 = 2;
+ const MASK: u16 = 1;
+
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ PIDErR(bits)
+ }
+
+ pub fn dapider(&self) -> DaPIDErR {
+ let bits = {
+ const POS: u8 = 1;
+ const MASK: u16 = 1;
+
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ DaPIDErR(bits)
+ }
+
+ pub fn dtgler(&self) -> DTglErR {
+ let bits = {
+ const POS: u8 = 0;
+ const MASK: u16 = 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: u16) -> &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 u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << 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 u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << 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 u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << 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 u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << 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 u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << 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 u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << 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/app/src/usb/usbproto.rs b/app/src/usb/usbproto.rs
new file mode 100644
index 0000000..9a86ed7
--- /dev/null
+++ b/app/src/usb/usbproto.rs
@@ -0,0 +1,331 @@
+/// USB Protocol level types and functions.
+///
+/// Everything in here is defined by the USB specification, and
+/// hardware independent.
+
+// TODO: Put protocol section references in for types and
+// documentation.
+
+#[derive(Copy, Clone, Debug, Default)]
+#[repr(C, packed)]
+pub struct USBDeviceDescriptor {
+ pub b_length: u8,
+ pub b_descriptor_type: u8,
+ pub bcd_usb: u16,
+ pub b_device_class: u8,
+ pub b_device_sub_class: u8,
+ pub b_device_protocol: u8,
+ pub b_max_packet_size: u8,
+ pub id_vendor: u16,
+ pub id_product: u16,
+ pub bcd_device: u16,
+ pub i_manufacturer: u8,
+ pub i_product: u8,
+ pub i_serial_number: u8,
+ pub b_num_configurations: u8,
+}
+
+#[derive(Copy, Clone, Debug, Default)]
+#[repr(C, packed)]
+pub struct USBConfigurationDescriptor {
+ pub b_length: u8,
+ pub b_descriptor_type: u8,
+ pub w_total_length: u16,
+ pub b_num_interfaces: u8,
+ pub b_configuration_value: u8,
+ pub i_configuration: u8,
+ pub bm_attributes: u8,
+ pub b_max_power: u8,
+}
+
+#[derive(Copy, Clone, Debug, Default)]
+#[repr(C, packed)]
+pub struct USBInterfaceDescriptor {
+ pub b_length: u8,
+ pub b_descriptor_type: u8,
+ pub b_interface_number: u8,
+ pub b_alternate_setting: u8,
+ pub b_num_endpoints: u8,
+ pub b_interface_class: u8,
+ pub b_interface_sub_class: u8,
+ pub b_interface_protocol: u8,
+ pub i_interface: u8,
+}
+
+#[derive(Copy, Clone, Debug, Default)]
+#[repr(C, packed)]
+pub struct USBEndpointDescriptor {
+ pub b_length: u8,
+ pub b_descriptor_type: u8,
+ pub b_endpoint_address: u8,
+ pub bm_attributes: u8,
+ pub w_max_packet_size: u16,
+ pub b_interval: u8,
+}
+
+#[derive(Copy, Clone, Debug)]
+#[repr(C, packed)]
+pub struct USBSetupPacket {
+ pub bm_request_type: BMRequestType,
+ pub b_request: USBRequest,
+ pub w_value: WValue,
+ pub w_index: u16,
+ pub w_length: u16,
+}
+// TODO: shortcuts for standard device requests §9.4 of USB standard.
+
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub enum USBSetupDirection {
+ HostToDevice = 0x00,
+ DeviceToHost = 0x80,
+}
+impl<T> From<T> for USBSetupDirection
+where
+ T: Into<u8>,
+{
+ fn from(v: T) -> Self {
+ match v.into() {
+ 0x00 => Self::HostToDevice,
+ 0x80 => Self::DeviceToHost,
+ _ => panic!("direction can only be 0x00 or 0x80"),
+ }
+ }
+}
+
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub enum USBSetupType {
+ Standard = 0x00,
+ Class = 0x20,
+ Vendor = 0x40,
+}
+impl<T> From<T> for USBSetupType
+where
+ T: Into<u8>,
+{
+ fn from(v: T) -> Self {
+ match v.into() {
+ 0x00 => Self::Standard,
+ 0x20 => Self::Class,
+ 0x40 => Self::Vendor,
+ _ => panic!("type can only be 0x00, 0x20, or 0x40"),
+ }
+ }
+}
+
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub enum USBSetupRecipient {
+ Device = 0x00,
+ Interface = 0x01,
+ Endpoint = 0x02,
+ Other = 0x03,
+}
+impl<T> From<T> for USBSetupRecipient
+where
+ T: Into<u8>,
+{
+ fn from(v: T) -> Self {
+ match v.into() {
+ 0x00 => Self::Device,
+ 0x01 => Self::Interface,
+ 0x02 => Self::Endpoint,
+ 0x03 => Self::Other,
+ _ => panic!("recipient can only be between 0 and 3"),
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+#[repr(C)]
+pub struct BMRequestType(u8);
+impl BMRequestType {
+ // Get descriptor request type.
+ pub fn get_descr() -> Self {
+ Self::from((
+ USBSetupDirection::DeviceToHost,
+ USBSetupType::Standard,
+ USBSetupRecipient::Device,
+ ))
+ }
+
+ // Set request type for all but 'set feature' and 'set interface'.
+ pub fn set() -> Self {
+ Self::from((
+ USBSetupDirection::HostToDevice,
+ USBSetupType::Standard,
+ USBSetupRecipient::Device,
+ ))
+ }
+
+ // Get interface request type.
+ pub fn cl_get_intf() -> Self {
+ Self::from((
+ USBSetupDirection::DeviceToHost,
+ USBSetupType::Class,
+ USBSetupRecipient::Interface,
+ ))
+ }
+
+ pub fn recipient(&self) -> USBSetupRecipient {
+ const POS: u8 = 0;
+ const MASK: u8 = 0x1f;
+ (self.0 & (MASK << POS)).into()
+ }
+
+ pub fn set_recipient(&mut self, v: USBSetupRecipient) {
+ const POS: u8 = 0;
+ const MASK: u8 = 0x1f;
+ self.0 &= !(MASK << POS);
+ self.0 |= v as u8 & MASK;
+ }
+
+ pub fn typ(&self) -> USBSetupType {
+ const POS: u8 = 5;
+ const MASK: u8 = 0x3;
+ (self.0 & (MASK << POS)).into()
+ }
+
+ pub fn set_typ(&mut self, v: USBSetupType) {
+ const POS: u8 = 5;
+ const MASK: u8 = 0x3;
+ self.0 &= !(MASK << POS);
+ self.0 |= v as u8 & MASK;
+ }
+
+ pub fn direction(&self) -> USBSetupDirection {
+ const POS: u8 = 7;
+ const MASK: u8 = 0x1;
+ (self.0 & (MASK << POS)).into()
+ }
+
+ pub fn set_direction(&mut self, v: USBSetupDirection) {
+ const POS: u8 = 7;
+ const MASK: u8 = 0x1;
+ self.0 &= !(MASK << POS);
+ self.0 |= v as u8 & MASK;
+ }
+}
+impl From<u8> for BMRequestType {
+ fn from(v: u8) -> Self {
+ Self(v)
+ }
+}
+impl From<(USBSetupDirection, USBSetupType, USBSetupRecipient)> for BMRequestType {
+ fn from(v: (USBSetupDirection, USBSetupType, USBSetupRecipient)) -> Self {
+ Self(v.0 as u8 | v.1 as u8 | v.2 as u8)
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+#[repr(C)]
+pub struct WValue(u16);
+impl WValue {
+ pub fn w_value_lo(&self) -> u8 {
+ const POS: u8 = 0;
+ const MASK: u16 = 0xff;
+ ((self.0 >> POS) & MASK) as u8
+ }
+
+ pub fn set_w_value_lo(&mut self, v: u8) {
+ const POS: u8 = 0;
+ const MASK: u8 = 0xff;
+ self.0 &= !((MASK as u16) << POS);
+ self.0 |= ((v & MASK) as u16) << POS;
+ }
+
+ pub fn w_value_hi(&self) -> u8 {
+ const POS: u8 = 8;
+ const MASK: u16 = 0xff;
+ ((self.0 >> POS) & MASK) as u8
+ }
+
+ pub fn set_w_value_hi(&mut self, v: u8) {
+ const POS: u8 = 8;
+ const MASK: u8 = 0xff;
+ self.0 &= !((MASK as u16) << POS);
+ self.0 |= ((v & MASK) as u16) << POS;
+ }
+}
+impl From<(u8, u8)> for WValue {
+ fn from(v: (u8, u8)) -> Self {
+ let mut rc = Self(0);
+ rc.set_w_value_lo(v.0);
+ rc.set_w_value_hi(v.1);
+ rc
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum USBRequest {
+ GetStatus = 0,
+ ClearFeature = 1,
+ SetFeature = 3,
+ SetAddress = 5,
+ GetDescriptor = 6,
+ SetDescriptor = 7,
+ GetConfiguration = 8,
+ SetConfiguration = 9,
+ GetInterface = 10,
+ SetInterface = 11,
+ SynchFrame = 12,
+}
+impl<T> From<T> for USBRequest
+where
+ T: Into<u8>,
+{
+ fn from(v: T) -> Self {
+ match v.into() {
+ 0 => Self::GetStatus,
+ 1 => Self::ClearFeature,
+ 3 => Self::SetFeature,
+ 5 => Self::SetAddress,
+ 6 => Self::GetDescriptor,
+ 7 => Self::SetDescriptor,
+ 8 => Self::GetConfiguration,
+ 9 => Self::SetConfiguration,
+ 10 => Self::GetInterface,
+ 11 => Self::SetInterface,
+ 12 => Self::SynchFrame,
+ _ => panic!("invalid request value"),
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum USBFeature {
+ EndpointHalt = 0,
+ DeviceRemoteWakeup = 1,
+ TestMode = 2,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum USBDescriptor {
+ Device = 0x01,
+ Configuration = 0x02,
+ String = 0x03,
+ Interface = 0x04,
+ Endpoint = 0x05,
+ DeviceQualifier = 0x06,
+ OtherSpeed = 0x07,
+ InterfacePower = 0x08,
+ OTG = 0x09,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum HIDDescriptor {
+ HID = 0x21,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum OTGFeature {
+ BHNPEnable = 3,
+ AHNPSupport = 4,
+ AAltHNPSupport = 5,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum USBTransferType {
+ Control = 0x00,
+ Isochronous = 0x01,
+ Bulk = 0x02,
+ Interrupt = 0x03,
+}
diff --git a/rb/Cargo.lock b/rb/Cargo.lock
new file mode 100644
index 0000000..1adf307
--- /dev/null
+++ b/rb/Cargo.lock
@@ -0,0 +1,6 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+[[package]]
+name = "rb"
+version = "0.1.0"
+
diff --git a/rb/Cargo.toml b/rb/Cargo.toml
new file mode 100644
index 0000000..d18a9e2
--- /dev/null
+++ b/rb/Cargo.toml
@@ -0,0 +1,5 @@
+[package]
+name = "rb"
+version = "0.1.0"
+authors = ["Brian Cully <bjc@kublai.com>"]
+edition = "2018"
diff --git a/rb/src/lib.rs b/rb/src/lib.rs
new file mode 100755
index 0000000..d51bb26
--- /dev/null
+++ b/rb/src/lib.rs
@@ -0,0 +1,221 @@
+// FIXME: Currently RingBuffer requires its type parameter to be
+// `Copy` because items are stored in a fixed-length array (which,
+// itself, is required to allow creating RingBuffers
+// statically). There may be work-arounds with ptr routines, and it
+// should be investigated.
+//
+// TODO: Needs impls for Iter/IterMut.
+#![no_std]
+#![feature(const_fn)]
+
+use core::{
+ cell::UnsafeCell,
+ marker::PhantomData,
+ sync::atomic::{AtomicUsize, Ordering},
+};
+
+/// Underlying buffer capacity. Needs to be hard-coded for now,
+/// because the size of the structure needs to be known at compile
+/// time so it can be statically allocated or created on the stack.
+///
+/// This will disappear when const generics appear.
+const CAPACITY: usize = 256;
+
+#[derive(Debug, PartialEq)]
+pub enum Error {
+ BufferFull,
+}
+
+/// A lock-free concurrent ring buffer that prevents overwriting data
+/// before it is read.
+pub struct RingBuffer<T> {
+ head: AtomicUsize,
+ tail: AtomicUsize,
+
+ // Backing store needs to be UnsafeCell to make sure it's not
+ // stored in read-only data sections.
+ buf: UnsafeCell<[T; CAPACITY]>,
+}
+
+impl<T> RingBuffer<T>
+where
+ T: Copy,
+{
+ /// Create a new RingBuffer.
+ pub const fn new(default: T) -> Self {
+ Self {
+ head: AtomicUsize::new(0),
+ tail: AtomicUsize::new(0),
+ buf: UnsafeCell::new([default; CAPACITY]),
+ }
+ }
+
+ // Honestly, this should consume `self` or at least be `mut`, but
+ // it needs to be available in const static contexts, which
+ // prevents that. Basically all the rest of the unsafe stuff in
+ // here is a consequence of that.
+ //
+ // No, lazy_static is not an option, because it doesn't work on
+ // architectures where CAS atomics are missing.
+ pub const fn split<'a>(&'a self) -> (Reader<T>, Writer<T>) {
+ let rbr = Reader {
+ rb: self as *const _,
+ _marker: PhantomData,
+ };
+ let rbw = Writer {
+ rb: self as *const _,
+ _marker: PhantomData,
+ };
+ (rbr, rbw)
+ }
+}
+
+pub struct Reader<'a, T> {
+ rb: *const RingBuffer<T>,
+ _marker: PhantomData<&'a ()>,
+}
+unsafe impl<T> Send for Reader<'_, T> where T: Send {}
+unsafe impl<T> Sync for Reader<'_, T> {}
+
+pub struct Writer<'a, T> {
+ rb: *const RingBuffer<T>,
+ _marker: PhantomData<&'a ()>,
+}
+unsafe impl<T> Send for Writer<'_, T> where T: Send {}
+unsafe impl<T> Sync for Writer<'_, T> {}
+
+impl<'a, T> Reader<'a, T>
+where
+ T: Copy,
+{
+ pub fn len(&self) -> usize {
+ let rb: &mut RingBuffer<T> = unsafe { core::mem::transmute(self.rb) };
+ let h = rb.head.load(Ordering::SeqCst);
+ let t = rb.tail.load(Ordering::SeqCst);
+ let rc = (t + CAPACITY - h) % CAPACITY;
+ rc
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+
+ /// Returns the value at the start of the buffer and advances the
+ /// start of the buffer to the next element.
+ ///
+ /// If nothing is available in the buffer, returns `None`
+ pub fn shift(&mut self) -> Option<T> {
+ let rb: &mut RingBuffer<T> = unsafe { core::mem::transmute(self.rb) };
+ let h = rb.head.load(Ordering::SeqCst);
+ let t = rb.tail.load(Ordering::SeqCst);
+ if h == t {
+ None
+ } else {
+ let nh = (h + 1) % CAPACITY;
+ let buf = unsafe { &mut *rb.buf.get() };
+ let rc = Some(buf[h]);
+ rb.head.store(nh, Ordering::SeqCst);
+ rc
+ }
+ }
+}
+
+impl<'a, T> Writer<'a, T>
+where
+ T: Copy,
+{
+ /// Put `v` at the end of the buffer.
+ ///
+ /// Returns `BufferFull` if appending `v` would overlap with the
+ /// start of the buffer.
+ pub fn unshift(&mut self, v: T) -> Result<(), Error> {
+ let rb: &mut RingBuffer<T> = unsafe { core::mem::transmute(self.rb) };
+ let h = rb.head.load(Ordering::SeqCst);
+ let t = rb.tail.load(Ordering::SeqCst);
+ let nt = (t + 1) % CAPACITY;
+ // We can't allow overwrites of the head position, because it
+ // would then be possible to write to the same memory location
+ // that is being read. If reading a value of `T` takes more
+ // than one memory read, then reading from the head would
+ // produce garbage in this scenario.
+ if nt == h {
+ // FIXME: this comparison is wrong in the trivial
+ // 1-element buffer case which would never allow an
+ // `unshift`. In larger buffers it wastes a buffer slot.
+ Err(Error::BufferFull)
+ } else {
+ let buf = unsafe { &mut *rb.buf.get() };
+ buf[t] = v;
+ rb.tail.store(nt, Ordering::SeqCst);
+ Ok(())
+ }
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ #[test]
+ fn detects_empty() {
+ let rb = RingBuffer::<bool>::new(false);
+ let (mut rbr, mut rbw) = rb.split();
+ assert!(rbr.is_empty());
+ rbw.unshift(true).ok();
+ assert!(!rbr.is_empty());
+ rbr.shift();
+ assert!(rbr.is_empty());
+ }
+
+ #[test]
+ fn len_matches() {
+ let rb = RingBuffer::<bool>::new(false);
+ let (mut rbr, mut rbw) = rb.split();
+
+ // Count length up.
+ for i in 0..CAPACITY - 1 {
+ assert_eq!(rbr.len(), i);
+ assert_eq!(rbw.unshift(true), Ok(()));
+ }
+
+ // ...and back down again.
+ for i in 0..CAPACITY - 1 {
+ assert_eq!(rbr.len(), CAPACITY - 1 - i);
+ rbr.shift();
+ }
+
+ // Final check for empty.
+ assert_eq!(rbr.len(), 0);
+ }
+
+ #[test]
+ fn can_wrap() {
+ let rb = RingBuffer::<usize>::new(0);
+ let (mut rbr, mut rbw) = rb.split();
+
+ // Make sure we can store n-1 elements.
+ for i in 0..CAPACITY - 1 {
+ assert_eq!(rbw.unshift(i), Ok(()))
+ }
+
+ // ...and that we can load them back again.
+ for i in 0..CAPACITY - 1 {
+ assert_eq!(rbr.shift(), Some(i))
+ }
+ }
+
+ #[test]
+ fn cannot_overwrite() {
+ let rb = RingBuffer::<usize>::new(0);
+ let (mut rbr, mut rbw) = rb.split();
+
+ for i in 0..CAPACITY - 1 {
+ assert_eq!(rbw.unshift(i), Ok(()));
+ }
+ assert_eq!(rbw.unshift(0xffff), Err(Error::BufferFull));
+
+ // We can drop an element to allow a slot to write to again.
+ rbr.shift();
+ assert_eq!(rbw.unshift(0xffff), Ok(()));
+ }
+}