aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.cargo/config6
-rw-r--r--.gitignore5
-rw-r--r--COPYING674
-rw-r--r--COPYING.LESSER165
-rw-r--r--Cargo.toml30
-rw-r--r--Makefile38
-rw-r--r--README.md34
-rw-r--r--TODO.org37
-rw-r--r--examples/simple/logger.rs139
-rw-r--r--examples/simple/macros.rs15
-rwxr-xr-xexamples/simple/main.rs192
-rw-r--r--examples/simple/rtc.rs74
-rwxr-xr-xfind-serial-port16
-rwxr-xr-xsrc/lib.rs645
-rw-r--r--src/pipe.rs809
-rw-r--r--src/pipe/addr.rs98
-rw-r--r--src/pipe/ctrl_pipe.rs177
-rw-r--r--src/pipe/ext_reg.rs156
-rw-r--r--src/pipe/pck_size.rs368
-rw-r--r--src/pipe/status_bk.rs170
-rw-r--r--src/pipe/status_pipe.rs407
21 files changed, 4255 insertions, 0 deletions
diff --git a/.cargo/config b/.cargo/config
new file mode 100644
index 0000000..b6cdff0
--- /dev/null
+++ b/.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/.gitignore b/.gitignore
new file mode 100644
index 0000000..39705a2
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+*.bin
+*.uf2
+/target
+**/*.rs.bk
+Cargo.lock
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/COPYING.LESSER b/COPYING.LESSER
new file mode 100644
index 0000000..0a04128
--- /dev/null
+++ b/COPYING.LESSER
@@ -0,0 +1,165 @@
+ GNU LESSER 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.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser 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
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..9e1bdcb
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,30 @@
+[package]
+name = "atsamd-usb-host"
+description = "usb-host driver support for Atmel SAMD* microcontrollers."
+version = "0.1.0"
+authors = ["Brian Cully <bjc@kublai.com>"]
+edition = "2018"
+license = "LGPL-3.0-or-later"
+categories = ["no-std", "embedded", "hardware-support"]
+keywords = ["usb", "usb-host", "hal", "peripheral"]
+repository = "https://github.com/bjc/atsamd-21-host.git"
+readme = "README.md"
+
+[dependencies]
+usb-host = "~0.1"
+starb = "~0.1"
+log = "~0.4"
+embedded-hal = "~0.2"
+atsamd-hal = "~0.6"
+
+[dev-dependencies]
+bootkbd = "~0.1"
+clint = "~0.2"
+cortex-m = "~0.6"
+cortex-m-rt = "~0.6"
+nb = "~0.1"
+trinket_m0 = "~0.4"
+
+[patch.crates-io]
+atsamd-hal = { git = "https://github.com/atsamd-rs/atsamd", rev = "97d55c19" }
+trinket_m0 = { git = "https://github.com/atsamd-rs/atsamd", rev = "97d55c19" }
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..87fbc8d
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,38 @@
+APP = simple
+
+USBVID = 239a
+USBPID = '001e|801e'
+
+BOSSAC = bossac
+SERIAL = $(shell ./find-serial-port $(USBVID) $(USBPID) || echo 'cant-find-serial-port')
+OFFSET = 0x2000
+
+.PHONY: all clean cargo-build target/thumbv6m-none-eabi/debug/examples/$(APP)
+
+all: $(APP).uf2
+
+clean:
+ rm -f $(APP).uf2
+ rm -f $(APP).bin
+ cargo clean
+
+cargo-build:
+ cargo build --example $(APP)
+
+target/thumbv6m-none-eabi/debug/examples/$(APP): cargo-build
+
+$(APP).bin: target/thumbv6m-none-eabi/debug/examples/$(APP)
+ cargo objcopy --example $(APP) -- -O binary $(APP).bin
+
+# Requires https://github.com/sajattack/uf2conv-rs.git
+%.uf2: %.bin
+ uf2conv-rs $< --base $(OFFSET) --output $@
+
+flash: $(APP).bin $(SERIAL)
+ $(BOSSAC) -R -e -w -v -o$(OFFSET) -p$(SERIAL) $<
+
+qemu: target/thumbv6m-none-eabi/debug/$(APP)
+ qemu-system-arm -d in_asm,int,exec,cpu,guest_errors,unimp -pidfile qemu.pid -cpu cortex-m0 -machine lm3s6965evb -nographic -semihosting-config enable=on,target=native -s -S -kernel $<
+
+gdb: target/thumbv6m-none-eabi/debug/$(APP)
+ gdb-multiarch -ex "target remote localhost:1234" -ex "break main" -ex "continue" $<
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..0a25168
--- /dev/null
+++ b/README.md
@@ -0,0 +1,34 @@
+# atsamd-usb-host
+
+This is a [usb-host](https://github.com/bjc/usb-host) driver for
+Atmel's SAMD series of chips.
+
+# Examples
+
+## (Sort of) Simple Example
+
+This assumes you have an [Adafruit Trinket
+M0](https://www.adafruit.com/product/3500). You'll need to make
+modifications to `Makefile` and `examples/simple/main.rs` for your
+board otherwise.
+
+You'll need at least `bossac` installed somewhere in your path in
+order to actually do the flashing. You'll also need rust installed for
+your target device.
+
+1) Grab the above branch and stick it one directory level up (e.g., if
+this is checked out into `~/src/atsamd-usb-host` the `atsamd-hal`
+checkout should be in `~/src/atsamd`).
+
+2) Connect a serial port to your device (the Trinket M0 uses pin 4 to
+do UART transmission at TTL voltage).
+
+3) Plug the device in, put it into firmware-update mode (double-tap
+the reset button on the Trinket M0) and run `make flash`. When it's
+done you should see boot messages on your serial device.
+
+4) Unplug the device from the computer, hook it up to another power
+supply somehow (I wire GND to ground and USB to 5V), plug in a
+keyboard, and hit some keys. You should see it print out the keyboard
+reports as keys are pressed and released. Alternately, you may see
+error messages if something is broken.
diff --git a/TODO.org b/TODO.org
new file mode 100644
index 0000000..710b509
--- /dev/null
+++ b/TODO.org
@@ -0,0 +1,37 @@
+* Documentation
+ - README.md
+ - Literally every trait and method.
+
+* Use channel for interrupt -> task messages.
+Currently we use a static mut which holds the latest event. This was
+done for expediency to try and get somethnig working and this was
+working in Arduino. It's also massively wrong in the general case and
+overflowing with race conditions.
+
+A channel will allow us to deterministically walk events and make sure
+everything's ordered properly.
+
+* Clean up pipe descriptor stuff.
+There's a bunch of unsafe functions that can be made safe.
+
+* Some SVD patches needed for SAMD21/51.
+There's a lot of `unsafe` code where there shouldn't be, because the
+SVD files are lacking.
+
+* Stop passing millis function around.
+This is horrible, but currently necessary because there are places
+where we need to loop on a timer at it needs to be
+hardware-independent.
+
+If the USB host library can be made asynchronouse, we could instead
+pass a current timestamp around and use that for delays where
+necessary.
+
+As a last resort, there's a countdown timer trait in embedded-hal that
+may be useful.
+
+* Tighten up timings on requests.
+There are a few timer checks on USB requests, but not necessarily of
+the right duration nor subdivided correctly. For instance, the
+setup-with-data cycle has requirements on total duration as well as
+per-packet duration, but currently we're only using the total.
diff --git a/examples/simple/logger.rs b/examples/simple/logger.rs
new file mode 100644
index 0000000..9641dac
--- /dev/null
+++ b/examples/simple/logger.rs
@@ -0,0 +1,139 @@
+use crate::rtc;
+use starb::{Reader, RingBuffer, Writer};
+
+use core::cell::UnsafeCell;
+use core::fmt::{self, Write};
+use embedded_hal::{digital::v2::OutputPin, serial};
+use log::{Metadata, Record};
+use trinket_m0::{
+ gpio::{Pa6, Pa7, PfD},
+ sercom::{Sercom0Pad2, Sercom0Pad3, UART0},
+};
+
+static mut UART0: usize = 0;
+
+struct JoinedRingBuffer<'a> {
+ lbr: Reader<'a, u8>,
+ lbw: Writer<'a, u8>,
+}
+
+impl<'a> JoinedRingBuffer<'a> {
+ const fn new(rb: &'a RingBuffer<u8>) -> Self {
+ let (lbr, lbw) = rb.split();
+ Self { lbr: lbr, lbw: lbw }
+ }
+}
+
+impl fmt::Write for JoinedRingBuffer<'_> {
+ fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> {
+ for b in s.bytes() {
+ if let Err(_) = self.lbw.unshift(b) {
+ // Ignore buffer full errors for logging.
+ return Ok(());
+ }
+ }
+ Ok(())
+ }
+}
+
+static mut LB: RingBuffer<u8> = RingBuffer::<u8>::new(0);
+static mut JRB: JoinedRingBuffer = unsafe { JoinedRingBuffer::new(&LB) };
+
+// The UART isn't necessarily Sync, so wrap it in something that
+// is. As long as flush() is only called from one thread, we're fine,
+// but this is a guarantee that the logger module doesn't make.
+pub struct WriteWrapper<W> {
+ w: W,
+}
+impl<W> WriteWrapper<W>
+where
+ W: serial::Write<u8>,
+{
+ pub const fn new(writer: W) -> Self {
+ Self { w: writer }
+ }
+}
+unsafe impl<W> Sync for WriteWrapper<W> {}
+
+pub struct SerialLogger<W, L> {
+ writer: UnsafeCell<WriteWrapper<W>>,
+ led: UnsafeCell<L>,
+}
+
+impl<W, L> SerialLogger<W, L>
+where
+ W: serial::Write<u8>,
+ L: OutputPin + Send + Sync,
+{
+ pub fn new(writer: WriteWrapper<W>, led: L) -> Self {
+ // Stash this for unsafe usage in case there's an issue with
+ // the rest of the logging.
+ unsafe { UART0 = core::mem::transmute(&writer.w) };
+ Self {
+ writer: UnsafeCell::new(writer),
+ led: UnsafeCell::new(led),
+ }
+ }
+}
+unsafe impl<W, L> Send for SerialLogger<W, L> {}
+unsafe impl<W, L> Sync for SerialLogger<W, L> {}
+
+impl<W, L> log::Log for SerialLogger<W, L>
+where
+ W: serial::Write<u8>,
+ L: OutputPin + Send + Sync,
+{
+ fn enabled(&self, metadata: &Metadata) -> bool {
+ metadata.level() <= log::max_level()
+ }
+
+ fn log(&self, record: &Record) {
+ if !self.enabled(record.metadata()) {
+ return;
+ }
+
+ let jrb = unsafe { &mut JRB };
+ write!(
+ jrb,
+ "[{}] {} {} -- {}\r\n",
+ rtc::millis(),
+ record.level(),
+ record.target(),
+ record.args()
+ )
+ .ok();
+ }
+
+ fn flush(&self) {
+ // Unsafe due to mutable static. We can only deal with the
+ // tail position of the buffer here to keep things safe.
+ let jrb = unsafe { &mut JRB };
+ if jrb.lbr.is_empty() {
+ return;
+ }
+
+ let led = unsafe { &mut (*self.led.get()) };
+ let writer = unsafe { &mut (*self.writer.get()) };
+
+ led.set_high().ok();
+ while let Some(b) = jrb.lbr.shift() {
+ nb::block!(writer.w.write(b)).ok();
+ }
+ led.set_low().ok();
+ }
+}
+
+// Write to the UART right now, instead of putting it on a ring
+// buffer. This function is a huge hack, and only useful for debugging
+// either before the main loop starts or if the ring buffer is broken.
+pub unsafe fn write_fmt_now(args: fmt::Arguments, nl: bool) {
+ if UART0 == 0 {
+ return;
+ }
+ let uart: &mut UART0<Sercom0Pad3<Pa7<PfD>>, Sercom0Pad2<Pa6<PfD>>, (), ()> =
+ core::mem::transmute(UART0);
+ fmt::write(uart, args).expect("writing fmt now to uart");
+ if nl {
+ uart.write_str("\r\n").expect("writing nl now to uart");
+ }
+}
diff --git a/examples/simple/macros.rs b/examples/simple/macros.rs
new file mode 100644
index 0000000..46d2d07
--- /dev/null
+++ b/examples/simple/macros.rs
@@ -0,0 +1,15 @@
+#[macro_export]
+macro_rules! logln_now {
+ ($($arg:tt)*) => {
+ unsafe {crate::logger::write_fmt_now(format_args!($($arg)*), true);}
+ };
+ (_) => {};
+}
+
+#[macro_export]
+macro_rules! log_now {
+ ($($arg:tt)*) => {
+ unsafe {crate::logger::write_fmt_now(format_args!($($arg)*), false);}
+ };
+ (_) => {};
+}
diff --git a/examples/simple/main.rs b/examples/simple/main.rs
new file mode 100755
index 0000000..84b5e33
--- /dev/null
+++ b/examples/simple/main.rs
@@ -0,0 +1,192 @@
+#![no_std]
+#![no_main]
+#![feature(const_fn)]
+#![feature(const_transmute)]
+#![allow(dead_code)]
+
+mod logger;
+mod macros;
+mod rtc;
+
+use atsamd_usb_host::SAMDHost;
+use bootkbd::BootKeyboard;
+use clint::HandlerArray;
+use cortex_m::asm::wfi;
+use cortex_m_rt::{entry, exception, ExceptionFrame};
+use embedded_hal::digital::v2::OutputPin;
+use log::{debug, info, LevelFilter};
+use trinket_m0::{
+ self as hal,
+ clock::GenericClockController,
+ gpio::{OpenDrain, Output, Pa10, Pa6, Pa7, PfD},
+ sercom,
+ target_device::{interrupt, Interrupt},
+ time::*,
+ CorePeripherals, Peripherals,
+};
+use usb_host::Driver;
+
+static HANDLERS: HandlerArray = HandlerArray::new();
+
+static mut LED: usize = 0;
+
+#[entry]
+fn main() -> ! {
+ let mut peripherals = Peripherals::take().expect("taking peripherals");
+ let mut core = CorePeripherals::take().expect("taking core peripherals");
+
+ let mut clocks = GenericClockController::with_internal_32kosc(
+ peripherals.GCLK,
+ &mut peripherals.PM,
+ &mut peripherals.SYSCTRL,
+ &mut peripherals.NVMCTRL,
+ );
+
+ let mut pins = hal::Pins::new(peripherals.PORT);
+
+ let uart = hal::uart(
+ &mut clocks,
+ 115_200.hz(),
+ peripherals.SERCOM0,
+ &mut core.NVIC,
+ &mut peripherals.PM,
+ pins.d3,
+ pins.d4,
+ &mut pins.port,
+ );
+
+ let mut red_led = pins.d13.into_open_drain_output(&mut pins.port);
+ red_led.set_low().expect("turning off red LED");
+ unsafe { LED = core::mem::transmute(&red_led) }
+
+ // We do the transmute because, while all the underlying data is
+ // static, we're unable to get a referecence to the UART or LED
+ // until run-time. Another option would be to use Option in the
+ // SerialLogger definition, but that requires a check every time
+ // they might be used.
+ let uart_wrapped = logger::WriteWrapper::new(uart);
+ let logger = logger::SerialLogger::new(uart_wrapped, red_led);
+
+ // Wow, would I love to not be annotating this type.
+ let logger_ref: &'static logger::SerialLogger<
+ sercom::UART0<sercom::Sercom0Pad3<Pa7<PfD>>, sercom::Sercom0Pad2<Pa6<PfD>>, (), ()>,
+ Pa10<Output<OpenDrain>>,
+ > = unsafe { core::mem::transmute(&logger) };
+ unsafe { log::set_logger_racy(logger_ref).expect("couldn't set logger") };
+ log::set_max_level(LevelFilter::Info);
+
+ info!("setting up timer");
+ let mut rtc_handler = rtc::setup(peripherals.RTC, &mut clocks);
+
+ info!("setting up usb host");
+ let (mut usb_host, mut usb_handler) = SAMDHost::new(
+ peripherals.USB,
+ pins.usb_sof,
+ pins.usb_dm,
+ pins.usb_dp,
+ Some(pins.usb_host_enable),
+ &mut pins.port,
+ &mut clocks,
+ &mut peripherals.PM,
+ &rtc::millis,
+ );
+
+ let mut bootkbd = BootKeyboard::new();
+ let mut drivers: [&mut dyn Driver; 1] = [&mut bootkbd];
+
+ info!("setting up handlers");
+ HANDLERS.with_overrides(|hs| {
+ hs.register(0, &mut rtc_handler);
+ core.NVIC.enable(Interrupt::RTC);
+
+ hs.register(1, &mut usb_handler);
+ unsafe { core.NVIC.set_priority(Interrupt::USB, 0) };
+ core.NVIC.enable(Interrupt::USB);
+
+ info!("Boot up complete.");
+
+ loop {
+ usb_host.task(&mut drivers[..]);
+ wfi();
+ }
+ });
+ unreachable!();
+}
+
+#[panic_handler]
+fn panic_handler(pi: &core::panic::PanicInfo) -> ! {
+ let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) };
+ red_led.set_high().ok();
+
+ logln_now!("~~~ PANIC ~~~");
+ logln_now!("{}", pi);
+ logln_now!("flushing log");
+ loop {
+ log::logger().flush();
+ wfi()
+ }
+}
+
+#[exception]
+fn HardFault(ef: &ExceptionFrame) -> ! {
+ let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) };
+ red_led.set_high().ok();
+
+ log::logger().flush();
+ logln_now!("!!! Hard Fault - ef: {:?} !!!", ef);
+ logln_now!("flushing log");
+ loop {
+ log::logger().flush();
+ wfi()
+ }
+}
+
+#[exception]
+fn DefaultHandler(interrupt: i16) {
+ let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) };
+ red_led.set_high().ok();
+
+ debug!("*** Default Handler: {} ***", interrupt);
+}
+
+#[exception]
+fn NonMaskableInt() {
+ let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) };
+ red_led.set_high().ok();
+
+ debug!("+++ NonMaskableInt +++");
+}
+
+#[exception]
+fn SVCall() {
+ let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) };
+ red_led.set_high().ok();
+
+ debug!("+++ SVCall +++");
+}
+
+#[exception]
+fn PendSV() {
+ let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) };
+ red_led.set_high().ok();
+
+ debug!("+++ PendSV +++");
+}
+
+#[exception]
+fn SysTick() {
+ let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) };
+ red_led.set_high().ok();
+
+ debug!("+++ SysTick +++");
+}
+
+#[interrupt]
+fn RTC() {
+ HANDLERS.call(0);
+}
+
+#[interrupt]
+fn USB() {
+ HANDLERS.call(1);
+}
diff --git a/examples/simple/rtc.rs b/examples/simple/rtc.rs
new file mode 100644
index 0000000..79e450a
--- /dev/null
+++ b/examples/simple/rtc.rs
@@ -0,0 +1,74 @@
+use core::sync::atomic::{AtomicUsize, Ordering};
+use log;
+use trinket_m0::{clock::GenericClockController, RTC};
+
+struct Clock(AtomicUsize);
+impl Clock {
+ const fn new() -> Self {
+ Self(AtomicUsize::new(0))
+ }
+
+ fn set(&self, millis: usize) {
+ self.0.store(millis, Ordering::SeqCst)
+ }
+
+ // Slightly less than 1ms, due to using a 32,768Hz clock, we can't
+ // hit exactly 1ms, so we shoot for a bit under.
+ fn millis(&self) -> usize {
+ self.0.load(Ordering::SeqCst)
+ }
+}
+
+static CLOCK: Clock = Clock::new();
+
+// Set to run every ~500µs.
+static COUNTER: u32 = 16; // 32 ticks requires 1024 cycles at 32,768Hz for 1 second.
+
+pub fn setup(mut rtc: RTC, clocks: &mut GenericClockController) -> impl FnMut() {
+ let rtc_clock = &clocks.gclk1();
+ clocks.rtc(&rtc_clock);
+
+ rtc.mode0().ctrl.write(|w| w.swrst().set_bit());
+ while rtc.mode0().status.read().syncbusy().bit_is_set() {}
+
+ rtc.mode0().ctrl.write(|w| {
+ w.mode().count32();
+
+ // Neither the prescaler nor matchlr values seem to work. Not
+ // sure why.
+ //w.prescaler().div1024();
+ w.matchclr().set_bit() // Reset on match for periodic
+ });
+
+ rtc.mode0().comp[0].write(|w| unsafe { w.bits(COUNTER) });
+ rtc.mode0().intflag.write(|w| w.cmp0().set_bit());
+ rtc.mode0().intenset.write(|w| w.cmp0().set_bit());
+
+ // Enable the RTC and wait for sync.
+ rtc.mode0().ctrl.write(|w| w.enable().set_bit());
+ while rtc.mode0().status.read().syncbusy().bit_is_set() {}
+
+ move || handler(&mut rtc)
+}
+
+pub fn millis() -> usize {
+ CLOCK.millis()
+}
+
+fn handler(rtc: &mut RTC) {
+ // FIXME: matchclr doesn't seem to work to reset the counter?
+ rtc.mode0().count.write(|w| unsafe { w.bits(0) });
+ rtc.mode0().intflag.write(|w| w.cmp0().set_bit());
+
+ static mut TICKS: usize = 0;
+ static mut ADD: bool = false;
+ unsafe {
+ if ADD {
+ TICKS += 1;
+ CLOCK.set(TICKS);
+ }
+ ADD = !ADD;
+
+ log::logger().flush();
+ }
+}
diff --git a/find-serial-port b/find-serial-port
new file mode 100755
index 0000000..62e2c0c
--- /dev/null
+++ b/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/src/lib.rs b/src/lib.rs
new file mode 100755
index 0000000..85b3b8f
--- /dev/null
+++ b/src/lib.rs
@@ -0,0 +1,645 @@
+#![no_std]
+mod pipe;
+
+use pipe::{PipeErr, PipeTable};
+
+use usb_host::{
+ DescriptorType, DeviceDescriptor, Direction, Driver, DriverError, Endpoint, RequestCode,
+ RequestDirection, RequestKind, RequestRecipient, RequestType, TransferError, TransferType,
+ USBHost, WValue,
+};
+
+use atsamd_hal::{
+ calibration::{usb_transn_cal, usb_transp_cal, usb_trim_cal},
+ clock::{ClockGenId, ClockSource, GenericClockController},
+ gpio::{self, Floating, Input, OpenDrain, Output},
+ target_device::{PM, USB},
+};
+use embedded_hal::digital::v2::OutputPin;
+use log::{debug, error, trace, warn};
+use starb::{Reader, RingBuffer, Writer};
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Event {
+ Error,
+ Detached,
+ Attached,
+}
+type Events = RingBuffer<Event>;
+type EventReader = Reader<'static, Event>;
+type EventWriter = Writer<'static, Event>;
+
+const NAK_LIMIT: usize = 15;
+
+// Must be at least 100ms. cf §9.1.2 of USB 2.0.
+const SETTLE_DELAY: usize = 205; // Delay in sec/1024
+
+// Ring buffer for sharing events from interrupt context.
+static mut EVENTS: Events = Events::new(Event::Error);
+// FIXME: this is just for testing. The enum needs to be
+// thread-safe if this is the way we're going.
+static mut LATEST_EVENT: Event = Event::Detached;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum DetachedState {
+ Initialize,
+ WaitForDevice,
+ Illegal,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum AttachedState {
+ WaitForSettle(usize),
+ WaitResetComplete,
+ WaitSOF(usize),
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum SteadyState {
+ Configuring,
+ Running,
+ Error,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum TaskState {
+ Detached(DetachedState),
+ Attached(AttachedState),
+ Steady(SteadyState),
+}
+
+use core::mem::{self, MaybeUninit};
+use core::ptr;
+
+const MAX_DEVICES: usize = 4;
+struct DeviceTable {
+ tbl: [Option<Device>; MAX_DEVICES],
+}
+impl DeviceTable {
+ fn new() -> Self {
+ let tbl = {
+ let mut devs: [MaybeUninit<Option<Device>>; MAX_DEVICES] =
+ unsafe { MaybeUninit::uninit().assume_init() };
+ for d in &mut devs[..] {
+ unsafe { ptr::write(d.as_mut_ptr(), None) }
+ }
+ unsafe { mem::transmute(devs) }
+ };
+
+ Self { tbl: tbl }
+ }
+
+ /// Allocate a device with the next available address.
+ // TODO: get rid of the millis argument somehow, but the device
+ // does need a way of tracking time for Settle reasons.
+ fn next(&mut self) -> Option<&mut Device> {
+ for i in 1..self.tbl.len() {
+ if self.tbl[i].is_none() {
+ let d = Device { addr: i as u8 };
+ self.tbl[i] = Some(d);
+ return self.tbl[i].as_mut();
+ }
+ }
+ None
+ }
+
+ /// Remove the device at address `addr`.
+ fn remove(&mut self, addr: u8) -> Option<Device> {
+ let v = core::mem::replace(&mut self.tbl[addr as usize], None);
+ v
+ }
+}
+
+struct Device {
+ addr: u8,
+}
+
+pub struct SAMDHost<'a, F> {
+ usb: USB,
+
+ events: EventReader,
+ task_state: TaskState,
+
+ // Need chunk of RAM for USB pipes, which gets used with DESCADD
+ // register.
+ pipe_table: PipeTable,
+
+ devices: DeviceTable,
+
+ // need sof 1kHz pad?
+ _sof_pad: gpio::Pa23<gpio::PfG>,
+ _dm_pad: gpio::Pa24<gpio::PfG>,
+ _dp_pad: gpio::Pa25<gpio::PfG>,
+ host_enable_pin: Option<gpio::Pa28<Output<OpenDrain>>>,
+
+ // To get current milliseconds.
+ millis: &'a F,
+}
+
+impl<'a, F> SAMDHost<'a, F>
+where
+ F: Fn() -> usize,
+{
+ pub fn new(
+ usb: USB,
+ sof_pin: gpio::Pa23<Input<Floating>>,
+ dm_pin: gpio::Pa24<Input<Floating>>,
+ dp_pin: gpio::Pa25<Input<Floating>>,
+ host_enable_pin: Option<gpio::Pa28<Input<Floating>>>,
+ port: &mut gpio::Port,
+ clocks: &mut GenericClockController,
+ pm: &mut PM,
+ millis: &'a F,
+ ) -> (Self, impl FnMut()) {
+ let (eventr, mut eventw) = unsafe { EVENTS.split() };
+
+ let mut rc = Self {
+ usb: usb,
+
+ events: eventr,
+ task_state: TaskState::Detached(DetachedState::Initialize),
+
+ pipe_table: PipeTable::new(),
+
+ devices: DeviceTable::new(),
+
+ _sof_pad: sof_pin.into_function_g(port),
+ _dm_pad: dm_pin.into_function_g(port),
+ _dp_pad: dp_pin.into_function_g(port),
+ host_enable_pin: None,
+
+ millis: millis,
+ };
+
+ if let Some(he_pin) = host_enable_pin {
+ rc.host_enable_pin = Some(he_pin.into_open_drain_output(port));
+ }
+
+ pm.apbbmask.modify(|_, w| w.usb_().set_bit());
+
+ // Set up USB clock from 48MHz source on generic clock 6.
+ clocks.configure_gclk_divider_and_source(ClockGenId::GCLK6, 1, ClockSource::DFLL48M, false);
+ let gclk6 = clocks
+ .get_gclk(ClockGenId::GCLK6)
+ .expect("Could not get clock 6");
+ clocks.usb(&gclk6);
+
+ let usbp = &rc.usb as *const _ as usize;
+ (rc, move || handler(usbp, &mut eventw))
+ }
+
+ pub fn reset_periph(&mut self) {
+ debug!("resetting usb");
+ // Reset the USB peripheral and wait for sync.
+ self.usb.host().ctrla.write(|w| w.swrst().set_bit());
+ while self.usb.host().syncbusy.read().swrst().bit_is_set() {}
+
+ // Specify host mode.
+ self.usb.host().ctrla.modify(|_, w| w.mode().host());
+
+ // Unsafe due to use of raw bits method.
+ unsafe {
+ self.usb.host().padcal.write(|w| {
+ w.transn().bits(usb_transn_cal());
+ w.transp().bits(usb_transp_cal());
+ w.trim().bits(usb_trim_cal())
+ });
+ }
+
+ // Use normal, which is 0 and apparently means low-and-full capable
+ self.usb.host().ctrlb.modify(|_, w| w.spdconf().normal());
+ // According to docs, 1,2,3 are reserved, but .fs returns 3
+ //self.usb.host().ctrlb.modify(|_, w| w.spdconf().fs());
+
+ self.usb.host().ctrla.modify(|_, w| w.runstdby().set_bit()); // keep usb clock running in standby.
+
+ // Set address of USB SRAM.
+ // Unsafe due to use of raw bits method.
+ unsafe {
+ self.usb
+ .host()
+ .descadd
+ .write(|w| w.bits(&self.pipe_table as *const _ as u32));
+ }
+
+ if let Some(he_pin) = &mut self.host_enable_pin {
+ he_pin.set_high().expect("turning on usb host enable pin");
+ }
+
+ self.usb.host().intenset.write(|w| {
+ w.wakeup().set_bit();
+ w.dconn().set_bit();
+ w.ddisc().set_bit()
+ });
+
+ self.usb.host().ctrla.modify(|_, w| w.enable().set_bit());
+ while self.usb.host().syncbusy.read().enable().bit_is_set() {}
+
+ // Set VBUS OK to allow host operation.
+ self.usb.host().ctrlb.modify(|_, w| w.vbusok().set_bit());
+ debug!("...done");
+ }
+
+ pub fn task(&mut self, drivers: &mut [&mut dyn Driver]) {
+ static mut LAST_EVENT: Event = Event::Error;
+ unsafe {
+ if LAST_EVENT != LATEST_EVENT {
+ trace!("new event: {:?}", LATEST_EVENT);
+ }
+ }
+
+ static mut LAST_TASK_STATE: TaskState = TaskState::Detached(DetachedState::Illegal);
+ self.task_state = match unsafe { LATEST_EVENT } {
+ Event::Error => TaskState::Detached(DetachedState::Illegal),
+ Event::Detached => {
+ if let TaskState::Detached(_) = self.task_state {
+ self.task_state
+ } else {
+ TaskState::Detached(DetachedState::Initialize)
+ }
+ }
+ Event::Attached => {
+ if let TaskState::Detached(_) = self.task_state {
+ TaskState::Attached(AttachedState::WaitForSettle(
+ (self.millis)() + SETTLE_DELAY,
+ ))
+ } else {
+ self.task_state
+ }
+ }
+ };
+
+ static mut LAST_CBITS: u16 = 0;
+ static mut LAST_FLAGS: u16 = 0;
+ let cbits = self.usb.host().ctrlb.read().bits();
+ let bits = self.usb.host().intflag.read().bits();
+ unsafe {
+ if LAST_CBITS != cbits || LAST_FLAGS != bits || LAST_TASK_STATE != self.task_state {
+ trace!(
+ "cb: {:x}, f: {:x} changing state {:?} -> {:?}",
+ cbits,
+ bits,
+ LAST_TASK_STATE,
+ self.task_state,
+ );
+ }
+ LAST_CBITS = cbits;
+ LAST_FLAGS = bits;
+ LAST_TASK_STATE = self.task_state
+ };
+
+ if let Some(_event) = self.events.shift() {
+ // trace!("Found event: {:?}", event);
+ // self.task_state = match event {
+ // Event::None => TaskState::Detached(DetachedState::Illegal),
+ // Event::Detached => {
+ // if let TaskState::Detached(_) = self.task_state {
+ // self.task_state
+ // } else {
+ // TaskState::Detached(DetachedState::Initialize)
+ // }
+ // }
+ // Event::Attached => {
+ // if let TaskState::Detached(_) = self.task_state {
+ // self.delay = self.millis() + SETTLE_DELAY;
+ // TaskState::Attached(AttachedState::WaitForSettle)
+ // } else {
+ // self.task_state
+ // }
+ // }
+ // };
+ }
+
+ self.fsm(drivers);
+
+ unsafe {
+ LAST_EVENT = LATEST_EVENT;
+ }
+ }
+ fn fsm(&mut self, drivers: &mut [&mut dyn Driver]) {
+ // respond to events from interrupt.
+ match self.task_state {
+ TaskState::Detached(s) => self.detached_fsm(s),
+ TaskState::Attached(s) => self.attached_fsm(s),
+ TaskState::Steady(s) => self.steady_fsm(s, drivers),
+ };
+ }
+
+ fn detached_fsm(&mut self, s: DetachedState) {
+ match s {
+ DetachedState::Initialize => {
+ self.reset_periph();
+ // TODO: Free resources.
+
+ self.task_state = TaskState::Detached(DetachedState::WaitForDevice);
+ }
+
+ // Do nothing state. Just wait for an interrupt to come in
+ // saying we have a device attached.
+ DetachedState::WaitForDevice => {}
+
+ // TODO: should probably reset everything if we end up here somehow.
+ DetachedState::Illegal => {}
+ }
+ }
+
+ fn attached_fsm(&mut self, s: AttachedState) {
+ match s {
+ AttachedState::WaitForSettle(until) => {
+ if (self.millis)() >= until {
+ self.usb.host().ctrlb.modify(|_, w| w.busreset().set_bit());
+ self.task_state = TaskState::Attached(AttachedState::WaitResetComplete);
+ }
+ }
+
+ AttachedState::WaitResetComplete => {
+ if self.usb.host().intflag.read().rst().bit_is_set() {
+ trace!("reset was sent");
+ self.usb.host().intflag.write(|w| w.rst().set_bit());
+
+ // Seems unneccesary, since SOFE will be set
+ // immediately after reset according to §32.6.3.3.
+ self.usb.host().ctrlb.modify(|_, w| w.sofe().set_bit());
+ // USB spec requires 20ms of SOF after bus reset.
+ self.task_state =
+ TaskState::Attached(AttachedState::WaitSOF((self.millis)() + 20));
+ }
+ }
+
+ AttachedState::WaitSOF(until) => {
+ if self.usb.host().intflag.read().hsof().bit_is_set() {
+ self.usb.host().intflag.write(|w| w.hsof().set_bit());
+ if (self.millis)() >= until {
+ self.task_state = TaskState::Steady(SteadyState::Configuring);
+ }
+ }
+ }
+ }
+ }
+
+ fn steady_fsm(&mut self, s: SteadyState, drivers: &mut [&mut dyn Driver]) {
+ match s {
+ SteadyState::Configuring => {
+ self.task_state = match self.configure_dev(drivers) {
+ Ok(_) => TaskState::Steady(SteadyState::Running),
+ Err(e) => {
+ warn!("Enumeration error: {:?}", e);
+ TaskState::Steady(SteadyState::Error)
+ }
+ }
+ }
+
+ SteadyState::Running => {
+ for d in &mut drivers[..] {
+ if let Err(e) = d.tick((self.millis)(), self) {
+ warn!("running driver {:?}: {:?}", d, e);
+ if let DriverError::Permanent(a, _) = e {
+ self.devices.remove(a);
+ }
+ }
+ }
+ }
+
+ SteadyState::Error => {}
+ }
+ }
+
+ fn configure_dev(&mut self, drivers: &mut [&mut dyn Driver]) -> Result<(), TransferError> {
+ let none: Option<&mut [u8]> = None;
+ let mut a0ep0 = Addr0EP0 {
+ in_toggle: true,
+ out_toggle: true,
+ };
+ let mut dev_desc: DeviceDescriptor =
+ unsafe { MaybeUninit::<DeviceDescriptor>::uninit().assume_init() };
+ self.control_transfer(
+ &mut a0ep0,
+ RequestType::from((
+ RequestDirection::DeviceToHost,
+ RequestKind::Standard,
+ RequestRecipient::Device,
+ )),
+ RequestCode::GetDescriptor,
+ WValue::from((0, DescriptorType::Device as u8)),
+ 0,
+ Some(unsafe { to_slice_mut(&mut dev_desc) }),
+ )?;
+
+ trace!(" -- dev_desc: {:?}", dev_desc);
+
+ // TODO: new error for being out of devices.
+ let addr = self
+ .devices
+ .next()
+ .ok_or(TransferError::Permanent("out of devices"))?
+ .addr;
+ debug!("Setting address to {}.", addr);
+ self.control_transfer(
+ &mut a0ep0,
+ RequestType::from((
+ RequestDirection::HostToDevice,
+ RequestKind::Standard,
+ RequestRecipient::Device,
+ )),
+ RequestCode::SetAddress,
+ WValue::from((addr, 0)),
+ 0,
+ none,
+ )?;
+
+ // Now that the device is addressed, see if any drivers want
+ // it.
+ for d in &mut drivers[..] {
+ if d.want_device(&dev_desc) {
+ let res = d.add_device(dev_desc, addr);
+ match res {
+ Ok(_) => return Ok(()),
+ Err(_) => return Err(TransferError::Permanent("out of addresses")),
+ }
+ }
+ }
+ Ok(())
+ }
+}
+
+struct Addr0EP0 {
+ in_toggle: bool,
+ out_toggle: bool,
+}
+impl Endpoint for Addr0EP0 {
+ fn address(&self) -> u8 {
+ 0
+ }
+
+ fn endpoint_num(&self) -> u8 {
+ 0
+ }
+
+ fn transfer_type(&self) -> TransferType {
+ TransferType::Control
+ }
+
+ fn direction(&self) -> Direction {
+ Direction::In
+ }
+
+ fn max_packet_size(&self) -> u16 {
+ 8
+ }
+
+ fn in_toggle(&self) -> bool {
+ self.in_toggle
+ }
+
+ fn set_in_toggle(&mut self, toggle: bool) {
+ self.in_toggle = toggle;
+ }
+
+ fn out_toggle(&self) -> bool {
+ self.out_toggle
+ }
+
+ fn set_out_toggle(&mut self, toggle: bool) {
+ self.out_toggle = toggle;
+ }
+}
+
+pub fn handler(usbp: usize, events: &mut EventWriter) {
+ let usb: &mut USB = unsafe { core::mem::transmute(usbp) };
+ let flags = usb.host().intflag.read();
+
+ trace!("USB - {:x}", flags.bits());
+
+ let mut unshift_event = |e: Event| {
+ unsafe { LATEST_EVENT = e };
+ if let Err(_) = events.unshift(e) {
+ error!("Couldn't write USB event to queue.");
+ }
+ };
+
+ if flags.hsof().bit_is_set() {
+ trace!(" +hsof");
+ usb.host().intflag.write(|w| w.hsof().set_bit());
+ unshift_event(Event::Attached);
+ }
+
+ if flags.rst().bit_is_set() {
+ // We seem to get this whenever a device attaches/detaches.
+ trace!(" +rst");
+ usb.host().intflag.write(|w| w.rst().set_bit());
+ unshift_event(Event::Detached);
+ }
+
+ if flags.uprsm().bit_is_set() {
+ trace!(" +uprsm");
+ usb.host().intflag.write(|w| w.uprsm().set_bit());
+ unshift_event(Event::Detached);
+ }
+
+ if flags.dnrsm().bit_is_set() {
+ trace!(" +dnrsm");
+ usb.host().intflag.write(|w| w.dnrsm().set_bit());
+ unshift_event(Event::Detached);
+ }
+
+ if flags.wakeup().bit_is_set() {
+ // §32.8.5.8 - since VBUSOK is set, then this happens when a
+ // device is connected.
+ trace!(" +wakeup");
+ usb.host().intflag.write(|w| w.wakeup().set_bit());
+ unshift_event(Event::Attached);
+ }
+
+ if flags.ramacer().bit_is_set() {
+ trace!(" +ramacer");
+ usb.host().intflag.write(|w| w.ramacer().set_bit());
+ unshift_event(Event::Detached);
+ }
+
+ if flags.dconn().bit_is_set() {
+ trace!(" +dconn");
+ usb.host().intflag.write(|w| w.dconn().set_bit());
+ usb.host().intenclr.write(|w| w.dconn().set_bit());
+ usb.host().intflag.write(|w| w.ddisc().set_bit());
+ usb.host().intenset.write(|w| w.ddisc().set_bit());
+ usb.host().intflag.write(|w| w.dconn().set_bit());
+ unshift_event(Event::Attached);
+ }
+
+ if flags.ddisc().bit_is_set() {
+ trace!(" +ddisc");
+ usb.host().intflag.write(|w| w.ddisc().set_bit());
+ usb.host().intenclr.write(|w| w.ddisc().set_bit());
+ usb.host().intflag.write(|w| w.dconn().set_bit());
+ usb.host().intenset.write(|w| w.dconn().set_bit());
+ usb.host().intflag.write(|w| w.ddisc().set_bit());
+ unshift_event(Event::Detached);
+ }
+}
+
+impl From<PipeErr> for TransferError {
+ fn from(v: PipeErr) -> Self {
+ match v {
+ PipeErr::TransferFail => Self::Retry("transfer failed"),
+ PipeErr::Flow => Self::Retry("data flow"),
+ PipeErr::DataToggle => Self::Retry("toggle sequence"),
+ PipeErr::ShortPacket => Self::Permanent("short packet"),
+ PipeErr::InvalidPipe => Self::Permanent("invalid pipe"),
+ PipeErr::InvalidToken => Self::Permanent("invalid token"),
+ PipeErr::Stall => Self::Permanent("stall"),
+ PipeErr::PipeErr => Self::Permanent("pipe error"),
+ PipeErr::HWTimeout => Self::Permanent("hardware timeout"),
+ PipeErr::SWTimeout => Self::Permanent("software timeout"),
+ PipeErr::Other(s) => Self::Permanent(s),
+ }
+ }
+}
+
+impl<F> USBHost for SAMDHost<'_, F>
+where
+ F: Fn() -> usize,
+{
+ fn control_transfer(
+ &mut self,
+ ep: &mut dyn Endpoint,
+ bm_request_type: RequestType,
+ b_request: RequestCode,
+ w_value: WValue,
+ w_index: u16,
+ buf: Option<&mut [u8]>,
+ ) -> Result<usize, TransferError> {
+ let mut pipe = self.pipe_table.pipe_for(self.usb.host_mut(), ep);
+ let len = pipe.control_transfer(
+ ep,
+ bm_request_type,
+ b_request,
+ w_value,
+ w_index,
+ buf,
+ self.millis,
+ )?;
+ Ok(len)
+ }
+
+ fn in_transfer(
+ &mut self,
+ ep: &mut dyn Endpoint,
+ buf: &mut [u8],
+ ) -> Result<usize, TransferError> {
+ let mut pipe = self.pipe_table.pipe_for(self.usb.host_mut(), ep);
+ let len = pipe.in_transfer(ep, buf, NAK_LIMIT, self.millis)?;
+ Ok(len)
+ }
+
+ fn out_transfer(&mut self, ep: &mut dyn Endpoint, buf: &[u8]) -> Result<usize, TransferError> {
+ let mut pipe = self.pipe_table.pipe_for(self.usb.host_mut(), ep);
+ let len = pipe.out_transfer(ep, buf, NAK_LIMIT, self.millis)?;
+ Ok(len)
+ }
+}
+
+unsafe fn to_slice_mut<T>(v: &mut T) -> &mut [u8] {
+ let ptr = v as *mut T as *mut u8;
+ let len = mem::size_of::<T>();
+ core::slice::from_raw_parts_mut(ptr, len)
+}
diff --git a/src/pipe.rs b/src/pipe.rs
new file mode 100644
index 0000000..0da0e7f
--- /dev/null
+++ b/src/pipe.rs
@@ -0,0 +1,809 @@
+#[allow(unused)]
+pub mod addr;
+#[allow(unused)]
+pub mod ctrl_pipe;
+#[allow(unused)]
+pub mod ext_reg;
+#[allow(unused)]
+pub mod pck_size;
+#[allow(unused)]
+pub mod status_bk;
+#[allow(unused)]
+pub mod status_pipe;
+
+use addr::Addr;
+use ctrl_pipe::CtrlPipe;
+use ext_reg::ExtReg;
+use pck_size::PckSize;
+use status_bk::StatusBk;
+use status_pipe::StatusPipe;
+
+use usb_host::{
+ Endpoint, RequestCode, RequestDirection, RequestType, SetupPacket, TransferType, WValue,
+};
+
+use atsamd_hal::target_device::usb::{
+ self,
+ host::{BINTERVAL, PCFG, PINTFLAG, PSTATUS, PSTATUSCLR, PSTATUSSET},
+};
+use core::convert::TryInto;
+use log::trace;
+
+// Maximum time to wait for a control request with data to finish. cf
+// §9.2.6.1 of USB 2.0.
+const USB_TIMEOUT: usize = 5 * 1024; // 5 Seconds
+
+// samd21 only supports 8 pipes.
+const MAX_PIPES: usize = 8;
+
+// How many times to retry a transaction that has transient errors.
+const NAK_LIMIT: usize = 15;
+
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub(crate) enum PipeErr {
+ ShortPacket,
+ InvalidPipe,
+ InvalidToken,
+ Stall,
+ TransferFail,
+ PipeErr,
+ Flow,
+ HWTimeout,
+ DataToggle,
+ SWTimeout,
+ Other(&'static str),
+}
+impl From<&'static str> for PipeErr {
+ fn from(v: &'static str) -> Self {
+ Self::Other(v)
+ }
+}
+
+pub(crate) struct PipeTable {
+ tbl: [PipeDesc; MAX_PIPES],
+}
+
+impl PipeTable {
+ pub(crate) fn new() -> Self {
+ let tbl = {
+ let mut tbl: [core::mem::MaybeUninit<PipeDesc>; MAX_PIPES] =
+ unsafe { core::mem::MaybeUninit::uninit().assume_init() };
+
+ for e in &mut tbl[..] {
+ unsafe { core::ptr::write(e.as_mut_ptr(), PipeDesc::new()) }
+ }
+
+ unsafe { core::mem::transmute(tbl) }
+ };
+ Self { tbl: tbl }
+ }
+
+ pub(crate) fn pipe_for<'a, 'b>(
+ &'a mut self,
+ host: &'b mut usb::HOST,
+ endpoint: &dyn Endpoint,
+ ) -> Pipe<'a, 'b> {
+ // Just use two pipes for now. 0 is always for control
+ // endpoints, 1 for everything else.
+ //
+ // TODO: cache in-use pipes and return them without init if
+ // possible.
+ let i = if endpoint.endpoint_num() == 0 { 0 } else { 1 };
+
+ let pregs = PipeRegs::from(host, i);
+ let pdesc = &mut self.tbl[i];
+
+ pregs.cfg.write(|w| {
+ let ptype = PType::from(endpoint.transfer_type()) as u8;
+ unsafe { w.ptype().bits(ptype) }
+ });
+ trace!(
+ "setting paddr of pipe {} to {}:{}",
+ i,
+ endpoint.address(),
+ endpoint.endpoint_num()
+ );
+ pdesc.bank0.ctrl_pipe.write(|w| {
+ w.pdaddr().set_addr(endpoint.address());
+ w.pepnum().set_epnum(endpoint.endpoint_num())
+ });
+ Pipe {
+ num: i,
+ regs: pregs,
+ desc: pdesc,
+ }
+ }
+}
+
+// TODO: hide regs/desc fields. Needed right now for init_pipe0.
+pub(crate) struct Pipe<'a, 'b> {
+ num: usize,
+
+ pub(crate) regs: PipeRegs<'b>,
+ pub(crate) desc: &'a mut PipeDesc,
+}
+impl Pipe<'_, '_> {
+ pub(crate) fn control_transfer(
+ &mut self,
+ ep: &mut dyn Endpoint,
+ bm_request_type: RequestType,
+ b_request: RequestCode,
+ w_value: WValue,
+ w_index: u16,
+ buf: Option<&mut [u8]>,
+ millis: &dyn Fn() -> usize,
+ ) -> Result<usize, PipeErr> {
+ /*
+ * Setup stage.
+ */
+ let buflen = buf.as_ref().map_or(0, |b| b.len() as u16);
+ let mut setup_packet = SetupPacket {
+ bm_request_type: bm_request_type,
+ b_request: b_request,
+ w_value: w_value,
+ w_index: w_index,
+ w_length: buflen,
+ };
+ self.send(
+ ep,
+ PToken::Setup,
+ &DataBuf::from(&mut setup_packet),
+ NAK_LIMIT,
+ millis,
+ )?;
+
+ /*
+ * Data stage.
+ */
+ let mut transfer_len = 0;
+ if let Some(b) = buf {
+ // TODO: data stage, has up to 5,000ms (in 500ms
+ // per-packet chunks) to complete. cf §9.2.6.4 of USB 2.0.
+ match bm_request_type.direction()? {
+ RequestDirection::DeviceToHost => {
+ transfer_len = self.in_transfer(ep, b, NAK_LIMIT, millis)?;
+ }
+
+ RequestDirection::HostToDevice => {
+ transfer_len = self.out_transfer(ep, b, NAK_LIMIT, millis)?;
+ }
+ }
+ }
+
+ /*
+ * Status stage.
+ */
+ // TODO: status stage has up to 50ms to complete. cf §9.2.6.4
+ // of USB 2.0.
+ self.desc.bank0.pcksize.write(|w| {
+ unsafe { w.byte_count().bits(0) };
+ unsafe { w.multi_packet_size().bits(0) }
+ });
+
+ let token = match bm_request_type.direction()? {
+ RequestDirection::DeviceToHost => PToken::Out,
+ RequestDirection::HostToDevice => PToken::In,
+ };
+
+ trace!("dispatching status stage");
+ self.dispatch_retries(ep, token, NAK_LIMIT, millis)?;
+
+ Ok(transfer_len)
+ }
+
+ fn send(
+ &mut self,
+ ep: &mut dyn Endpoint,
+ token: PToken,
+ buf: &DataBuf,
+ nak_limit: usize,
+ millis: &dyn Fn() -> usize,
+ ) -> Result<(), PipeErr> {
+ trace!("p{}: sending {:?}", self.num, buf);
+
+ self.desc
+ .bank0
+ .addr
+ .write(|w| unsafe { w.addr().bits(buf.ptr as u32) });
+ // configure packet size PCKSIZE.SIZE
+ self.desc.bank0.pcksize.write(|w| {
+ unsafe { w.byte_count().bits(buf.len as u16) };
+ unsafe { w.multi_packet_size().bits(0) }
+ });
+
+ self.dispatch_retries(ep, token, nak_limit, millis)
+ }
+
+ pub(crate) fn in_transfer(
+ &mut self,
+ ep: &mut dyn Endpoint,
+ buf: &mut [u8],
+ nak_limit: usize,
+ millis: &dyn Fn() -> usize,
+ ) -> Result<usize, PipeErr> {
+ // TODO: pull this from pipe descriptor for this addr/ep.
+ let packet_size = 8;
+
+ trace!("p{}: Should IN for {}b.", self.num, buf.len());
+ self.desc.bank0.pcksize.write(|w| {
+ unsafe { w.byte_count().bits(buf.len() as u16) };
+ unsafe { w.multi_packet_size().bits(0) }
+ });
+
+ // Read until we get a short packet (indicating that there's
+ // nothing left for us in this transaction) or the buffer is
+ // full.
+ //
+ // TODO: It is sometimes valid to get a short packet when
+ // variable length data is desired by the driver. cf §5.3.2 of
+ // USB 2.0.
+ let mut bytes_received = 0;
+ while bytes_received < buf.len() {
+ // Move the buffer pointer forward as we get data.
+ self.desc.bank0.addr.write(|w| unsafe {
+ w.addr()
+ .bits(buf.as_mut_ptr() as u32 + bytes_received as u32)
+ });
+ self.regs.statusclr.write(|w| w.bk0rdy().set_bit());
+ trace!("--- !!! regs-pre-dispatch !!! ---");
+ self.log_regs();
+
+ self.dispatch_retries(ep, PToken::In, nak_limit, millis)?;
+ let recvd = self.desc.bank0.pcksize.read().byte_count().bits() as usize;
+ bytes_received += recvd;
+ trace!("!! read {} of {}", bytes_received, buf.len());
+ if recvd < packet_size {
+ break;
+ }
+
+ // Don't allow writing past the buffer.
+ assert!(bytes_received <= buf.len());
+ }
+
+ self.regs.statusset.write(|w| w.pfreeze().set_bit());
+ if bytes_received < buf.len() {
+ self.log_regs();
+ // TODO: honestly, this is probably a panic condition,
+ // since whatever's in DataBuf.ptr is totally
+ // invalid. Alternately, this function should be declared
+ // `unsafe`. OR! Make the function take a mutable slice of
+ // u8, and leave it up to the caller to figure out how to
+ // deal with short packets.
+ Err(PipeErr::ShortPacket)
+ } else {
+ Ok(bytes_received)
+ }
+ }
+
+ pub(crate) fn out_transfer(
+ &mut self,
+ ep: &mut dyn Endpoint,
+ buf: &[u8],
+ nak_limit: usize,
+ millis: &dyn Fn() -> usize,
+ ) -> Result<usize, PipeErr> {
+ trace!("p{}: Should OUT for {}b.", self.num, buf.len());
+ self.desc.bank0.pcksize.write(|w| {
+ unsafe { w.byte_count().bits(buf.len() as u16) };
+ unsafe { w.multi_packet_size().bits(0) }
+ });
+
+ let mut bytes_sent = 0;
+ while bytes_sent < buf.len() {
+ self.desc
+ .bank0
+ .addr
+ .write(|w| unsafe { w.addr().bits(buf.as_ptr() as u32 + bytes_sent as u32) });
+ self.dispatch_retries(ep, PToken::Out, nak_limit, millis)?;
+
+ let sent = self.desc.bank0.pcksize.read().byte_count().bits() as usize;
+ bytes_sent += sent;
+ trace!("!! wrote {} of {}", bytes_sent, buf.len());
+ }
+
+ Ok(bytes_sent)
+ }
+
+ fn dtgl(&mut self, ep: &mut dyn Endpoint, token: PToken) {
+ // TODO: this makes no sense to me, and docs are unclear. If
+ // the status bit is set, set it again? if it's clear then
+ // clear it? This is what I get for having to work from
+ // Arduino sources.
+ trace!(
+ "~~~ tok: {:?}, dtgl: {}, i: {}, o: {}",
+ token,
+ self.regs.status.read().dtgl().bit(),
+ ep.in_toggle(),
+ ep.out_toggle(),
+ );
+
+ let toggle = match token {
+ PToken::In => {
+ let t = !ep.in_toggle();
+ ep.set_in_toggle(t);
+ t
+ }
+
+ PToken::Out => {
+ let t = !ep.out_toggle();
+ ep.set_out_toggle(t);
+ t
+ }
+
+ _ => !self.regs.status.read().dtgl().bit_is_set(),
+ };
+
+ if toggle {
+ self.dtgl_set();
+ } else {
+ self.dtgl_clear();
+ }
+ }
+
+ fn dtgl_set(&mut self) {
+ self.regs.statusset.write(|w| w.dtgl().set_bit());
+ }
+
+ fn dtgl_clear(&mut self) {
+ self.regs.statusclr.write(|w| unsafe {
+ // FIXME: need to patch the SVD for
+ // PSTATUSCLR.DTGL at bit0. No? This is in the SVD, but
+ // not the rust output.
+ w.bits(1)
+ });
+ }
+
+ // This is the only function that calls `millis`. If we can make
+ // this just take the current timestamp, we can make this
+ // non-blocking.
+ fn dispatch_retries(
+ &mut self,
+ ep: &mut dyn Endpoint,
+ token: PToken,
+ retries: usize,
+ millis: &dyn Fn() -> usize,
+ ) -> Result<(), PipeErr> {
+ self.dispatch_packet(ep, token);
+
+ let until = millis() + USB_TIMEOUT;
+ let mut last_err = PipeErr::SWTimeout;
+ let mut naks = 0;
+ while millis() < until {
+ let res = self.dispatch_result(token);
+ match res {
+ Ok(true) => {
+ if token == PToken::In {
+ ep.set_in_toggle(self.regs.status.read().dtgl().bit_is_set());
+ } else if token == PToken::Out {
+ ep.set_out_toggle(self.regs.status.read().dtgl().bit_is_set());
+ }
+ return Ok(());
+ }
+ Ok(false) => continue,
+
+ Err(e) => {
+ last_err = e;
+ match last_err {
+ PipeErr::DataToggle => self.dtgl(ep, token),
+
+ // Flow error on interrupt pipes means we got
+ // a NAK, which in this context means there's
+ // no data. cf §32.8.7.5 of SAM D21 data
+ // sheet.
+ PipeErr::Flow if ep.transfer_type() == TransferType::Interrupt => break,
+
+ PipeErr::Stall => break,
+ _ => {
+ naks += 1;
+ if naks > retries {
+ break;
+ } else {
+ self.dispatch_packet(ep, token);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ Err(last_err)
+ }
+
+ fn dispatch_packet(&mut self, ep: &mut dyn Endpoint, token: PToken) {
+ self.regs
+ .cfg
+ .modify(|_, w| unsafe { w.ptoken().bits(token as u8) });
+ self.regs.intflag.modify(|_, w| w.trfail().set_bit());
+ self.regs.intflag.modify(|_, w| w.perr().set_bit());
+
+ match token {
+ PToken::Setup => {
+ self.regs.intflag.write(|w| w.txstp().set_bit());
+ self.regs.statusset.write(|w| w.bk0rdy().set_bit());
+
+ // Toggles should be 1 for host and function's
+ // sequence at end of setup transaction. cf §8.6.1 of
+ // USB 2.0.
+ self.dtgl_clear();
+ ep.set_in_toggle(true);
+ ep.set_out_toggle(true);
+ }
+ PToken::In => {
+ self.regs.statusclr.write(|w| w.bk0rdy().set_bit());
+ if ep.in_toggle() {
+ self.dtgl_set();
+ } else {
+ self.dtgl_clear();
+ }
+ }
+ PToken::Out => {
+ self.regs.intflag.write(|w| w.trcpt0().set_bit());
+ self.regs.statusset.write(|w| w.bk0rdy().set_bit());
+ if ep.out_toggle() {
+ self.dtgl_set();
+ } else {
+ self.dtgl_clear();
+ }
+ }
+ _ => {}
+ }
+
+ trace!("initial regs");
+ self.log_regs();
+
+ self.regs.statusclr.write(|w| w.pfreeze().set_bit());
+ }
+
+ fn dispatch_result(&mut self, token: PToken) -> Result<bool, PipeErr> {
+ if self.is_transfer_complete(token)? {
+ self.regs.statusset.write(|w| w.pfreeze().set_bit());
+ Ok(true)
+ } else if self.regs.intflag.read().trfail().bit_is_set() {
+ self.regs.intflag.write(|w| w.trfail().set_bit());
+ trace!("trfail");
+ self.regs.statusset.write(|w| w.pfreeze().set_bit());
+ self.log_regs();
+ Err(PipeErr::TransferFail)
+ } else if self.desc.bank0.status_bk.read().errorflow().bit_is_set() {
+ trace!("errorflow");
+ self.regs.statusset.write(|w| w.pfreeze().set_bit());
+ self.log_regs();
+ Err(PipeErr::Flow)
+ } else if self.desc.bank0.status_pipe.read().touter().bit_is_set() {
+ trace!("touter");
+ self.regs.statusset.write(|w| w.pfreeze().set_bit());
+ self.log_regs();
+ Err(PipeErr::HWTimeout)
+ } else if self.desc.bank0.status_pipe.read().dtgler().bit_is_set() {
+ trace!("dtgler");
+ self.regs.statusset.write(|w| w.pfreeze().set_bit());
+ self.log_regs();
+ Err(PipeErr::DataToggle)
+ } else {
+ // Nothing wrong, but not done yet.
+ Ok(false)
+ }
+ }
+
+ fn is_transfer_complete(&mut self, token: PToken) -> Result<bool, PipeErr> {
+ match token {
+ PToken::Setup => {
+ if self.regs.intflag.read().txstp().bit_is_set() {
+ self.regs.intflag.write(|w| w.txstp().set_bit());
+ Ok(true)
+ } else {
+ Ok(false)
+ }
+ }
+ PToken::In => {
+ if self.regs.intflag.read().trcpt0().bit_is_set() {
+ self.regs.intflag.write(|w| w.trcpt0().set_bit());
+ Ok(true)
+ } else {
+ Ok(false)
+ }
+ }
+ PToken::Out => {
+ if self.regs.intflag.read().trcpt0().bit_is_set() {
+ self.regs.intflag.write(|w| w.trcpt0().set_bit());
+ Ok(true)
+ } else {
+ Ok(false)
+ }
+ }
+ _ => Err(PipeErr::InvalidToken),
+ }
+ }
+
+ fn log_regs(&self) {
+ // Pipe regs
+ let cfg = self.regs.cfg.read().bits();
+ let bin = self.regs.binterval.read().bits();
+ let sts = self.regs.status.read().bits();
+ let ifl = self.regs.intflag.read().bits();
+ trace!(
+ "p{}: cfg: {:x}, bin: {:x}, sts: {:x}, ifl: {:x}",
+ self.num,
+ cfg,
+ bin,
+ sts,
+ ifl
+ );
+
+ // Pipe RAM regs
+ let adr = self.desc.bank0.addr.read().bits();
+ let pks = self.desc.bank0.pcksize.read().bits();
+ let ext = self.desc.bank0.extreg.read().bits();
+ let sbk = self.desc.bank0.status_bk.read().bits();
+ let hcp = self.desc.bank0.ctrl_pipe.read().bits();
+ let spi = self.desc.bank0.status_pipe.read().bits();
+ trace!(
+ "p{}: adr: {:x}, pks: {:x}, ext: {:x}, sbk: {:x}, hcp: {:x}, spi: {:x}",
+ self.num,
+ adr,
+ pks,
+ ext,
+ sbk,
+ hcp,
+ spi
+ );
+ }
+}
+
+// TODO: merge into SVD for pipe cfg register.
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub(crate) enum PToken {
+ Setup = 0x0,
+ In = 0x1,
+ Out = 0x2,
+ _Reserved = 0x3,
+}
+
+// TODO: merge into SVD for pipe cfg register.
+#[allow(unused)]
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub(crate) enum PType {
+ Disabled = 0x0,
+ Control = 0x1,
+ ISO = 0x2,
+ Bulk = 0x3,
+ Interrupt = 0x4,
+ Extended = 0x5,
+ _Reserved0 = 0x06,
+ _Reserved1 = 0x07,
+}
+impl From<TransferType> for PType {
+ fn from(v: TransferType) -> Self {
+ match v {
+ TransferType::Control => Self::Control,
+ TransferType::Isochronous => Self::ISO,
+ TransferType::Bulk => Self::Bulk,
+ TransferType::Interrupt => Self::Interrupt,
+ }
+ }
+}
+
+struct DataBuf<'a> {
+ ptr: *mut u8,
+ len: usize,
+ _marker: core::marker::PhantomData<&'a ()>,
+}
+impl DataBuf<'_> {}
+
+impl core::fmt::Debug for DataBuf<'_> {
+ fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
+ write!(f, "DataBuf {{ len: {}, ptr: [", self.len)?;
+ for i in 0..self.len {
+ write!(f, " {:x}", unsafe {
+ *self.ptr.offset(i.try_into().unwrap())
+ })?;
+ }
+ write!(f, " ] }}")
+ }
+}
+
+impl<'a, T> From<&'a mut T> for DataBuf<'a> {
+ fn from(v: &'a mut T) -> Self {
+ Self {
+ ptr: v as *mut T as *mut u8,
+ len: core::mem::size_of::<T>(),
+ _marker: core::marker::PhantomData,
+ }
+ }
+}
+
+pub(crate) struct PipeRegs<'a> {
+ pub(crate) cfg: &'a mut PCFG,
+ pub(crate) binterval: &'a mut BINTERVAL,
+ pub(crate) statusclr: &'a mut PSTATUSCLR,
+ pub(crate) statusset: &'a mut PSTATUSSET,
+ pub(crate) status: &'a mut PSTATUS,
+ pub(crate) intflag: &'a mut PINTFLAG,
+}
+impl<'a> PipeRegs<'a> {
+ pub(crate) fn from(host: &'a mut usb::HOST, i: usize) -> PipeRegs {
+ assert!(i < MAX_PIPES);
+ match i {
+ 0 => Self {
+ cfg: &mut host.pcfg0,
+ binterval: &mut host.binterval0,
+ statusclr: &mut host.pstatusclr0,
+ statusset: &mut host.pstatusset0,
+ status: &mut host.pstatus0,
+ intflag: &mut host.pintflag0,
+ },
+ 1 => Self {
+ cfg: &mut host.pcfg1,
+ binterval: &mut host.binterval1,
+ statusclr: &mut host.pstatusclr1,
+ statusset: &mut host.pstatusset1,
+ status: &mut host.pstatus1,
+ intflag: &mut host.pintflag1,
+ },
+ 2 => Self {
+ cfg: &mut host.pcfg2,
+ binterval: &mut host.binterval2,
+ statusclr: &mut host.pstatusclr2,
+ statusset: &mut host.pstatusset2,
+ status: &mut host.pstatus2,
+ intflag: &mut host.pintflag2,
+ },
+ 3 => Self {
+ cfg: &mut host.pcfg3,
+ binterval: &mut host.binterval3,
+ statusclr: &mut host.pstatusclr3,
+ statusset: &mut host.pstatusset3,
+ status: &mut host.pstatus3,
+ intflag: &mut host.pintflag3,
+ },
+ 4 => Self {
+ cfg: &mut host.pcfg4,
+ binterval: &mut host.binterval4,
+ statusclr: &mut host.pstatusclr4,
+ statusset: &mut host.pstatusset4,
+ status: &mut host.pstatus4,
+ intflag: &mut host.pintflag4,
+ },
+ 5 => Self {
+ cfg: &mut host.pcfg5,
+ binterval: &mut host.binterval5,
+ statusclr: &mut host.pstatusclr5,
+ statusset: &mut host.pstatusset5,
+ status: &mut host.pstatus5,
+ intflag: &mut host.pintflag5,
+ },
+ 6 => Self {
+ cfg: &mut host.pcfg6,
+ binterval: &mut host.binterval6,
+ statusclr: &mut host.pstatusclr6,
+ statusset: &mut host.pstatusset6,
+ status: &mut host.pstatus6,
+ intflag: &mut host.pintflag6,
+ },
+ 7 => Self {
+ cfg: &mut host.pcfg7,
+ binterval: &mut host.binterval7,
+ statusclr: &mut host.pstatusclr7,
+ statusset: &mut host.pstatusset7,
+ status: &mut host.pstatus7,
+ intflag: &mut host.pintflag7,
+ },
+ _ => unreachable!(),
+ }
+ }
+}
+
+// §32.8.7.1
+pub(crate) struct PipeDesc {
+ pub bank0: BankDesc,
+ pub bank1: BankDesc,
+}
+
+// 2 banks: 32 bytes per pipe.
+impl PipeDesc {
+ pub fn new() -> Self {
+ Self {
+ bank0: BankDesc::new(),
+ bank1: BankDesc::new(),
+ }
+ }
+}
+
+#[repr(C, packed)]
+// 16 bytes per bank.
+pub(crate) struct BankDesc {
+ pub addr: Addr,
+ pub pcksize: PckSize,
+ pub extreg: ExtReg,
+ pub status_bk: StatusBk,
+ _reserved0: u8,
+ pub ctrl_pipe: CtrlPipe,
+ pub status_pipe: StatusPipe,
+ _reserved1: u8,
+}
+
+impl BankDesc {
+ fn new() -> Self {
+ Self {
+ addr: Addr::from(0),
+ pcksize: PckSize::from(0),
+ extreg: ExtReg::from(0),
+ status_bk: StatusBk::from(0),
+ _reserved0: 0,
+ ctrl_pipe: CtrlPipe::from(0),
+ status_pipe: StatusPipe::from(0),
+ _reserved1: 0,
+ }
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ #[test]
+ fn bank_desc_sizes() {
+ assert_eq!(core::mem::size_of::<Addr>(), 4, "Addr register size.");
+ assert_eq!(core::mem::size_of::<PckSize>(), 4, "PckSize register size.");
+ assert_eq!(core::mem::size_of::<ExtReg>(), 2, "ExtReg register size.");
+ assert_eq!(
+ core::mem::size_of::<StatusBk>(),
+ 1,
+ "StatusBk register size."
+ );
+ assert_eq!(
+ core::mem::size_of::<CtrlPipe>(),
+ 2,
+ "CtrlPipe register size."
+ );
+ assert_eq!(
+ core::mem::size_of::<StatusPipe>(),
+ 1,
+ "StatusPipe register size."
+ );
+
+ // addr at 0x00 for 4
+ // pcksize at 0x04 for 4
+ // extreg at 0x08 for 2
+ // status_bk at 0x0a for 2
+ // ctrl_pipe at 0x0c for 2
+ // status_pipe at 0x0e for 1
+ assert_eq!(
+ core::mem::size_of::<BankDesc>(),
+ 16,
+ "Bank descriptor size."
+ );
+ }
+
+ #[test]
+ fn bank_desc_offsets() {
+ let bd = BankDesc::new();
+ let base = &bd as *const _ as usize;
+
+ assert_offset("Addr", &bd.addr, base, 0x00);
+ assert_offset("PckSize", &bd.pcksize, base, 0x04);
+ assert_offset("ExtReg", &bd.extreg, base, 0x08);
+ assert_offset("StatusBk", &bd.status_bk, base, 0x0a);
+ assert_offset("CtrlPipe", &bd.ctrl_pipe, base, 0x0c);
+ assert_offset("StatusPipe", &bd.status_pipe, base, 0x0e);
+ }
+
+ #[test]
+ fn pipe_desc_size() {
+ assert_eq!(core::mem::size_of::<PipeDesc>(), 32);
+ }
+
+ #[test]
+ fn pipe_desc_offsets() {
+ let pd = PipeDesc::new();
+ let base = &pd as *const _ as usize;
+
+ assert_offset("Bank0", &pd.bank0, base, 0x00);
+ assert_offset("Bank1", &pd.bank1, base, 0x10);
+ }
+
+ fn assert_offset<T>(name: &str, field: &T, base: usize, offset: usize) {
+ let ptr = field as *const _ as usize;
+ assert_eq!(ptr - base, offset, "{} register offset.", name);
+ }
+}
diff --git a/src/pipe/addr.rs b/src/pipe/addr.rs
new file mode 100644
index 0000000..b3548cf
--- /dev/null
+++ b/src/pipe/addr.rs
@@ -0,0 +1,98 @@
+/// § 32.8.7.2
+/// Address of the Data Buffer.
+///
+/// Offset: 0x00 & 0x10
+/// Reset: 0xxxxxxxxx
+/// Property: NA
+#[derive(Clone, Copy, Debug)]
+#[repr(C, packed)]
+pub struct Addr(u32);
+
+pub struct R {
+ bits: u32,
+}
+
+pub struct W {
+ bits: u32,
+}
+
+impl Addr {
+ pub fn read(&self) -> R {
+ R { bits: self.0 }
+ }
+
+ pub fn write<F>(&mut self, f: F)
+ where
+ F: FnOnce(&mut W) -> &mut W,
+ {
+ let mut w = W { bits: self.0 };
+ f(&mut w);
+ self.0 = w.bits;
+ }
+
+ pub fn modify<F>(&mut self, f: F)
+ where
+ for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
+ {
+ let r = R { bits: self.0 };
+ let mut w = W { bits: self.0 };
+ f(&r, &mut w);
+ self.0 = w.bits;
+ }
+}
+
+impl From<u32> for Addr {
+ fn from(v: u32) -> Self {
+ Self(v)
+ }
+}
+
+impl R {
+ /// Value in raw bits.
+ pub fn bits(&self) -> u32 {
+ self.bits
+ }
+
+ pub fn addr(&self) -> AddrR {
+ AddrR(self.bits)
+ }
+}
+
+/// Data Pointer Address Value
+///
+/// These bits define the data pointer address as an absolute double
+/// word address in RAM. The two least significant bits must be zero
+/// to ensure the descriptor is 32-bit aligned.
+pub struct AddrR(u32);
+impl AddrR {
+ pub fn bits(&self) -> u32 {
+ self.0
+ }
+}
+
+impl W {
+ /// Write raw bits.
+ pub unsafe fn bits(&mut self, v: u32) -> &mut Self {
+ self.bits = v;
+ self
+ }
+
+ pub fn addr(&mut self) -> AddrW {
+ AddrW { w: self }
+ }
+}
+
+pub struct AddrW<'a> {
+ w: &'a mut W,
+}
+impl<'a> AddrW<'a> {
+ pub unsafe fn bits(self, v: u32) -> &'a mut W {
+ // Address must be 32-bit aligned. cf §32.8.7.2 of SAMD21 data
+ // sheet.
+ assert!((v & 0x3) == 0);
+ self.w.bits = v;
+ self.w
+ }
+
+ // TODO: "safe" method take a pointer instead of raw u32
+}
diff --git a/src/pipe/ctrl_pipe.rs b/src/pipe/ctrl_pipe.rs
new file mode 100644
index 0000000..9301d51
--- /dev/null
+++ b/src/pipe/ctrl_pipe.rs
@@ -0,0 +1,177 @@
+/// Host Control Pipe.
+///
+/// Offset: 0x0c
+/// Reset: 0xXXXX
+/// Property: PAC Write-Protection, Write-Synchronized, Read-Synchronized
+#[derive(Clone, Copy, Debug)]
+#[repr(C, packed)]
+pub struct CtrlPipe(u16);
+
+pub struct R {
+ bits: u16,
+}
+
+pub struct W {
+ bits: u16,
+}
+
+impl CtrlPipe {
+ pub fn read(&self) -> R {
+ R { bits: self.0 }
+ }
+
+ pub fn write<F>(&mut self, f: F)
+ where
+ F: FnOnce(&mut W) -> &mut W,
+ {
+ let mut w = W { bits: self.0 };
+ f(&mut w);
+ self.0 = w.bits;
+ }
+}
+
+impl From<u16> for CtrlPipe {
+ fn from(v: u16) -> Self {
+ Self(v)
+ }
+}
+
+impl R {
+ /// Value in raw bits.
+ pub fn bits(&self) -> u16 {
+ self.bits
+ }
+
+ pub fn permax(&self) -> PErMaxR {
+ let bits = {
+ const POS: u8 = 12;
+ const MASK: u16 = 0xf;
+ ((self.bits >> POS) & MASK) as u8
+ };
+
+ PErMaxR(bits)
+ }
+
+ pub fn pepnum(&self) -> PEpNumR {
+ let bits = {
+ const POS: u8 = 8;
+ const MASK: u16 = 0xf;
+ ((self.bits >> POS) & MASK) as u8
+ };
+
+ PEpNumR(bits)
+ }
+
+ pub fn pdaddr(&self) -> PDAddrR {
+ let bits = {
+ const POS: u8 = 0;
+ const MASK: u16 = 0x3f;
+ ((self.bits >> POS) & MASK) as u8
+ };
+
+ PDAddrR(bits)
+ }
+}
+
+/// Pipe Error Max Number
+///
+/// These bits define the maximum number of error for this Pipe before
+/// freezing the pipe automatically.
+pub struct PErMaxR(u8);
+impl PErMaxR {
+ pub fn max(&self) -> u8 {
+ self.0
+ }
+}
+
+/// Pipe EndPoint Number
+///
+/// These bits define the number of endpoint for this Pipe.
+pub struct PEpNumR(u8);
+impl PEpNumR {
+ pub fn epnum(&self) -> u8 {
+ self.0
+ }
+}
+
+/// Pipe Device Address
+///
+/// These bits define the Device Address for this pipe.
+pub struct PDAddrR(u8);
+impl PDAddrR {
+ pub fn addr(&self) -> u8 {
+ self.0
+ }
+}
+
+impl W {
+ /// Write raw bits.
+
+ pub unsafe fn bits(&mut self, v: u16) -> &mut Self {
+ self.bits = v;
+ self
+ }
+
+ pub fn permax(&mut self) -> PErMaxW {
+ PErMaxW { w: self }
+ }
+
+ pub fn pepnum(&mut self) -> PEpNumW {
+ PEpNumW { w: self }
+ }
+
+ pub fn pdaddr(&mut self) -> PDAddrW {
+ PDAddrW { w: self }
+ }
+}
+
+pub struct PErMaxW<'a> {
+ w: &'a mut W,
+}
+impl<'a> PErMaxW<'a> {
+ pub unsafe fn bits(self, v: u8) -> &'a mut W {
+ const POS: u8 = 12;
+ const MASK: u8 = 0xf;
+ self.w.bits &= !((MASK as u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << POS;
+ self.w
+ }
+
+ pub fn set_max(self, v: u8) -> &'a mut W {
+ unsafe { self.bits(v) }
+ }
+}
+
+pub struct PEpNumW<'a> {
+ w: &'a mut W,
+}
+impl<'a> PEpNumW<'a> {
+ pub unsafe fn bits(self, v: u8) -> &'a mut W {
+ const POS: u8 = 8;
+ const MASK: u8 = 0xf;
+ self.w.bits &= !((MASK as u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << POS;
+ self.w
+ }
+
+ pub fn set_epnum(self, v: u8) -> &'a mut W {
+ unsafe { self.bits(v) }
+ }
+}
+
+pub struct PDAddrW<'a> {
+ w: &'a mut W,
+}
+impl<'a> PDAddrW<'a> {
+ pub unsafe fn bits(self, v: u8) -> &'a mut W {
+ const POS: u8 = 0;
+ const MASK: u8 = 0x3f;
+ self.w.bits &= !((MASK as u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << POS;
+ self.w
+ }
+
+ pub fn set_addr(self, v: u8) -> &'a mut W {
+ unsafe { self.bits(v) }
+ }
+}
diff --git a/src/pipe/ext_reg.rs b/src/pipe/ext_reg.rs
new file mode 100644
index 0000000..9778f1b
--- /dev/null
+++ b/src/pipe/ext_reg.rs
@@ -0,0 +1,156 @@
+/// §32.8.7.4
+/// Extended Register.
+///
+/// Offset: 0x08
+/// Reset: 0xxxxxxxx
+/// Property: NA
+#[derive(Clone, Copy, Debug)]
+#[repr(C, packed)]
+pub(crate) struct ExtReg(u16);
+
+pub(crate) struct R {
+ bits: u16,
+}
+
+pub(crate) struct W {
+ bits: u16,
+}
+
+impl ExtReg {
+ pub fn read(&self) -> R {
+ R { bits: self.0 }
+ }
+
+ pub fn write<F>(&mut self, f: F)
+ where
+ F: FnOnce(&mut W) -> &mut W,
+ {
+ let mut w = W { bits: self.0 };
+ f(&mut w);
+ self.0 = w.bits;
+ }
+}
+
+impl From<u16> for ExtReg {
+ fn from(v: u16) -> Self {
+ Self(v)
+ }
+}
+
+impl R {
+ /// Value in raw bits.
+ pub fn bits(&self) -> u16 {
+ self.bits
+ }
+
+ pub fn variable(&self) -> VariableR {
+ let bits = {
+ const POS: u8 = 4;
+ const MASK: u16 = 0x7ff;
+ (self.bits >> POS) & MASK
+ };
+
+ VariableR(bits)
+ }
+
+ pub fn subpid(&self) -> SubPIDR {
+ let bits = {
+ const POS: u8 = 0;
+ const MASK: u16 = 0xf;
+ ((self.bits >> POS) & MASK) as u8
+ };
+
+ SubPIDR(bits)
+ }
+}
+
+/// Variable field send with extended token
+///
+/// These bits define the VARIABLE field sent with extended token. See
+/// “Section 2.1.1 Protocol Extension Token in the reference document
+/// ENGINEERING CHANGE NOTICE, USB 2.0 Link Power Management
+/// Addendum.”
+///
+/// To support the USB2.0 Link Power Management addition the VARIABLE
+/// field should be set as described below.
+///
+/// | VARIABLE | Description |
+/// +----------------+-----------------------+
+/// | VARIABLE[3:0] | bLinkState[1] |
+/// | VARIABLE[7:4] | BESL (See LPM ECN)[2] |
+/// | VARIABLE[8] | bRemoteWake[1] |
+/// | VARIABLE[10:9] | Reserved |
+///
+/// [1] for a definition of LPM Token bRemoteWake and bLinkState
+/// fields, refer to "Table 2-3 in the reference document ENGINEERING
+/// CHANGE NOTICE, USB 2.0 Link Power Management Addendum"
+///
+/// [2] for a definition of LPM Token BESL field, refer to "Table 2-3
+/// in the reference document ENGINEERING CHANGE NOTICE, USB 2.0 Link
+/// Power Management Addendum" and "Table X-X1 in Errata for ECN USB
+/// 2.0 Link Power Management.
+pub(crate) struct VariableR(u16);
+impl VariableR {
+ pub fn bits(&self) -> u16 {
+ self.0
+ }
+}
+
+/// SUBPID field with extended token
+///
+/// These bits define the SUBPID field sent with extended token. See
+/// “Section 2.1.1 Protocol Extension Token in the reference document
+/// ENGINEERING CHANGE NOTICE, USB 2.0 Link Power Management
+/// Addendum”.
+///
+/// To support the USB2.0 Link Power Management addition the SUBPID
+/// field should be set as described in “Table 2.2 SubPID Types in the
+/// reference document ENGINEERING CHANGE NOTICE, USB 2.0 Link Power
+/// Management Addendum”.
+pub(crate) struct SubPIDR(u8);
+impl SubPIDR {
+ pub fn bits(&self) -> u8 {
+ self.0
+ }
+}
+
+impl W {
+ /// Write raw bits.
+ pub unsafe fn bits(&mut self, v: u16) -> &mut Self {
+ self.bits = v;
+ self
+ }
+
+ pub fn variable(&mut self) -> VariableW {
+ VariableW { w: self }
+ }
+ pub fn subpid(&mut self) -> SubPIDW {
+ SubPIDW { w: self }
+ }
+}
+
+pub(crate) struct VariableW<'a> {
+ w: &'a mut W,
+}
+impl<'a> VariableW<'a> {
+ pub unsafe fn bits(self, v: u16) -> &'a mut W {
+ const POS: u8 = 4;
+ const MASK: u16 = 0x7ff;
+ self.w.bits &= !((MASK as u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << POS;
+ self.w
+ }
+}
+
+pub(crate) struct SubPIDW<'a> {
+ w: &'a mut W,
+}
+impl<'a> SubPIDW<'a> {
+ pub unsafe fn bits(self, v: u16) -> &'a mut W {
+ const POS: u8 = 0;
+ const MASK: u16 = 0xf;
+ self.w.bits &= !((MASK as u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << POS;
+ self.w
+ }
+}
diff --git a/src/pipe/pck_size.rs b/src/pipe/pck_size.rs
new file mode 100644
index 0000000..acc499f
--- /dev/null
+++ b/src/pipe/pck_size.rs
@@ -0,0 +1,368 @@
+/// § 32.8.7.3
+/// Packet Size.
+///
+/// Offset: 0x04 & 0x14
+/// Reset: 0xxxxxxxxx
+/// Property: NA
+#[derive(Clone, Copy, Debug)]
+#[repr(C, packed)]
+pub(crate) struct PckSize(u32);
+
+pub(crate) struct R {
+ bits: u32,
+}
+
+pub(crate) struct W {
+ bits: u32,
+}
+
+impl PckSize {
+ pub fn read(&self) -> R {
+ R { bits: self.0 }
+ }
+
+ pub fn write<F>(&mut self, f: F)
+ where
+ F: FnOnce(&mut W) -> &mut W,
+ {
+ let mut w = W { bits: self.0 };
+ f(&mut w);
+ self.0 = w.bits;
+ }
+}
+
+impl From<u32> for PckSize {
+ fn from(v: u32) -> Self {
+ Self(v)
+ }
+}
+
+impl R {
+ /// Value in raw bits.
+ pub fn bits(&self) -> u32 {
+ self.bits
+ }
+
+ pub fn auto_zlp(&self) -> AutoZLPR {
+ let bits = {
+ const POS: u8 = 31;
+ const MASK: u32 = 1;
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ AutoZLPR(bits)
+ }
+
+ pub fn size(&self) -> SizeR {
+ let bits = {
+ const POS: u8 = 28;
+ const MASK: u32 = 0x7;
+ ((self.bits >> POS) & MASK) as u8
+ };
+
+ SizeR::from(bits)
+ }
+
+ pub fn multi_packet_size(&self) -> MultiPacketSizeR {
+ let bits = {
+ const POS: u8 = 14;
+ const MASK: u32 = 0x3fff;
+ ((self.bits >> POS) & MASK) as u16
+ };
+
+ MultiPacketSizeR(bits)
+ }
+
+ // Documentation is wrong on this field. Actually 14 bits from
+ // offset 0.
+ pub fn byte_count(&self) -> ByteCountR {
+ let bits = {
+ const POS: u8 = 0;
+ const MASK: u32 = 0x3fff;
+ ((self.bits >> POS) & MASK) as u16
+ };
+
+ ByteCountR(bits)
+ }
+}
+
+/// Automatic Zero Length Packet
+///
+/// This bit defines the automatic Zero Length Packet mode of the
+/// pipe.
+///
+/// When enabled, the USB module will manage the ZLP handshake by
+/// hardware. This bit is for OUT pipes only. When disabled the
+/// handshake should be managed by firmware.
+pub(crate) struct AutoZLPR(bool);
+impl AutoZLPR {
+ pub fn bit(&self) -> bool {
+ self.0
+ }
+
+ pub fn bit_is_set(&self) -> bool {
+ self.bit()
+ }
+
+ pub fn bit_is_clear(&self) -> bool {
+ !self.bit()
+ }
+}
+
+/// Pipe size
+///
+/// These bits contains the size of the pipe.
+///
+/// These bits are cleared upon sending a USB reset.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) enum SizeR {
+ Bytes8,
+ Bytes16,
+ Bytes32,
+ Bytes64,
+ Bytes128,
+ Bytes256,
+ Bytes512,
+ Bytes1024,
+}
+
+impl SizeR {
+ pub fn bits(&self) -> u8 {
+ match *self {
+ Self::Bytes8 => 0x0,
+ Self::Bytes16 => 0x1,
+ Self::Bytes32 => 0x2,
+ Self::Bytes64 => 0x3,
+ Self::Bytes128 => 0x4,
+ Self::Bytes256 => 0x5,
+ Self::Bytes512 => 0x6,
+ Self::Bytes1024 => 0x7,
+ }
+ }
+
+ fn is_bytes8(&self) -> bool {
+ *self == Self::Bytes8
+ }
+ fn is_bytes16(&self) -> bool {
+ *self == Self::Bytes16
+ }
+ fn is_bytes32(&self) -> bool {
+ *self == Self::Bytes32
+ }
+ fn is_bytes64(&self) -> bool {
+ *self == Self::Bytes64
+ }
+ fn is_bytes128(&self) -> bool {
+ *self == Self::Bytes128
+ }
+ fn is_bytes256(&self) -> bool {
+ *self == Self::Bytes256
+ }
+ fn is_bytes512(&self) -> bool {
+ *self == Self::Bytes512
+ }
+ fn is_bytes1024(&self) -> bool {
+ *self == Self::Bytes1024
+ }
+}
+
+impl From<u8> for SizeR {
+ fn from(v: u8) -> Self {
+ match v {
+ 0x0 => Self::Bytes8,
+ 0x1 => Self::Bytes16,
+ 0x2 => Self::Bytes32,
+ 0x3 => Self::Bytes64,
+ 0x4 => Self::Bytes128,
+ 0x5 => Self::Bytes256,
+ 0x6 => Self::Bytes512,
+ 0x7 => Self::Bytes1024,
+ _ => panic!("pcksize between 0 and 7 only"),
+ }
+ }
+}
+
+/// Multi Packet IN or OUT size
+///
+/// These bits define the 14-bit value that is used for multi-packet
+/// transfers.
+///
+/// For IN pipes, MULTI_PACKET_SIZE holds the total number of bytes
+/// sent. MULTI_PACKET_SIZE should be written to zero when setting up
+/// a new transfer.
+///
+/// For OUT pipes, MULTI_PACKET_SIZE holds the total data size for the
+/// complete transfer. This value must be a multiple of the maximum
+/// packet size.
+pub(crate) struct MultiPacketSizeR(u16);
+impl MultiPacketSizeR {
+ pub fn bits(&self) -> u16 {
+ self.0
+ }
+}
+
+/// Byte Count
+///
+/// These bits define the 14-bit value that contains number of bytes
+/// sent in the last OUT or SETUP transaction for an OUT pipe, or of
+/// the number of bytes to be received in the next IN transaction for
+/// an input pipe.
+pub(crate) struct ByteCountR(u16);
+impl ByteCountR {
+ pub fn bits(&self) -> u16 {
+ self.0
+ }
+}
+
+impl W {
+ /// Write raw bits.
+ pub unsafe fn bits(&mut self, v: u32) -> &mut Self {
+ self.bits = v;
+ self
+ }
+
+ pub fn auto_zlp(&mut self) -> AutoZLPW {
+ AutoZLPW { w: self }
+ }
+
+ pub fn size(&mut self) -> _SizeW {
+ _SizeW { w: self }
+ }
+
+ pub fn multi_packet_size(&mut self) -> MultiPacketSizeW {
+ MultiPacketSizeW { w: self }
+ }
+
+ pub fn byte_count(&mut self) -> ByteCountW {
+ ByteCountW { w: self }
+ }
+}
+
+pub(crate) struct AutoZLPW<'a> {
+ w: &'a mut W,
+}
+impl<'a> AutoZLPW<'a> {
+ pub fn bit(self, v: bool) -> &'a mut W {
+ const POS: u8 = 31;
+ const MASK: bool = true;
+ self.w.bits &= !((MASK as u32) << POS);
+ self.w.bits |= ((v & MASK) as u32) << POS;
+ self.w
+ }
+
+ pub fn set_bit(self) -> &'a mut W {
+ self.bit(true)
+ }
+
+ pub fn clear_bit(self) -> &'a mut W {
+ self.bit(false)
+ }
+}
+
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub(crate) enum SizeW {
+ Bytes8,
+ Bytes16,
+ Bytes32,
+ Bytes64,
+ Bytes128,
+ Bytes256,
+ Bytes512,
+ Bytes1024,
+}
+impl SizeW {
+ pub fn bits(&self) -> u8 {
+ match *self {
+ Self::Bytes8 => 0,
+ Self::Bytes16 => 1,
+ Self::Bytes32 => 2,
+ Self::Bytes64 => 3,
+ Self::Bytes128 => 4,
+ Self::Bytes256 => 5,
+ Self::Bytes512 => 6,
+ Self::Bytes1024 => 7,
+ }
+ }
+}
+
+/// Proxy for `SizeW`
+pub(crate) struct _SizeW<'a> {
+ w: &'a mut W,
+}
+impl<'a> _SizeW<'a> {
+ pub unsafe fn bits(self, v: u8) -> &'a mut W {
+ const POS: u8 = 28;
+ const MASK: u8 = 0x7;
+ self.w.bits &= !((MASK as u32) << POS);
+ self.w.bits |= ((v & MASK) as u32) << POS;
+ self.w
+ }
+
+ pub fn variant(self, v: SizeW) -> &'a mut W {
+ unsafe { self.bits(v.bits()) }
+ }
+
+ pub fn bytes8(self) -> &'a mut W {
+ self.variant(SizeW::Bytes8)
+ }
+
+ pub fn bytes16(self) -> &'a mut W {
+ self.variant(SizeW::Bytes16)
+ }
+
+ pub fn bytes32(self) -> &'a mut W {
+ self.variant(SizeW::Bytes32)
+ }
+
+ pub fn bytes64(self) -> &'a mut W {
+ self.variant(SizeW::Bytes64)
+ }
+
+ pub fn bytes128(self) -> &'a mut W {
+ self.variant(SizeW::Bytes128)
+ }
+
+ pub fn bytes256(self) -> &'a mut W {
+ self.variant(SizeW::Bytes256)
+ }
+
+ pub fn bytes512(self) -> &'a mut W {
+ self.variant(SizeW::Bytes512)
+ }
+
+ pub fn bytes1024(self) -> &'a mut W {
+ self.variant(SizeW::Bytes1024)
+ }
+}
+
+pub(crate) struct MultiPacketSizeW<'a> {
+ w: &'a mut W,
+}
+impl<'a> MultiPacketSizeW<'a> {
+ pub unsafe fn bits(self, v: u16) -> &'a mut W {
+ assert!(v < 16_384);
+
+ const POS: u8 = 14;
+ const MASK: u16 = 0x3fff;
+ self.w.bits &= !((MASK as u32) << POS);
+ self.w.bits |= ((v & MASK) as u32) << POS;
+ self.w
+ }
+}
+
+pub(crate) struct ByteCountW<'a> {
+ w: &'a mut W,
+}
+impl<'a> ByteCountW<'a> {
+ // Documentation is wrong on this field. Actually 14 bits from
+ // offset 0.
+ pub unsafe fn bits(self, v: u16) -> &'a mut W {
+ assert!(v < 16_384);
+
+ const POS: u8 = 0;
+ const MASK: u16 = 0x3fff;
+ self.w.bits &= !((MASK as u32) << POS);
+ self.w.bits |= ((v & MASK) as u32) << POS;
+ self.w
+ }
+}
diff --git a/src/pipe/status_bk.rs b/src/pipe/status_bk.rs
new file mode 100644
index 0000000..489fc62
--- /dev/null
+++ b/src/pipe/status_bk.rs
@@ -0,0 +1,170 @@
+/// §32.8.7.5
+/// Host Status Bank.
+///
+/// Offset: 0x0a & 0x1a
+/// Reset: 0xxxxxxx
+/// Property: NA
+#[derive(Clone, Copy, Debug)]
+#[repr(C, packed)]
+pub(crate) struct StatusBk(u8);
+
+pub(crate) struct R {
+ bits: u8,
+}
+
+pub(crate) struct W {
+ bits: u8,
+}
+
+impl StatusBk {
+ pub fn read(&self) -> R {
+ R { bits: self.0 }
+ }
+
+ pub fn write<F>(&mut self, f: F)
+ where
+ F: FnOnce(&mut W) -> &mut W,
+ {
+ let mut w = W { bits: self.0 };
+ f(&mut w);
+ self.0 = w.bits;
+ }
+}
+
+impl From<u8> for StatusBk {
+ fn from(v: u8) -> Self {
+ Self(v)
+ }
+}
+
+impl R {
+ /// Value in raw bits.
+ pub fn bits(&self) -> u8 {
+ self.bits
+ }
+
+ pub fn errorflow(&self) -> ErrorFlowR {
+ let bits = {
+ const POS: u8 = 1;
+ const MASK: u8 = 1;
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ ErrorFlowR(bits)
+ }
+
+ pub fn crcerr(&self) -> CRCErrR {
+ let bits = {
+ const POS: u8 = 0;
+ const MASK: u8 = 1;
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ CRCErrR(bits)
+ }
+}
+
+/// Error Flow Status
+///
+/// This bit defines the Error Flow Status.
+///
+/// This bit is set when a Error Flow has been detected during
+/// transfer from/towards this bank.
+///
+/// For IN transfer, a NAK handshake has been received. For OUT
+/// transfer, a NAK handshake has been received. For Isochronous IN
+/// transfer, an overrun condition has occurred. For Isochronous OUT
+/// transfer, an underflow condition has occurred.
+pub(crate) struct ErrorFlowR(bool);
+impl ErrorFlowR {
+ pub fn bit(&self) -> bool {
+ self.0
+ }
+
+ pub fn bit_is_set(&self) -> bool {
+ self.bit()
+ }
+
+ pub fn bit_is_clear(&self) -> bool {
+ !self.bit_is_set()
+ }
+}
+
+/// CRC Error
+///
+/// This bit defines the CRC Error Status.
+///
+/// This bit is set when a CRC error has been detected in an
+/// isochronous IN endpoint bank.
+pub(crate) struct CRCErrR(bool);
+impl CRCErrR {
+ pub fn bit(&self) -> bool {
+ self.0
+ }
+
+ pub fn bit_is_set(&self) -> bool {
+ self.bit()
+ }
+
+ pub fn bit_is_clear(&self) -> bool {
+ !self.bit_is_set()
+ }
+}
+
+impl W {
+ /// Write raw bits.
+ pub unsafe fn bits(&mut self, v: u8) -> &mut Self {
+ self.bits = v;
+ self
+ }
+
+ pub fn errorflow(&mut self) -> ErrorFlowW {
+ ErrorFlowW { w: self }
+ }
+
+ pub fn crcerr(&mut self) -> CRCErrW {
+ CRCErrW { w: self }
+ }
+}
+
+pub(crate) struct ErrorFlowW<'a> {
+ w: &'a mut W,
+}
+impl<'a> ErrorFlowW<'a> {
+ pub fn bit(self, v: bool) -> &'a mut W {
+ const POS: u8 = 1;
+ const MASK: bool = true;
+ self.w.bits &= !((MASK as u8) << POS);
+ self.w.bits |= ((v & MASK) as u8) << POS;
+ self.w
+ }
+
+ pub fn set_bit(self) -> &'a mut W {
+ self.bit(true)
+ }
+
+ pub fn clear_bit(self) -> &'a mut W {
+ self.bit(false)
+ }
+}
+
+pub(crate) struct CRCErrW<'a> {
+ w: &'a mut W,
+}
+impl<'a> CRCErrW<'a> {
+ pub fn bit(self, v: bool) -> &'a mut W {
+ const POS: u8 = 0;
+ const MASK: bool = true;
+ self.w.bits &= !((MASK as u8) << POS);
+ self.w.bits |= ((v & MASK) as u8) << POS;
+ self.w
+ }
+
+ pub fn set_bit(self) -> &'a mut W {
+ self.bit(true)
+ }
+
+ pub fn clear_bit(self) -> &'a mut W {
+ self.bit(false)
+ }
+}
diff --git a/src/pipe/status_pipe.rs b/src/pipe/status_pipe.rs
new file mode 100644
index 0000000..be135c5
--- /dev/null
+++ b/src/pipe/status_pipe.rs
@@ -0,0 +1,407 @@
+/// Host Status Pipe.
+///
+/// Offset: 0x0e & 0x1e
+/// Reset: 0xxxxxx
+/// Property: PAC Write-Protection, Write-Synchronized, Read-Synchronized
+#[derive(Clone, Copy, Debug)]
+#[repr(C, packed)]
+pub(crate) struct StatusPipe(u8);
+
+pub(crate) struct R {
+ bits: u8,
+}
+pub(crate) struct W {
+ bits: u8,
+}
+
+impl StatusPipe {
+ pub fn read(&self) -> R {
+ R { bits: self.0 }
+ }
+
+ pub fn write<F>(&mut self, f: F)
+ where
+ F: FnOnce(&mut W) -> &mut W,
+ {
+ let mut w = W { bits: self.0 };
+ f(&mut w);
+ self.0 = w.bits;
+ }
+}
+
+impl From<u8> for StatusPipe {
+ fn from(v: u8) -> Self {
+ Self(v)
+ }
+}
+
+impl R {
+ /// Value in raw bits.
+ pub fn bits(&self) -> u8 {
+ self.bits
+ }
+
+ pub fn ercnt(&self) -> ErCntR {
+ let bits = {
+ const POS: u8 = 5;
+ const MASK: u8 = 0x7;
+ ((self.bits >> POS) & MASK) as u8
+ };
+
+ ErCntR(bits)
+ }
+
+ pub fn crc16er(&self) -> CRC16ErR {
+ let bits = {
+ const POS: u8 = 4;
+ const MASK: u8 = 1;
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ CRC16ErR(bits)
+ }
+
+ pub fn touter(&self) -> TOutErrR {
+ let bits = {
+ const POS: u8 = 3;
+ const MASK: u8 = 1;
+
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ TOutErrR(bits)
+ }
+
+ pub fn pider(&self) -> PIDErR {
+ let bits = {
+ const POS: u8 = 2;
+ const MASK: u8 = 1;
+
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ PIDErR(bits)
+ }
+
+ pub fn dapider(&self) -> DaPIDErR {
+ let bits = {
+ const POS: u8 = 1;
+ const MASK: u8 = 1;
+
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ DaPIDErR(bits)
+ }
+
+ pub fn dtgler(&self) -> DTglErR {
+ let bits = {
+ const POS: u8 = 0;
+ const MASK: u8 = 1;
+
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ DTglErR(bits)
+ }
+}
+
+/// Pipe Error Counter
+///
+/// The number of errors detected on the pipe.
+pub(crate) struct ErCntR(u8);
+impl ErCntR {
+ pub fn bits(&self) -> u8 {
+ self.0
+ }
+}
+
+/// CRC16 ERROR
+///
+/// This bit defines the CRC16 Error Status.
+///
+/// This bit is set when a CRC 16 error has been detected during a IN
+/// transactions.
+pub(crate) struct CRC16ErR(bool);
+impl CRC16ErR {
+ pub fn bit(&self) -> bool {
+ self.0
+ }
+
+ pub fn bit_is_set(&self) -> bool {
+ self.bit()
+ }
+
+ pub fn bit_is_clear(&self) -> bool {
+ !self.bit_is_set()
+ }
+}
+
+/// TIME OUT ERROR
+///
+/// This bit defines the Time Out Error Status.
+///
+/// This bit is set when a Time Out error has been detected during a
+/// USB transaction.
+pub(crate) struct TOutErrR(bool);
+impl TOutErrR {
+ pub fn bit(&self) -> bool {
+ self.0
+ }
+
+ pub fn bit_is_set(&self) -> bool {
+ self.bit()
+ }
+
+ pub fn bit_is_clear(&self) -> bool {
+ !self.bit_is_set()
+ }
+}
+
+/// PID ERROR
+///
+/// This bit defines the PID Error Status.
+///
+/// This bit is set when a PID error has been detected during a USB
+/// transaction.
+pub(crate) struct PIDErR(bool);
+impl PIDErR {
+ pub fn bit(&self) -> bool {
+ self.0
+ }
+
+ pub fn bit_is_set(&self) -> bool {
+ self.bit()
+ }
+
+ pub fn bit_is_clear(&self) -> bool {
+ !self.bit_is_set()
+ }
+}
+
+/// Data PID ERROR
+///
+/// This bit defines the PID Error Status.
+///
+/// This bit is set when a Data PID error has been detected during a
+/// USB transaction.
+pub(crate) struct DaPIDErR(bool);
+impl DaPIDErR {
+ pub fn bit(&self) -> bool {
+ self.0
+ }
+
+ pub fn bit_is_set(&self) -> bool {
+ self.bit()
+ }
+
+ pub fn bit_is_clear(&self) -> bool {
+ !self.bit_is_set()
+ }
+}
+
+/// Data Toggle Error
+///
+/// This bit defines the Data Toggle Error Status.
+///
+/// This bit is set when a Data Toggle Error has been detected.
+pub(crate) struct DTglErR(bool);
+impl DTglErR {
+ pub fn bit(&self) -> bool {
+ self.0
+ }
+
+ pub fn bit_is_set(&self) -> bool {
+ self.bit()
+ }
+
+ pub fn bit_is_clear(&self) -> bool {
+ !self.bit_is_set()
+ }
+}
+
+impl W {
+ /// Write raw bits.
+ pub unsafe fn bits(&mut self, v: u8) -> &mut Self {
+ self.bits = v;
+ self
+ }
+
+ pub fn ercnt(&mut self) -> ErCntW {
+ ErCntW { w: self }
+ }
+
+ pub fn crc16er(&mut self) -> CRC16ErW {
+ CRC16ErW { w: self }
+ }
+
+ pub fn touter(&mut self) -> TOutErW {
+ TOutErW { w: self }
+ }
+
+ pub fn pider(&mut self) -> PIDErW {
+ PIDErW { w: self }
+ }
+
+ pub fn dapider(&mut self) -> DaPIDErW {
+ DaPIDErW { w: self }
+ }
+
+ pub fn dtgler(&mut self) -> DTglErW {
+ DTglErW { w: self }
+ }
+}
+
+/// Pipe Error Counter
+///
+/// The number of errors detected on the pipe.
+pub(crate) struct ErCntW<'a> {
+ w: &'a mut W,
+}
+impl<'a> ErCntW<'a> {
+ pub unsafe fn bits(self, v: u8) -> &'a mut W {
+ const POS: u8 = 5;
+ const MASK: u8 = 0x7;
+ self.w.bits &= !((MASK as u8) << POS);
+ self.w.bits |= ((v & MASK) as u8) << POS;
+ self.w
+ }
+
+ pub fn set_count(self, v: u8) -> &'a mut W {
+ unsafe { self.bits(v) }
+ }
+}
+
+/// CRC16 ERROR
+///
+/// This bit defines the CRC16 Error Status.
+///
+/// This bit is set when a CRC 16 error has been detected during a IN
+/// transactions.
+pub(crate) struct CRC16ErW<'a> {
+ w: &'a mut W,
+}
+impl<'a> CRC16ErW<'a> {
+ pub fn bit(self, v: bool) -> &'a mut W {
+ const POS: u8 = 4;
+ const MASK: bool = true;
+ self.w.bits &= !((MASK as u8) << POS);
+ self.w.bits |= ((v & MASK) as u8) << POS;
+ self.w
+ }
+
+ pub fn set_bit(self) -> &'a mut W {
+ self.bit(true)
+ }
+
+ pub fn clear_bit(self) -> &'a mut W {
+ self.bit(false)
+ }
+}
+
+/// TIME OUT ERROR
+///
+/// This bit defines the Time Out Error Status.
+///
+/// This bit is set when a Time Out error has been detected during a
+/// USB transaction.
+pub(crate) struct TOutErW<'a> {
+ w: &'a mut W,
+}
+impl<'a> TOutErW<'a> {
+ pub fn bit(self, v: bool) -> &'a mut W {
+ const POS: u8 = 3;
+ const MASK: bool = true;
+ self.w.bits &= !((MASK as u8) << POS);
+ self.w.bits |= ((v & MASK) as u8) << POS;
+ self.w
+ }
+
+ pub fn set_bit(self) -> &'a mut W {
+ self.bit(true)
+ }
+
+ pub fn clear_bit(self) -> &'a mut W {
+ self.bit(false)
+ }
+}
+
+/// PID ERROR
+///
+/// This bit defines the PID Error Status.
+///
+/// This bit is set when a PID error has been detected during a USB
+/// transaction.
+pub(crate) struct PIDErW<'a> {
+ w: &'a mut W,
+}
+impl<'a> PIDErW<'a> {
+ pub fn bit(self, v: bool) -> &'a mut W {
+ const POS: u8 = 2;
+ const MASK: bool = true;
+ self.w.bits &= !((MASK as u8) << POS);
+ self.w.bits |= ((v & MASK) as u8) << POS;
+ self.w
+ }
+
+ pub fn set_bit(self) -> &'a mut W {
+ self.bit(true)
+ }
+
+ pub fn clear_bit(self) -> &'a mut W {
+ self.bit(false)
+ }
+}
+
+/// Data PID ERROR
+///
+/// This bit defines the PID Error Status.
+///
+/// This bit is set when a Data PID error has been detected during a
+/// USB transaction.
+pub(crate) struct DaPIDErW<'a> {
+ w: &'a mut W,
+}
+impl<'a> DaPIDErW<'a> {
+ pub fn bit(self, v: bool) -> &'a mut W {
+ const POS: u8 = 1;
+ const MASK: bool = true;
+ self.w.bits &= !((MASK as u8) << POS);
+ self.w.bits |= ((v & MASK) as u8) << POS;
+ self.w
+ }
+
+ pub fn set_bit(self) -> &'a mut W {
+ self.bit(true)
+ }
+
+ pub fn clear_bit(self) -> &'a mut W {
+ self.bit(false)
+ }
+}
+
+/// Data Toggle Error
+///
+/// This bit defines the Data Toggle Error Status.
+///
+/// This bit is set when a Data Toggle Error has been detected.
+pub(crate) struct DTglErW<'a> {
+ w: &'a mut W,
+}
+impl<'a> DTglErW<'a> {
+ pub fn bit(self, v: bool) -> &'a mut W {
+ const POS: u8 = 0;
+ const MASK: bool = true;
+ self.w.bits &= !((MASK as u8) << POS);
+ self.w.bits |= ((v & MASK) as u8) << POS;
+ self.w
+ }
+
+ pub fn set_bit(self) -> &'a mut W {
+ self.bit(true)
+ }
+
+ pub fn clear_bit(self) -> &'a mut W {
+ self.bit(false)
+ }
+}