From 0a656a4a84f920194958d339d61ed567eba9c03c Mon Sep 17 00:00:00 2001 From: Javier Date: Tue, 29 Sep 2026 23:40:31 +0200 Subject: initial import --- .gitignore | 6 + COPYING | 674 +++++++++++++++++++++++++++++++++++++++++++ README.md | 83 ++++++ ch375.h | 423 +++++++++++++++++++++++++++ chud.c | 418 +++++++++++++++++++++++++++ chudinit.c | 221 +++++++++++++++ chudisk.c | 896 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ chudisk.h | 90 ++++++ chudisk.lnk | 4 + cio.c | 147 ++++++++++ cio.h | 31 ++ dlog.h | 359 +++++++++++++++++++++++ inc/bda.h | 67 +++++ inc/bpb.h | 83 ++++++ inc/dosapi.h | 182 ++++++++++++ inc/dosdrv.h | 319 +++++++++++++++++++++ inc/dosint.h | 250 ++++++++++++++++ inc/mbr.h | 46 +++ inc/sassert.h | 8 + makefile | 67 +++++ test.c | 489 ++++++++++++++++++++++++++++++++ usb.h | 47 +++ utils.h | 60 ++++ 23 files changed, 4970 insertions(+) create mode 100644 .gitignore create mode 100644 COPYING create mode 100644 README.md create mode 100644 ch375.h create mode 100644 chud.c create mode 100644 chudinit.c create mode 100644 chudisk.c create mode 100644 chudisk.h create mode 100644 chudisk.lnk create mode 100644 cio.c create mode 100644 cio.h create mode 100644 dlog.h create mode 100644 inc/bda.h create mode 100644 inc/bpb.h create mode 100644 inc/dosapi.h create mode 100644 inc/dosdrv.h create mode 100644 inc/dosint.h create mode 100644 inc/mbr.h create mode 100644 inc/sassert.h create mode 100644 makefile create mode 100644 test.c create mode 100644 usb.h create mode 100644 utils.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e25cf3b --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +*.obj +*.exe +*.err +*.com +*.sys +*.map 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. + 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/README.md b/README.md new file mode 100644 index 0000000..7a30ef9 --- /dev/null +++ b/README.md @@ -0,0 +1,83 @@ +This is a DOS disk driver for the CH375 "USB ISA adapter", mostly designed with the Pocket386/Book386 in mind. + +There is already a good number of drivers out there, but as far as I can see they are all derivatives of the original one, +and I got tired of all the obscure hangs and crashes. This driver is in OpenWatcom C and written from scratch +using the datasheets, so it has a (hopefully different) new repertoire of bugs to play with. + +Some features: + +* Can support multiple partitions. You can either show multiple drive letters (the number of drive letters is fixed at boot, though) +and/or dynamically switch a single drive letter to a different partition from the command prompt. +This does wonders to workaround the FAT16 2GG limit, as you can define a dozen FAT16 partitions and switch. + +* On DOSes which support FAT32, can optionally show FAT32 partitions to the DOS. + +* I mostly ignore CHS addressing and focus on LBA. This makes it way more capable of handling non-DOS formatted USB pendrives, +and is generally less of a pain. In theory this allows disks of up to 2TB (be mindful of partition size limits though). +If DOS asks for geometry, it gives whatever is on your current partition. + +* Supports just enough IOCTLs to make DOS 6.x format.com "work" +(only to re-format existing partitions, since it will simply re-use geometry from whatever FAT is already there). +Note this is a DOS-level driver, so FDISK won't work (which expects a BIOS-level driver). + +* Build is for 386+, tested on pocket386/book386, but source builds on 8086. + +* Extensive (not included by default) verbose log over serial port. + +As usual, this driver is in OpenWatcom C, do not expect it to beat +any benchmark in speed or memory usage, but it gets around. About 400KB/s on the Book386, which is the same +I get with other drivers anyway; and around 7KiB of memory usage (the official driver sits at 4KiB). +Hopefully much easier to experiment with than with the official one. + +# Download + + + +# Installation + +```` +DEVICE=CHUDISK.SYS [options] +```` + +## CHUDISK.SYS configuration options + +Current options: + +* /P260 : IO port for CH375 (defaults to 0x260, as on the pocket386) + +* /N1 : number of drive letters to allocate (defaults to just 1). +Each drive letter will by default be mapped to a different partition in order. + +* /R : read-only mode. Writes to disk will fail. + +* /3 : show FAT32 partitions to the OS. Useful for OSes with native FAT32 support like FreeDOS. + + +# Usage + +The program CHUD.EXE can be used to switch a CHUDISK.SYS managed drive letter to a different partition. +E.g. + +```` +C:\> CHUD D: + + Index Type Label Size + [1] fat16 USBPART1 1996 MB + [2] fat16 USBPART2 1996 MB + [3] fat32 USBPARTBIG 4726 MB +Select partition in [1..3] range: +```` + +Extended partitions, W95/LBA partitions are supported. Of course you can only select FAT16 partitions, +and perhaps FAT32 ones if lucky (DOS7.1, FreeDOS, etc.) or forced with /3. + +Note the drive letters <-> partitions mapping is not persistent, and will in fact be reset if you reboot +or disconnect the USB drive. + +# Building + +Tested with OpenWatcom 2, build from any OS where OpenWatcom runs. + +```` + wmake all +```` diff --git a/ch375.h b/ch375.h new file mode 100644 index 0000000..a1ff1b0 --- /dev/null +++ b/ch375.h @@ -0,0 +1,423 @@ +/* + * CH375 hardware header + * Copyright (C) 2024 Javier S. Pedro + * + * 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 . + */ + + +#ifndef CH375_H +#define CH375_H + +#include +#include +#include +#include + +#include "usb.h" + +extern unsigned short ch375_port; + +enum { + CH375_PORT_DATA = 0, + CH375_PORT_CMD = 1, +}; + +enum ch375_command { + /** Returns chip and firmware version in bit 5-0. + * output: 1byte. + * C375B is 0x37. */ + CH375_GET_IC_VERSION = 0x01, + /** (Host mode) Set serial port baud rate. */ + CH375_SET_BAUDRATE = 0x02, + /** Enter low power mode. Wakes up with USB or host activity. */ + CH375_ENTER_SLEEP = 0x03, + /** Manualy force USB speed. + * Input: 1 byte: + * 0: Full speed + * 1: Full speed with low speed clock frequency (??) + * 2: Low speed */ + CH375_SET_USB_SPEED = 0x04, + /** Hardware reset. May take up to 40ms. */ + CH375_RESET = 0x05, + /** Simple eco function. Returns input byte negated. + * Input: 1 byte: x + * Output: 1 byte: ~x */ + CH375_CHECK_EXIST = 0x06, + + CH375_READ_REG = 0x0A, + CH375_WRITE_REG = 0x0B, + /** Sets a 100us timer. + * Output: infinite bytes. 0 while timer not expired, non-0 when expired. */ + CH375_DELAY_100US = 0x0F, + /** (Device mode) set our USB vid and PID. + * Input: 4 bytes: VID LSB, VID MSB, PID LSB, PID MSB */ + CH375_SET_USB_ID = 0x12, + /** (Device mode) set USB address. ?? */ + CH375_SET_USB_ADDR = 0x13, + /** Set USB mode. Usually takes 20µs. + * Input: 1 byte: + * 0 : Device mode disabled (i.e. device plug-in detection) + * 1 : Device mode with external firmware + * 2 : Device mode with built-in firmware + * 4 : Host mode disabled (i.e. device plug-in detection) + * 5 : Host mode without automatic SOF packets. + * 6 : Host mode with automatic SOF packets. + * 7 : Host mode, initiate bus reset + * Output: 1 byte: + * CMD_RET_SUCCESS if OK + * CMD_RET_ABORT, etc. if error + */ + CH375_SET_USB_MODE = 0x15, + /** (Host mode) Check the connection status. + * Output: 1 byte: either USB_INT_CONNECT or USB_INT_DISCONNECT or USB_INT_USB_READY. */ + CH375_TEST_CONNECT = 0x16, + /** Abandon retrying and return NAK. */ + CH375_ABORT_NAK = 0x17, + + CH375_SET_ENDP2 = 0x18, + CH375_SET_ENDP3 = 0x19, + CH375_SET_ENDP4 = 0x1A, + CH375_SET_ENDP5 = 0x1B, + CH375_SET_ENDP6 = 0x1C, + CH375_SET_ENDP7 = 0x1D, + + /** Get interrupt status and ack pending interrupts. + * Output: 1 byte */ + CH375_GET_INT_STATUS = 0x22, + /** (Device mode) Release current USB buffer. */ + CH375_UNLOCK_USB = 0x23, + /** Read buffer of endpoint of current interrupt. + * Output: length byte + data. */ + CH375_RD_USB_DATA0 = 0x27, + /** Equivalent to RD_USB_DATA0 + UNLOCK_USB. */ + CH375_RD_USB_DATA = 0x28, + CH375_WR_USB_DATA3 = 0x29, + CH375_WR_USB_DATA5 = 0x2A, + CH375_WR_USB_DATA7 = 0x2B, + /** (Host mode) Clear error state on endpoint. + * Input: 1 byte: endpoint number. + * On done: Triggers interrupt. */ + CH375_CLR_STALL = 0x41, + /** (Host mode) Set USB address. + * Input: USB address. + * On done: Triggers interrupt. */ + CH375_SET_ADDRESS = 0x45, + CH375_GET_DESCR = 0x46, + CH375_SET_CONFIG = 0x49, + CH375_AUTO_SETUP = 0x4D, + CH375_ISSUE_TKN_X = 0x4E, + CH375_ISSUE_TOKEN = 0x4F, + + CH375_DISK_BOC = 0x50, + CH375_DISK_INIT = 0x51, + CH375_DISK_RESET = 0x52, + CH375_DISK_SIZE = 0x53, + CH375_DISK_READ = 0x54, + CH375_DISK_RD_GO = 0x55, + CH375_DISK_WRITE = 0x56, + CH375_DISK_WR_GO = 0x57, + CH375_DISK_INQUIRY = 0x58, + CH375_DISK_READY = 0x59, + CH375_DISK_R_SENSE = 0x5A, +}; + +enum ch375_cmd_ret { + CH375_RET_SUCESS = 0x51, + CH375_RET_ABORT = 0x5F +}; + +enum ch375_int { + /** if (x & mask) == val, this is a USB device mode interrupt. */ + CH375_INT_DEVICE_MASK = 0xF0, + CH375_INT_DEVICE_VAL = 0x00, + + CH375_INT_HOST_MASK = 0xE0, + CH375_INT_HOST_VAL = 0x20, + + CH375_INT_BUS_RESET1 = 0x03, + CH375_INT_BUS_RESET2 = 0x07, + CH375_INT_BUS_RESET3 = 0x0B, + CH375_INT_BUS_RESET4 = 0x0F, + + /** USB bus suspend event. */ + CH375_INT_USB_SUSPEND = 0x05, + /** Wakeup from USB suspend. */ + CH375_INT_USB_WAKE_UP = 0x06, + CH375_INT_USB_SUCCESS = 0x14, + CH375_INT_USB_CONNECT = 0x15, + CH375_INT_USB_DISCONNECT = 0x16, + CH375_INT_USB_BUF_OVER = 0x17, + CH375_INT_USB_READY = 0x18, + CH375_INT_USB_DISK_READ = 0x1D, + CH375_INT_USB_DISK_WRITE = 0x1E, + CH375_INT_USB_DISK_ERR = 0x1F, +}; + +static inline void ch375_iodelay(void) +{ + // Doesn't look to be required on pocket386 + //outp(0x80, 0); +} + +static inline uint8_t ch375_read_data(void) +{ + return inp(ch375_port + CH375_PORT_DATA); +} + +static inline void ch375_write_data(uint8_t data) +{ + outp(ch375_port + CH375_PORT_DATA, data); + ch375_iodelay(); +} + +static inline void ch375_send_command(enum ch375_command cmd) +{ + outp(ch375_port + CH375_PORT_CMD, cmd); + ch375_iodelay(); +} + +/// True if interrupt line is currently active (i.e. low) +static inline bool ch375_poll_interrupt(void) +{ + return !(inp(ch375_port + CH375_PORT_CMD) & 0x80); +} + +enum CH375_REG { + /** (Host mode) Get data rate of current USB device. + * Bit 4: if 1= Low Speed. if 0 = Full Speed.*/ + CH375_REG_DEV_RATE = 0x0A, + /** (Device mode): how to check USB bus suspend status. + * 0: Do not check + * 4: Check at 50ms intervals + * 5: Check at 10ms intervals */ + CH375_REG_CHK_SUSPEND = 0x10, + CH375_REG_TOGGLE = 0x1A, + + /** ??? + * Bit 5 : set after disk is online? but never unset... */ + CH375_REG_DISK_STATUS = 0x20, + /** (Host mode) Set the number of retries for USB transactions. + * If bit 7 is 0, no retry is performed when NAK is received. + * If bit 7 is 1 and bit 6 is 0, unlimited retries are performed when NAK is received. + * If bit 7 is 1 and bit 6 is 1, the maximum retry is 2 seconds when NAK is received. + * Bits 5-0 are the number of retries after timeout. */ + CH375_REG_RETRY = 0x25, + /** (Host disk mode) Set the current LUN. */ + CH375_REG_DISK_LUN = 0x34, + CH375_REG_DISK_MAX_LUN = 0x38, + /** (Host disk mode) Set the total number of 64-byte packets per sector. + * E.g. 8 = 512 byte sectors. */ + CH375_REG_DISK_PKT_P_SEC = 0x39, + /// Drive letter (in ASCII) currently assigned. This is set by software. + CH375_REG_DISK_NAME = 0x3E + + // 0x1B what's on this register ? 0x7F , 0x80 values seen + // 0x20 ?? some type of status ? + // 0x31, 0x32, 0x33 ?? + +}; + +static uint8_t ch375_read_reg(enum CH375_REG reg) +{ + ch375_send_command(CH375_READ_REG); + ch375_write_data(reg); + return ch375_read_data(); +} + +static void ch375_write_reg(enum CH375_REG reg, uint8_t value) +{ + ch375_send_command(CH375_WRITE_REG); + ch375_write_data(reg); + ch375_write_data(value); +} + +/** Reads one transfer block (64 bytes max). */ +#if _M_IX86 >= 200 +// Watcom does not seem able to synthesize rep ins/outs. Do it in 286+ mode. +static uint8_t ch375_read_data_block(uint8_t far *buffer); +#pragma aux ch375_read_data_block = \ + "mov dx, [ch375_port]" \ + "in al, dx" \ + "movzx cx, al" \ + "rep ins byte ptr es:[di], dx" \ + __parm [es di] \ + __value [al] \ + __modify exact [cx dx di] +#else +static uint8_t ch375_read_data_block(uint8_t far *buffer) +{ + uint8_t i, n = ch375_read_data(); + + for (i = 0; i < n; i++) { + buffer[i] = ch375_read_data(); + } + + return n; +} +#endif + +#if _M_IX86 >= 200 +static void ch375_write_data_block(uint8_t far * buffer, uint8_t n); +#pragma aux ch375_write_data_block = \ + "mov dx, [ch375_port]" \ + "out dx, al" \ + "movzx cx, al" \ + "rep outs dx, byte ptr es:[si]" \ + __parm [es si] [al] \ + __modify exact [cx dx si] +#else +static void ch375_write_data_block(uint8_t far * buffer, uint8_t n) +{ + uint8_t i; + + ch375_write_data(n); + + for (i = 0; i < n; i++) { + ch375_write_data(buffer[i]); + } +} +#endif + +// GLOBAL COMMANDS + +static inline uint8_t ch375_get_version(void) +{ + ch375_send_command(CH375_GET_IC_VERSION); + return ch375_read_data() & 0x3F; +} + +static inline void ch375_enter_sleep(void) +{ + ch375_send_command(CH375_ENTER_SLEEP); +} + +static inline void ch375_reset(void) +{ + ch375_send_command(CH375_RESET); +} + +static inline uint8_t ch375_check_exists(uint8_t val) +{ + ch375_send_command(CH375_CHECK_EXIST); + ch375_write_data(val); + return ch375_read_data(); +} + +static inline uint8_t ch375_get_int_status(void) +{ + ch375_send_command(CH375_GET_INT_STATUS); + return ch375_read_data(); +} + +enum ch375_usb_mode { + CH375_USB_MODE_DEVICE_DISABLED = 0, + CH375_USB_MODE_DEVICE_EXTERNAL_FIRMWARE = 1, + CH375_USB_MODE_DEVICE_INTERNAL_FIRMWARE = 2, + CH375_USB_MODE_HOST_DISABLED = 4, + CH375_USB_MODE_HOST = 5, + CH375_USB_MODE_HOST_AUTO_SOF = 6, + CH375_USB_MODE_HOST_RESET = 7 +}; + +static void ch375_set_usb_mode(enum ch375_usb_mode mode) { + ch375_send_command(CH375_SET_USB_MODE); + ch375_write_data(mode); +} + +enum ch375_usb_speed { + CH375_USB_SPEED_FULL = 0, + CH375_USB_SPEED_LOW = 2 +}; + +// Seems to be for CH375B only. See below for CH375A alternative. +static void ch375_set_usb_speed(enum ch375_usb_speed speed) { + ch375_send_command(CH375_SET_USB_SPEED); + ch375_write_data(speed); +} + +static void ch375a_set_low_speed(void) { + // Undocumented. + ch375_write_reg(0x17, 0xd8); +} + +// HOST COMMANDS + +static void ch375_test_connect(void) { + ch375_send_command(CH375_TEST_CONNECT); +} + +static void ch375_auto_setup(void) { + ch375_send_command(CH375_AUTO_SETUP); +} + +enum ch375_retry_mode { + CH375_RETRY_NAK_INFINITE = 0x80, + CH375_RETRY_NAK_2S = 0xC0, + CH375_RETRY_NAK_NONE = 0x00, + + CH375_RETRY_TIMEOUT_MAX = 0x1F +}; + +static void ch375_set_retry(enum ch375_retry_mode mode) { + ch375_write_reg(CH375_REG_RETRY, mode); +} + +static void ch375_get_descriptor(usb_descriptor_type type) { + ch375_send_command(CH375_GET_DESCR); + ch375_write_data(type); +} + +// DISK COMMANDS + +enum ch375_reg_disk_status { + CH375_REG_DISK_STATUS_READY = 0x20 +}; + +static inline bool ch375_is_disk_ready(void) +{ + return ch375_read_reg(CH375_REG_DISK_STATUS) & CH375_REG_DISK_STATUS_READY; +} + +static void ch375_disk_init() +{ + ch375_send_command(CH375_DISK_INIT); +} + +static void ch375_disk_read(uint32_t lba, uint8_t nsectors) +{ + ch375_send_command(CH375_DISK_READ); + ch375_write_data((lba >> 0) & 0xFF); + ch375_write_data((lba >> 8) & 0xFF); + ch375_write_data((lba >> 16) & 0xFF); + ch375_write_data((lba >> 24) & 0xFF); + ch375_write_data(nsectors); +} + +static void ch375_disk_write(uint32_t lba, uint8_t nsectors) +{ + ch375_send_command(CH375_DISK_WRITE); + ch375_write_data((lba >> 0) & 0xFF); + ch375_write_data((lba >> 8) & 0xFF); + ch375_write_data((lba >> 16) & 0xFF); + ch375_write_data((lba >> 24) & 0xFF); + ch375_write_data(nsectors); +} + +static void ch375_test_disk_ready(void) +{ + ch375_send_command(CH375_DISK_READY); +} + +#endif diff --git a/chud.c b/chud.c new file mode 100644 index 0000000..c6d728c --- /dev/null +++ b/chud.c @@ -0,0 +1,418 @@ +/* + * CHU - driver for CH375 in disk mode + * Copyright (C) 2024 Javier S. Pedro + * + * 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 . + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "inc/mbr.h" +#include "inc/dosdrv.h" + +#include "chudisk.h" + +uint16_t ch375_port; + +bool read_only; +bool show_fat32; + +uint8_t drive; +uint32_t partition_start; +uint32_t partition_len; + +#define MAX_PARTITIONS 32 +struct partinfo { + uint32_t start_sector; + uint32_t num_sectors; + uint8_t type; +} partinfo[MAX_PARTITIONS]; +unsigned int num_parts; + +static int ioctl_read_control(uint8_t drive, void *buffer, int len) +{ + union REGS regs; + regs.h.ah = DOS_IOCTL; + regs.h.al = 0x04; // Read control string from block device + regs.x.bx = drive; + regs.x.cx = len; + regs.x.dx = FP_OFF(buffer); + + intdos(®s, ®s); + + if (regs.x.cflag) { + return -1; + } else { + return regs.x.ax; + } +} + +static int ioctl_write_control(uint8_t drive, void *buffer, int len) +{ + union REGS regs; + regs.h.ah = DOS_IOCTL; + regs.h.al = 0x05; // Write control string to block device + regs.x.bx = drive; + regs.x.cx = len; + regs.x.dx = FP_OFF(buffer); + + intdos(®s, ®s); + + if (regs.x.cflag) { + return -1; + } else { + return regs.x.ax; + } +} + +static int ioctl_read_abs_sector(uint8_t drive, void *buffer, uint32_t sector, int sectors) +{ + CHUDISK_IOCTL_DISK_DATA ciod; + union REGS regs; + + ciod.rwabs.buffer = buffer; + ciod.rwabs.sector = sector; + ciod.rwabs.sectors = sectors; + + regs.h.ah = DOS_IOCTL; + regs.h.al = 0x0D; // IOCTL for block devices + regs.x.bx = drive; + regs.h.ch = DOS_IOCTL_DISK; + regs.h.cl = CHUDISK_IOCTL_DISK_READ_ABS_SECTOR; + regs.x.dx = FP_OFF(&ciod); + + intdos(®s, ®s); + + return regs.x.cflag ? -1 : 0; +} + +static void dos_disk_reset() +{ + union REGS regs; + regs.h.ah = 0x0D; // DOS DISK RESET + + intdos(®s, ®s); +} + +static int parse_chudisk_control_string(const char *b, int len) +{ + // Not sure why I'm doing it this way instead of just sharing a pointer. + int i = 0; +#if 0 + printf("control string:\n"); + for (i = 0; i < len; i+=8) { + printf(" %hx %hx %hx %hx %hx %hx %hx %hx\n", + b[i+0], b[i+1], b[i+2], b[i+3], b[i+4], b[i+5], b[i+6], b[i+7]); + } + i = 0; +#endif + while (i < len) { + char c = b[i++]; + switch (c) { + case 'B': + memcpy(&ch375_port, &b[i], sizeof(ch375_port)); + i+=sizeof(ch375_port); + break; + case '3': + show_fat32 = b[i++]; + break; + case 'R': + read_only = b[i++]; + break; + case 'S': + memcpy(&partition_start, &b[i], sizeof(partition_start)); + i+=sizeof(partition_start); + break; + case 'L': + memcpy(&partition_len, &b[i], sizeof(partition_len)); + i+=sizeof(partition_len); + break; + case '\0': + return 0; + default: + fprintf(stderr, "Unidentified control string parameter: '%c'\n", c); + return -1; + } + } + + return 0; +} + +static bool is_selectable_partition(const MBR_PARTENTRY *partentry) +{ + return partentry->type == MBR_FAT12 || partentry->type == MBR_FAT16_32MB + || partentry->type == MBR_FAT16 || partentry->type == MBR_FAT16_LBA + || (show_fat32 && (partentry->type == MBR_FAT32 || partentry->type == MBR_FAT32_LBA)); +} + +static const char *get_partition_type(const MBR_PARTENTRY *partentry) +{ + static char buffer[8]; + switch (partentry->type) { + case MBR_EMPTY: + return "invalid"; + case MBR_FAT12: + return "fat12"; + case MBR_FAT16_32MB: + case MBR_FAT16: + case MBR_FAT16_LBA: + return "fat16"; + case MBR_IFS: + return "ntfs"; + case MBR_FAT32: + case MBR_FAT32_LBA: + return "fat32"; + case MBR_EXT: + case MBR_EXT_LBA: + return "extended"; + case MBR_LINUX: + case MBR_LINUX_SWAP: + return "linux"; + default: + sprintf(buffer, "%#X", partentry->type); + return buffer; + } +} + + +static const char * show_partition_size(const MBR_PARTENTRY *partentry) +{ + static char buffer[12]; + uint32_t size = partentry->lbaLen / 2; + STATIC_ASSERT(SECTOR_SIZE == 512); + + if (size <= 10000) { + sprintf(buffer, "%lu KB", size); + return buffer; + } + + size /= 1024; + if (size <= 10000) { + sprintf(buffer, "%lu MB", size); + return buffer; + } + + size /= 1024; + + sprintf(buffer, "%lu GB", size); + return buffer; +} + +static const char *get_partition_label(const MBR_PARTENTRY *partentry, const uint32_t start_sector) +{ + static char buffer[SECTOR_SIZE]; + DOS_BPB *bpb = (DOS_BPB*) &buffer[DOS_BPB_OFFSET_ON_DISK]; + + switch (partentry->type) { + // Focus on well-known types for now + case MBR_FAT12: + case MBR_FAT16_32MB: + case MBR_FAT16: + case MBR_FAT16_LBA: + case MBR_FAT32: + case MBR_FAT32_LBA: + break; + default: + return " "; + } + + if (ioctl_read_abs_sector(drive, buffer, start_sector, 1) != 0) { + fprintf(stderr, "while reading partition boot record at %lu: %s\n", start_sector, strerror(errno)); + return " ???? "; + } + + if (bpb->sectorsPerFAT != 0) { + // Assume FAT16 + return bpb->fat16.volumeLabel; + } else { + // Assume FAT32 + return bpb->fat32.volumeLabel; + } +} + +static void print_partition(const uint32_t mbr_sector, const MBR_PARTENTRY *partentry, bool selectable) +{ + const bool ebr = mbr_sector != 0; + const uint32_t start_sector = mbr_sector + partentry->lbaFirst; + const bool is_current = partition_start == start_sector; + const char *typeLabel = get_partition_type(partentry); + const char *volumeLabel = get_partition_label(partentry, start_sector); + const char *sizeLabel = show_partition_size(partentry); + + if (partentry->type == MBR_EMPTY) { + // Skip empty partitions no matter what + return; + } + if (ebr && (partentry->type == MBR_EXT || partentry->type == MBR_EXT_LBA)) { + // Skip displaying EXT partitions EBR, noisy + return; + } + + if (selectable) { + const unsigned index = num_parts + 1; + + printf(" %c[%2u] %8s %-11.11s %10s \n", + is_current ? '*' : ' ', index, typeLabel, volumeLabel, sizeLabel); + } else { + printf(" %c[ ] %8s %-11.11s %10s \n", + is_current ? '*' : ' ', typeLabel, volumeLabel, sizeLabel); + } + +} + +static int scan_disk_partitions() +{ + static char buffer[SECTOR_SIZE]; + uint32_t next_sector = 0; + + printf(" Index %8s %-11.11s %10s \n", + "Type", "Label", "Size"); + + // Start with MBR at sector 0 + next_sector = 0; + do { + const uint32_t this_sector = next_sector; + const MBR_PARTENTRY *partentry; + int i; + + // Try to read sector + if (ioctl_read_abs_sector(drive, buffer, this_sector, 1) != 0) { + fprintf(stderr, "while reading %s at disk sector %lu: %s\n", + this_sector == 0 ? "MBR" : "EBR", + this_sector, strerror(errno)); + // Fatal for MBR, non-fatal for EBR + if (this_sector == 0) { + fprintf(stderr, "is the disk present?\n"); + return -1; + } + break; + } + + // Check for signature + if (*(uint16_t*)&buffer[MBR_SIGNATURE_OFFSET_ON_DISK] != 0xAA55U) { + fprintf(stderr, "on disk sector %lu: invalid MBR signature %x\n", + this_sector, *(uint16_t*)&buffer[MBR_SIGNATURE_OFFSET_ON_DISK]); + if (this_sector == 0) return -1; + break; + } + + // Parse the MBR + partentry = (MBR_PARTENTRY*)&buffer[MBR_PARTENTRY_OFFSET_ON_DISK]; + + next_sector = 0; // If there is another EBR we will store it here + for (i = 0; i < 4 && num_parts < MAX_PARTITIONS; i++) { + bool is_selectable = is_selectable_partition(&partentry[i]); + + print_partition(this_sector, &partentry[i], is_selectable); + + if (is_selectable) { + partinfo[num_parts].type = partentry[i].type; + partinfo[num_parts].start_sector = this_sector + partentry[i].lbaFirst; + partinfo[num_parts].num_sectors = partentry[i].lbaLen; + num_parts++; + } + if (partentry[i].type == MBR_EXT || partentry[i].type == MBR_EXT_LBA) { + // Go to the EBR next + next_sector = this_sector + partentry[i].lbaFirst; + } + } + } while (next_sector != 0 && num_parts < MAX_PARTITIONS); + + return 0; +} + +static void usage() +{ + printf("Usage: chud X:, where X is a drive letter handled by CHUDISK.SYS\n"); +} + +int main(int argc, const char *argv[]) +{ + static char buffer[16]; + int i; + unsigned part; + + for (i = 1; i < argc; i++) { + // Drive letter? + if (argv[i][0] >= 'A' && argv[i][0] <= 'Z' && argv[i][1] == ':') { + drive = 1 + argv[i][0] - 'A'; + } else if (argv[i][0] >= 'a' && argv[i][0] <= 'z' && argv[i][1] == ':') { + drive = 1 + argv[i][0] - 'a'; + } + } + + // Now read the driver settings and current partition + i = ioctl_read_control(drive, buffer, sizeof(buffer)); + if (i < 0) { + perror("ioctl_read_control"); + usage(); + return EXIT_FAILURE; + } + + if (parse_chudisk_control_string(buffer, i)) { + fprintf(stderr, "wrong IOCTL string returned by driver\n"); + usage(); + return EXIT_FAILURE; + } + + if (scan_disk_partitions() != 0) { + return EXIT_FAILURE; + } + if (num_parts == 0) { + fprintf(stderr, "No partitions found on the disk\n"); + return EXIT_FAILURE; + } + + printf("Select partition in [1..%u] range: ", num_parts); + i = scanf("%u", &part); + + if (i != 1) { + // Assume cancel + return EXIT_FAILURE; + } + + if (part == 0 || part > num_parts) { + fprintf(stderr, "Invalid partition %u\n", part); + return EXIT_FAILURE; + } + + printf("Switching drive to partition %u at offset %lu size %lu\n", part, + partinfo[part-1].start_sector, partinfo[part-1].num_sectors); + + dos_disk_reset(); // Flush caches before we swap the drive... + + i = 0; + buffer[i++] = 'S'; + memcpy(&buffer[i], &partinfo[part-1].start_sector, sizeof(uint32_t)); + i+=sizeof(uint32_t); + buffer[i++] = 'L'; + memcpy(&buffer[i], &partinfo[part-1].num_sectors, sizeof(uint32_t)); + i+=sizeof(uint32_t); + buffer[i] = '\0'; + + if (ioctl_write_control(drive, buffer, i) < i) { + perror("ioctl_write_control"); + return EXIT_FAILURE; + } + + // The above IOCTL will also cause the next mediacheck from DOS to return changed. + + return EXIT_SUCCESS; +} diff --git a/chudinit.c b/chudinit.c new file mode 100644 index 0000000..1919100 --- /dev/null +++ b/chudinit.c @@ -0,0 +1,221 @@ +/* + * CHU - driver for CH375 in disk mode + * Copyright (C) 2024 Javier S. Pedro + * + * 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 . + */ + + +#include +#include + +#include "inc/dosapi.h" +#include "inc/dosint.h" +#include "inc/bda.h" + +#include "chudisk.h" +#include "ch375.h" +#include "dlog.h" +#include "cio.h" +#include "utils.h" + +static int parse_int(const char far * far *s) +{ + int i = 0; + while (**s >= '0' && **s <= '9') { + i = (i * 10) + (**s - '0'); + (*s)++; + } + if (**s == ' ' || **s == '\r' || **s == '\n') { + return i; + } else { + return -1; + } +} + +static int parse_hex(const char far * far *s) +{ + int i = 0; + while ((**s >= '0' && **s <= '9') || (**s >= 'A' && **s <= 'F') || (**s >= 'a' && **s <= 'f')) { + if (**s >= '0' && **s <= '9') i = (i * 16) + (**s - '0'); + else if (**s >= 'A' && **s <= 'F') i = (i * 16) + (**s - 'A'); + else if (**s >= 'a' && **s <= 'f') i = (i * 16) + (**s - 'a'); + (*s)++; + } + if (**s == ' ' || **s == '\r' || **s == '\n') { + return i; + } else { + return -1; + } +} + +static bool parse_cmdline(const char far *cmdline) +{ + // Source command line string + // E.g. DEVICE.SYS /N3\r\n + const char far *s = cmdline; + + // Skip filename part (search for first sep) + while (*s != ' ' && *s != '\r' && *s != '\n') { s++; } + if (*s == '\r' || *s == '\n') return true; // No arguments + // Now skip whitespace + while (*s == ' ') { s++; } + + // Now handle options like /N3 /X4 + while (*s != '\r' && *s != '\n') { + char c = *s++, opt; + int num; + switch (c) { + case '/': + opt = *s++; + switch (opt) { + case 'N': + case 'n': // number of units + num = parse_int(&s); + if (num > 0 && num <= MAX_UNITS) { + num_units = num; + } else { + c_printf("invalid value '%d' for option '%c'\n", num, opt); + return false; + } + break; + case 'P': + case 'p': // IO port + num = parse_hex(&s); + if (num > 0) { + ch375_port = num; + } else { + c_printf("invalid value '%d' for option '%c'\n", num, opt); + return false; + } + break; + case 'R': + case 'r': // Read only + read_only = true; + break; + case '3': // Show FAT32 partitions + show_fat32 = true; + break; + default: + c_printf("invalid option '%c'\n", opt); + return false; + } + break; + case ' ': + break; + default: + c_printf("invalid syntax '%c'\n", c); + return false; + } + } + + dprintf("Configured num drives: %hu\n", num_units); + + return true; +} + +static void fill_initial_bpb(DOS_BPB *bpb) +{ + // Dummy, only used during driver init + // Most likely these values can be anything you want, + // as long as it remotely looks like a valid FAT16 BPB + bpb->bytesPerSector = 512; + bpb->sectorsPerCluster = 1; + bpb->reservedSectors = 0; + bpb->numberOfFATs = 2; + bpb->rootDirEntries = 16; + bpb->numberOfSectors = 512; + bpb->mediaType = DOS_BPB_MEDIA_HDD; + bpb->sectorsPerFAT = 1; + bpb->sectorsPerTrack = 63; + bpb->numberOfHeads = 255; + bpb->hiddenSectors = 0; + bpb->numberOfSectorsLarge = 0; + memcpy(bpb->fat16.volumeLabel, "NO NAME ", 11); +} + +void driver_init(DOS_DRS __far *drs) +{ + unsigned i; + uint16_t dos_version; + uint8_t dos_major, dos_minor; + uint8_t hw_version; + + dlog_init(); + + // Defaults + ch375_port = 0x260; + num_units = 1; + read_only = false; + show_fat32 = false; + + // If DOS > 7.1, enable FAT32 by default + dos_version = dos_get_version(); + dos_major = dos_version & 0xFF; + dos_minor = (dos_version >> 8) & 0xFF; + dprintf("DOS version %d.%d\n", dos_major, dos_minor); + if (dos_major > 7 || (dos_major == 7 && dos_minor >= 10)) { + show_fat32 = true; + } + + // Parse command line arguments + if (!parse_cmdline(drs->cmd.init.in.cmdline)) { + c_puts("CHUDISK: Syntax error in cmdline arguments"); + goto fail; + } + + // Try to initialize CH375 + dputs("CH375 reset..."); + ch375_reset(); + bda_wait_ticks(3); // wait 100-150ms + dputs("CH375 reset wait done"); + + if (ch375_check_exists(0xA5) != (uint8_t)~0xA5) { + c_printf("CHUDISK: CH375 not detected at @%x", ch375_port); + goto fail; + } + + hw_version = ch375_get_version(); + + // Do not really set up the chip until it is used + ch375_set_usb_mode(CH375_USB_MODE_HOST_DISABLED); + ch375_enter_sleep(); + + data.ready = false; + data.sectors = 0; + data.bytesPerSector = 0; + + // Build the template BPBs + drs->cmd.init.out.number_units = num_units; + for (i = 0; i < num_units; i++) { + fill_initial_bpb(&data.unit[i].bpb); + data.bpb_ptrs[i] = &data.unit[i].bpb; + } + drs->cmd.init.out.bpbs = data.bpb_ptrs; + drs->cmd.init.out.break_addr = MK_FP(get_cs(), FP_OFF(&resident_end)); + drs->status = DOS_DD_STATUS_DONE; + + c_printf("CHUDISK v.0 (HW v.%x), drives", hw_version); + for (i = 0; i < num_units; i++) { + c_printf(" %c:", drive_index_to_letter(drs->cmd.init.in.first_drive_number + i)); + } + c_putc('\n'); + + return; +fail: + drs->status = DOS_DD_STATUS_DONE | DOS_DD_STATUS_ERROR | DOS_DD_ERR_GENERAL_FAILURE; + drs->cmd.init.out.number_units = 0; + drs->cmd.init.out.break_addr = MK_FP(get_cs(), 0); // Deallocate everything + return; +} diff --git a/chudisk.c b/chudisk.c new file mode 100644 index 0000000..24de25e --- /dev/null +++ b/chudisk.c @@ -0,0 +1,896 @@ +/* + * CHU - driver for CH375 in disk mode + * Copyright (C) 2024 Javier S. Pedro + * + * 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 . + */ + + +#include +#include + +#include "inc/dosdrv.h" +#include "inc/bda.h" +#include "inc/mbr.h" + +#include "chudisk.h" +#include "ch375.h" +#include "dlog.h" +#include "utils.h" + +// Pre-declarations for the two driver routines, note there is a pragma aux for them +DOS_DD_STRATEGY strategy_routine; +DOS_DD_INTERRUPT interrupt_routine; + +/** This is the actual .SYS header! */ +const DOS_DD_HEADER __based(__segname("_CODE")) header = { + MK_FP(-1, -1), + DOS_DD_BLOCK | DOS_BLOCK_SUPPORT_32BIT_ADDRESSES + | DOS_BLOCK_FORMAT_NON_IBM | DOS_BLOCK_SUPPORT_REMOVABLE_MEDIA + | DOS_DD_SUPPORT_IOCTL_RW + | DOS_BLOCK_SUPPORT_IOCTL_GENERIC | DOS_DD_SUPPORT_IOCTL_QUERY, + strategy_routine, + interrupt_routine, + "\1CHUDISK" +}; + +/** Strategy routine saves DRS here for interrupt routine to use */ +DOS_DRS far * saved_drs; + +// Some settings +/** The ch375 io port base. */ +unsigned short ch375_port; +/** Number of units handled by the driver (i.e. number of drive letters reserved. ) */ +unsigned char num_units; +/** Read-only mode (as if write-protected floppy) */ +bool read_only; +/** Process FAT32 partitions too. */ +bool show_fat32; + +/* Runtime data for the driver. */ +struct chudisk_data data; + +/** Buffer used to load boot sectors from disk and partitions. */ +char buffer[512]; + +/** Waits for the CH375 to generate an interrupt, returns result value. + * @param max_ticks max BIOS ticks to wait for interrupt. */ +uint8_t wait_for_ch375_result(unsigned int max_ticks) +{ + uint16_t last = bda_get_tick_count_lo(); + while (!ch375_poll_interrupt() && max_ticks > 0) { + uint16_t now = bda_get_tick_count_lo(); + if (now != last) { + last = now; + max_ticks--; + } + } + if (ch375_poll_interrupt()) { + uint8_t status = ch375_get_int_status(); + //("CH375 INT status=0x%x\n", status); + return status; + } else { + dprintf("CH375 int timeout\n"); + return 0; + } +} + +/** Gets the disk sector from RW command DRS. */ +static inline uint32_t get_start_sector(const DOS_DRS far * drs) +{ + return (drs->cmd.rw.start_sector == 0xFFFF + ? drs->cmd.rw.start_sector_huge + : drs->cmd.rw.start_sector); +} + +static inline uint32_t chs_to_lba(const DOS_BPB * bpb, uint16_t cylinder, uint16_t head, uint16_t sector) +{ + uint16_t track = cylinder * bpb->numberOfHeads + head; + return mul(track, bpb->sectorsPerTrack) + (sector - 1); +} + +/** Read N sectors from the disk + * @return number of sectors read + */ +static unsigned disk_read_sectors(uint8_t far *buffer, uint32_t lba, uint8_t num) +{ + uint8_t result; + unsigned total = 0; // Total bytes written + + dprintf("disk read buf=%Fp sector=%lu num=%u\n", buffer, lba, num); + + // Initiate read operation + ch375_disk_read(lba, num); + + // Now keep going as long as ch375 says to keep going + while ((result = wait_for_ch375_result(10)) == CH375_INT_USB_DISK_READ) { + unsigned len; + + // Sanity check + if (total / SECTOR_SIZE >= num) { + dputs("read overflow"); + break; + } + + ch375_send_command(CH375_RD_USB_DATA); + len = ch375_read_data_block(&buffer[total]); + + //dprintf(" disk read data block len = %d\n", len); + + if (len == 0) { + // Done? + break; + } + + total += len; + + // Continue + ch375_send_command(CH375_DISK_RD_GO); + } + + dprintf(" disk read total bytes = %u, sectors = %u, final status = 0x%hx\n", + total, total / SECTOR_SIZE, result); + + return total / SECTOR_SIZE; +} + +/** Write N sectors to the disk + * @return number of sectors written + */ +static unsigned disk_write_sectors(uint8_t far *buffer, uint32_t lba, uint8_t num) +{ + uint8_t result; + unsigned total = 0; // Total bytes written + + dprintf("disk write buf=%Fp sector=%lu num=%u\n", buffer, lba, num); + + // Initiate operation + ch375_disk_write(lba, num); + + // Now keep going as long as ch375 says to keep going + while ((result = wait_for_ch375_result(10)) == CH375_INT_USB_DISK_WRITE) { + const unsigned len = 64; + + // Sanity check + if (total / SECTOR_SIZE >= num) { + dputs("write overflow"); + break; + } + + ch375_send_command(CH375_WR_USB_DATA7); + ch375_write_data_block(&buffer[total], len); + + total += len; + + // Continue + ch375_send_command(CH375_DISK_WR_GO); + } + + dprintf(" disk write total bytes = %u, sectors = %u, final status = 0x%hx\n", + total, total / SECTOR_SIZE, result); + + return total / SECTOR_SIZE; +} + +/** Enables CH375 USB host mode, initializes "disk" mode on it + * and connects to a disk. */ +static bool disk_connect() +{ + int tries; + + dputs("switch to usb host"); + ch375_set_usb_mode(CH375_USB_MODE_HOST_AUTO_SOF); + if (wait_for_ch375_result(4) != CH375_INT_USB_CONNECT) { + dputs("could not turn on usb host"); + return false; + } + + dputs("try init disk"); + ch375_disk_init(); + if (wait_for_ch375_result(20) != CH375_INT_USB_SUCCESS) { + dputs("could not init disk"); + return false; + } + + // looks like we have to keep polling by asking "is the disk ready?" + // even if each time we ask we are already polling + tries = 3; + while (tries-- > 0) { + ch375_test_disk_ready(); + if (wait_for_ch375_result(20) == CH375_INT_USB_SUCCESS) { + dputs("disk now init"); + return true; + } + bda_wait_tick(); + } + + dputs("disk failed to init"); + return false; +} + +/** Scans the disk for partitions. */ +static int disk_scan() +{ + uint32_t next_sector; + int num_parts, i; + + dprintf("disk scan show_fat32=%d\n", show_fat32); + + // Clear current partitions + for (i = 0; i < num_units; ++i) { + data.unit[i].exists = false; + data.unit[i].ready = false; + data.unit[i].start_sector = 0; + data.unit[i].sectors = 0; + } + + // Refresh disk size + ch375_send_command(CH375_DISK_SIZE); + if (wait_for_ch375_result(4) != CH375_INT_USB_SUCCESS) { + return DOS_DD_ERR_MEDIA_UNAVAILABLE; + } + + ch375_send_command(CH375_RD_USB_DATA); + if (ch375_read_data_block(buffer) < 8) { + dprintf("disk size command return less than 8 bytes\n"); + return DOS_DD_ERR_UNKNOWN_MEDIA; + } + + data.sectors = SWAPNC_32(*(uint32_t*)&buffer[0]); + data.bytesPerSector = SWAPNC_32(*(uint32_t*)&buffer[4]); + + dprintf("sectors %lu bytesPerSector %lu\n", data.sectors, data.bytesPerSector); + if (data.bytesPerSector != SECTOR_SIZE) { + return DOS_DD_ERR_UNKNOWN_MEDIA; + } + + // Start creating partitions/units from partition tables + num_parts = 0; + + // Start with MBR at sector 0 + next_sector = 0; + do { + const MBR_PARTENTRY *partentry; + const uint32_t this_sector = next_sector; + + dprintf("reading boot record at sector %lu\n", this_sector); + + // Try to read sector + if (disk_read_sectors(buffer, this_sector, 1) != 1) { + // Fatal for MBR, non-fatal for EBR + if (this_sector == 0) return DOS_DD_ERR_READ_FAULT; + break; + } + + // Check for signature + if (*(uint16_t*)&buffer[510] != 0xAA55U) { + dprintf(" invalid MBR signature %x\n", *(uint16_t*)&buffer[510]); + if (this_sector == 0) return DOS_DD_ERR_UNKNOWN_MEDIA; + break; + } + + // Parse the MBR + partentry = (MBR_PARTENTRY*)&buffer[446]; + + next_sector = 0; // If there is another EBR we will store it here + for (i = 0; i < 4 && num_parts < MAX_UNITS; i++) { + dprintf(" partition %d type %x start %lu len %lu\n", i, partentry[i].type, partentry[i].lbaFirst, partentry[i].lbaLen); + + if (partentry[i].type == MBR_FAT12 || partentry[i].type == MBR_FAT16_32MB + || partentry[i].type == MBR_FAT16 || partentry[i].type == MBR_FAT16_LBA + || (show_fat32 && (partentry[i].type == MBR_FAT32 || partentry[i].type == MBR_FAT32_LBA)) ) { + data.unit[num_parts].exists = true; + data.unit[num_parts].start_sector = this_sector + partentry[i].lbaFirst; + data.unit[num_parts].sectors = partentry[i].lbaLen; + dprintf(" added as unit %u starts at %lu\n", num_parts, data.unit[num_parts].start_sector); + num_parts++; + } else if (partentry[i].type == MBR_EXT || partentry[i].type == MBR_EXT_LBA) { + // Go to the EBR next + next_sector = this_sector + partentry[i].lbaFirst; + } + } + } while (next_sector != 0 && num_parts < MAX_UNITS); + + // OK! + dprintf("found %u partitions\n", num_parts); + data.ready = true; + + return 0; +} + +static int disk_init() +{ + ch375_test_disk_ready(); + if (wait_for_ch375_result(4) != CH375_INT_USB_SUCCESS) { + // Disk is not even connected, try to connect + if (!disk_connect()) { + // Nothing works: fail + return DOS_DD_ERR_DRIVE_NOT_READY; + } + } + // Disk is now ready: initiate scan for partitions + return disk_scan(); +} + +/** Return the volume label from the cached BPB, i.e. from the last time the drive was accessed. */ +static inline const char * unit_get_volume_label(uint8_t unit) +{ + const DOS_BPB *bpb = &data.unit[unit].bpb; + + if (bpb->sectorsPerFAT != 0) { + // FAT16 + return bpb->fat16.volumeLabel; + } else { + // FAT32 + return bpb->fat32.volumeLabel; + } +} + +/** Try to initialize logigcal drive 'unit'. This also initializes the entire disk + * if it was not done yet (scanning all partitions). + * It will read the BPB of the corresponding partition and cache it. */ +static int unit_init(uint8_t unit) +{ + DOS_BPB *bpb = &data.unit[unit].bpb; + int err; + + // Check if disk is ready, and initialize it if not + if (!data.ready) { + if (err = disk_init()) { + return err; + } + } + + // Disk should be ready, partitions enumerated + if (!data.unit[saved_drs->unit].exists) { + dputs("disk is ready, but partition does not exist"); + return DOS_DD_ERR_MEDIA_UNAVAILABLE; + } + + // Try to read starting sector of partition into buffer + if (disk_read_sectors(buffer, data.unit[unit].start_sector, 1) != 1) { + // Cannot read start sector... + return DOS_DD_ERR_READ_FAULT; + } + + // For now, copy largest possible BPB into our internal cache + memcpy(bpb, &buffer[DOS_BPB_OFFSET_ON_DISK], sizeof(DOS_BPB)); + + dprintf("unit %u BPB sectorsPerCluster=%u sectorsPerTrack=%u numberOfHeads=%u\n", + unit, bpb->sectorsPerCluster, + bpb->sectorsPerTrack, bpb->numberOfHeads); + dprintf(" bytesPerSector=%u numberOfFats=%u sectorsPerFat=%u \n", + bpb->bytesPerSector,bpb->numberOfFATs, + bpb->sectorsPerFAT); + dprintf(" numberOfSectors=%u numberOfSectorsLarge=%lu\n", + bpb->numberOfSectors, bpb->numberOfSectorsLarge); + + if (bpb->sectorsPerFAT != 0) { + // FAT12/16 + dprintf(" %s volumeSerialNumber=%lx volumeLabel='%.11s' fsType='%.8s'\n", + "FAT16", bpb->fat16.volumeSerialNumber, bpb->fat16.volumeLabel, bpb->fat16.fsType); + } else if (bpb->fat32.sectorPerFatLarge != 0) { + dprintf(" %s volumeSerialNumber=%lx volumeLabel='%.11s' fsType='%.8s'\n", + "FAT32", bpb->fat32.volumeSerialNumber, bpb->fat32.volumeLabel, bpb->fat32.fsType); + } else { + dprintf(" -> unknown filesystem\n"); + return DOS_DD_ERR_UNKNOWN_MEDIA; + } + + data.unit[saved_drs->unit].ready = true; + return 0; +} + +static bool unit_check_media_changed(uint8_t unit) +{ + if (data.ready) { + // Recheck if disk is still ready + ch375_test_disk_ready(); + if (wait_for_ch375_result(4) == CH375_INT_USB_SUCCESS) { + // Disk is ready. But is partition ready ? + if (data.unit[unit].ready) { + // Disk ready, partition ready. Perfect! + dputs("mediaquery -> disk ready -> unit ready -> not changed"); + return false; + } else { + // Disk ready, but this partition is not. + // Likely first time access for this partition. + dputs("mediaquery -> disk ready -> unit !ready -> changed"); + return true; + } + } else { + // CH375 is not ready but we thought it was. USB has been removed! + dputs("mediaquery -> disk not ready -> changed"); + // Invalidate disk ready flag so that we rescan for partitions + data.ready = false; + return true; + } + } else { + // We do not think CH375 is ready. First time we check, or USB not present. + dputs("mediaquery -> !ready -> changed"); + return true; + } +} + +void strategy_routine(DOS_DRS __far *drs) +{ + load_ds_from_cs(); + //dprintf("strategy routine drs=%Fp len=%u func=%u\n", drs, drs->len, drs->function); + saved_drs = drs; +} + +void interrupt_routine() +{ + int err; + load_ds_from_cs(); + //dprintf("interrupt routine drs=%Fp len=%u func=%u\n", saved_drs, saved_drs->len, saved_drs->function); + switch (saved_drs->function) { + case DOS_DD_FUNC_INIT: + driver_init(saved_drs); + break; + case DOS_DD_FUNC_MEDIA_CHECK: + if (saved_drs->unit >= num_units) { + saved_drs->status = DOS_DD_ERR_UNKNOWN_UNIT | DOS_DD_STATUS_ERROR_DONE; + return; + } + saved_drs->cmd.mediacheck.out.result = unit_check_media_changed(saved_drs->unit) + ? DOS_DD_MEDIAQUERY_CHANGED : DOS_DD_MEDIAQUERY_NOT_CHANGED; + saved_drs->cmd.mediacheck.out.volume_id = unit_get_volume_label(saved_drs->unit); + saved_drs->status = DOS_DD_STATUS_DONE; + break; + case DOS_DD_FUNC_BUILD_BPB: + dprintf("build bpb unit=%hu\n", saved_drs->unit); + if (saved_drs->unit >= num_units) { + dputs("unit is unknown"); + saved_drs->status = DOS_DD_ERR_UNKNOWN_UNIT | DOS_DD_STATUS_ERROR_DONE; + return; + } + // Try to initialize disk and unit + if (err = unit_init(saved_drs->unit)) { + saved_drs->status = err | DOS_DD_STATUS_ERROR_DONE; + return; + } + // Return pointer to our cached BPB + saved_drs->cmd.buildbpb.out.bpb = &data.unit[saved_drs->unit].bpb; + saved_drs->status = DOS_DD_STATUS_DONE; + break; + case DOS_DD_FUNC_READ: + dprintf("read unit=%hu sector=%u large_sector=%lu len=%u\n", saved_drs->unit, + saved_drs->cmd.rw.start_sector, saved_drs->cmd.rw.start_sector_huge, saved_drs->cmd.rw.len); + if (saved_drs->unit >= num_units) { + saved_drs->status = DOS_DD_ERR_UNKNOWN_UNIT | DOS_DD_STATUS_ERROR_DONE; + return; + } + if (!data.ready || !data.unit[saved_drs->unit].ready) { + dputs("partition not ready"); + // We don't try to initialize the drive here, DOS must do that by calling buildBPB + saved_drs->status = DOS_DD_ERR_MEDIA_UNAVAILABLE | DOS_DD_STATUS_ERROR_DONE; + return; + } + if (saved_drs->cmd.rw.len > 128) { + // Too many sectors at once! + // TODO: Should we allow partial reads? When I tried even "type " crashes. + // TODO: Should we also check for segment wraparound? + saved_drs->cmd.rw.len = 0; + saved_drs->status = DOS_DD_ERR_READ_FAULT | DOS_DD_STATUS_ERROR_DONE; + return; + } else if (saved_drs->cmd.rw.len >= 1) { + uint32_t sector = get_start_sector(saved_drs); + if (sector > data.unit[saved_drs->unit].sectors) { + saved_drs->cmd.rw.len = 0; + saved_drs->status = DOS_DD_ERR_SECTOR_NOT_FOUND | DOS_DD_STATUS_ERROR_DONE; + return; + } + // Make absolute + sector += data.unit[saved_drs->unit].start_sector; + if (sector > data.sectors) { + saved_drs->cmd.rw.len = 0; + saved_drs->status = DOS_DD_ERR_SEEK | DOS_DD_STATUS_ERROR_DONE; + return; + } + + saved_drs->cmd.rw.len = disk_read_sectors(saved_drs->cmd.rw.buffer, sector, saved_drs->cmd.rw.len); + if (saved_drs->cmd.rw.len == 0) { + // Not sure if required + saved_drs->status = DOS_DD_ERR_READ_FAULT | DOS_DD_STATUS_ERROR_DONE; + return; + } + } + saved_drs->cmd.rw.volume_id = unit_get_volume_label(saved_drs->unit); + saved_drs->status = DOS_DD_STATUS_DONE; + break; + case DOS_DD_FUNC_WRITE: + case DOS_DD_FUNC_WRITE_VERIFY: // TODO Not doing the verify yet part... + dprintf("write unit=%hu sector=%u large_sector=%lu len=%u\n", saved_drs->unit, + saved_drs->cmd.rw.start_sector, saved_drs->cmd.rw.start_sector_huge, saved_drs->cmd.rw.len); + if (saved_drs->unit >= num_units) { + saved_drs->status = DOS_DD_ERR_UNKNOWN_UNIT | DOS_DD_STATUS_ERROR_DONE; + return; + } + if (!data.ready || !data.unit[saved_drs->unit].ready) { + dputs("partition not ready"); + saved_drs->status = DOS_DD_ERR_MEDIA_UNAVAILABLE | DOS_DD_STATUS_ERROR_DONE; + return; + } + if (read_only) { + saved_drs->status = DOS_DD_ERR_WRITE_PROTECT | DOS_DD_STATUS_ERROR_DONE; + return; + } + if (saved_drs->cmd.rw.len > 128) { + // Too much! + saved_drs->cmd.rw.len = 0; + saved_drs->status = DOS_DD_ERR_WRITE_FAULT | DOS_DD_STATUS_ERROR_DONE; + return; + } else if (saved_drs->cmd.rw.len >= 1) { + // Check relative sector value against partition limit + uint32_t sector = get_start_sector(saved_drs); + if (sector > data.unit[saved_drs->unit].sectors) { + saved_drs->cmd.rw.len = 0; + saved_drs->status = DOS_DD_ERR_SECTOR_NOT_FOUND | DOS_DD_STATUS_ERROR_DONE; + return; + } + // Make absolute and check against disk limit + sector += data.unit[saved_drs->unit].start_sector; + if (sector > data.sectors) { + saved_drs->cmd.rw.len = 0; + saved_drs->status = DOS_DD_ERR_SEEK | DOS_DD_STATUS_ERROR_DONE; + return; + } + + saved_drs->cmd.rw.len = disk_write_sectors(saved_drs->cmd.rw.buffer, sector, saved_drs->cmd.rw.len); + if (saved_drs->cmd.rw.len == 0) { + // Not sure if required + saved_drs->status = DOS_DD_ERR_WRITE_FAULT | DOS_DD_STATUS_ERROR_DONE; + return; + } + + if (saved_drs->function == DOS_DD_FUNC_WRITE_VERIFY) { + // Verify one sector at a time. Use our internal buffer. + uint8_t far * origbuf = saved_drs->cmd.rw.buffer; + unsigned i; + for (i = 0; i < saved_drs->cmd.rw.len; i++) { + dprintf(" verifying sector %u\n", i); + if (disk_read_sectors(buffer, sector + i, 1) != 1) { + saved_drs->status = DOS_DD_ERR_READ_FAULT | DOS_DD_STATUS_ERROR_DONE; + return; + } + + if (_fmemcmp(&origbuf[i * SECTOR_SIZE], buffer, SECTOR_SIZE) != 0) { + dprintf(" cmp error for sec %u\n", i); + saved_drs->status = DOS_DD_ERR_CRC | DOS_DD_STATUS_ERROR_DONE; + return; + } + } + } + } + saved_drs->cmd.rw.volume_id = unit_get_volume_label(saved_drs->unit); + saved_drs->status = DOS_DD_STATUS_DONE; + break; + case DOS_DD_FUNC_DEVICE_OPEN: + dputs("device open"); + // Do nothing here -- we init the device on build bpb, as with older DOSes + saved_drs->status = DOS_DD_STATUS_DONE; + break; + case DOS_DD_FUNC_DEVICE_CLOSE: + dputs("device close"); + saved_drs->status = DOS_DD_STATUS_DONE; + break; + case DOS_DD_FUNC_REMOVEABLE_MEDIA: + dputs("removable device"); + // If the disk is fixed, we must set "busy" bit here. We are removable. + saved_drs->status = DOS_DD_STATUS_DONE; + break; + case DOS_DD_FUNC_IOCTL_READ: + dprintf("ioctl read unit=%hu buf=%Fp len=%u\n", saved_drs->unit, + saved_drs->cmd.ioctlrw.buffer, saved_drs->cmd.ioctlrw.len); + if (saved_drs->unit >= num_units) { + saved_drs->status = DOS_DD_ERR_UNKNOWN_UNIT | DOS_DD_STATUS_ERROR_DONE; + return; + } + // If there's enough space, return our internal config string. + if (saved_drs->cmd.ioctlrw.len >= 3 + 2 + 1 + 5 + 1) { + uint8_t far * buf = saved_drs->cmd.ioctlrw.buffer; + int len = 0; + // B = base port (2 byte) + buf[len++] = 'B'; + _fmemcpy(&buf[len], &ch375_port, sizeof(ch375_port)); + len += sizeof(ch375_port); + // 3 = showing FAT32 (1 byte) + buf[len++] = '3'; + buf[len++] = show_fat32; + // R = read only (1 byte) + buf[len++] = 'R'; + buf[len++] = read_only; + // S = partition start (4 bytes) + buf[len++] = 'S'; + _fmemcpy(&buf[len], &data.unit[saved_drs->unit].start_sector, sizeof(uint32_t)); + len += sizeof(uint32_t); + buf[len++] = '\0'; + saved_drs->cmd.ioctlrw.len = len; + } else { + saved_drs->cmd.ioctlrw.len = 0; + } + saved_drs->status = DOS_DD_STATUS_DONE; + break; + case DOS_DD_FUNC_IOCTL_WRITE: + dprintf("ioctl write unit=%hu buf=%Fp len=%u\n", saved_drs->unit, + saved_drs->cmd.ioctlrw.buffer, saved_drs->cmd.ioctlrw.len); + if (saved_drs->unit >= num_units) { + saved_drs->status = DOS_DD_ERR_UNKNOWN_UNIT | DOS_DD_STATUS_ERROR_DONE; + return; + } + if (saved_drs->cmd.ioctlrw.len >= 2) { + uint8_t far * buf = saved_drs->cmd.ioctlrw.buffer; + int i = 0; + do { + char c = buf[i++]; + switch (c) { + case 'S': // Partition start (5 bytes) + _fmemcpy(&data.unit[saved_drs->unit].start_sector, &buf[i], sizeof(uint32_t)); + i += sizeof(uint32_t); + dprintf(" unit=%hu new start=%lu\n", saved_drs->unit, data.unit[saved_drs->unit].start_sector); + // Mark unit as valid but needing refresh + data.unit[saved_drs->unit].exists = true; + data.unit[saved_drs->unit].ready = false; + break; + case 'L': // Partition len (5 bytes) + _fmemcpy(&data.unit[saved_drs->unit].sectors, &buf[i], sizeof(uint32_t)); + i += sizeof(uint32_t); + dprintf(" unit=%hu new len=%lu\n", saved_drs->unit, data.unit[saved_drs->unit].sectors); + // Mark unit as valid but needing refresh + data.unit[saved_drs->unit].exists = true; + data.unit[saved_drs->unit].ready = false; + break; + case '\0': + break; + default: + dprintf(" invalid control string char '%c' at %d\n", c, i-1); + saved_drs->cmd.ioctlrw.len = i; + saved_drs->status = DOS_DD_ERR_WRITE_FAULT | DOS_DD_STATUS_ERROR_DONE; + return; + } + } while (i < saved_drs->cmd.ioctlrw.len); + } else { + saved_drs->cmd.ioctlrw.len = 0; + saved_drs->status = DOS_DD_ERR_WRITE_FAULT | DOS_DD_STATUS_ERROR_DONE; + return; + } + saved_drs->status = DOS_DD_STATUS_DONE; + break; + case DOS_DD_FUNC_IOCTL_GENERIC: + dprintf("ioctl unit=%hu %x:%x buf=%Fp\n", saved_drs->unit, + saved_drs->cmd.ioctl.category, saved_drs->cmd.ioctl.minor, saved_drs->cmd.ioctl.data); + if (saved_drs->unit >= num_units) { + saved_drs->status = DOS_DD_ERR_UNKNOWN_UNIT | DOS_DD_STATUS_ERROR_DONE; + return; + } + // DOS can call these functions without doing a mediacheck/buildBPB + // Do not want to "forget" about a media change, so can't just call buildBPB here. + // But some functions (like get device parameters?) seem to act like a buildBPB. + if (unit_check_media_changed(saved_drs->unit)) { + // Init the disk, but not the partition, until we are sure we want to. + if (!data.ready) { + if (err = disk_init()) { + // Cannot access to disk or scan for partitions? No IOCTLs for you! + saved_drs->status = err | DOS_DD_STATUS_ERROR_DONE; + return; + } + } + } + if (saved_drs->cmd.ioctl.category == DOS_IOCTL_DISK) { + DOS_IOCTL_DISK_DATA far * iod = saved_drs->cmd.ioctl.data; + CHUDISK_IOCTL_DISK_DATA far * ciod = saved_drs->cmd.ioctl.data; + DOS_BPB * bpb = &data.unit[saved_drs->unit].bpb; + + switch (saved_drs->cmd.ioctl.minor) { + case DOS_IOCTL_DISK_GET_DEVICE_PARAMETERS: // Get CHS values (full disk!) and BPB + dprintf(" get_device_parameters specialFunctions=0x%x\n", iod->devparams.specialFunctions); + // If partition's BPB is not cached, read it from the disk + if (!data.unit[saved_drs->unit].ready) { + // This acts as if buildBPB was called + if ((err = unit_init(saved_drs->unit))) { + // TODO Now would be a good time to talk about a default BPB... + saved_drs->status = err | DOS_DD_STATUS_ERROR_DONE; + return; + } + } + + iod->devparams.specialFunctions = DOS_DEVICEPARAMS_USE_DEVICE_BPB | DOS_DEVICEPARAMS_REGULARTRACKS; + iod->devparams.deviceType = DOS_DEVICEPARAMS_HDD; + iod->devparams.deviceAttributes = DOS_DEVICEPARAMS_REMOVABLE; + if (bpb->numberOfHeads && bpb->sectorsPerTrack) { + // Compute number of cylinders of entire disk based on this part's BPB... + iod->devparams.numberOfCylinders = + div(data.sectors, bpb->numberOfHeads * bpb->sectorsPerTrack); + // TODO Check for overflows... + } else { + iod->devparams.numberOfCylinders = 0; + } + iod->devparams.mediaType = 0; + + // Return only DOS3.x BPB -- not sure if caller will have space for anything larger. + _fmemcpy(&iod->devparams.bpb, bpb, sizeof(DOS_BPB_DOS3)); + + dprintf(" get_device_parameters -> numberOfCylinders=%u\n", iod->devparams.numberOfCylinders); + + saved_drs->status = DOS_DD_STATUS_DONE; + return; + case DOS_IOCTL_DISK_GET_MEDIA_ID: // Get the volume label + if (!data.unit[saved_drs->unit].ready) { + // TODO Should we reload BPB here like above? + dputs(" but partition is not ready"); + saved_drs->status = DOS_DD_ERR_MEDIA_UNAVAILABLE | DOS_DD_STATUS_ERROR_DONE; + return; + } + iod->mid.infoLevel = 0; + if (bpb->sectorsPerFAT != 0) { + iod->mid.serialNumber = bpb->fat16.volumeSerialNumber; + _fmemcpy(iod->mid.volumeLabel, bpb->fat16.volumeLabel, 11); + _fmemcpy(iod->mid.fsType, bpb->fat16.fsType, 8); + } else if (bpb->fat32.sectorPerFatLarge != 0) { + iod->mid.serialNumber = bpb->fat32.volumeSerialNumber; + _fmemcpy(iod->mid.volumeLabel, bpb->fat32.volumeLabel, 11); + _fmemcpy(iod->mid.fsType, bpb->fat32.fsType, 8); + } + dprintf(" get media id -> volumeSerialNumber=%lx volumeLabel='%.11Fs' fsType='%.8Fs'\n", + iod->mid.serialNumber, iod->mid.volumeLabel, iod->mid.fsType); + saved_drs->status = DOS_DD_STATUS_DONE; + return; + case DOS_IOCTL_DISK_SET_MEDIA_ID: // Set the volume label, etc. + if (!data.unit[saved_drs->unit].exists) { + dputs(" but partition does not exist!"); + saved_drs->status = DOS_DD_ERR_MEDIA_UNAVAILABLE | DOS_DD_STATUS_ERROR_DONE; + return; + } + dprintf(" set media id to volumeSerialNumber=%lx volumeLabel='%.11Fs' fsType='%.8Fs'\n", + iod->mid.serialNumber, iod->mid.volumeLabel, iod->mid.fsType); + if (read_only) { + saved_drs->status = DOS_DD_ERR_WRITE_PROTECT | DOS_DD_STATUS_ERROR_DONE; + return; + } + // Here we always reload BPB -- do not want to write back outdated stuff. + if (disk_read_sectors(buffer, data.unit[saved_drs->unit].start_sector, 1) != 1) { + // Cannot read start sector... + saved_drs->status = DOS_DD_ERR_READ_FAULT | DOS_DD_STATUS_ERROR_DONE; + return; + } + bpb = (DOS_BPB*) &buffer[DOS_BPB_OFFSET_ON_DISK]; + if (bpb->sectorsPerFAT != 0) { + bpb->fat16.volumeSerialNumber = iod->mid.serialNumber; + _fmemcpy(bpb->fat16.volumeLabel, iod->mid.volumeLabel, 11); + _fmemcpy(bpb->fat16.fsType, iod->mid.fsType, 8); + } else if (bpb->fat32.sectorPerFatLarge != 0) { + bpb->fat32.volumeSerialNumber = iod->mid.serialNumber; + _fmemcpy(bpb->fat32.volumeLabel, iod->mid.volumeLabel, 11); + _fmemcpy(bpb->fat32.fsType, iod->mid.fsType, 8); + } else { + saved_drs->status = DOS_DD_ERR_UNKNOWN_MEDIA | DOS_DD_STATUS_ERROR_DONE; + return; + } + if (disk_write_sectors(buffer, data.unit[saved_drs->unit].start_sector, 1) != 1) { + // Cannot re-write start sector... + saved_drs->status = DOS_DD_ERR_WRITE_FAULT | DOS_DD_STATUS_ERROR_DONE; + return; + } + // Re-sync our internal BPB + memcpy(&data.unit[saved_drs->unit].bpb, bpb, sizeof(DOS_BPB)); + saved_drs->status = DOS_DD_STATUS_DONE; + return; + case DOS_IOCTL_DISK_READ_TRACK_ON_LOGICAL_DEVICE: // Absolute read + dprintf(" read track cylinder %u head %u sector %u sectors %u buf %Fp -> lba %lu\n", + iod->rw.cylinder, iod->rw.head, iod->rw.firstSector, iod->rw.sectors, iod->rw.buffer, + chs_to_lba(bpb, iod->rw.cylinder, iod->rw.head, iod->rw.firstSector + 1)); + // Need the partition's BPB to map CHS to LBA... + if (!data.unit[saved_drs->unit].ready) { + saved_drs->status = DOS_DD_ERR_MEDIA_UNAVAILABLE | DOS_DD_STATUS_ERROR_DONE; + return; + } + if (disk_read_sectors(iod->rw.buffer, chs_to_lba(bpb, iod->rw.cylinder, iod->rw.head, iod->rw.firstSector + 1), iod->rw.sectors) != iod->rw.sectors) { + saved_drs->status = DOS_DD_ERR_READ_FAULT | DOS_DD_STATUS_ERROR_DONE; + return; + } + saved_drs->status = DOS_DD_STATUS_DONE; + return; + case DOS_IOCTL_DISK_WRITE_TRACK_ON_LOGICAL_DEVICE: + dprintf(" write track cylinder %u head %u sector %u sectors %u buf %Fp -> lba %lu\n", + iod->rw.cylinder, iod->rw.head, iod->rw.firstSector, iod->rw.sectors, iod->rw.buffer, + chs_to_lba(bpb, iod->rw.cylinder, iod->rw.head, iod->rw.firstSector + 1)); + // Need the partition's BPB to map CHS to LBA... + if (!data.unit[saved_drs->unit].ready) { + saved_drs->status = DOS_DD_ERR_MEDIA_UNAVAILABLE | DOS_DD_STATUS_ERROR_DONE; + return; + } + if (read_only) { + saved_drs->status = DOS_DD_ERR_WRITE_PROTECT | DOS_DD_STATUS_ERROR_DONE; + return; + } + if (disk_write_sectors(iod->rw.buffer, chs_to_lba(bpb, iod->rw.cylinder, iod->rw.head, iod->rw.firstSector + 1), iod->rw.sectors) != iod->rw.sectors) { + saved_drs->status = DOS_DD_ERR_WRITE_FAULT | DOS_DD_STATUS_ERROR_DONE; + return; + } + saved_drs->status = DOS_DD_STATUS_DONE; + return; + case DOS_IOCTL_DISK_FORMAT_TRACK_ON_LOGICAL_DEVICE: + dprintf(" formatting track cylinder %u head %u\n", + iod->fv.cylinder, iod->fv.head); + if (!data.unit[saved_drs->unit].exists) { + dputs(" but partition does not exist!"); + saved_drs->status = DOS_DD_ERR_MEDIA_UNAVAILABLE | DOS_DD_STATUS_ERROR_DONE; + return; + } + if (read_only) { + saved_drs->status = DOS_DD_ERR_WRITE_PROTECT | DOS_DD_STATUS_ERROR_DONE; + return; + } + // Total nop. Should we zerofill the track or something? + iod->fv.specialFunctions = 1; // Not supported by BIOS? + saved_drs->status = DOS_DD_STATUS_DONE; + return; + case CHUDISK_IOCTL_DISK_READ_ABS_SECTOR: + dprintf(" read abs sector %lu sectors %u buf %Fp\n", + ciod->rw.sector, ciod->rw.sectors, ciod->rw.buffer); + if (disk_read_sectors(ciod->rwabs.buffer, ciod->rwabs.sector, ciod->rwabs.sectors) != ciod->rwabs.sectors) { + saved_drs->status = DOS_DD_ERR_READ_FAULT | DOS_DD_STATUS_ERROR_DONE; + return; + } + saved_drs->status = DOS_DD_STATUS_DONE; + return; + } + } + + dputs(" ioctl not supported\n"); + saved_drs->status = DOS_DD_ERR_UNKNOWN_COMMAND | DOS_DD_STATUS_ERROR_DONE; + break; + case DOS_DD_FUNC_GET_LOGICAL_DEVICE: + dprintf("get logical device unit=%hu\n", saved_drs->unit); + saved_drs->unit = 0; + saved_drs->status = DOS_DD_STATUS_DONE; + break; + case DOS_DD_FUNC_SET_LOGICAL_DEVICE: + // We do not support this. Ignore it. + dprintf("set logical device unit=%hu\n", saved_drs->unit); + saved_drs->status = DOS_DD_STATUS_DONE; + break; + case DOS_DD_FUNC_IOCTL_QUERY: + dprintf("ioctl query %x:%x buf=%Fp\n", saved_drs->cmd.ioctl.category, saved_drs->cmd.ioctl.minor, saved_drs->cmd.ioctl.data); + switch (saved_drs->cmd.ioctl.category) { + case DOS_IOCTL_DISK: + switch (saved_drs->cmd.ioctl.minor) { + case DOS_IOCTL_DISK_GET_DEVICE_PARAMETERS: + case DOS_IOCTL_DISK_GET_MEDIA_ID: + case DOS_IOCTL_DISK_SET_MEDIA_ID: + case DOS_IOCTL_DISK_READ_TRACK_ON_LOGICAL_DEVICE: + case DOS_IOCTL_DISK_WRITE_TRACK_ON_LOGICAL_DEVICE: + case DOS_IOCTL_DISK_FORMAT_TRACK_ON_LOGICAL_DEVICE: + case CHUDISK_IOCTL_DISK_READ_ABS_SECTOR: + // Supported + saved_drs->status = DOS_DD_STATUS_DONE; + return; + } + break; + } + // Unsupported + saved_drs->status = DOS_DD_ERR_UNKNOWN_COMMAND | DOS_DD_STATUS_ERROR_DONE; + break; + default: + dprintf("unknown function received %u\n", saved_drs->function); + break; + } +} + +// Required by Watcom ABI -- since we do not link to the runtime +void _small_code() {} + +// Symbol to let initialization code know the end of resident data +char resident_end; diff --git a/chudisk.h b/chudisk.h new file mode 100644 index 0000000..f3761fb --- /dev/null +++ b/chudisk.h @@ -0,0 +1,90 @@ +/* + * CHU - driver for CH375 in disk mode + * Copyright (C) 2024 Javier S. Pedro + * + * 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 . + */ + +#ifndef CHUDISK_H +#define CHUDISK_H + +#include + +#include "inc/dosdrv.h" + +#define MAX_UNITS 4 + +#define SECTOR_SIZE 512 + +// Configuration values shared between driver init code and resident code +/* Used by ch375.h, too. */ +extern unsigned short ch375_port; + +extern unsigned char num_units; + +extern bool read_only; + +extern bool show_fat32; + +extern struct chudisk_data +{ + /** Pointers to all BPBs, to return to DOS during init. */ + DOS_BPB * bpb_ptrs[MAX_UNITS]; + + /** Whether we are ready to handle IO, i.e. disk init, partitions scanned. */ + bool ready; + + uint32_t sectors; + uint32_t bytesPerSector; + + struct chudisk_unit { + /** Whether the partition exists (start_sector points to it) */ + bool exists; + /** Note in theory may be zero (superfloppy) */ + uint32_t start_sector; + /** Number of sectors for this partition. */ + uint32_t sectors; + /** Whether the partition's BPB was loaded. */ + bool ready; + /** DOS device params (contains BPB), only valid if 'ready'. */ + DOS_BPB bpb; + } unit[MAX_UNITS]; +} data; + +// Functions called by both init part and resident part +extern void driver_init(DOS_DRS __far *drs); + +extern char resident_end; + +extern uint8_t wait_for_ch375_result(unsigned int max_ticks); + + +// CHUDISK IOCTLs +// These are used with the DISK major +// TODO Not sure we can really happily add custom minors here, +// but then again DOS outright refuses to accept any other major +enum CHUDISK_IOCTL_DISK_MINOR { + CHUDISK_IOCTL_DISK_READ_ABS_SECTOR = 0xC1 +}; + +typedef _Packed union CHUDISK_IOCTL_DISK_DATA +{ + struct CHUDISK_RWABSSECTOR { + uint32_t sector; + uint8_t sectors; + void far * buffer; + } rwabs; +} CHUDISK_IOCTL_DISK_DATA; + +#endif // CHUDISK_H diff --git a/chudisk.lnk b/chudisk.lnk new file mode 100644 index 0000000..bec3794 --- /dev/null +++ b/chudisk.lnk @@ -0,0 +1,4 @@ +format dos com + +option statics +option map=chudisk.map diff --git a/cio.c b/cio.c new file mode 100644 index 0000000..43a2a27 --- /dev/null +++ b/cio.c @@ -0,0 +1,147 @@ +/* + * CHU - driver for CH375 in disk mode + * Copyright (C) 2024 Javier S. Pedro + * + * 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 . + */ + +/* Simple printf function for console, a bit wasteful for what it is used. + * But it is part of the init code, so it will be thrown away. + * dlog.h is more powerful but only in debug builds. */ + + +#include +#include +#include +#include + +#include "inc/dosapi.h" + +#include "cio.h" + +static inline void c_llputc(char c) +{ + dos_print_char(c); +} + +void c_utoa(unsigned num, unsigned base) +{ + char buf[6]; + int i = 0; + + do { + unsigned digit = num % base; + + if (digit < 10) { + buf[i] = '0' + digit; + } else { + buf[i] = 'a' + (digit - 10); + } + + i++; + num /= base; + } while (num > 0 && i < sizeof(buf)); + + while (i--) { + c_llputc(buf[i]); + } +} + +void c_itoa(int num, unsigned base) +{ + unsigned unum; + + if (num < 0) { + c_llputc('-'); + unum = -num; + } else { + unum = num; + } + + c_utoa(unum, base); +} + +unsigned c_strtou(const char * *str) +{ + unsigned i = 0; + const char *s = *str; + char c = *s; + while (c >= '0' && c <= '9') { + i = (i * 10) + (c - '0'); + c = *(++s); + } + *str = s; + return i; +} + +static void c_printstr(const char *s) +{ + while (*s) { c_llputc(*s++); } +} + +void c_printf(const char *fmt, ...) +{ + va_list va; + char c; + + va_start(va, fmt); + + while ((c = *(fmt++))) { + if (c == '%') { + switch ((c = *(fmt++))) { + case 'd': + c_itoa(va_arg(va, int), 10); + break; + case 'u': + c_utoa(va_arg(va, unsigned), 10); + break; + case 'x': + case 'p': + c_utoa(va_arg(va, unsigned), 16); + break; + case 's': + c_printstr(va_arg(va, const char *)); + break; + case 'c': + c_putc(va_arg(va, char)); + break; + case '%': + c_llputc('%'); + break; + } + } else { + c_putc(c); + } + } + + va_end(va); +} + +void c_putc(char c) +{ + if (c == '\n') { + c_llputc('\r'); + } + c_llputc(c); +} + + +void c_puts(const char *s) +{ + char c; + while ((c = *(s++))) { + c_putc(c); + } + c_putc('\n'); +} diff --git a/cio.h b/cio.h new file mode 100644 index 0000000..24a67ae --- /dev/null +++ b/cio.h @@ -0,0 +1,31 @@ +/* + * CHU - driver for CH375 in disk mode + * Copyright (C) 2024 Javier S. Pedro + * + * 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 . + */ + + +#ifndef CIO_H +#define CIO_H + +void c_utoa(unsigned num, unsigned base); +void c_itoa(int num, unsigned base); +unsigned c_strtou(const char * *str); + +void c_printf(const char *fmt, ...); +void c_putc(char c); +void c_puts(const char *s); + +#endif // CIO_H diff --git a/dlog.h b/dlog.h new file mode 100644 index 0000000..00cd5b5 --- /dev/null +++ b/dlog.h @@ -0,0 +1,359 @@ +/* + * VBMouse - printf & logging routines + * Copyright (C) 2022 Javier S. Pedro + * + * 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 2 + * 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#ifndef DLOG_H +#define DLOG_H + +#include +#include +#include +#include +#include + +// Customizable defines +/** If 0, these routines become nops */ +#define ENABLE_DLOG 0 +/** 1 means target serial port, 0 means target IO port. */ +#define DLOG_TARGET DLOG_TARGET_SERIAL +/** When using DLOG_TARGET_IOPORT, which IO port to target. + * VirtualBox uses 0x504, Bochs, DOSBox and descendants use 0xE9. + * When using DLOG_TARGET_SERIAL, the desired UART IO base port. (e.g. COM1 = 0x3F8). */ +#define DLOG_TARGET_PORT 0x3F8 + +// End of customizable defines + +#define DLOG_TARGET_BIOSTTY 1 +#define DLOG_TARGET_SERIAL 2 +#define DLOG_TARGET_IOPORT 3 + +#if ENABLE_DLOG + +/** Initializes the debug log port. */ +static void dlog_init(); + +/** Logs a single character to the debug message IO port. */ +static inline void dputc(char c); + +#if DLOG_TARGET == DLOG_TARGET_BIOSTTY + +static inline void dlog_init() +{ + // No initialization required +} + +static inline void dconputc(char c); +#pragma aux dconputc = \ + "mov ah, 0x0E" \ + "xor bx, bx" \ + "int 0x10" \ + __parm [AL] \ + __modify __exact [AH AL BH BL]; + +static inline void dputc(char c) +{ + // Need to convert CR into CRLF... + if (c == '\n') { + dconputc('\n'); + dconputc('\r'); + } else { + dconputc(c); + } +} + + +#elif DLOG_TARGET == DLOG_TARGET_SERIAL + +static void dlog_init() +{ + // Comes from https://wiki.osdev.org/Serial_Ports#Initialization + outp(DLOG_TARGET_PORT + 1, 0x00); // Disable all interrupts + outp(DLOG_TARGET_PORT + 3, 0x80); // Enable DLAB (set baud rate divisor) + outp(DLOG_TARGET_PORT + 0, 0x01); // Set divisor to 1 (lo byte) 115200 baud + outp(DLOG_TARGET_PORT + 1, 0x00); // (hi byte) + outp(DLOG_TARGET_PORT + 3, 0x03); // 8 bits, no parity, one stop bit + outp(DLOG_TARGET_PORT + 2, 0xC7); // Enable FIFO, clear them, with 14-byte threshold + outp(DLOG_TARGET_PORT + 4, 0x03); // RTS/DSR set, IRQs disabled +} + +static inline void dputc(char c) +{ + while (!(inp(DLOG_TARGET_PORT + 5) & 0x20)); + outp(DLOG_TARGET_PORT, c); +} + +#elif DLOG_TARGET == DLOG_TARGET_IOPORT + +static inline void dlog_init() +{ + // No initialization required +} + +static inline void dputc(char c) +{ + outp(DLOG_TARGET_PORT, c); +} + +#endif /* DLOG_TARGET */ + +static void d_utoa(unsigned num, unsigned base) +{ + char buf[6]; + int i = 0; + + do { + unsigned digit = num % base; + + if (digit < 10) { + buf[i] = '0' + digit; + } else { + buf[i] = 'a' + (digit - 10); + } + + i++; + num /= base; + } while (num > 0 && i < sizeof(buf)); + + while (i--) { + dputc(buf[i]); + } +} + +static void d_ultoa(unsigned long num, unsigned base) +{ + char buf[12]; + int i = 0; + + do { + unsigned digit = 0; + + static inline void uldiv(void); +#pragma aux uldiv = \ + "push eax" \ + "push ecx" \ + "push edx" \ + "mov eax, [num]" \ + "movzx ecx, [base]" \ + "xor edx, edx" \ + \ + "div ecx" \ + \ + "mov [num], eax" \ + "mov [digit], dx" \ + \ + "pop edx" \ + "pop ecx" \ + "pop eax" \ + __modify __exact []; + uldiv(); + + if (digit < 10) { + buf[i] = '0' + digit; + } else { + buf[i] = 'a' + (digit - 10); + } + + i++; + } while (num > 0 && i < sizeof(buf)); + + while (i--) { + dputc(buf[i]); + } +} + +static void d_itoa(int num, unsigned base) +{ + unsigned unum; + + if (num < 0) { + dputc('-'); + unum = -num; + } else { + unum = num; + } + + d_utoa(unum, base); +} + +static void d_ltoa(long num, unsigned base) +{ + unsigned long unum; + + if (num < 0) { + dputc('-'); + unum = -num; + } else { + unum = num; + } + + d_ultoa(unum, base); +} + +static unsigned d_strtou(const char * __far *str) +{ + unsigned i = 0; + const char *s = *str; + char c = *s; + while (c >= '0' && c <= '9') { + i = (i * 10) + (c - '0'); + c = *(++s); + } + *str = s; + return i; +} + +static void d_printstr(const char __far *s, unsigned l) +{ + while (l > 0 && *s) { + dputc(*s++); + l--; + } +} + +static void dprintf(const char *fmt, ...) +{ + va_list va; + char c; + + va_start(va, fmt); + + while ((c = *(fmt++))) { + if (c == '%') { + unsigned width, precision, size; + bool is_far = false; + + width = d_strtou(&fmt); + + if ((c = *fmt) == '.') { + fmt++; + precision = d_strtou(&fmt); + } else { + precision = UINT_MAX; + } + + switch ((c = *fmt)) { + case 'l': + size = sizeof(long); + fmt++; + break; + case 'h': + size = sizeof(short); + fmt++; + break; + case 'F': + is_far = true; + fmt++; + break; + default: + size = sizeof(int); + break; + } + + switch ((c = *fmt)) { + case 'd': + switch (size) { + case sizeof(int): + d_itoa(va_arg(va, int), 10); + break; + case sizeof(long): + d_ltoa(va_arg(va, long), 10); + break; + } + break; + case 'u': + switch (size) { + case sizeof(int): + d_utoa(va_arg(va, int), 10); + break; + case sizeof(long): + d_ultoa(va_arg(va, long), 10); + break; + } + break; + case 'x': + switch (size) { + case sizeof(int): + d_utoa(va_arg(va, int), 16); + break; + case sizeof(long): + d_ultoa(va_arg(va, long), 16); + break; + } + break; + case 'b': + switch (size) { + case sizeof(int): + d_utoa(va_arg(va, int), 2); + break; + case sizeof(long): + d_ultoa(va_arg(va, long), 2); + break; + } + break; + case 'p': + if (is_far) { + void __far *p = va_arg(va, void __far *); + d_utoa(FP_SEG(p), 16); + dputc(':'); + d_utoa(FP_OFF(p), 16); + } else { + d_utoa(va_arg(va, unsigned), 16); + } + break; + case 's': + d_printstr(is_far ? va_arg(va, const char __far *) + : va_arg(va, const char *), + precision); + break; + case 'c': + dputc(va_arg(va, char)); + break; + case '%': + dputc('%'); + break; + } + fmt++; + } else { + dputc(c); + } + } + + va_end(va); +} + +static void dputs(const char *s) +{ + char c; + while ((c = *(s++))) { + dputc(c); + } + dputc('\n'); +} + +#else /* ENABLE_DLOG */ + +#define dlog_nop() do { } while(0) +#define dlog_init() dlog_nop() +#define dputc(c) dlog_nop() +#define dputs(s) dlog_nop() +#define dprintf(...) dlog_nop() + + +#endif /* ENABLE_DLOG */ + +#endif /* DLOG_H */ diff --git a/inc/bda.h b/inc/bda.h new file mode 100644 index 0000000..b447221 --- /dev/null +++ b/inc/bda.h @@ -0,0 +1,67 @@ +/* + * VBMouse - BIOS data area access routines + * Copyright (C) 2022 Javier S. Pedro + * + * 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 2 + * 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#ifndef BDA_H +#define BDA_H + +#define BIOS_DATA_AREA_SEGMENT 0x40 + +static inline uint32_t bda_get_dword(unsigned int offset) { + uint32_t __far *p = MK_FP(BIOS_DATA_AREA_SEGMENT, offset); + return *p; +} + +static inline uint16_t bda_get_word(unsigned int offset) { + uint16_t __far *p = MK_FP(BIOS_DATA_AREA_SEGMENT, offset); + return *p; +} + +static inline uint8_t bda_get_byte(unsigned int offset) { + uint8_t __far *p = MK_FP(BIOS_DATA_AREA_SEGMENT, offset); + return *p; +} + +#define bda_get_ebda_segment() bda_get_word(0x0e) + +#define bda_get_equipment() bda_get_word(0x10) + +#define bda_get_video_mode() bda_get_byte(0x49) +#define bda_get_num_columns() bda_get_word(0x4a) +#define bda_get_video_page_size() bda_get_word(0x4c) +#define bda_get_cur_video_page() bda_get_word(0x62) +#define bda_get_last_row() bda_get_byte(0x84) +#define bda_get_char_height() bda_get_word(0x85) + +#define bda_get_tick_count() bda_get_dword(0x6c) +#define bda_get_tick_count_lo() bda_get_word(0x6c) + +static inline void bda_wait_tick() { + uint16_t cur_ticks = bda_get_tick_count_lo(); + do { + //pause(); + } while (cur_ticks == bda_get_tick_count_lo()); +} + +static inline void bda_wait_ticks(unsigned int ticks) { + for (; ticks > 0; ticks--) { + bda_wait_tick(); + } +} + +#endif // BDA_H diff --git a/inc/bpb.h b/inc/bpb.h new file mode 100644 index 0000000..8df04a1 --- /dev/null +++ b/inc/bpb.h @@ -0,0 +1,83 @@ +#ifndef BPB_H +#define BPB_H + +#include +#include "sassert.h" + +#define DOS_BPB_OFFSET_ON_DISK 0x0B + +typedef _Packed struct DOS_BPB_DOS3 +{ + /** Number of bytes per sector. */ + uint16_t bytesPerSector; + /** Number of sectors per cluster. Must be power of 2. */ + uint8_t sectorsPerCluster; + /** Number of reserved sectors. */ + uint16_t reservedSectors; + /** Number of FATs. */ + uint8_t numberOfFATs; + /** Maximum number of entries in the root directory. */ + uint16_t rootDirEntries; + /** Total number of sectors on the drive. If drive larger than 32MB, this field is zero, see numberOfSectorsLarge. */ + uint16_t numberOfSectors; + /** Media descriptor byte. */ + uint8_t mediaType; + /** Number of sectors used by a FAT. */ + uint16_t sectorsPerFAT; + /** Number of sectors per track. */ + uint16_t sectorsPerTrack; + /** Number of heads. */ + uint16_t numberOfHeads; + /** Number of hidden sectors on the drive, from the start of the drive. */ + uint32_t hiddenSectors; + /** Number of sectors, only used if drive > 32MB. */ + uint32_t numberOfSectorsLarge; +} DOS_BPB_DOS3; +STATIC_ASSERT(sizeof(DOS_BPB_DOS3) == 25); + +typedef _Packed struct DOS_BPB_DOS4 +{ + struct DOS_BPB_DOS3; + uint8_t physicalDriveNumber; + uint8_t flags; + uint8_t extendedBootSignature; + uint32_t volumeSerialNumber; + char volumeLabel[11]; + char fsType[8]; +} DOS_BPB_DOS4; +STATIC_ASSERT(sizeof(DOS_BPB_DOS4) == 25 + 26); + +typedef _Packed struct DOS_BPB_FAT32 +{ + struct DOS_BPB_DOS3; + uint32_t sectorPerFatLarge; + uint16_t extendedFlags; + uint16_t version; + uint32_t rootDirCluster; + uint16_t infoSector; + uint16_t backupBootSector; + + char bootFileName[12]; + uint8_t physicalDriveNumber; + uint8_t flags; + uint8_t extendedBootSignature; + uint32_t volumeSerialNumber; + char volumeLabel[11]; + char fsType[8]; +} DOS_BPB_FAT32; +STATIC_ASSERT(sizeof(DOS_BPB_FAT32) == 25 + 54); + +/** Union of all BPB types. Default is DOS4 / FAT16. */ +typedef union DOS_BPB +{ + struct DOS_BPB_DOS3; + struct DOS_BPB_DOS4 fat16; + struct DOS_BPB_FAT32 fat32; +} DOS_BPB; + +typedef enum DOS_BPB_MEDIA_TYPE +{ + DOS_BPB_MEDIA_HDD = 0xF8 +} DOS_BPB_MEDIA_TYPE; + +#endif // BPB_H diff --git a/inc/dosapi.h b/inc/dosapi.h new file mode 100644 index 0000000..18dbde0 --- /dev/null +++ b/inc/dosapi.h @@ -0,0 +1,182 @@ +/* + * VBMouse - Interface to some DOS int 21h services + * Copyright (C) 2022 Javier S. Pedro + * + * 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 2 + * 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#ifndef INT21DOS_H +#define INT21DOS_H + +#include +#include +#include +#include +#include "sassert.h" + +#define DOS_PSP_SIZE 256 + +enum dos_error { + DOS_ERROR_SUCCESS = 0, + DOS_ERROR_INVALID_FUNCTION = 1, + DOS_ERROR_FILE_NOT_FOUND = 2, + DOS_ERROR_PATH_NOT_FOUND = 3, + DOS_ERROR_TOO_MANY_OPEN_FILES = 4, + DOS_ERROR_ACCESS_DENIED = 5, + DOS_ERROR_INVALID_HANDLE = 6, + DOS_ERROR_ARENA_TRASHED = 7, + DOS_ERROR_NOT_ENOUGH_MEMORY = 8, + DOS_ERROR_INVALID_BLOCK = 9, + DOS_ERROR_BAD_ENVIRONMENT = 10, + DOS_ERROR_BAD_FORMAT = 11, + DOS_ERROR_INVALID_ACCESS = 12, + DOS_ERROR_INVALID_DATA = 13, + DOS_ERROR_OUT_OF_MEMORY = 14, + DOS_ERROR_INVALID_DRIVE = 15, + DOS_ERROR_CURRENT_DIRECTORY = 16, + DOS_ERROR_NOT_SAME_DEVICE = 17, + DOS_ERROR_NO_MORE_FILES = 18, + DOS_ERROR_WRITE_PROTECT = 19, + DOS_ERROR_BAD_UNIT = 20, + DOS_ERROR_NOT_READY = 21, + DOS_ERROR_BAD_COMMAND = 22, + DOS_ERROR_CRC = 23, + DOS_ERROR_BAD_LENGTH = 24, + DOS_ERROR_SEEK = 25, + DOS_ERROR_NOT_DOS_DISK = 26, + DOS_ERROR_SECTOR_NOT_FOUND = 27, + + DOS_ERROR_GEN_FAILURE = 31, + + DOS_ERROR_HANDLE_EOF = 38, + DOS_ERROR_HANDLE_DISK_FULL = 39, + + DOS_ERROR_FILE_EXISTS = 80, + DOS_ERROR_CANNOT_MAKE = 82, +}; + +// General functions + +static inline void dos_print_char(char c); +#pragma aux dos_print_char = \ + "mov ah, 0x02" \ + "int 0x21" \ + __parm [dl] \ + __modify [ah] + +static inline uint8_t dos_read_char(void); +#pragma aux dos_read_char = \ + "mov ah, 0x08" \ + "int 0x21" \ + __value [al] \ + __modify [ax] + +static inline void dos_print_string(const char *s); +#pragma aux dos_print_string = \ + "mov ah, 0x09" \ + "int 0x21" \ + __parm [dx] \ + __modify [ah] + +static inline uint16_t dos_get_version(void); +#pragma aux dos_get_version = \ + "mov ah, 0x30" \ + "int 0x21" \ + __value [ax] \ + __modify [bx cx] + +// Memory manipulation functions + +typedef __segment segment_t; + +enum dos_allocation_strategy { + DOS_FIT_FIRST = 0, + DOS_FIT_BEST = 1, + DOS_FIT_LAST = 2, + + DOS_FIT_HIGH = 0x80, + DOS_FIT_HIGHONLY = 0x40, +}; + +/** Converts bytes to paragraphs (16 bytes), rounding up. */ +static inline unsigned get_paragraphs(unsigned bytes) +{ + return (bytes + 15) / 16; +} + +static unsigned dos_query_allocation_strategy(void); +#pragma aux dos_query_allocation_strategy = \ + "mov ax, 0x5800" \ + "int 0x21" \ + __value [ax] + +static int dos_set_allocation_strategy(unsigned strategy); +#pragma aux dos_set_allocation_strategy = \ + "clc" \ + "mov ax, 0x5801" \ + "int 0x21" \ + "jc end" \ + "mov ax, 0" \ + "end:" \ + __parm [bx] \ + __value [ax] + +static bool dos_query_umb_link_state(void); +#pragma aux dos_query_umb_link_state = \ + "mov ax, 0x5802" \ + "int 0x21" \ + __value [al] + +static int dos_set_umb_link_state(bool state); +#pragma aux dos_set_umb_link_state = \ + "clc" \ + "mov ax, 0x5803" \ + "int 0x21" \ + "jc end" \ + "mov ax, 0" \ + "end:" \ + __parm [bx] \ + __value [ax] + +/** Allocates a new DOS segment. + * @returns either the allocated segment or 0 if any error. */ +static __segment dos_alloc(unsigned paragraphs); +#pragma aux dos_alloc = \ + "clc" \ + "mov ah, 0x48" \ + "int 0x21" \ + "jnc end" \ + "mov ax, 0xB" \ + "end:" \ + __parm [bx] \ + __value [ax] + +/** Frees DOS segment. */ +static void dos_free(segment_t segment); +#pragma aux dos_free = \ + "mov ah, 0x49" \ + "int 0x21" \ + __parm [es] \ + __modify [ax] + +/** Sets a given PSP as the current active process. */ +static void dos_set_psp(segment_t psp); +#pragma aux dos_set_psp = \ + "mov ah, 0x50" \ + "int 0x21" \ + __parm [bx] \ + __modify [ax] + +#endif // INT21DOS_H diff --git a/inc/dosdrv.h b/inc/dosdrv.h new file mode 100644 index 0000000..0c33c54 --- /dev/null +++ b/inc/dosdrv.h @@ -0,0 +1,319 @@ +#ifndef DOSDRV_H +#define DOSDRV_H + +#include +#include "bpb.h" +#include "sassert.h" + +typedef enum DOS_DD_ERROR +{ + DOS_DD_ERR_WRITE_PROTECT = 0, + DOS_DD_ERR_UNKNOWN_UNIT = 1, + DOS_DD_ERR_DRIVE_NOT_READY = 2, + DOS_DD_ERR_UNKNOWN_COMMAND = 3, + DOS_DD_ERR_CRC = 4, + DOS_DD_ERR_BAD_DRS_LEN = 5, + DOS_DD_ERR_SEEK = 6, + DOS_DD_ERR_UNKNOWN_MEDIA = 7, + DOS_DD_ERR_SECTOR_NOT_FOUND = 8, + DOS_DD_ERR_PRINTER_OUT_OF_PAPER = 9, + DOS_DD_ERR_WRITE_FAULT = 10, + DOS_DD_ERR_READ_FAULT = 11, + DOS_DD_ERR_GENERAL_FAILURE = 12, + DOS_DD_ERR_MEDIA_UNAVAILABLE = 0xE, + DOS_DD_ERR_INVALID_DISK_CHANGE = 0xF +} DOS_DD_ERROR; + +typedef enum DOS_DD_STATUS { + DOS_DD_STATUS_DONE = 1 << 8, + DOS_DD_STATUS_BUSY = 1 << 9, + DOS_DD_STATUS_ERROR = 1 << 15, + + DOS_DD_STATUS_ERROR_DONE = DOS_DD_STATUS_ERROR | DOS_DD_STATUS_DONE +} DOS_DD_STATUS; + +typedef enum DOS_DD_MEDIAQUERY_RESULT { + DOS_DD_MEDIAQUERY_CHANGED = -1, + DOS_DD_MEDIAQUERY_UNKNOWN = 0, + DOS_DD_MEDIAQUERY_NOT_CHANGED = 1 +} DOS_DD_MEDIAQUERY_RESULT; + +typedef _Packed struct DOS_DRS +{ + /** The length of this structure. */ + uint8_t len; + /** The subunit the operation is for. */ + uint8_t unit; + + uint8_t function; + + uint16_t status; + + uint32_t reserved1; + uint32_t reserved2; + + union { + union { + struct { + uint8_t reserved; + /** End of memory available for driver. */ + void __far * avail_addr; + /** Command line (i.e. the DEVICE= line used to load this driver. ) */ + const char __far * cmdline; + /** First drive that is going to be allocated for this driver. */ + uint8_t first_drive_number; + } in; + struct { + /** Number of units/drive letters to allocate for this driver. */ + uint8_t number_units; + /** Break addr: everything after this address is deallocated after init. */ + void __far * break_addr; + /** Pointer to the BPB array. */ + DOS_BPB * __far * bpbs; + uint8_t reserved; + /** Display error message on failure. */ + uint16_t error_msg_flag; + } out; + } init; + union { + struct { + /** Media descriptor of the current media. */ + uint8_t cur_media_desc; + } in; + struct { + uint8_t reserved; + uint8_t result; + /** Volume ID of previous loaded media. */ + char far * volume_id; + } out; + } mediacheck; + union { + struct { + /** Media descriptor of the current media. */ + uint8_t cur_media_desc; + /** Buffer with sector 0 of the disk, depending on driver flags */ + void __far * sector_zero; + } in; + struct { + uint8_t reserved; + void __far * sector_zero; + /** Address for the new BPB. */ + DOS_BPB __far * bpb; + } out; + } buildbpb; + struct { + uint8_t data; + /** Input: pointer to buffer. */ + void __far * buffer; + /** Input/Output: buffer len / actual len */ + uint16_t len; + } ioctlrw; + struct { + /** Input: current media descriptor byte. */ + uint8_t cur_media_desc; + /** Input: pointer to buffer. */ + void __far * buffer; + /** Input: Number of sectors to read/write. Output: number sectors actually read/written. */ + uint16_t len; + /** Input: Begin sector. Or, if 0xFFFF, see start_sector_huge. */ + uint16_t start_sector; + /** Output: Current Volume ID. */ + char far * volume_id; + uint32_t start_sector_huge; + } rw; + struct { + uint8_t category; + uint8_t minor; + uint32_t reserved; + void __far * data; + } ioctl; + } cmd; +} DOS_DRS; + +typedef void (DOS_DD_STRATEGY)(DOS_DRS __far *drs); +typedef void (DOS_DD_INTERRUPT)(DOS_DRS __far *drs); +#pragma aux DOS_DD_STRATEGY __parm __caller [es bx] __modify [] __loadds __far +#pragma aux DOS_DD_INTERRUPT __parm __caller [] __modify [] __loadds __far + +typedef enum DOS_DD_FUNCTIONS +{ + DOS_DD_FUNC_INIT = 0, + DOS_DD_FUNC_MEDIA_CHECK = 1, + DOS_DD_FUNC_BUILD_BPB = 2, + DOS_DD_FUNC_IOCTL_READ = 3, + DOS_DD_FUNC_READ = 4, + DOS_DD_FUNC_NONDESTRUCTIVE_READ = 5, + DOS_DD_FUNC_INPUT_STATUS = 6, + DOS_DD_FUNC_INPUT_FLUSH = 7, + DOS_DD_FUNC_WRITE = 8, + DOS_DD_FUNC_WRITE_VERIFY = 9, + DOS_DD_FUNC_OUTPUT_STATUS = 10, + DOS_DD_FUNC_OUTPUT_FLUSH = 11, + DOS_DD_FUNC_IOCTL_WRITE = 12, + DOS_DD_FUNC_DEVICE_OPEN = 13, + DOS_DD_FUNC_DEVICE_CLOSE = 14, + DOS_DD_FUNC_REMOVEABLE_MEDIA = 15, + DOS_DD_FUNC_OUTPUT_UNTIL_BUSY = 16, + DOS_DD_FUNC_IOCTL_GENERIC = 19, + DOS_DD_FUNC_GET_LOGICAL_DEVICE = 23, + DOS_DD_FUNC_SET_LOGICAL_DEVICE = 24, + DOS_DD_FUNC_IOCTL_QUERY = 25, +} DOS_DD_COMMAND; + + +/** Device driver (.sys) header */ +typedef _Packed struct DOS_DD_HEADER +{ + void __far *nextDevice; + uint16_t attributes; + DOS_DD_STRATEGY *strategyCb; + DOS_DD_INTERRUPT *interrupCb; + char name[8]; +} DOS_DD_HEADER; + +typedef enum DOS_DD_ATTRIBUTES +{ + /** Character-device driver. */ + DOS_DD_CHAR = 1 << 15, + /** Block-device driver. */ + DOS_DD_BLOCK = 0, + + /** Supports IOCTL Read/Write funcs */ + DOS_DD_SUPPORT_IOCTL_RW = 1 << 14, + + /** Support IOCTL query funcs. */ + DOS_DD_SUPPORT_IOCTL_QUERY = 1 << 7, + + // Character-device specific + DOS_CHAR_CURRENT_STDIN_DEVICE = 1 << 0, + DOS_CHAR_CURRENT_STDOUT_DEVICE = 1 << 1, + DOS_CHAR_CURRENT_NUL_DEVICE = 1 << 2, + DOS_CHAR_CURRENT_CLOCK_DEVICE = 1 << 3, + DOS_CHAR_SPECIAL_FAST_CONSOLE_IO = 1 << 4, + DOS_CHAR_OUTPUT_UNTIL_BUSY = 1 << 13, + + // Block-device specific + /** The driver support 32-bit sector address. (Can use the _huge fields. ) */ + DOS_BLOCK_SUPPORT_32BIT_ADDRESSES = 1 << 1, + + /** Support Get/Set Logical Drive and generic IOCTL funcs. */ + DOS_BLOCK_SUPPORT_IOCTL_GENERIC = 1 << 6, + + /** Supports Open/Close/Removable media funcs */ + DOS_BLOCK_SUPPORT_REMOVABLE_MEDIA = 1 << 11, + + /** if set, DOS not read the 1st sector of the 1st FAT during build bpb. */ + DOS_BLOCK_FORMAT_NON_IBM = 1 << 13, +} DOS_DD_ATTRIBUTES; + +// Generic IOCTLs + +typedef enum DOS_IOCTL_CATEGORY +{ + DOS_IOCTL_SERIAL = 0x1, + DOS_IOCTL_CONSOLE = 0x3, + DOS_IOCTL_PARALLEL = 0x5, + DOS_IOCTL_DISK = 0x8, +} DOS_IOCTL_CATEGORY; + +typedef enum DOS_IOCTL_MINOR +{ + DOS_IOCTL_CONSOLE_SET_ITERATION_COUNT = 0x45, + DOS_IOCTL_CONSOLE_SELECT_CODE_PAGE = 0x4A, + DOS_IOCTL_CONSOLE_START_CODE_PAGE_PREPARE = 0x4C, + DOS_IOCTL_CONSOLE_END_CODE_PAGE_PREPARE = 0x4D, + DOS_IOCTL_CONSOLE_GET_IERATION_COUNT = 0x65, + DOS_IOCTL_CONSOLE_QUERY_SELECTED_CODE_PAGE = 0x6A, + DOS_IOCTL_CONSOLE_QUERY_CODE_PAGE_PREPARE_LIST = 0x6B, + + DOS_IOCTL_DISK_SET_DEVICE_PARAMETERS = 0x40, + DOS_IOCTL_DISK_WRITE_TRACK_ON_LOGICAL_DEVICE = 0x41, + DOS_IOCTL_DISK_FORMAT_TRACK_ON_LOGICAL_DEVICE = 0x42, + DOS_IOCTL_DISK_SET_MEDIA_ID = 0x46, + DOS_IOCTL_DISK_GET_DEVICE_PARAMETERS = 0x60, + DOS_IOCTL_DISK_READ_TRACK_ON_LOGICAL_DEVICE = 0x61, + DOS_IOCTL_DISK_VERIFY_TRACK_ON_LOGICAL_DEVICE = 0x62, + DOS_IOCTL_DISK_GET_MEDIA_ID = 0x66, + DOS_IOCTL_DISK_SENSE_MEDIA_TYPE = 0x68, +} DOS_IOCTL_MINOR; + + +// Block-device / disk data structures + +typedef _Packed struct DOS_DEVICEPARAMS +{ + uint8_t specialFunctions; + uint8_t deviceType; + uint16_t deviceAttributes; + uint16_t numberOfCylinders; + uint8_t mediaType; + DOS_BPB_DOS3 bpb; +} DOS_DEVICEPARAMS; + +enum DOS_DEVICEPARAMS_SPECIAL_FUNCTIONS +{ + /** Use the device BPB for all subsequent Build BPB requests. */ + DOS_DEVICEPARAMS_USE_DEVICE_BPB = (1 << 0), + /** Ignore all fields except the TRACKLAYOUT structure appended after DEVICEPARAMS */ + DOS_DEVICEPARAMS_TRACKLAYOUT = (1 << 1), + /** The sectors in the track are all the same size, and sector numbers are in the range [1..N] + * where N is the total number of sectors in the track. */ + DOS_DEVICEPARAMS_REGULARTRACKS = (1 << 2), +}; + +enum DOS_DEVICEPARAMS_DEVICE_TYPE +{ + DOS_DEVICEPARAMS_320_360K = 0x0, + DOS_DEVICEPARAMS_1_2_MB = 0x1, + DOS_DEVICEPARAMS_720K = 0x2, + DOS_DEVICEPARAMS_8INCH_SD = 0x3, + DOS_DEVICEPARAMS_8INCH_DD = 0x4, + DOS_DEVICEPARAMS_HDD = 0x5, + DOS_DEVICEPARAMS_TAPE = 0x6, + DOS_DEVICEPARAMS_1_44_MB = 0x7, + DOS_DEVICEPARAMS_OPTICAL = 0x8, + DOS_DEVICEPARAMS_2_88_MB = 0x9 +}; + +enum DOS_DEVICEPARAMS_DEVICE_ATTR +{ + DOS_DEVICEPARAMS_REMOVABLE = 0, + DOS_DEVICEPARAMS_FIXED = 1, + DOS_DEVICEPARAMS_HAS_DOORLOCK = 1 << 1 +}; + +typedef _Packed struct DOS_MEDIA_ID +{ + /** Must be zero. */ + uint16_t infoLevel; + uint32_t serialNumber; + char volumeLabel[11]; + char fsType[8]; +} DOS_MEDIA_ID; + +typedef _Packed struct DOS_RWBLOCK +{ + uint8_t specialFunctions; + uint16_t head; + uint16_t cylinder; + uint16_t firstSector; + uint16_t sectors; + void far * buffer; +} DOS_RWBLOCK; + +typedef _Packed struct DOS_FVBLOCK +{ + uint8_t specialFunctions; + uint16_t head; + uint16_t cylinder; +} DOS_FVBLOCK; + +typedef _Packed union DOS_IOCTL_DISK_DATA +{ + DOS_DEVICEPARAMS devparams; + DOS_MEDIA_ID mid; + DOS_FVBLOCK fv; + DOS_RWBLOCK rw; +} DOS_IOCTL_DISK_DATA; + +#endif // DOSSYS_H diff --git a/inc/dosint.h b/inc/dosint.h new file mode 100644 index 0000000..cfa855d --- /dev/null +++ b/inc/dosint.h @@ -0,0 +1,250 @@ +#ifndef DOSINT_H +#define DOSINT_H + +// Internal DOS structures + +// For documentation of these, better grab "Undocumented DOS" or similar book +// These are probably valid only on DOS >= 4 + +typedef _Packed struct dos_current_directory_structure { + char curr_path[67]; + uint16_t flags; + uint32_t disk_blk; + void __far * info; + char pad1[11]; +} DOSCDS; +STATIC_ASSERT(sizeof(DOSCDS) == 88); + +enum dos_cds_flags { + DOS_CDS_FLAG_PHYSICAL = 0x4000, + DOS_CDS_FLAG_NETWORK = 0x8000 +}; + +typedef _Packed struct dos_system_file_table_entry { + uint16_t num_handles; + uint16_t open_mode; + uint8_t attr; + uint16_t dev_info; + void __far *dpb; + uint16_t start_cluster; + uint16_t f_time; + uint16_t f_date; + uint32_t f_size; + uint32_t f_pos; + uint16_t last_rel_cluster; + uint16_t last_abs_cluster; + uint16_t dir_sector; + uint8_t dir_entry; + char filename[11]; +} DOSSFT; +STATIC_ASSERT(sizeof(DOSSFT) == 43); + +enum dos_sft_dev_flags { + DOS_SFT_FLAG_NETWORK = 0x8000, + DOS_SFT_FLAG_TIME_SET = 0x4000, + DOS_SFT_FLAG_CLEAN = 0x0040, + DOS_SFT_DRIVE_MASK = 0x001F +}; + +typedef _Packed struct dos_search_data_block { + uint8_t drive; + char search_templ[11]; + uint8_t search_attr; + uint16_t dir_entry; + uint16_t par_clstr; + char pad1[4]; +} DOSSDB; +STATIC_ASSERT(sizeof(DOSSDB) == 21); + +enum dos_sdb_drive_flags { + DOS_SDB_DRIVE_FLAG_NETWORK = 0x80, + DOS_SDB_DRIVE_MASK = 0x1F +}; + +typedef _Packed struct dos_lock_params { + uint32_t start_offset; + uint32_t region_size; +} DOSLOCK; + +typedef _Packed struct dos_direntry { + char filename[11]; + uint8_t attr; + char pad1[10]; + uint16_t f_time; + uint16_t f_date; + uint16_t start_cluster; + uint32_t f_size; +} DOSDIR; +STATIC_ASSERT(sizeof(DOSDIR) == 32); + +typedef _Packed struct dos_swappable_area { + uint8_t criterr; + uint8_t indos; + uint8_t drive_num; + uint8_t lasterr_dum[9]; + uint8_t __far *cur_dta; + uint16_t cur_psp; + uint8_t pad1[4]; + uint8_t cur_drive; + uint8_t pad2[135]; + char fn1[128]; + char fn2[128]; + DOSSDB sdb; + DOSDIR found_file; + DOSCDS drive_cdscopy; + uint8_t fcb_fn1[11]; + uint8_t pad3[1]; + uint8_t fcb_fn2[11]; + uint8_t pad4[11]; + uint8_t search_attr; + uint8_t open_mode; + uint8_t pad5[51]; + DOSCDS __far *drive_cds; + uint8_t pad6[12]; + uint16_t fn1_csoffset; + uint16_t fn2_csoffset; + uint8_t pad7[71]; + uint16_t openex_act; + uint16_t openex_attr; + uint16_t openex_mode; + uint8_t pad8[29]; + DOSSDB rename_srcfile; + DOSDIR rename_file; +} DOSSDA; +STATIC_ASSERT(offsetof(DOSSDA, cur_dta) == 0xC); +STATIC_ASSERT(offsetof(DOSSDA, cur_drive) == 0x16); +STATIC_ASSERT(offsetof(DOSSDA, fn1) == 0x9E); +STATIC_ASSERT(offsetof(DOSSDA, fn2) == 0x11E); +STATIC_ASSERT(offsetof(DOSSDA, sdb) == 0x19E); +STATIC_ASSERT(offsetof(DOSSDA, found_file) == 0x1B3); +STATIC_ASSERT(offsetof(DOSSDA, search_attr) == 0x24D); +STATIC_ASSERT(offsetof(DOSSDA, open_mode) == 0x24E); +STATIC_ASSERT(offsetof(DOSSDA, drive_cds) == 0x282); +STATIC_ASSERT(offsetof(DOSSDA, openex_act) == 0x2DD); +STATIC_ASSERT(offsetof(DOSSDA, openex_mode) == 0x2E1); + +typedef _Packed struct dos_list_of_lists { + char pad1[22]; + DOSCDS __far *cds; + char pad2[7]; + uint8_t last_drive; +} DOSLOL; + +typedef _Packed struct dos_nls_table { + uint8_t table_id; + void __far *table_data; +} NLSTABLE; + +typedef _Packed struct file_char_table { + uint16_t size; // table size (not counting this word) + uint8_t unk1; // ??? (01h for MS-DOS 3.30-6.00) + uint8_t lowest; // lowest permissible character value for filename + uint8_t highest; // highest permissible character value for filename + uint8_t unk2; // ??? (00h for MS-DOS 3.30-6.00) + uint8_t first_x; // first excluded character in range \ all characters in this + uint8_t last_x; // last excluded character in range / range are illegal + uint8_t unk3; // ??? (02h for MS-DOS 3.30-6.00) + uint8_t n_illegal; // number of illegal (terminator) characters + uint8_t illegal[1]; // characters which terminate a filename: ."/\[]:|<>+=;, +} FCHAR; + +static inline int drive_letter_to_index(char letter) +{ + if (letter >= 'A' && letter <= 'Z') return letter - 'A'; + else if (letter >= 'a' && letter <= 'z') return letter - 'a'; + else return -1; +} + +static inline char drive_index_to_letter(int index) +{ + return 'A' + index; +} + +static inline DOSSDA __far * dos_get_swappable_dos_area(void); +#pragma aux dos_get_swappable_dos_area = \ + "push ds" \ + "mov ax, 0x5D06" \ + "int 0x21" \ + "jnc success" \ + "xor si, si" \ + "mov es, si" \ + "jmp end" \ + "success: mov ax, ds" \ + "mov es, ax" \ + "end: pop ds" \ + __value [es si] \ + __modify [ax cx dx] + +static inline DOSLOL __far * dos_get_list_of_lists(void); +#pragma aux dos_get_list_of_lists = \ + "mov ax, 0x5200" \ + "int 0x21" \ + __value [es bx] \ + __modify [ax] + +static inline uint16_t dos_sft_decref(DOSSFT __far *sft); +#pragma aux dos_sft_decref = \ + "mov ax, 0x1208" \ + "int 0x2F" \ + __parm [es di] \ + __value [ax] + +// Network redirector interface + +enum DOS_REDIR_SUBFUNCTION { + DOS_FN_RMDIR = 0x01, + DOS_FN_MKDIR = 0x03, + DOS_FN_CHDIR = 0x05, + DOS_FN_CLOSE = 0x06, + DOS_FN_COMMIT = 0x07, + DOS_FN_READ = 0x08, + DOS_FN_WRITE = 0x09, + DOS_FN_LOCK = 0x0A, + DOS_FN_UNLOCK = 0x0B, + DOS_FN_GET_DISK_FREE = 0x0C, + DOS_FN_SET_FILE_ATTR = 0x0E, + DOS_FN_GET_FILE_ATTR = 0x0F, + DOS_FN_RENAME = 0x11, + DOS_FN_DELETE = 0x13, + DOS_FN_OPEN = 0x16, + DOS_FN_CREATE = 0x17, + DOS_FN_FIND_FIRST = 0x1B, + DOS_FN_FIND_NEXT = 0x1C, + DOS_FN_CLOSE_ALL = 0x1D, + DOS_FN_DO_REDIR = 0x1E, + DOS_FN_PRINTSETUP = 0x1F, + DOS_FN_FLUSH = 0x20, + DOS_FN_SEEK_END = 0x21, + DOS_FN_ATEXIT = 0x22, + DOS_FN_QUALIFY = 0x23, + DOS_FN_OPEN_EX = 0x2E +}; + +enum OPENEX_ACTIONS { + OPENEX_FAIL_IF_EXISTS = 0x00, + OPENEX_OPEN_IF_EXISTS = 0x01, + OPENEX_REPLACE_IF_EXISTS = 0x02, + OPENEX_FAIL_IF_NEW = 0x00, + OPENEX_CREATE_IF_NEW = 0x10, +}; + +enum OPENEX_MODE { + OPENEX_MODE_READ = 0, + OPENEX_MODE_WRITE = 1, + OPENEX_MODE_RDWR = 2, + OPENEX_MODE_MASK = 3, + OPENEX_SHARE_COMPAT = 0x00, + OPENEX_SHARE_DENYALL = 0x10, + OPENEX_SHARE_DENYWRITE = 0x20, + OPENEX_SHARE_DENYREAD = 0x30, + OPENEX_SHARE_DENYNONE = 0x40, + OPENEX_SHARE_MASK = 0x70, +}; + +enum OPENEX_RESULT { + OPENEX_FILE_OPENED = 1, + OPENEX_FILE_CREATED = 2, + OPENEX_FILE_REPLACED = 3, +}; + +#endif // DOSINT_H diff --git a/inc/mbr.h b/inc/mbr.h new file mode 100644 index 0000000..d45727d --- /dev/null +++ b/inc/mbr.h @@ -0,0 +1,46 @@ +#ifndef MBR_H +#define MBR_H + +#include "sassert.h" + +enum MBR_PARTTYPE +{ + MBR_EMPTY = 0, + MBR_FAT12 = 0x01, + MBR_FAT16_32MB = 0x04, + MBR_EXT = 0x05, + MBR_FAT16 = 0x06, + MBR_IFS = 0x07, + MBR_FAT32 = 0x0B, + MBR_FAT32_LBA = 0x0C, + MBR_FAT16_LBA = 0x0E, + MBR_EXT_LBA = 0x0F, + MBR_LINUX_SWAP = 0x82, + MBR_LINUX = 0x83, +}; + +typedef _Packed struct MBR_CHS +{ + uint8_t head; + unsigned sector : 6; + unsigned cyl : 10; +} MBR_CHS; + +STATIC_ASSERT(sizeof(MBR_CHS) == 3); + +typedef _Packed struct MBR_PARTENTRY +{ + uint8_t status; + MBR_CHS chsFirst; + uint8_t type; + MBR_CHS chsLast; + uint32_t lbaFirst; + uint32_t lbaLen; +} MBR_PARTENTRY; + +STATIC_ASSERT(sizeof(MBR_PARTENTRY) == 16); + +#define MBR_PARTENTRY_OFFSET_ON_DISK 446 +#define MBR_SIGNATURE_OFFSET_ON_DISK 510 + +#endif // MBR_H diff --git a/inc/sassert.h b/inc/sassert.h new file mode 100644 index 0000000..71a0c0e --- /dev/null +++ b/inc/sassert.h @@ -0,0 +1,8 @@ +#ifndef SASSERT_H +#define SASSERT_H + +#include + +#define STATIC_ASSERT(expr) typedef int STATIC_ASSERT_FAILED[(expr) ? 1 : -1] + +#endif // SASSERT_H diff --git a/makefile b/makefile new file mode 100644 index 0000000..a42e957 --- /dev/null +++ b/makefile @@ -0,0 +1,67 @@ +#!/usr/bin/env wmake + +# All binaries to build +bins = test.exe chudisk.sys chud.exe + +# Object files for chdisk +chudisk_objs = chudisk.obj chudinit.obj cio.obj + +# Compiler arguments for DOS +dos_cflags = -bt=dos -3 -ms -osi -ox -w3 -wcd=202 -g=DGROUP +# -ms to use small memory model (this assumes ss == ds) +# -osi to optimize for size, put intrinsics inline (to avoid runtime calls) +# -ox extra optimization (impact is not very big) +# -w3 enables warnings +# -wcd=202 disables the unreferenced function warning (e.g., for inline functions in headers) + +# Compiler arguments for the DOS drivers +dosdrv_cflags = -bt=dos -3 -ms -zu -s -osi -ox -w3 -wcd=202 -g=DGROUP +# -zu since ss != ds in the driver +# -s to disable stack checks, since it inserts calls to the runtime + +# Full compiler command lines +compile_dos = *wcc -fo=$^@ $(dos_cflags) $[@ +compile_dosdrv = *wcc -fo=$^@ $(dosdrv_cflags) $[@ + +# Object files + +.BEFORE: + # We need DOS and Windows headers, not host platform's + set include=$(%watcom)/h/win;$(%watcom)/h + +all: $(bins) .SYMBOLIC + +test.exe: test.obj .AUTODEPEND + *wlink system dos name $@ file { test.obj } + +test.obj: test.c .AUTODEPEND + *wcc -fo=$^@ -bt=dos -3 -osi -w3 -wcd=202 $[@ + +chudisk.sys: chudisk.lnk $(chudisk_objs) .AUTODEPEND + *wlink @$[@ name $@ file { $(chudisk_objs) } + +chudisk.obj: chudisk.c .AUTODEPEND + $(compile_dosdrv) + +chudinit.obj: chudinit.c .AUTODEPEND + $(compile_dosdrv) + +cio.obj: cio.c .AUTODEPEND + $(compile_dosdrv) + +chud.exe: chud.obj .AUTODEPEND + *wlink name $@ system dos file { chud.obj } + +chud.obj: chud.c .AUTODEPEND + $(compile_dos) + +clean: .SYMBOLIC + rm -f $(bins) *.obj + +# Build a zip with the driver binaries +zip: $(bins) .SYMBOLIC + zip --DOS-names -fz- chu.zip $(bins) + +srczip: .SYMBOLIC + zip -fz- chusrc.zip COPYING README.md makefile *.lnk *.h *.c inc/*.h + diff --git a/test.c b/test.c new file mode 100644 index 0000000..3cb2ffd --- /dev/null +++ b/test.c @@ -0,0 +1,489 @@ +#include +#include +#include +#include + +#include "usb.h" +#include "ch375.h" + +unsigned short ch375_port = 0x260; + +#define SWAPNC_32(w) (\ + (((w) & 0x000000FFUL) << 24) |\ + (((w) & 0x0000FF00UL) << 8) |\ + (((w) & 0x00FF0000UL) >> 8) |\ + (((w) & 0xFF000000UL) >> 24)\ + ) + +static uint8_t buffer[64]; + +typedef uint16_t Centisecs; +#define CENTISECS_MAX (60 * 100U) + +/// Gets the current wallclock centisecond (1/100 of a second). +// Note this wraps around every minute, so max value is CENTISECS_MAX. +static Centisecs get_centisecs() +{ + struct dostime_t now; + _dos_gettime(&now); + return (now.second * 100U) + now.hsecond; +} + +static inline Centisecs centisecs_remaining(Centisecs start, Centisecs deadline) +{ + Centisecs now = get_centisecs(); + if (now < start) { + // Rollover happened + now += CENTISECS_MAX; + } + if (now >= deadline) { + return 0; + } else { + return deadline - now; + } +} + +static void delay_centisecs(Centisecs timeout) +{ + Centisecs start = get_centisecs(); + Centisecs deadline = start + timeout; + while (centisecs_remaining(start, deadline)) { + printf("Delay deadline=%u now=%u\n", deadline, get_centisecs()); + } +} + + +typedef bool (*PollFunction)(void); + +static bool wait_with_timeout(Centisecs timeout, PollFunction pf) { + Centisecs start = get_centisecs(); + Centisecs deadline = start + timeout; + Centisecs last_print = 0; + while (!pf() && centisecs_remaining(start, deadline)) { + ch375_iodelay(); + if (last_print != get_centisecs()) { + printf("Wait with timeout deadline=%u now=%u\n", deadline, get_centisecs()); + last_print = get_centisecs(); + } + } + if (pf()) { + printf("Wait OK, %d centisecs elapsed\n", get_centisecs() - start); + return true; + } else { + printf("Wait timeout\n"); + return false; + } + //return pf(); +} + +static bool poll_test_connect(void) { + return ch375_read_data() != 0; +} + + +static bool wait_interrupt_with_timeout(unsigned int timeout) { + return wait_with_timeout(timeout, ch375_poll_interrupt); +} + +static void dump_int_status() +{ + char i = ch375_poll_interrupt() ? 'I' : ' '; + printf("Int Status: [%c] 0x%hx\n", i, ch375_get_int_status()); + // Above also clears pending ints... +} + +void chip_reset() +{ + printf("Chip reset\n"); + ch375_reset(); + delay_centisecs(5); +} + +void chip_sleep() +{ + printf("Chip sleep\n"); + ch375_enter_sleep(); +} + +void usb_host_off() +{ + printf("Set usb mode disabled...\n"); + ch375_set_usb_mode(CH375_USB_MODE_HOST_DISABLED); + if (!wait_with_timeout(1, poll_test_connect) || ch375_read_data() != CH375_RET_SUCESS) { + printf("Set usb mode failed\n"); + } +} + +void usb_host_reset(void) +{ + printf("Set usb mode reset...\n"); + ch375_set_usb_mode(CH375_USB_MODE_HOST_RESET); + if (!wait_with_timeout(1, poll_test_connect) || ch375_read_data() != CH375_RET_SUCESS) { + printf("Set usb mode reset failed\n"); + } +} + +bool usb_host_on(void) +{ + printf("Set usb mode...\n"); + ch375_set_usb_mode(CH375_USB_MODE_HOST_AUTO_SOF); + if (!wait_with_timeout(1, poll_test_connect) || ch375_read_data() != CH375_RET_SUCESS) { + printf("Set usb mode failed\n"); + return false; + } + + dump_int_status(); + + return true; +} + +bool usb_host_connect(void) +{ + uint8_t status; + + printf("Test connect...\n"); + ch375_test_connect(); + if (!wait_with_timeout(1, poll_test_connect)) { + printf("Test connect timedout\n"); + } + status = ch375_read_data(); + printf("Test connect status = 0x%hx\n", status); + switch (status) { + case CH375_INT_USB_CONNECT: + printf("USB device connected\n"); + return true; + case CH375_INT_USB_READY: + printf("USB device ready\n"); + return true; + case CH375_INT_USB_DISCONNECT: + printf("USB device not connected\n"); + default: + return false; + } +} + +static int usb_host_wait_int_read_data(Centisecs timeout, uint8_t buffer[]) +{ + uint8_t status; + if (!wait_with_timeout(timeout, ch375_poll_interrupt)) { + return -1; + } + + // Get and acknowledge interrupt + status = ch375_get_int_status(); + printf("Wait int read data status=0x%hx\n", status); + if (status != CH375_INT_USB_SUCCESS) { + return -status; + } + + + // USB host mode doesn't need to do unlock, so we can use DATA0 here? + ch375_send_command(CH375_RD_USB_DATA0); + return ch375_read_data_block(buffer); +} + +static bool init_disk() +{ + uint8_t status; + + printf("Disk init...\n"); + ch375_disk_init(); + if (!wait_interrupt_with_timeout(100)) { + printf("Disk init timeout\n"); + } + status = ch375_get_int_status(); + printf("Disk init status = 0x%hx\n", status); + + return status == CH375_INT_USB_SUCCESS; +} + +static bool disk_ready() +{ + uint8_t status; + ch375_test_disk_ready(); + if (!wait_interrupt_with_timeout(100)) { + printf("Disk ready timeout\n"); + } + status = ch375_get_int_status(); + printf("Disk ready status = 0x%hx\n", status); + return status == CH375_INT_USB_SUCCESS; +} + +static void disk_size() +{ + uint8_t status; + + printf("Disk size...\n"); + ch375_send_command(CH375_DISK_SIZE); + if (!wait_interrupt_with_timeout(100)) { + printf("Disk size timeout\n"); + } + status = ch375_get_int_status(); + printf("Disk size status = 0x%hx\n", status); + + if (status == CH375_INT_USB_SUCCESS) { + int len; + + ch375_send_command(CH375_RD_USB_DATA); + + len = ch375_read_data_block(buffer); + printf("Read %d bytes\n", len); + + if (len >= 8) { + uint32_t sectors = SWAPNC_32(*(uint32_t*)&buffer[0]), + bytes_per_sector = SWAPNC_32(*(uint32_t*)&buffer[4]); + uint32_t kbytes = sectors / 2; + uint32_t mbytes = kbytes / 1024; + + printf("%hx %hx %hx %hx %hx %hx %hx %hx\n", + buffer[0], buffer[1], buffer[2], buffer[3], + buffer[4], buffer[5], buffer[6], buffer[7]); + printf("%lu sectors, %lu bytes per sector, %u MiB\n", sectors, bytes_per_sector, mbytes); + } + } +} + +int disk() +{ + bool ready = disk_ready(); + int i = 0; + + if (ready) { + printf("Disk ready\n"); + } else { + printf("Disk not ready\n"); + + if (!usb_host_connect()) { + return EXIT_FAILURE; + } + + if (!init_disk()) { + return EXIT_FAILURE; + } + + i = 3; + while (i >= 0 && !(ready = disk_ready())) { + i--; + printf("Give more time..\n"); + } + + if (ready) { + printf("Disk now ready\n"); + } else { + printf("Disk NOT ready\n"); + return EXIT_FAILURE; + } + } + + dump_int_status(); + + disk_size(); + + return EXIT_SUCCESS; +} + +int disk_read(uint32_t lba) +{ + uint8_t status; + unsigned total = 0; + unsigned i; + ch375_disk_read(lba, 1); + if (!wait_interrupt_with_timeout(100)) { + printf("Disk read timeout\n"); + } + while ((status = ch375_get_int_status() == CH375_INT_USB_DISK_READ)) { + int len; + ch375_send_command(CH375_RD_USB_DATA); + + if (total >= 512) { + printf("Read buffer overflow!"); + break; + } + + len = ch375_read_data_block(&buffer[total]); + printf("Disk read data block len = %d\n", len); + if (len > 0) { + total += len; + + ch375_send_command(CH375_DISK_RD_GO); + if (!wait_interrupt_with_timeout(100)) { + printf("Disk read more timeout\n"); + } + } else if (len == 0) { + break; + } + } + printf("Disk read status = 0x%hx\n", status); + + printf("Disk read total bytes = %u\n", total); + + for (i = 512 - (8*4); i < total; i+=8) { + printf("%hx %hx %hx %hx %hx %hx %hx %hx\n", + buffer[i+0], buffer[i+1], buffer[i+2], buffer[i+3], + buffer[i+4], buffer[i+5], buffer[i+6], buffer[i+7]); + } + + return EXIT_SUCCESS; +} + +int autou() +{ + uint8_t status; + +#if 1 + usb_host_reset(); + delay(100); +#endif + +#if 1 + if (!usb_host_on()) { + return EXIT_FAILURE; + } + delay(100); +#endif + +#if 1 + // TODO: Try to get descriptor in high speed, then retry in low speed? + ch375_set_usb_speed(CH375_USB_SPEED_LOW); +#endif + +#if 1 + printf("Auto setup...\n"); + + ch375_auto_setup(); + ch375_send_command(CH375_AUTO_SETUP); + if (!wait_interrupt_with_timeout(100)) { + printf("Auto setup timeout\n"); + } + status = ch375_get_int_status(); + printf("Auto setup status = 0x%hx\n", status); + + delay(100); +#endif + + if (status == CH375_INT_USB_SUCCESS) { + printf("Auto setup success\n"); + } else { + printf("Auto setup fail, status=0x%x\n", status); + } + + dump_int_status(); + + return EXIT_SUCCESS; +} + +int host() +{ + uint8_t status; + usb_device_descriptor *dev_descr; + int n; + + //ch375_set_retry(CH375_RETRY_NAK_INFINITE | CH375_RETRY_TIMEOUT_MAX); + +#if 0 + usb_host_reset(); + //delay(100); +#endif + +#if 1 + if (!usb_host_on()) { + + return EXIT_FAILURE; + } + //delay(100); +#endif + +#if 1 + // TODO: Try to get descriptor in high speed, then retry in low speed? + ch375_set_usb_speed(CH375_USB_SPEED_LOW); +#endif + +#if 0 + if (!usb_host_connect()) { + return EXIT_FAILURE; + } +#endif + + dump_int_status(); + + printf("Reading descriptor %d...\n", USB_DESCRIPTOR_TYPE_DEVICE); + ch375_get_descriptor(USB_DESCRIPTOR_TYPE_DEVICE); + n = usb_host_wait_int_read_data(100, buffer); + if (n >= 0) { + printf("Got descriptor 1 size = %d\n", n); + } else { + printf("Failed to get descriptor 1, err=0x%hx\n", -n); + return EXIT_FAILURE; + } + + dump_int_status(); + + dev_descr = (usb_device_descriptor*)buffer; + + printf("Got USB device VID:PID %04x:%04x\n", dev_descr->idVendor, dev_descr->idProduct); + + printf("Reading descriptor %d...\n", USB_DESCRIPTOR_TYPE_CONFIG); + ch375_get_descriptor(USB_DESCRIPTOR_TYPE_CONFIG); + n = usb_host_wait_int_read_data(100, buffer); + if (n >= 0) { + printf("Got descriptor 2 size = %d\n", n); + } else { + printf("Failed to get descriptor 2, err=0x%hx\n", -n); + return EXIT_FAILURE; + } + + dump_int_status(); + + return EXIT_SUCCESS; +} + +int main(int argc, const char *argv[]) +{ + char mode = 'd'; + + if (argc > 1) { + mode = argv[1][0]; + } + + printf("Test mode %c\n", mode); + + dump_int_status(); + + switch (mode) { + case 'd': + return disk(); + case 'e': + return disk_read(0); + case 'a': + return autou(); + case 'm': + return host(); + case 'h': + usb_host_on(); + return EXIT_SUCCESS; + case 'c': + usb_host_connect(); + return EXIT_SUCCESS; + case 'o': + usb_host_off(); + return EXIT_SUCCESS; + case 'b': + usb_host_reset(); + return EXIT_SUCCESS; + case 's': + chip_sleep(); + return EXIT_SUCCESS; + case 'r': + chip_reset(); + return EXIT_SUCCESS; + case 'i': + dump_int_status(); + return EXIT_SUCCESS; + case 'v': + printf("IC Version: 0x%hx\n", ch375_get_version()); + return EXIT_SUCCESS; + default: + printf("Unknown mode %c\n", mode); + return EXIT_FAILURE; + } +} diff --git a/usb.h b/usb.h new file mode 100644 index 0000000..d8e156e --- /dev/null +++ b/usb.h @@ -0,0 +1,47 @@ +/* + * CHU - driver for CH375 in disk mode + * Copyright (C) 2024 Javier S. Pedro + * + * 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 . + */ + + +#ifndef USB_H +#define USB_H + +#include + +typedef enum usb_descriptor_type { + USB_DESCRIPTOR_TYPE_DEVICE = 1, + USB_DESCRIPTOR_TYPE_CONFIG = 2 +} usb_descriptor_type; + +typedef _Packed struct usb_device_descriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t bcdUSB; + uint8_t bDeviceClass; + uint8_t bDeviceSubClass; + uint8_t bDeviceProtocol; + uint8_t bMaxPacketSize0; + uint16_t idVendor; + uint16_t idProduct; + uint16_t bcdDevice; + uint8_t iManufacturer; + uint8_t iProduct; + uint8_t iSerialNumber; + uint8_t bNumConfigurations; +} usb_device_descriptor; + +#endif // USB_H diff --git a/utils.h b/utils.h new file mode 100644 index 0000000..138a774 --- /dev/null +++ b/utils.h @@ -0,0 +1,60 @@ +/* + * CHU - driver for CH375 in disk mode + * Copyright (C) 2024 Javier S. Pedro + * + * 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 . + */ + + +#ifndef UTILS_H +#define UTILS_H + +#include + +static inline __segment get_cs(void); +#pragma aux get_cs = "mov ax, cs" value [ax] modify exact [] nomemory + +static inline __segment get_ds(void); +#pragma aux get_ds = "mov ax, ds" value [ax] modify exact [] nomemory + +static void load_ds_from_cs(void); +#pragma aux load_ds_from_cs = \ + "push cs" \ + "pop ds" \ + __modify __exact [] + +#define SWAPNC_32(w) (\ + (((w) & 0x000000FFUL) << 24) |\ + (((w) & 0x0000FF00UL) << 8) |\ + (((w) & 0x00FF0000UL) >> 8) |\ + (((w) & 0xFF000000UL) >> 24)\ + ) + +static inline uint16_t div(uint32_t dividend, uint16_t divisor); +#pragma aux div = \ + "div bx" \ + __parm [dx ax] [bx] \ + __value [ax] \ + __modify __exact [dx ax] + +static inline uint32_t mul(uint16_t a, uint16_t b); +#pragma aux mul = \ + "mul dx" \ + __parm [ax] [dx] \ + __value [dx ax] \ + __modify __exact [dx ax] + + + +#endif // UTILS_H -- cgit v1.2.3