diff --git a/firmware/lib/can2040/COPYING b/firmware/lib/can2040/COPYING
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/firmware/lib/can2040/COPYING
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ 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.
+
+
+ Copyright (C)
+
+ 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 .
+
+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:
+
+ Copyright (C)
+ 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
+.
+
+ 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
+.
diff --git a/firmware/lib/can2040/src/can2040.c b/firmware/lib/can2040/src/can2040.c
new file mode 100644
index 0000000..7c4e09c
--- /dev/null
+++ b/firmware/lib/can2040/src/can2040.c
@@ -0,0 +1,1371 @@
+// Software CANbus implementation for rp2040
+//
+// Copyright (C) 2022,2023 Kevin O'Connor
+//
+// This file may be distributed under the terms of the GNU GPLv3 license.
+
+#include // uint32_t
+#include // memset
+// NOTE: This was changed from the original checkout
+// #include "RP2040.h" // hw_set_bits
+#include "hardware/address_mapped.h" // hw_set_bits
+#include "can2040.h" // can2040_setup
+#include "hardware/regs/dreq.h" // DREQ_PIO0_RX1
+#include "hardware/structs/dma.h" // dma_hw
+#include "hardware/structs/iobank0.h" // iobank0_hw
+#include "hardware/structs/padsbank0.h" // padsbank0_hw
+#include "hardware/structs/pio.h" // pio0_hw
+#include "hardware/structs/resets.h" // RESETS_RESET_PIO0_BITS
+
+
+/****************************************************************
+ * rp2040 and low-level helper functions
+ ****************************************************************/
+
+// Helper compiler definitions
+#define barrier() __asm__ __volatile__("": : :"memory")
+#define likely(x) __builtin_expect(!!(x), 1)
+#define unlikely(x) __builtin_expect(!!(x), 0)
+#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
+#define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d))
+
+// Helper functions for writing to "io" memory
+static inline void writel(void *addr, uint32_t val) {
+ barrier();
+ *(volatile uint32_t *)addr = val;
+}
+static inline uint32_t readl(const void *addr) {
+ uint32_t val = *(volatile const uint32_t *)addr;
+ barrier();
+ return val;
+}
+
+// rp2040 helper function to clear a hardware reset bit
+static void
+rp2040_clear_reset(uint32_t reset_bit)
+{
+ if (resets_hw->reset & reset_bit) {
+ hw_clear_bits(&resets_hw->reset, reset_bit);
+ while (!(resets_hw->reset_done & reset_bit))
+ ;
+ }
+}
+
+// Helper to set the mode and extended function of a pin
+static void
+rp2040_gpio_peripheral(uint32_t gpio, int func, int pull_up)
+{
+ padsbank0_hw->io[gpio] = (
+ PADS_BANK0_GPIO0_IE_BITS
+ | (PADS_BANK0_GPIO0_DRIVE_VALUE_4MA << PADS_BANK0_GPIO0_DRIVE_MSB)
+ | (pull_up > 0 ? PADS_BANK0_GPIO0_PUE_BITS : 0)
+ | (pull_up < 0 ? PADS_BANK0_GPIO0_PDE_BITS : 0));
+ iobank0_hw->io[gpio].ctrl = func << IO_BANK0_GPIO0_CTRL_FUNCSEL_LSB;
+}
+
+
+/****************************************************************
+ * rp2040 PIO support
+ ****************************************************************/
+
+#define PIO_CLOCK_PER_BIT 32
+#define PIO_RX_WAKE_BITS 10
+
+#define can2040_offset_sync_found_end_of_message 2u
+#define can2040_offset_sync_signal_start 4u
+#define can2040_offset_sync_entry 6u
+#define can2040_offset_sync_end 13u
+#define can2040_offset_shared_rx_read 13u
+#define can2040_offset_shared_rx_end 15u
+#define can2040_offset_match_load_next 18u
+#define can2040_offset_tx_conflict 24u
+#define can2040_offset_match_end 25u
+#define can2040_offset_tx_got_recessive 25u
+#define can2040_offset_tx_write_pin 27u
+
+static const uint16_t can2040_program_instructions[] = {
+ 0x0085, // 0: jmp y--, 5
+ 0x0048, // 1: jmp x--, 8
+ 0xe029, // 2: set x, 9
+ 0x00cc, // 3: jmp pin, 12
+ 0xc000, // 4: irq nowait 0
+ 0x00c0, // 5: jmp pin, 0
+ 0xc040, // 6: irq clear 0
+ 0xe429, // 7: set x, 9 [4]
+ 0xf043, // 8: set y, 3 [16]
+ 0xc104, // 9: irq nowait 4 [1]
+ 0x03c5, // 10: jmp pin, 5 [3]
+ 0x0307, // 11: jmp 7 [3]
+ 0x0043, // 12: jmp x--, 3
+ 0x20c4, // 13: wait 1 irq, 4
+ 0x4001, // 14: in pins, 1
+ 0xa046, // 15: mov y, isr
+ 0x01b2, // 16: jmp x != y, 18 [1]
+ 0xc002, // 17: irq nowait 2
+ 0x40eb, // 18: in osr, 11
+ 0x4054, // 19: in y, 20
+ 0xa047, // 20: mov y, osr
+ 0x8080, // 21: pull noblock
+ 0xa027, // 22: mov x, osr
+ 0x0098, // 23: jmp y--, 24
+ 0xa0e2, // 24: mov osr, y
+ 0x6021, // 25: out x, 1
+ 0x00df, // 26: jmp pin, 31
+ 0xb801, // 27: mov pins, x [24]
+ 0x02d9, // 28: jmp pin, 25 [2]
+ 0x0058, // 29: jmp x--, 24
+ 0x6021, // 30: out x, 1
+ 0x011b, // 31: jmp 27 [1]
+};
+
+// Local names for PIO state machine IRQs
+#define SI_MAYTX PIO_IRQ0_INTE_SM0_BITS
+#define SI_MATCHED PIO_IRQ0_INTE_SM2_BITS
+#define SI_ACKDONE PIO_IRQ0_INTE_SM3_BITS
+#define SI_RX_DATA PIO_IRQ0_INTE_SM1_RXNEMPTY_BITS
+#define SI_TXPENDING PIO_IRQ0_INTE_SM1_BITS // Misc bit manually forced
+
+// Setup PIO "sync" state machine (state machine 0)
+static void
+pio_sync_setup(struct can2040 *cd)
+{
+ pio_hw_t *pio_hw = cd->pio_hw;
+ struct pio_sm_hw *sm = &pio_hw->sm[0];
+ sm->execctrl = (
+ cd->gpio_rx << PIO_SM0_EXECCTRL_JMP_PIN_LSB
+ | (can2040_offset_sync_end - 1) << PIO_SM0_EXECCTRL_WRAP_TOP_LSB
+ | can2040_offset_sync_signal_start << PIO_SM0_EXECCTRL_WRAP_BOTTOM_LSB);
+ sm->pinctrl = (
+ 1 << PIO_SM0_PINCTRL_SET_COUNT_LSB
+ | cd->gpio_rx << PIO_SM0_PINCTRL_SET_BASE_LSB);
+ sm->instr = 0xe080; // set pindirs, 0
+ sm->pinctrl = 0;
+ pio_hw->txf[0] = 9 + 6 * PIO_CLOCK_PER_BIT / 2;
+ sm->instr = 0x80a0; // pull block
+ sm->instr = can2040_offset_sync_entry; // jmp sync_entry
+}
+
+// Setup PIO "rx" state machine (state machine 1)
+static void
+pio_rx_setup(struct can2040 *cd)
+{
+ pio_hw_t *pio_hw = cd->pio_hw;
+ struct pio_sm_hw *sm = &pio_hw->sm[1];
+ sm->execctrl = (
+ (can2040_offset_shared_rx_end - 1) << PIO_SM0_EXECCTRL_WRAP_TOP_LSB
+ | can2040_offset_shared_rx_read << PIO_SM0_EXECCTRL_WRAP_BOTTOM_LSB);
+ sm->pinctrl = cd->gpio_rx << PIO_SM0_PINCTRL_IN_BASE_LSB;
+ sm->shiftctrl = 0; // flush fifo on a restart
+ sm->shiftctrl = (PIO_SM0_SHIFTCTRL_FJOIN_RX_BITS
+ | PIO_RX_WAKE_BITS << PIO_SM0_SHIFTCTRL_PUSH_THRESH_LSB
+ | PIO_SM0_SHIFTCTRL_AUTOPUSH_BITS);
+ sm->instr = can2040_offset_shared_rx_read; // jmp shared_rx_read
+}
+
+// Setup PIO "match" state machine (state machine 2)
+static void
+pio_match_setup(struct can2040 *cd)
+{
+ pio_hw_t *pio_hw = cd->pio_hw;
+ struct pio_sm_hw *sm = &pio_hw->sm[2];
+ sm->execctrl = (
+ (can2040_offset_match_end - 1) << PIO_SM0_EXECCTRL_WRAP_TOP_LSB
+ | can2040_offset_shared_rx_read << PIO_SM0_EXECCTRL_WRAP_BOTTOM_LSB);
+ sm->pinctrl = cd->gpio_rx << PIO_SM0_PINCTRL_IN_BASE_LSB;
+ sm->shiftctrl = 0;
+ sm->instr = 0xe040; // set y, 0
+ sm->instr = 0xa0e2; // mov osr, y
+ sm->instr = 0xa02a, // mov x, !y
+ sm->instr = can2040_offset_match_load_next; // jmp match_load_next
+}
+
+// Setup PIO "tx" state machine (state machine 3)
+static void
+pio_tx_setup(struct can2040 *cd)
+{
+ pio_hw_t *pio_hw = cd->pio_hw;
+ struct pio_sm_hw *sm = &pio_hw->sm[3];
+ sm->execctrl = (
+ cd->gpio_rx << PIO_SM0_EXECCTRL_JMP_PIN_LSB
+ | can2040_offset_tx_conflict << PIO_SM0_EXECCTRL_WRAP_TOP_LSB
+ | can2040_offset_tx_conflict << PIO_SM0_EXECCTRL_WRAP_BOTTOM_LSB);
+ sm->shiftctrl = (PIO_SM0_SHIFTCTRL_FJOIN_TX_BITS
+ | PIO_SM0_SHIFTCTRL_AUTOPULL_BITS);
+ sm->pinctrl = (1 << PIO_SM0_PINCTRL_SET_COUNT_LSB
+ | 1 << PIO_SM0_PINCTRL_OUT_COUNT_LSB
+ | cd->gpio_tx << PIO_SM0_PINCTRL_SET_BASE_LSB
+ | cd->gpio_tx << PIO_SM0_PINCTRL_OUT_BASE_LSB);
+ sm->instr = 0xe001; // set pins, 1
+ sm->instr = 0xe081; // set pindirs, 1
+}
+
+// Set PIO "sync" machine to signal "may transmit" (sm irq 0) on 11 idle bits
+static void
+pio_sync_normal_start_signal(struct can2040 *cd)
+{
+ pio_hw_t *pio_hw = cd->pio_hw;
+ uint32_t eom_idx = can2040_offset_sync_found_end_of_message;
+ pio_hw->instr_mem[eom_idx] = 0xe12a; // set x, 10 [1]
+}
+
+// Set PIO "sync" machine to signal "may transmit" (sm irq 0) on 17 idle bits
+static void
+pio_sync_slow_start_signal(struct can2040 *cd)
+{
+ pio_hw_t *pio_hw = cd->pio_hw;
+ uint32_t eom_idx = can2040_offset_sync_found_end_of_message;
+ pio_hw->instr_mem[eom_idx] = 0xa127; // mov x, osr [1]
+}
+
+// Test if PIO "rx" state machine has overflowed its fifos
+static int
+pio_rx_check_stall(struct can2040 *cd)
+{
+ pio_hw_t *pio_hw = cd->pio_hw;
+ return pio_hw->fdebug & (1 << (PIO_FDEBUG_RXSTALL_LSB + 1));
+}
+
+// Set PIO "match" state machine to raise a "matched" signal on a bit sequence
+static void
+pio_match_check(struct can2040 *cd, uint32_t match_key)
+{
+ pio_hw_t *pio_hw = cd->pio_hw;
+ pio_hw->txf[2] = match_key;
+}
+
+// Calculate pos+bits identifier for PIO "match" state machine
+static uint32_t
+pio_match_calc_key(uint32_t raw_bits, uint32_t rx_bit_pos)
+{
+ return (raw_bits & 0x1fffff) | ((-rx_bit_pos) << 21);
+}
+
+// Cancel any pending checks on PIO "match" state machine
+static void
+pio_match_clear(struct can2040 *cd)
+{
+ pio_match_check(cd, 0);
+}
+
+// Flush and halt PIO "tx" state machine
+static void
+pio_tx_reset(struct can2040 *cd)
+{
+ pio_hw_t *pio_hw = cd->pio_hw;
+ pio_hw->ctrl = 0x07 << PIO_CTRL_SM_ENABLE_LSB;
+ pio_hw->ctrl = ((0x07 << PIO_CTRL_SM_ENABLE_LSB)
+ | (0x08 << PIO_CTRL_SM_RESTART_LSB));
+ pio_hw->irq = (SI_MATCHED | SI_ACKDONE) >> 8; // clear PIO irq flags
+ // Clear tx fifo
+ struct pio_sm_hw *sm = &pio_hw->sm[3];
+ sm->shiftctrl = 0;
+ sm->shiftctrl = (PIO_SM0_SHIFTCTRL_FJOIN_TX_BITS
+ | PIO_SM0_SHIFTCTRL_AUTOPULL_BITS);
+}
+
+// Queue a message for transmission on PIO "tx" state machine
+static void
+pio_tx_send(struct can2040 *cd, uint32_t *data, uint32_t count)
+{
+ pio_hw_t *pio_hw = cd->pio_hw;
+ pio_tx_reset(cd);
+ pio_hw->instr_mem[can2040_offset_tx_got_recessive] = 0x6021; // out x, 1
+ uint32_t i;
+ for (i=0; itxf[3] = data[i];
+ struct pio_sm_hw *sm = &pio_hw->sm[3];
+ sm->instr = 0xe001; // set pins, 1
+ sm->instr = 0x6021; // out x, 1
+ sm->instr = can2040_offset_tx_write_pin; // jmp tx_write_pin
+ sm->instr = 0x20c0; // wait 1 irq, 0
+ pio_hw->ctrl = 0x0f << PIO_CTRL_SM_ENABLE_LSB;
+}
+
+// Set PIO "tx" state machine to inject an ack after a CRC match
+static void
+pio_tx_inject_ack(struct can2040 *cd, uint32_t match_key)
+{
+ pio_hw_t *pio_hw = cd->pio_hw;
+ pio_tx_reset(cd);
+ pio_hw->instr_mem[can2040_offset_tx_got_recessive] = 0xc023; // irq wait 3
+ pio_hw->txf[3] = 0x7fffffff;
+ struct pio_sm_hw *sm = &pio_hw->sm[3];
+ sm->instr = 0xe001; // set pins, 1
+ sm->instr = 0x6021; // out x, 1
+ sm->instr = can2040_offset_tx_write_pin; // jmp tx_write_pin
+ sm->instr = 0x20c2; // wait 1 irq, 2
+ pio_hw->ctrl = 0x0f << PIO_CTRL_SM_ENABLE_LSB;
+
+ pio_match_check(cd, match_key);
+}
+
+// Did PIO "tx" state machine unexpectedly finish a transmit attempt?
+static int
+pio_tx_did_fail(struct can2040 *cd)
+{
+ pio_hw_t *pio_hw = cd->pio_hw;
+ // Check for passive/dominant bit conflict without parser noticing
+ if (pio_hw->sm[3].addr == can2040_offset_tx_conflict)
+ return !(pio_hw->intr & SI_RX_DATA);
+ // Check for unexpected drain of transmit queue without parser noticing
+ return (!(pio_hw->flevel & PIO_FLEVEL_TX3_BITS)
+ && (pio_hw->intr & (SI_MAYTX | SI_RX_DATA)) == SI_MAYTX);
+}
+
+// Enable host irqs for state machine signals
+static void
+pio_irq_set(struct can2040 *cd, uint32_t sm_irqs)
+{
+ pio_hw_t *pio_hw = cd->pio_hw;
+ pio_hw->inte0 = sm_irqs | SI_RX_DATA;
+}
+
+// Completely disable host irqs
+static void
+pio_irq_disable(struct can2040 *cd)
+{
+ pio_hw_t *pio_hw = cd->pio_hw;
+ pio_hw->inte0 = 0;
+}
+
+// Return current host irq mask
+static uint32_t
+pio_irq_get(struct can2040 *cd)
+{
+ pio_hw_t *pio_hw = cd->pio_hw;
+ return pio_hw->inte0;
+}
+
+// Raise the txpending flag
+static void
+pio_signal_set_txpending(struct can2040 *cd)
+{
+ pio_hw_t *pio_hw = cd->pio_hw;
+ pio_hw->irq_force = SI_TXPENDING >> 8;
+}
+
+// Clear the txpending flag
+static void
+pio_signal_clear_txpending(struct can2040 *cd)
+{
+ pio_hw_t *pio_hw = cd->pio_hw;
+ pio_hw->irq = SI_TXPENDING >> 8;
+}
+
+// Setup PIO state machines
+static void
+pio_sm_setup(struct can2040 *cd)
+{
+ // Reset state machines
+ pio_hw_t *pio_hw = cd->pio_hw;
+ pio_hw->ctrl = PIO_CTRL_SM_RESTART_BITS | PIO_CTRL_CLKDIV_RESTART_BITS;
+ pio_hw->fdebug = 0xffffffff;
+ pio_hw->irq = 0xff;
+ pio_signal_set_txpending(cd);
+
+ // Load pio program
+ uint32_t i;
+ for (i=0; iinstr_mem[i] = can2040_program_instructions[i];
+
+ // Set initial state machine state
+ pio_sync_setup(cd);
+ pio_rx_setup(cd);
+ pio_match_setup(cd);
+ pio_tx_setup(cd);
+
+ // Start state machines
+ pio_hw->ctrl = 0x07 << PIO_CTRL_SM_ENABLE_LSB;
+}
+
+// Initial setup of gpio pins and PIO state machines
+static void
+pio_setup(struct can2040 *cd, uint32_t sys_clock, uint32_t bitrate)
+{
+ // Configure pio0 clock
+ uint32_t rb = cd->pio_num ? RESETS_RESET_PIO1_BITS : RESETS_RESET_PIO0_BITS;
+ rp2040_clear_reset(rb);
+
+ // Setup and sync pio state machine clocks
+ pio_hw_t *pio_hw = cd->pio_hw;
+ uint32_t div = (256 / PIO_CLOCK_PER_BIT) * sys_clock / bitrate;
+ int i;
+ for (i=0; i<4; i++)
+ pio_hw->sm[i].clkdiv = div << PIO_SM0_CLKDIV_FRAC_LSB;
+
+ // Configure state machines
+ pio_sm_setup(cd);
+
+ // Map Rx/Tx gpios
+ uint32_t pio_func = cd->pio_num ? 7 : 6;
+ rp2040_gpio_peripheral(cd->gpio_rx, pio_func, 1);
+ rp2040_gpio_peripheral(cd->gpio_tx, pio_func, 0);
+}
+
+
+/****************************************************************
+ * CRC calculation
+ ****************************************************************/
+
+// Calculated 8-bit crc table (see scripts/crc.py)
+static const uint16_t crc_table[256] = {
+ 0x0000,0x4599,0x4eab,0x0b32,0x58cf,0x1d56,0x1664,0x53fd,0x7407,0x319e,
+ 0x3aac,0x7f35,0x2cc8,0x6951,0x6263,0x27fa,0x2d97,0x680e,0x633c,0x26a5,
+ 0x7558,0x30c1,0x3bf3,0x7e6a,0x5990,0x1c09,0x173b,0x52a2,0x015f,0x44c6,
+ 0x4ff4,0x0a6d,0x5b2e,0x1eb7,0x1585,0x501c,0x03e1,0x4678,0x4d4a,0x08d3,
+ 0x2f29,0x6ab0,0x6182,0x241b,0x77e6,0x327f,0x394d,0x7cd4,0x76b9,0x3320,
+ 0x3812,0x7d8b,0x2e76,0x6bef,0x60dd,0x2544,0x02be,0x4727,0x4c15,0x098c,
+ 0x5a71,0x1fe8,0x14da,0x5143,0x73c5,0x365c,0x3d6e,0x78f7,0x2b0a,0x6e93,
+ 0x65a1,0x2038,0x07c2,0x425b,0x4969,0x0cf0,0x5f0d,0x1a94,0x11a6,0x543f,
+ 0x5e52,0x1bcb,0x10f9,0x5560,0x069d,0x4304,0x4836,0x0daf,0x2a55,0x6fcc,
+ 0x64fe,0x2167,0x729a,0x3703,0x3c31,0x79a8,0x28eb,0x6d72,0x6640,0x23d9,
+ 0x7024,0x35bd,0x3e8f,0x7b16,0x5cec,0x1975,0x1247,0x57de,0x0423,0x41ba,
+ 0x4a88,0x0f11,0x057c,0x40e5,0x4bd7,0x0e4e,0x5db3,0x182a,0x1318,0x5681,
+ 0x717b,0x34e2,0x3fd0,0x7a49,0x29b4,0x6c2d,0x671f,0x2286,0x2213,0x678a,
+ 0x6cb8,0x2921,0x7adc,0x3f45,0x3477,0x71ee,0x5614,0x138d,0x18bf,0x5d26,
+ 0x0edb,0x4b42,0x4070,0x05e9,0x0f84,0x4a1d,0x412f,0x04b6,0x574b,0x12d2,
+ 0x19e0,0x5c79,0x7b83,0x3e1a,0x3528,0x70b1,0x234c,0x66d5,0x6de7,0x287e,
+ 0x793d,0x3ca4,0x3796,0x720f,0x21f2,0x646b,0x6f59,0x2ac0,0x0d3a,0x48a3,
+ 0x4391,0x0608,0x55f5,0x106c,0x1b5e,0x5ec7,0x54aa,0x1133,0x1a01,0x5f98,
+ 0x0c65,0x49fc,0x42ce,0x0757,0x20ad,0x6534,0x6e06,0x2b9f,0x7862,0x3dfb,
+ 0x36c9,0x7350,0x51d6,0x144f,0x1f7d,0x5ae4,0x0919,0x4c80,0x47b2,0x022b,
+ 0x25d1,0x6048,0x6b7a,0x2ee3,0x7d1e,0x3887,0x33b5,0x762c,0x7c41,0x39d8,
+ 0x32ea,0x7773,0x248e,0x6117,0x6a25,0x2fbc,0x0846,0x4ddf,0x46ed,0x0374,
+ 0x5089,0x1510,0x1e22,0x5bbb,0x0af8,0x4f61,0x4453,0x01ca,0x5237,0x17ae,
+ 0x1c9c,0x5905,0x7eff,0x3b66,0x3054,0x75cd,0x2630,0x63a9,0x689b,0x2d02,
+ 0x276f,0x62f6,0x69c4,0x2c5d,0x7fa0,0x3a39,0x310b,0x7492,0x5368,0x16f1,
+ 0x1dc3,0x585a,0x0ba7,0x4e3e,0x450c,0x0095
+};
+
+// Update a crc with 8 bits of data
+static uint32_t
+crc_byte(uint32_t crc, uint32_t data)
+{
+ return (crc << 8) ^ crc_table[((crc >> 7) ^ data) & 0xff];
+}
+
+// Update a crc with 8, 16, 24, or 32 bits of data
+static inline uint32_t
+crc_bytes(uint32_t crc, uint32_t data, uint32_t num)
+{
+ switch (num) {
+ default: crc = crc_byte(crc, data >> 24); /* FALLTHRU */
+ case 3: crc = crc_byte(crc, data >> 16); /* FALLTHRU */
+ case 2: crc = crc_byte(crc, data >> 8); /* FALLTHRU */
+ case 1: crc = crc_byte(crc, data);
+ }
+ return crc;
+}
+
+
+/****************************************************************
+ * Bit unstuffing
+ ****************************************************************/
+
+// Add 'count' number of bits from 'data' to the 'bu' unstuffer
+static void
+unstuf_add_bits(struct can2040_bitunstuffer *bu, uint32_t data, uint32_t count)
+{
+ uint32_t mask = (1 << count) - 1;
+ bu->stuffed_bits = (bu->stuffed_bits << count) | (data & mask);
+ bu->count_stuff = count;
+}
+
+// Reset state and set the next desired 'num_bits' unstuffed bits to extract
+static void
+unstuf_set_count(struct can2040_bitunstuffer *bu, uint32_t num_bits)
+{
+ bu->unstuffed_bits = 0;
+ bu->count_unstuff = num_bits;
+}
+
+// Clear bitstuffing state (used after crc field to avoid bitstuffing ack field)
+static void
+unstuf_clear_state(struct can2040_bitunstuffer *bu)
+{
+ uint32_t lb = 1 << bu->count_stuff;
+ bu->stuffed_bits = (bu->stuffed_bits & (lb - 1)) | (lb << 1);
+}
+
+// Restore raw bitstuffing state (used to undo unstuf_clear_state() )
+static void
+unstuf_restore_state(struct can2040_bitunstuffer *bu, uint32_t data)
+{
+ uint32_t cs = bu->count_stuff;
+ bu->stuffed_bits = (bu->stuffed_bits & ((1 << cs) - 1)) | (data << cs);
+}
+
+// Pull bits from unstuffer (as specified in unstuf_set_count() )
+static int
+unstuf_pull_bits(struct can2040_bitunstuffer *bu)
+{
+ uint32_t sb = bu->stuffed_bits, edges = sb ^ (sb >> 1);
+ uint32_t e2 = edges | (edges >> 1), e4 = e2 | (e2 >> 2), rm_bits = ~e4;
+ uint32_t cs = bu->count_stuff, cu = bu->count_unstuff;
+ if (!cs)
+ // Need more data
+ return 1;
+ for (;;) {
+ uint32_t try_cnt = cs > cu ? cu : cs;
+ for (;;) {
+ uint32_t try_mask = ((1 << try_cnt) - 1) << (cs + 1 - try_cnt);
+ if (likely(!(rm_bits & try_mask))) {
+ // No stuff bits in try_cnt bits - copy into unstuffed_bits
+ bu->count_unstuff = cu = cu - try_cnt;
+ bu->count_stuff = cs = cs - try_cnt;
+ bu->unstuffed_bits |= ((sb >> cs) & ((1 << try_cnt) - 1)) << cu;
+ if (! cu)
+ // Extracted desired bits
+ return 0;
+ break;
+ }
+ bu->count_stuff = cs = cs - 1;
+ if (rm_bits & (1 << (cs + 1))) {
+ // High bit is a stuff bit
+ if (unlikely(rm_bits & (1 << cs))) {
+ // Six consecutive bits - a bitstuff error
+ if (sb & (1 << cs))
+ return -1;
+ return -2;
+ }
+ break;
+ }
+ // High bit not a stuff bit - limit try_cnt and retry
+ bu->count_unstuff = cu = cu - 1;
+ bu->unstuffed_bits |= ((sb >> cs) & 1) << cu;
+ try_cnt /= 2;
+ }
+ if (likely(!cs))
+ // Need more data
+ return 1;
+ }
+}
+
+// Return most recent raw (still stuffed) bits
+static uint32_t
+unstuf_get_raw(struct can2040_bitunstuffer *bu)
+{
+ return bu->stuffed_bits >> bu->count_stuff;
+}
+
+
+/****************************************************************
+ * Bit stuffing
+ ****************************************************************/
+
+// Stuff 'num_bits' bits in '*pb' - upper bits must already be stuffed
+static uint32_t
+bitstuff(uint32_t *pb, uint32_t num_bits)
+{
+ uint32_t b = *pb, count = num_bits;
+ for (;;) {
+ uint32_t try_cnt = num_bits, edges = b ^ (b >> 1);
+ uint32_t e2 = edges | (edges >> 1), e4 = e2 | (e2 >> 2), add_bits = ~e4;
+ for (;;) {
+ uint32_t try_mask = ((1 << try_cnt) - 1) << (num_bits - try_cnt);
+ if (!(add_bits & try_mask)) {
+ // No stuff bits needed in try_cnt bits
+ if (try_cnt >= num_bits)
+ goto done;
+ num_bits -= try_cnt;
+ try_cnt = (num_bits + 1) / 2;
+ continue;
+ }
+ if (add_bits & (1 << (num_bits - 1))) {
+ // A stuff bit must be inserted prior to the high bit
+ uint32_t low_mask = (1 << num_bits) - 1, low = b & low_mask;
+ uint32_t high = (b & ~(low_mask >> 1)) << 1;
+ b = high ^ low ^ (1 << (num_bits - 1));
+ count += 1;
+ if (num_bits <= 4)
+ goto done;
+ num_bits -= 4;
+ break;
+ }
+ // High bit doesn't need stuff bit - accept it, limit try_cnt, retry
+ num_bits--;
+ try_cnt /= 2;
+ }
+ }
+done:
+ *pb = b;
+ return count;
+}
+
+// State storage for building bit stuffed transmit messages
+struct bitstuffer_s {
+ uint32_t prev_stuffed, bitpos, *buf;
+};
+
+// Push 'count' bits of 'data' into stuffer without performing bit stuffing
+static void
+bs_pushraw(struct bitstuffer_s *bs, uint32_t data, uint32_t count)
+{
+ uint32_t bitpos = bs->bitpos;
+ uint32_t wp = bitpos / 32, bitused = bitpos % 32, bitavail = 32 - bitused;
+ uint32_t *fb = &bs->buf[wp];
+ if (bitavail >= count) {
+ fb[0] |= data << (bitavail - count);
+ } else {
+ fb[0] |= data >> (count - bitavail);
+ fb[1] |= data << (32 - (count - bitavail));
+ }
+ bs->bitpos = bitpos + count;
+}
+
+// Push 'count' bits of 'data' into stuffer
+static void
+bs_push(struct bitstuffer_s *bs, uint32_t data, uint32_t count)
+{
+ data &= (1 << count) - 1;
+ uint32_t stuf = (bs->prev_stuffed << count) | data;
+ uint32_t newcount = bitstuff(&stuf, count);
+ bs_pushraw(bs, stuf, newcount);
+ bs->prev_stuffed = stuf;
+}
+
+// Pad final word of stuffer with high bits
+static uint32_t
+bs_finalize(struct bitstuffer_s *bs)
+{
+ uint32_t bitpos = bs->bitpos;
+ uint32_t words = DIV_ROUND_UP(bitpos, 32);
+ uint32_t extra = words * 32 - bitpos;
+ if (extra)
+ bs->buf[words - 1] |= (1 << extra) - 1;
+ return words;
+}
+
+
+/****************************************************************
+ * Transmit state tracking
+ ****************************************************************/
+
+// Transmit states (stored in cd->tx_state)
+enum {
+ TS_IDLE = 0, TS_QUEUED = 1, TS_ACKING_RX = 2, TS_CONFIRM_TX = 3
+};
+
+// Calculate queue array position from a transmit index
+static uint32_t
+tx_qpos(struct can2040 *cd, uint32_t pos)
+{
+ return pos % ARRAY_SIZE(cd->tx_queue);
+}
+
+// Queue the next message for transmission in the PIO
+static uint32_t
+tx_schedule_transmit(struct can2040 *cd)
+{
+ if (cd->tx_state == TS_QUEUED && !pio_tx_did_fail(cd))
+ // Already queued or actively transmitting
+ return 0;
+ uint32_t tx_pull_pos = cd->tx_pull_pos;
+ if (readl(&cd->tx_push_pos) == tx_pull_pos) {
+ // No new messages to transmit
+ cd->tx_state = TS_IDLE;
+ pio_signal_clear_txpending(cd);
+ __DMB();
+ if (likely(readl(&cd->tx_push_pos) == tx_pull_pos))
+ return SI_TXPENDING;
+ // Raced with can2040_transmit() - msg is now available for transmit
+ pio_signal_set_txpending(cd);
+ }
+ cd->tx_state = TS_QUEUED;
+ cd->stats.tx_attempt++;
+ struct can2040_transmit *qt = &cd->tx_queue[tx_qpos(cd, tx_pull_pos)];
+ pio_tx_send(cd, qt->stuffed_data, qt->stuffed_words);
+ return 0;
+}
+
+// Setup PIO state for ack injection
+static void
+tx_inject_ack(struct can2040 *cd, uint32_t match_key)
+{
+ cd->tx_state = TS_ACKING_RX;
+ pio_tx_inject_ack(cd, match_key);
+}
+
+// Check if the current parsed message is feedback from current transmit
+static int
+tx_check_local_message(struct can2040 *cd)
+{
+ if (cd->tx_state != TS_QUEUED)
+ return 0;
+ struct can2040_transmit *qt = &cd->tx_queue[tx_qpos(cd, cd->tx_pull_pos)];
+ struct can2040_msg *pm = &cd->parse_msg, *tm = &qt->msg;
+ if (tm->id == pm->id) {
+ if (qt->crc != cd->parse_crc || tm->dlc != pm->dlc
+ || tm->data32[0] != pm->data32[0] || tm->data32[1] != pm->data32[1])
+ // Message with same id that differs in content - an error
+ return -1;
+ // This is a self transmit
+ cd->tx_state = TS_CONFIRM_TX;
+ return 1;
+ }
+ return 0;
+}
+
+
+/****************************************************************
+ * Notification callbacks
+ ****************************************************************/
+
+// Report state flags (stored in cd->report_state)
+enum {
+ RS_NEED_EOF_FLAG = 1<<2,
+ // States
+ RS_IDLE = 0, RS_NEED_RX_ACK = 1, RS_NEED_TX_ACK = 2,
+ RS_NEED_RX_EOF = RS_NEED_RX_ACK | RS_NEED_EOF_FLAG,
+ RS_NEED_TX_EOF = RS_NEED_TX_ACK | RS_NEED_EOF_FLAG,
+};
+
+// Report error to calling code (via callback interface)
+static void
+report_callback_error(struct can2040 *cd, uint32_t error_code)
+{
+ struct can2040_msg msg = {};
+ cd->rx_cb(cd, CAN2040_NOTIFY_ERROR | error_code, &msg);
+}
+
+// Report a received message to calling code (via callback interface)
+static void
+report_callback_rx_msg(struct can2040 *cd)
+{
+ cd->stats.rx_total++;
+ cd->rx_cb(cd, CAN2040_NOTIFY_RX, &cd->parse_msg);
+}
+
+// Report a message that was successfully transmited (via callback interface)
+static void
+report_callback_tx_msg(struct can2040 *cd)
+{
+ writel(&cd->tx_pull_pos, cd->tx_pull_pos + 1);
+ cd->stats.tx_total++;
+ cd->rx_cb(cd, CAN2040_NOTIFY_TX, &cd->parse_msg);
+}
+
+// EOF phase complete - report message (rx or tx) to calling code
+static void
+report_handle_eof(struct can2040 *cd)
+{
+ if (cd->report_state & RS_NEED_EOF_FLAG) { // RS_NEED_xX_EOF
+ // Successfully processed a new message - report to calling code
+ pio_sync_normal_start_signal(cd);
+ if (cd->report_state == RS_NEED_TX_EOF)
+ report_callback_tx_msg(cd);
+ else
+ report_callback_rx_msg(cd);
+ }
+ cd->report_state = RS_IDLE;
+ pio_match_clear(cd);
+}
+
+// Check if message being processed is an rx message (not self feedback from tx)
+static int
+report_is_not_in_tx(struct can2040 *cd)
+{
+ return !(cd->report_state & RS_NEED_TX_ACK);
+}
+
+// Parser found a new message start
+static void
+report_note_message_start(struct can2040 *cd)
+{
+ pio_irq_set(cd, SI_MAYTX);
+}
+
+// Setup for ack injection (if receiving) or ack confirmation (if transmit)
+static int
+report_note_crc_start(struct can2040 *cd)
+{
+ int ret = tx_check_local_message(cd);
+ if (ret) {
+ if (ret < 0)
+ return -1;
+ // This is a self transmit - setup tx eof "matched" signal
+ cd->report_state = RS_NEED_TX_ACK;
+ uint32_t bits = (cd->parse_crc_bits << 9) | 0x0ff;
+ pio_match_check(cd, pio_match_calc_key(bits, cd->parse_crc_pos + 9));
+ return 0;
+ }
+
+ // Setup for ack inject (after rx fifos fully drained)
+ cd->report_state = RS_NEED_RX_ACK;
+ pio_signal_set_txpending(cd);
+ pio_irq_set(cd, SI_MAYTX | SI_TXPENDING);
+ return 0;
+}
+
+// Parser successfully found matching crc
+static void
+report_note_crc_success(struct can2040 *cd)
+{
+ if (cd->report_state == RS_NEED_TX_ACK)
+ // Enable "matched" irq for fast back-to-back transmit scheduling
+ pio_irq_set(cd, SI_MAYTX | SI_MATCHED);
+}
+
+// Parser found successful ack
+static void
+report_note_ack_success(struct can2040 *cd)
+{
+ if (cd->report_state == RS_IDLE)
+ // Got "matched" signal already
+ return;
+ // Transition RS_NEED_xX_ACK to RS_NEED_xX_EOF
+ cd->report_state |= RS_NEED_EOF_FLAG;
+}
+
+// Parser found successful EOF
+static void
+report_note_eof_success(struct can2040 *cd)
+{
+ if (cd->report_state == RS_IDLE)
+ // Got "matched" signal already
+ return;
+ report_handle_eof(cd);
+ pio_irq_set(cd, SI_TXPENDING);
+}
+
+// Parser found unexpected data on input
+static void
+report_note_discarding(struct can2040 *cd)
+{
+ if (cd->report_state != RS_IDLE) {
+ cd->report_state = RS_IDLE;
+ pio_match_clear(cd);
+ }
+ pio_sync_slow_start_signal(cd);
+ pio_irq_set(cd, SI_MAYTX | SI_TXPENDING);
+}
+
+// Received PIO rx "ackdone" irq
+static void
+report_line_ackdone(struct can2040 *cd)
+{
+ // Setup "matched" irq for fast rx callbacks
+ uint32_t bits = (cd->parse_crc_bits << 8) | 0x7f;
+ pio_match_check(cd, pio_match_calc_key(bits, cd->parse_crc_pos + 8));
+ // Schedule next transmit (so it is ready for next frame line arbitration)
+ uint32_t check_txpending = tx_schedule_transmit(cd);
+ pio_irq_set(cd, SI_MAYTX | SI_MATCHED | check_txpending);
+}
+
+// Received PIO "matched" irq
+static void
+report_line_matched(struct can2040 *cd)
+{
+ // A match event indicates an ack and eof are present
+ if (cd->report_state != RS_IDLE) {
+ // Transition RS_NEED_xX_ACK to RS_NEED_xX_EOF (if not already there)
+ cd->report_state |= RS_NEED_EOF_FLAG;
+ report_handle_eof(cd);
+ }
+ // Implement fast back-to-back tx scheduling (if applicable)
+ uint32_t check_txpending = tx_schedule_transmit(cd);
+ pio_irq_set(cd, check_txpending);
+}
+
+// Received 10+ passive bits on the line (between 10 and 17 bits)
+static void
+report_line_maytx(struct can2040 *cd)
+{
+ // Line is idle - may be unexpected EOF, missed ack injection,
+ // or missed "matched" signal.
+ if (cd->report_state != RS_IDLE)
+ report_handle_eof(cd);
+ uint32_t check_txpending = tx_schedule_transmit(cd);
+ pio_irq_set(cd, check_txpending);
+}
+
+// Schedule a transmit
+static void
+report_line_txpending(struct can2040 *cd)
+{
+ uint32_t pio_irqs = pio_irq_get(cd);
+ if (pio_irqs == (SI_MAYTX | SI_TXPENDING | SI_RX_DATA)
+ && cd->report_state == RS_NEED_RX_ACK) {
+ // Ack inject request from report_note_crc_start()
+ uint32_t mk = pio_match_calc_key(cd->parse_crc_bits, cd->parse_crc_pos);
+ tx_inject_ack(cd, mk);
+ pio_irq_set(cd, SI_MAYTX | SI_ACKDONE);
+ return;
+ }
+ // Tx request from can2040_transmit(), report_note_eof_success(),
+ // or report_note_discarding().
+ uint32_t check_txpending = tx_schedule_transmit(cd);
+ pio_irq_set(cd, (pio_irqs & ~SI_TXPENDING) | check_txpending);
+}
+
+
+/****************************************************************
+ * Input state tracking
+ ****************************************************************/
+
+// Parsing states (stored in cd->parse_state)
+enum {
+ MS_START, MS_HEADER, MS_EXT_HEADER, MS_DATA0, MS_DATA1,
+ MS_CRC, MS_ACK, MS_EOF0, MS_EOF1, MS_DISCARD
+};
+
+// Reset any bits in the incoming parsing state
+static void
+data_state_clear_bits(struct can2040 *cd)
+{
+ cd->raw_bit_count = cd->unstuf.stuffed_bits = cd->unstuf.count_stuff = 0;
+}
+
+// Transition to the next parsing state
+static void
+data_state_go_next(struct can2040 *cd, uint32_t state, uint32_t num_bits)
+{
+ cd->parse_state = state;
+ unstuf_set_count(&cd->unstuf, num_bits);
+}
+
+// Transition to the MS_DISCARD state - drop all bits until 6 passive bits
+static void
+data_state_go_discard(struct can2040 *cd)
+{
+ if (pio_rx_check_stall(cd)) {
+ // CPU couldn't keep up for some read data - must reset pio state
+ data_state_clear_bits(cd);
+ pio_sm_setup(cd);
+ report_callback_error(cd, 0);
+ }
+
+ data_state_go_next(cd, MS_DISCARD, 32);
+
+ // Clear report state and update hw irqs after transition to MS_DISCARD
+ report_note_discarding(cd);
+}
+
+// Note a data parse error and transition to discard state
+static void
+data_state_go_error(struct can2040 *cd)
+{
+ cd->stats.parse_error++;
+ data_state_go_discard(cd);
+}
+
+// Received six dominant bits on the line
+static void
+data_state_line_error(struct can2040 *cd)
+{
+ if (cd->parse_state == MS_DISCARD)
+ data_state_go_discard(cd);
+ else
+ data_state_go_error(cd);
+}
+
+// Received six unexpected passive bits on the line
+static void
+data_state_line_passive(struct can2040 *cd)
+{
+ if (cd->parse_state != MS_DISCARD && cd->parse_state != MS_START) {
+ // Bitstuff error
+ data_state_go_error(cd);
+ return;
+ }
+
+ uint32_t stuffed_bits = unstuf_get_raw(&cd->unstuf);
+ uint32_t dom_bits = ~stuffed_bits;
+ if (!dom_bits) {
+ // Counter overflow in "sync" state machine - reset it
+ data_state_clear_bits(cd);
+ pio_sm_setup(cd);
+ data_state_go_discard(cd);
+ return;
+ }
+
+ // Look for sof after 10 passive bits (most "PIO sync" will produce)
+ if (!(dom_bits & 0x3ff)) {
+ data_state_go_next(cd, MS_START, 1);
+ return;
+ }
+
+ data_state_go_discard(cd);
+}
+
+// Transition to MS_CRC state - await 16 bits of crc
+static void
+data_state_go_crc(struct can2040 *cd)
+{
+ cd->parse_crc &= 0x7fff;
+
+ // Calculate raw stuffed bits after crc and crc delimiter
+ uint32_t crcstart_bitpos = cd->raw_bit_count - cd->unstuf.count_stuff - 1;
+ uint32_t crc_bits = (unstuf_get_raw(&cd->unstuf) << 15) | cd->parse_crc;
+ uint32_t crc_bitcount = bitstuff(&crc_bits, 15 + 1) - 1;
+ cd->parse_crc_bits = (crc_bits << 1) | 0x01; // Add crc delimiter
+ cd->parse_crc_pos = crcstart_bitpos + crc_bitcount + 1;
+
+ int ret = report_note_crc_start(cd);
+ if (ret) {
+ data_state_go_error(cd);
+ return;
+ }
+ data_state_go_next(cd, MS_CRC, 16);
+}
+
+// Transition to MS_DATA0 state (if applicable) - await data bits
+static void
+data_state_go_data(struct can2040 *cd, uint32_t id, uint32_t data)
+{
+ if (data & (0x03 << 4)) {
+ // Not a supported header
+ data_state_go_discard(cd);
+ return;
+ }
+ cd->parse_msg.data32[0] = cd->parse_msg.data32[1] = 0;
+ uint32_t dlc = data & 0x0f;
+ cd->parse_msg.dlc = dlc;
+ if (data & (1 << 6)) {
+ dlc = 0;
+ id |= CAN2040_ID_RTR;
+ }
+ cd->parse_msg.id = id;
+ if (dlc)
+ data_state_go_next(cd, MS_DATA0, dlc >= 4 ? 32 : dlc * 8);
+ else
+ data_state_go_crc(cd);
+}
+
+// Handle reception of first bit of header (after start-of-frame (SOF))
+static void
+data_state_update_start(struct can2040 *cd, uint32_t data)
+{
+ cd->parse_msg.id = data;
+ report_note_message_start(cd);
+ data_state_go_next(cd, MS_HEADER, 17);
+}
+
+// Handle reception of next 17 header bits
+static void
+data_state_update_header(struct can2040 *cd, uint32_t data)
+{
+ data |= cd->parse_msg.id << 17;
+ if ((data & 0x60) == 0x60) {
+ // Extended header
+ cd->parse_msg.id = data;
+ data_state_go_next(cd, MS_EXT_HEADER, 20);
+ return;
+ }
+ cd->parse_crc = crc_bytes(0, data, 3);
+ data_state_go_data(cd, (data >> 7) & 0x7ff, data);
+}
+
+// Handle reception of additional 20 bits of "extended header"
+static void
+data_state_update_ext_header(struct can2040 *cd, uint32_t data)
+{
+ uint32_t hdr1 = cd->parse_msg.id;
+ uint32_t crc = crc_bytes(0, hdr1 >> 4, 2);
+ cd->parse_crc = crc_bytes(crc, ((hdr1 & 0x0f) << 20) | data, 3);
+ uint32_t id = (((hdr1 << 11) & 0x1ffc0000) | ((hdr1 << 13) & 0x3e000)
+ | (data >> 7) | CAN2040_ID_EFF);
+ data_state_go_data(cd, id, data);
+}
+
+// Handle reception of first 1-4 bytes of data content
+static void
+data_state_update_data0(struct can2040 *cd, uint32_t data)
+{
+ uint32_t dlc = cd->parse_msg.dlc, bits = dlc >= 4 ? 32 : dlc * 8;
+ cd->parse_crc = crc_bytes(cd->parse_crc, data, dlc);
+ cd->parse_msg.data32[0] = __builtin_bswap32(data << (32 - bits));
+ if (dlc > 4)
+ data_state_go_next(cd, MS_DATA1, dlc >= 8 ? 32 : (dlc - 4) * 8);
+ else
+ data_state_go_crc(cd);
+}
+
+// Handle reception of bytes 5-8 of data content
+static void
+data_state_update_data1(struct can2040 *cd, uint32_t data)
+{
+ uint32_t dlc = cd->parse_msg.dlc, bits = dlc >= 8 ? 32 : (dlc - 4) * 8;
+ cd->parse_crc = crc_bytes(cd->parse_crc, data, dlc - 4);
+ cd->parse_msg.data32[1] = __builtin_bswap32(data << (32 - bits));
+ data_state_go_crc(cd);
+}
+
+// Handle reception of 16 bits of message CRC (15 crc bits + crc delimiter)
+static void
+data_state_update_crc(struct can2040 *cd, uint32_t data)
+{
+ if (((cd->parse_crc << 1) | 1) != data) {
+ data_state_go_error(cd);
+ return;
+ }
+
+ report_note_crc_success(cd);
+ unstuf_clear_state(&cd->unstuf);
+ data_state_go_next(cd, MS_ACK, 2);
+}
+
+// Handle reception of 2 bits of ack phase (ack, ack delimiter)
+static void
+data_state_update_ack(struct can2040 *cd, uint32_t data)
+{
+ if (data != 0x01) {
+ // Undo unstuf_clear_state() for correct SOF detection in
+ // data_state_line_passive()
+ unstuf_restore_state(&cd->unstuf, (cd->parse_crc_bits << 2) | data);
+
+ data_state_go_error(cd);
+ return;
+ }
+ report_note_ack_success(cd);
+ data_state_go_next(cd, MS_EOF0, 4);
+}
+
+// Handle reception of first four end-of-frame (EOF) bits
+static void
+data_state_update_eof0(struct can2040 *cd, uint32_t data)
+{
+ if (data != 0x0f || pio_rx_check_stall(cd)) {
+ data_state_go_error(cd);
+ return;
+ }
+ unstuf_clear_state(&cd->unstuf);
+ data_state_go_next(cd, MS_EOF1, 5);
+}
+
+// Handle reception of end-of-frame (EOF) bits 5-7 and first two IFS bits
+static void
+data_state_update_eof1(struct can2040 *cd, uint32_t data)
+{
+ if (data == 0x1f) {
+ // Success
+ report_note_eof_success(cd);
+ data_state_go_next(cd, MS_START, 1);
+ } else if (data >= 0x1c || (data >= 0x18 && report_is_not_in_tx(cd))) {
+ // Message fully transmitted - followed by "overload frame"
+ report_note_eof_success(cd);
+ data_state_go_discard(cd);
+ } else {
+ data_state_go_error(cd);
+ }
+}
+
+// Handle data received while in MS_DISCARD state
+static void
+data_state_update_discard(struct can2040 *cd, uint32_t data)
+{
+ data_state_go_discard(cd);
+}
+
+// Update parsing state after reading the bits of the current field
+static void
+data_state_update(struct can2040 *cd, uint32_t data)
+{
+ switch (cd->parse_state) {
+ case MS_START: data_state_update_start(cd, data); break;
+ case MS_HEADER: data_state_update_header(cd, data); break;
+ case MS_EXT_HEADER: data_state_update_ext_header(cd, data); break;
+ case MS_DATA0: data_state_update_data0(cd, data); break;
+ case MS_DATA1: data_state_update_data1(cd, data); break;
+ case MS_CRC: data_state_update_crc(cd, data); break;
+ case MS_ACK: data_state_update_ack(cd, data); break;
+ case MS_EOF0: data_state_update_eof0(cd, data); break;
+ case MS_EOF1: data_state_update_eof1(cd, data); break;
+ case MS_DISCARD: data_state_update_discard(cd, data); break;
+ }
+}
+
+
+/****************************************************************
+ * Input processing
+ ****************************************************************/
+
+// Process incoming data from PIO "rx" state machine
+static void
+process_rx(struct can2040 *cd, uint32_t rx_data)
+{
+ unstuf_add_bits(&cd->unstuf, rx_data, PIO_RX_WAKE_BITS);
+ cd->raw_bit_count += PIO_RX_WAKE_BITS;
+
+ // undo bit stuffing
+ for (;;) {
+ int ret = unstuf_pull_bits(&cd->unstuf);
+ if (likely(ret > 0)) {
+ // Need more data
+ break;
+ } else if (likely(!ret)) {
+ // Pulled the next field - process it
+ data_state_update(cd, cd->unstuf.unstuffed_bits);
+ } else {
+ if (ret == -1)
+ // 6 consecutive high bits
+ data_state_line_passive(cd);
+ else
+ // 6 consecutive low bits
+ data_state_line_error(cd);
+ }
+ }
+}
+
+// Main API irq notification function
+void
+can2040_pio_irq_handler(struct can2040 *cd)
+{
+ pio_hw_t *pio_hw = cd->pio_hw;
+ uint32_t ints = pio_hw->ints0;
+ while (likely(ints & SI_RX_DATA)) {
+ uint32_t rx_data = pio_hw->rxf[1];
+ process_rx(cd, rx_data);
+ ints = pio_hw->ints0;
+ if (likely(!ints))
+ return;
+ }
+
+ if (ints & SI_ACKDONE)
+ // Ack of received message completed successfully
+ report_line_ackdone(cd);
+ else if (ints & SI_MATCHED)
+ // Transmit message completed successfully
+ report_line_matched(cd);
+ else if (ints & SI_MAYTX)
+ // Bus is idle, but not all bits may have been flushed yet
+ report_line_maytx(cd);
+ else if (ints & SI_TXPENDING)
+ // Schedule a transmit
+ report_line_txpending(cd);
+}
+
+
+/****************************************************************
+ * Transmit queuing
+ ****************************************************************/
+
+// API function to check if transmit space available
+int
+can2040_check_transmit(struct can2040 *cd)
+{
+ uint32_t tx_pull_pos = readl(&cd->tx_pull_pos);
+ uint32_t tx_push_pos = cd->tx_push_pos;
+ uint32_t pending = tx_push_pos - tx_pull_pos;
+ return pending < ARRAY_SIZE(cd->tx_queue);
+}
+
+// API function to transmit a message
+int
+can2040_transmit(struct can2040 *cd, struct can2040_msg *msg)
+{
+ uint32_t tx_pull_pos = readl(&cd->tx_pull_pos);
+ uint32_t tx_push_pos = cd->tx_push_pos;
+ uint32_t pending = tx_push_pos - tx_pull_pos;
+ if (pending >= ARRAY_SIZE(cd->tx_queue))
+ // Tx queue full
+ return -1;
+
+ // Copy msg into transmit queue
+ struct can2040_transmit *qt = &cd->tx_queue[tx_qpos(cd, tx_push_pos)];
+ uint32_t id = msg->id;
+ if (id & CAN2040_ID_EFF)
+ qt->msg.id = id & ~0x20000000;
+ else
+ qt->msg.id = id & (CAN2040_ID_RTR | 0x7ff);
+ qt->msg.dlc = msg->dlc & 0x0f;
+ uint32_t data_len = qt->msg.dlc > 8 ? 8 : qt->msg.dlc;
+ if (qt->msg.id & CAN2040_ID_RTR)
+ data_len = 0;
+ qt->msg.data32[0] = qt->msg.data32[1] = 0;
+ memcpy(qt->msg.data, msg->data, data_len);
+
+ // Calculate crc and stuff bits
+ uint32_t crc = 0;
+ memset(qt->stuffed_data, 0, sizeof(qt->stuffed_data));
+ struct bitstuffer_s bs = { 1, 0, qt->stuffed_data };
+ uint32_t edlc = qt->msg.dlc | (qt->msg.id & CAN2040_ID_RTR ? 0x40 : 0);
+ if (qt->msg.id & CAN2040_ID_EFF) {
+ // Extended header
+ uint32_t id = qt->msg.id;
+ uint32_t h1 = ((id & 0x1ffc0000) >> 11) | 0x60 | ((id & 0x3e000) >> 13);
+ uint32_t h2 = ((id & 0x1fff) << 7) | edlc;
+ crc = crc_bytes(crc, h1 >> 4, 2);
+ crc = crc_bytes(crc, ((h1 & 0x0f) << 20) | h2, 3);
+ bs_push(&bs, h1, 19);
+ bs_push(&bs, h2, 20);
+ } else {
+ // Standard header
+ uint32_t hdr = ((qt->msg.id & 0x7ff) << 7) | edlc;
+ crc = crc_bytes(crc, hdr, 3);
+ bs_push(&bs, hdr, 19);
+ }
+ uint32_t i;
+ for (i=0; imsg.data[i];
+ crc = crc_byte(crc, v);
+ bs_push(&bs, v, 8);
+ }
+ qt->crc = crc & 0x7fff;
+ bs_push(&bs, qt->crc, 15);
+ bs_pushraw(&bs, 1, 1);
+ qt->stuffed_words = bs_finalize(&bs);
+
+ // Submit
+ writel(&cd->tx_push_pos, tx_push_pos + 1);
+
+ // Wakeup if in TS_IDLE state
+ __DMB();
+ pio_signal_set_txpending(cd);
+
+ return 0;
+}
+
+
+/****************************************************************
+ * Setup
+ ****************************************************************/
+
+// API function to initialize can2040 code
+void
+can2040_setup(struct can2040 *cd, uint32_t pio_num)
+{
+ memset(cd, 0, sizeof(*cd));
+ cd->pio_num = !!pio_num;
+ cd->pio_hw = cd->pio_num ? pio1_hw : pio0_hw;
+}
+
+// API function to configure callback
+void
+can2040_callback_config(struct can2040 *cd, can2040_rx_cb rx_cb)
+{
+ cd->rx_cb = rx_cb;
+}
+
+// API function to start CANbus interface
+void
+can2040_start(struct can2040 *cd, uint32_t sys_clock, uint32_t bitrate
+ , uint32_t gpio_rx, uint32_t gpio_tx)
+{
+ cd->gpio_rx = gpio_rx;
+ cd->gpio_tx = gpio_tx;
+ data_state_clear_bits(cd);
+ pio_setup(cd, sys_clock, bitrate);
+ data_state_go_discard(cd);
+}
+
+// API function to stop can2040 code
+void
+can2040_stop(struct can2040 *cd)
+{
+ pio_irq_disable(cd);
+ pio_sm_setup(cd);
+}
+
+// API function to access can2040 statistics
+void
+can2040_get_statistics(struct can2040 *cd, struct can2040_stats *stats)
+{
+ for (;;) {
+ memcpy(stats, &cd->stats, sizeof(*stats));
+ if (memcmp(stats, &cd->stats, sizeof(*stats)) == 0)
+ // Successfully copied data
+ return;
+ // Raced with irq handler update - retry copy
+ }
+}
diff --git a/firmware/lib/can2040/src/can2040.h b/firmware/lib/can2040/src/can2040.h
new file mode 100644
index 0000000..7dbee11
--- /dev/null
+++ b/firmware/lib/can2040/src/can2040.h
@@ -0,0 +1,86 @@
+#ifndef _CAN2040_H
+#define _CAN2040_H
+
+#include // uint32_t
+
+struct can2040_msg {
+ uint32_t id;
+ uint32_t dlc;
+ union {
+ uint8_t data[8];
+ uint32_t data32[2];
+ };
+};
+
+enum {
+ CAN2040_ID_RTR = 1<<30,
+ CAN2040_ID_EFF = 1<<31,
+};
+
+enum {
+ CAN2040_NOTIFY_RX = 1<<20,
+ CAN2040_NOTIFY_TX = 1<<21,
+ CAN2040_NOTIFY_ERROR = 1<<23,
+};
+struct can2040;
+typedef void (*can2040_rx_cb)(struct can2040 *cd, uint32_t notify
+ , struct can2040_msg *msg);
+
+struct can2040_stats {
+ uint32_t rx_total, tx_total;
+ uint32_t tx_attempt;
+ uint32_t parse_error;
+};
+
+void can2040_setup(struct can2040 *cd, uint32_t pio_num);
+void can2040_callback_config(struct can2040 *cd, can2040_rx_cb rx_cb);
+void can2040_start(struct can2040 *cd, uint32_t sys_clock, uint32_t bitrate
+ , uint32_t gpio_rx, uint32_t gpio_tx);
+void can2040_stop(struct can2040 *cd);
+void can2040_get_statistics(struct can2040 *cd, struct can2040_stats *stats);
+void can2040_pio_irq_handler(struct can2040 *cd);
+int can2040_check_transmit(struct can2040 *cd);
+int can2040_transmit(struct can2040 *cd, struct can2040_msg *msg);
+
+
+/****************************************************************
+ * Internal definitions
+ ****************************************************************/
+
+struct can2040_bitunstuffer {
+ uint32_t stuffed_bits, count_stuff;
+ uint32_t unstuffed_bits, count_unstuff;
+};
+
+struct can2040_transmit {
+ struct can2040_msg msg;
+ uint32_t crc, stuffed_words, stuffed_data[5];
+};
+
+struct can2040 {
+ // Setup
+ uint32_t pio_num;
+ void *pio_hw;
+ uint32_t gpio_rx, gpio_tx;
+ can2040_rx_cb rx_cb;
+ struct can2040_stats stats;
+
+ // Bit unstuffing
+ struct can2040_bitunstuffer unstuf;
+ uint32_t raw_bit_count;
+
+ // Input data state
+ uint32_t parse_state;
+ uint32_t parse_crc, parse_crc_bits, parse_crc_pos;
+ struct can2040_msg parse_msg;
+
+ // Reporting
+ uint32_t report_state;
+
+ // Transmits
+ uint32_t tx_state;
+ uint32_t tx_pull_pos, tx_push_pos;
+ struct can2040_transmit tx_queue[4];
+};
+
+#endif // can2040.h
diff --git a/firmware/src/main.cpp b/firmware/src/main.cpp
index 305396e..4aeaa64 100644
--- a/firmware/src/main.cpp
+++ b/firmware/src/main.cpp
@@ -4,6 +4,7 @@
#include "sd.h"
#include "leds.h"
#include "gfx_decoder.h"
+#include "can2040.h"
void loadVideo(size_t index);