commit 7c1679774c01810ff1a8aa5bcad03b32e1c411e7 Author: Yu Chen Date: Mon Jun 27 21:48:28 2022 +0800 init version diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c4929e4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +.idea +Cargo.lock +target +os/src/link_app.S +os/last-* +user +ci-user/ +tools +workplace/ \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -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/Makefile b/Makefile new file mode 100644 index 0000000..347ac58 --- /dev/null +++ b/Makefile @@ -0,0 +1,58 @@ +DOCKER_NAME ?= dinghao188/rcore-tutorial +DIR := workplace +.PHONY: docker build_docker + +test: test3 test4 test5 test6 test7 test8 + +setup: + rm -rf ${DIR} + mkdir ${DIR} + cp -r easy-fs ${DIR} + cp -r easy-fs-fuse ${DIR} + cp -r ci-user ${DIR} + cp -r bootloader ${DIR} + cp -r reports ${DIR} + cp rust-toolchain ${DIR} + +test1: setup + cp -r os1 ${DIR}/os + cd ${DIR}/ci-user && make test CHAPTER=1 + + +test2: setup + cp -r os2 ${DIR}/os + cd ${DIR}/ci-user && make test CHAPTER=2 + +test3: setup + cp -r os3 ${DIR}/os + cd ${DIR}/ci-user && make test CHAPTER=3 + +test4: setup + cp -r os4 ${DIR}/os + cd ${DIR}/ci-user && make test CHAPTER=4 + +test5: setup + cp -r os5 ${DIR}/os + cd ${DIR}/ci-user && make test CHAPTER=5 + +test6: setup + cp -r os6 ${DIR}/os + cd ${DIR}/ci-user && make test CHAPTER=6 + +test7: setup + cp -r os7 ${DIR}/os + cd ${DIR}/ci-user && make test CHAPTER=7 + +test8: setup + cp -r os8 ${DIR}/os + cd ${DIR}/ci-user && make test CHAPTER=8 + +clean: + rm -rf ${DIR} + +docker: + docker run --rm -it --mount type=bind,source=$(shell pwd),destination=/mnt ${DOCKER_NAME} + +build_docker: + docker build -t ${DOCKER_NAME} . + diff --git a/bootloader/rustsbi-qemu.bin b/bootloader/rustsbi-qemu.bin new file mode 100644 index 0000000..9822f54 Binary files /dev/null and b/bootloader/rustsbi-qemu.bin differ diff --git a/easy-fs-fuse/Cargo.toml b/easy-fs-fuse/Cargo.toml new file mode 100644 index 0000000..ee0ef97 --- /dev/null +++ b/easy-fs-fuse/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "easy-fs-fuse" +version = "0.1.0" +authors = ["Yifan Wu "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +clap = "2.33.3" +easy-fs = { path = "../easy-fs" } +rand = "0.8.0" \ No newline at end of file diff --git a/easy-fs-fuse/src/main.rs b/easy-fs-fuse/src/main.rs new file mode 100644 index 0000000..7363136 --- /dev/null +++ b/easy-fs-fuse/src/main.rs @@ -0,0 +1,155 @@ +use clap::{App, Arg}; +use easy_fs::{BlockDevice, EasyFileSystem}; +use std::fs::{read_dir, File, OpenOptions}; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::sync::Arc; +use std::sync::Mutex; + +/// Use a block size of 512 bytes +const BLOCK_SZ: usize = 512; +const BLOCK_NUM: usize = 16384; + +/// Wrapper for turning a File into a BlockDevice +struct BlockFile(Mutex); + +impl BlockDevice for BlockFile { + /// Read a block from file + fn read_block(&self, block_id: usize, buf: &mut [u8]) { + let mut file = self.0.lock().unwrap(); + file.seek(SeekFrom::Start((block_id * BLOCK_SZ) as u64)) + .expect("Error when seeking!"); + assert_eq!(file.read(buf).unwrap(), BLOCK_SZ, "Not a complete block!"); + } + /// Write a block into file + fn write_block(&self, block_id: usize, buf: &[u8]) { + let mut file = self.0.lock().unwrap(); + file.seek(SeekFrom::Start((block_id * BLOCK_SZ) as u64)) + .expect("Error when seeking!"); + assert_eq!(file.write(buf).unwrap(), BLOCK_SZ, "Not a complete block!"); + } +} + +fn main() { + easy_fs_pack().expect("Error when packing easy-fs!"); +} + +/// Pack a directory into a easy-fs disk image +fn easy_fs_pack() -> std::io::Result<()> { + let matches = App::new("EasyFileSystem packer") + .arg( + Arg::with_name("source") + .short("s") + .long("source") + .takes_value(true) + .help("Executable source dir(with backslash)"), + ) + .arg( + Arg::with_name("target") + .short("t") + .long("target") + .takes_value(true) + .help("Executable target dir(with backslash)"), + ) + .get_matches(); + let src_path = matches.value_of("source").unwrap(); + let target_path = matches.value_of("target").unwrap(); + println!("src_path = {}\ntarget_path = {}", src_path, target_path); + let block_file = Arc::new(BlockFile(Mutex::new({ + let f = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .open(format!("{}{}", target_path, "fs.img"))?; + f.set_len((BLOCK_NUM * BLOCK_SZ) as u64).unwrap(); + f + }))); + let efs = EasyFileSystem::create(block_file.clone(), BLOCK_NUM as u32, 1); + let root_inode = Arc::new(EasyFileSystem::root_inode(&efs)); + let apps: Vec<_> = read_dir(src_path) + .unwrap() + .into_iter() + .map(|dir_entry| { + let mut name_with_ext = dir_entry.unwrap().file_name().into_string().unwrap(); + name_with_ext.drain(name_with_ext.find('.').unwrap()..name_with_ext.len()); + name_with_ext + }) + .collect(); + for app in apps { + // load app data (elf) from host file system + let mut host_file = File::open(format!("{}{}", target_path, app)).unwrap(); + let mut all_data: Vec = Vec::new(); + host_file.read_to_end(&mut all_data).unwrap(); + // create a file in easy-fs + let inode = root_inode.create(app.as_str()).unwrap(); + // write data to easy-fs + inode.write_at(0, all_data.as_slice()); + } + // list apps + for app in root_inode.ls() { + println!("{}", app); + } + Ok(()) +} + +#[test] +fn efs_test() -> std::io::Result<()> { + let block_file = Arc::new(BlockFile(Mutex::new({ + let f = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .open("target/fs.img")?; + f.set_len(BLOCK_NUM * BLOCK_SZ).unwrap(); + f + }))); + EasyFileSystem::create(block_file.clone(), 4096, 1); + let efs = EasyFileSystem::open(block_file.clone()); + let root_inode = EasyFileSystem::root_inode(&efs); + root_inode.create("filea"); + root_inode.create("fileb"); + for name in root_inode.ls() { + println!("{}", name); + } + let filea = root_inode.find("filea").unwrap(); + let greet_str = "Hello, world!"; + filea.write_at(0, greet_str.as_bytes()); + //let mut buffer = [0u8; BLOCK_SZ]; + let mut buffer = [0u8; 233]; + let len = filea.read_at(0, &mut buffer); + assert_eq!(greet_str, core::str::from_utf8(&buffer[..len]).unwrap(),); + + let mut random_str_test = |len: usize| { + filea.clear(); + assert_eq!(filea.read_at(0, &mut buffer), 0,); + let mut str = String::new(); + use rand; + // random digit + for _ in 0..len { + str.push(char::from('0' as u8 + rand::random::() % 10)); + } + filea.write_at(0, str.as_bytes()); + let mut read_buffer = [0u8; 127]; + let mut offset = 0usize; + let mut read_str = String::new(); + loop { + let len = filea.read_at(offset, &mut read_buffer); + if len == 0 { + break; + } + offset += len; + read_str.push_str(core::str::from_utf8(&read_buffer[..len]).unwrap()); + } + assert_eq!(str, read_str); + }; + + random_str_test(4 * BLOCK_SZ); + random_str_test(8 * BLOCK_SZ + BLOCK_SZ / 2); + random_str_test(100 * BLOCK_SZ); + random_str_test(70 * BLOCK_SZ + BLOCK_SZ / 7); + random_str_test((12 + 128) * BLOCK_SZ); + random_str_test(400 * BLOCK_SZ); + random_str_test(1000 * BLOCK_SZ); + random_str_test(2000 * BLOCK_SZ); + + Ok(()) +} diff --git a/easy-fs/.gitignore b/easy-fs/.gitignore new file mode 100644 index 0000000..79f5db6 --- /dev/null +++ b/easy-fs/.gitignore @@ -0,0 +1,3 @@ +.idea/ +target/ +Cargo.lock diff --git a/easy-fs/Cargo.toml b/easy-fs/Cargo.toml new file mode 100644 index 0000000..6e7cd92 --- /dev/null +++ b/easy-fs/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "easy-fs" +version = "0.1.0" +authors = ["Yifan Wu "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +spin = "0.7.0" +lazy_static = { version = "1.4.0", features = ["spin_no_std"] } \ No newline at end of file diff --git a/easy-fs/src/bitmap.rs b/easy-fs/src/bitmap.rs new file mode 100644 index 0000000..d5416f2 --- /dev/null +++ b/easy-fs/src/bitmap.rs @@ -0,0 +1,77 @@ +use alloc::sync::Arc; +use super::{ + BlockDevice, + BLOCK_SZ, + get_block_cache, +}; + +/// A bitmap block +type BitmapBlock = [u64; 64]; + +/// Number of bits in a block +const BLOCK_BITS: usize = BLOCK_SZ * 8; + +/// A bitmap +pub struct Bitmap { + start_block_id: usize, + blocks: usize, +} + +/// Decompose bits into (block_pos, bits64_pos, inner_pos) +fn decomposition(mut bit: usize) -> (usize, usize, usize) { + let block_pos = bit / BLOCK_BITS; + bit = bit % BLOCK_BITS; + (block_pos, bit / 64, bit % 64) +} + +impl Bitmap { + /// A new bitmap from start block id and number of blocks + pub fn new(start_block_id: usize, blocks: usize) -> Self { + Self { + start_block_id, + blocks, + } + } + /// Allocate a new block from a block device + pub fn alloc(&self, block_device: &Arc) -> Option { + for block_id in 0..self.blocks { + let pos = get_block_cache( + block_id + self.start_block_id as usize, + Arc::clone(block_device), + ).lock().modify(0, |bitmap_block: &mut BitmapBlock| { + if let Some((bits64_pos, inner_pos)) = bitmap_block + .iter() + .enumerate() + .find(|(_, bits64)| **bits64 != u64::MAX) + .map(|(bits64_pos, bits64)| { + (bits64_pos, bits64.trailing_ones() as usize) + }) { + // modify cache + bitmap_block[bits64_pos] |= 1u64 << inner_pos; + Some(block_id * BLOCK_BITS + bits64_pos * 64 + inner_pos as usize) + } else { + None + } + }); + if pos.is_some() { + return pos; + } + } + None + } + /// Deallocate a block + pub fn dealloc(&self, block_device: &Arc, bit: usize) { + let (block_pos, bits64_pos, inner_pos) = decomposition(bit); + get_block_cache( + block_pos + self.start_block_id, + Arc::clone(block_device) + ).lock().modify(0, |bitmap_block: &mut BitmapBlock| { + assert!(bitmap_block[bits64_pos] & (1u64 << inner_pos) > 0); + bitmap_block[bits64_pos] -= 1u64 << inner_pos; + }); + } + /// Get the max number of allocatable blocks + pub fn maximum(&self) -> usize { + self.blocks * BLOCK_BITS + } +} diff --git a/easy-fs/src/block_cache.rs b/easy-fs/src/block_cache.rs new file mode 100644 index 0000000..1ae049e --- /dev/null +++ b/easy-fs/src/block_cache.rs @@ -0,0 +1,144 @@ +use super::{ + BLOCK_SZ, + BlockDevice, +}; +use alloc::collections::VecDeque; +use alloc::sync::Arc; +use lazy_static::*; +use spin::Mutex; + +/// Cached block inside memory +pub struct BlockCache { + /// cached block data + cache: [u8; BLOCK_SZ], + /// underlying block id + block_id: usize, + /// underlying block device + block_device: Arc, + /// whether the block is dirty + modified: bool, +} + +impl BlockCache { + /// Load a new BlockCache from disk. + pub fn new( + block_id: usize, + block_device: Arc + ) -> Self { + let mut cache = [0u8; BLOCK_SZ]; + block_device.read_block(block_id, &mut cache); + Self { + cache, + block_id, + block_device, + modified: false, + } + } + /// Get the address of an offset inside the cached block data + fn addr_of_offset(&self, offset: usize) -> usize { + &self.cache[offset] as *const _ as usize + } + + pub fn get_ref(&self, offset: usize) -> &T where T: Sized { + let type_size = core::mem::size_of::(); + assert!(offset + type_size <= BLOCK_SZ); + let addr = self.addr_of_offset(offset); + unsafe { &*(addr as *const T) } + } + + pub fn get_mut(&mut self, offset: usize) -> &mut T where T: Sized { + let type_size = core::mem::size_of::(); + assert!(offset + type_size <= BLOCK_SZ); + self.modified = true; + let addr = self.addr_of_offset(offset); + unsafe { &mut *(addr as *mut T) } + } + + pub fn read(&self, offset: usize, f: impl FnOnce(&T) -> V) -> V { + f(self.get_ref(offset)) + } + + pub fn modify(&mut self, offset:usize, f: impl FnOnce(&mut T) -> V) -> V { + f(self.get_mut(offset)) + } + + pub fn sync(&mut self) { + if self.modified { + self.modified = false; + self.block_device.write_block(self.block_id, &self.cache); + } + } +} + +impl Drop for BlockCache { + fn drop(&mut self) { + self.sync() + } +} + +/// Use a block cache of 16 blocks +const BLOCK_CACHE_SIZE: usize = 16; + +pub struct BlockCacheManager { + queue: VecDeque<(usize, Arc>)>, +} + +impl BlockCacheManager { + pub fn new() -> Self { + Self { queue: VecDeque::new() } + } + + pub fn get_block_cache( + &mut self, + block_id: usize, + block_device: Arc, + ) -> Arc> { + if let Some(pair) = self.queue + .iter() + .find(|pair| pair.0 == block_id) { + Arc::clone(&pair.1) + } else { + // substitute + if self.queue.len() == BLOCK_CACHE_SIZE { + // from front to tail + if let Some((idx, _)) = self.queue + .iter() + .enumerate() + .find(|(_, pair)| Arc::strong_count(&pair.1) == 1) { + self.queue.drain(idx..=idx); + } else { + panic!("Run out of BlockCache!"); + } + } + // load block into mem and push back + let block_cache = Arc::new(Mutex::new( + BlockCache::new(block_id, Arc::clone(&block_device)) + )); + self.queue.push_back((block_id, Arc::clone(&block_cache))); + block_cache + } + } +} + +lazy_static! { + /// The global block cache manager + pub static ref BLOCK_CACHE_MANAGER: Mutex = Mutex::new( + BlockCacheManager::new() + ); +} + +/// Get the block cache corresponding to the given block id and block device +pub fn get_block_cache( + block_id: usize, + block_device: Arc +) -> Arc> { + BLOCK_CACHE_MANAGER.lock().get_block_cache(block_id, block_device) +} + +/// Sync all block cache to block device +pub fn block_cache_sync_all() { + let manager = BLOCK_CACHE_MANAGER.lock(); + for (_, cache) in manager.queue.iter() { + cache.lock().sync(); + } +} diff --git a/easy-fs/src/block_dev.rs b/easy-fs/src/block_dev.rs new file mode 100644 index 0000000..7472c5d --- /dev/null +++ b/easy-fs/src/block_dev.rs @@ -0,0 +1,8 @@ +use core::any::Any; + +/// Trait for block devices +/// which reads and writes data in the unit of blocks +pub trait BlockDevice : Send + Sync + Any { + fn read_block(&self, block_id: usize, buf: &mut [u8]); + fn write_block(&self, block_id: usize, buf: &[u8]); +} diff --git a/easy-fs/src/efs.rs b/easy-fs/src/efs.rs new file mode 100644 index 0000000..33f6942 --- /dev/null +++ b/easy-fs/src/efs.rs @@ -0,0 +1,164 @@ +use alloc::sync::Arc; +use spin::Mutex; +use super::{ + BlockDevice, + Bitmap, + SuperBlock, + DiskInode, + DiskInodeType, + Inode, + get_block_cache, + block_cache_sync_all, +}; +use crate::BLOCK_SZ; + +/// An easy fs over a block device +pub struct EasyFileSystem { + pub block_device: Arc, + pub inode_bitmap: Bitmap, + pub data_bitmap: Bitmap, + inode_area_start_block: u32, + data_area_start_block: u32, +} + +/// A data block of block size +type DataBlock = [u8; BLOCK_SZ]; + +impl EasyFileSystem { + /// Create a filesystem from a block device + pub fn create( + block_device: Arc, + total_blocks: u32, + inode_bitmap_blocks: u32, + ) -> Arc> { + // calculate block size of areas & create bitmaps + let inode_bitmap = Bitmap::new(1, inode_bitmap_blocks as usize); + let inode_num = inode_bitmap.maximum(); + let inode_area_blocks = + ((inode_num * core::mem::size_of::() + BLOCK_SZ - 1) / BLOCK_SZ) as u32; + let inode_total_blocks = inode_bitmap_blocks + inode_area_blocks; + let data_total_blocks = total_blocks - 1 - inode_total_blocks; + let data_bitmap_blocks = (data_total_blocks + 4096) / 4097; + let data_area_blocks = data_total_blocks - data_bitmap_blocks; + let data_bitmap = Bitmap::new( + (1 + inode_bitmap_blocks + inode_area_blocks) as usize, + data_bitmap_blocks as usize, + ); + let mut efs = Self { + block_device: Arc::clone(&block_device), + inode_bitmap, + data_bitmap, + inode_area_start_block: 1 + inode_bitmap_blocks, + data_area_start_block: 1 + inode_total_blocks + data_bitmap_blocks, + }; + // clear all blocks + for i in 0..total_blocks { + get_block_cache( + i as usize, + Arc::clone(&block_device) + ) + .lock() + .modify(0, |data_block: &mut DataBlock| { + for byte in data_block.iter_mut() { *byte = 0; } + }); + } + // initialize SuperBlock + get_block_cache(0, Arc::clone(&block_device)) + .lock() + .modify(0, |super_block: &mut SuperBlock| { + super_block.initialize( + total_blocks, + inode_bitmap_blocks, + inode_area_blocks, + data_bitmap_blocks, + data_area_blocks, + ); + }); + // write back immediately + // create a inode for root node "/" + assert_eq!(efs.alloc_inode(), 0); + let (root_inode_block_id, root_inode_offset) = efs.get_disk_inode_pos(0); + get_block_cache( + root_inode_block_id as usize, + Arc::clone(&block_device) + ) + .lock() + .modify(root_inode_offset, |disk_inode: &mut DiskInode| { + disk_inode.initialize(DiskInodeType::Directory); + }); + block_cache_sync_all(); + Arc::new(Mutex::new(efs)) + } + /// Open a block device as a filesystem + pub fn open(block_device: Arc) -> Arc> { + // read SuperBlock + get_block_cache(0, Arc::clone(&block_device)) + .lock() + .read(0, |super_block: &SuperBlock| { + assert!(super_block.is_valid(), "Error loading EFS!"); + let inode_total_blocks = + super_block.inode_bitmap_blocks + super_block.inode_area_blocks; + let efs = Self { + block_device, + inode_bitmap: Bitmap::new( + 1, + super_block.inode_bitmap_blocks as usize + ), + data_bitmap: Bitmap::new( + (1 + inode_total_blocks) as usize, + super_block.data_bitmap_blocks as usize, + ), + inode_area_start_block: 1 + super_block.inode_bitmap_blocks, + data_area_start_block: 1 + inode_total_blocks + super_block.data_bitmap_blocks, + }; + Arc::new(Mutex::new(efs)) + }) + } + /// Get the root inode of the filesystem + pub fn root_inode(efs: &Arc>) -> Inode { + let block_device = Arc::clone(&efs.lock().block_device); + // acquire efs lock temporarily + let (block_id, block_offset) = efs.lock().get_disk_inode_pos(0); + // release efs lock + Inode::new( + block_id, + block_offset, + Arc::clone(efs), + block_device, + ) + } + /// Get inode by id + pub fn get_disk_inode_pos(&self, inode_id: u32) -> (u32, usize) { + let inode_size = core::mem::size_of::(); + let inodes_per_block = (BLOCK_SZ / inode_size) as u32; + let block_id = self.inode_area_start_block + inode_id / inodes_per_block; + (block_id, (inode_id % inodes_per_block) as usize * inode_size) + } + /// Get data block by id + pub fn get_data_block_id(&self, data_block_id: u32) -> u32 { + self.data_area_start_block + data_block_id + } + /// Allocate a new inode + pub fn alloc_inode(&mut self) -> u32 { + self.inode_bitmap.alloc(&self.block_device).unwrap() as u32 + } + /// Allocate a data block + pub fn alloc_data(&mut self) -> u32 { + self.data_bitmap.alloc(&self.block_device).unwrap() as u32 + self.data_area_start_block + } + /// Deallocate a data block + pub fn dealloc_data(&mut self, block_id: u32) { + get_block_cache( + block_id as usize, + Arc::clone(&self.block_device) + ) + .lock() + .modify(0, |data_block: &mut DataBlock| { + data_block.iter_mut().for_each(|p| { *p = 0; }) + }); + self.data_bitmap.dealloc( + &self.block_device, + (block_id - self.data_area_start_block) as usize + ) + } +} diff --git a/easy-fs/src/layout.rs b/easy-fs/src/layout.rs new file mode 100644 index 0000000..61a7b02 --- /dev/null +++ b/easy-fs/src/layout.rs @@ -0,0 +1,477 @@ +use core::fmt::{Debug, Formatter, Result}; +use super::{ + BLOCK_SZ, + BlockDevice, + get_block_cache, +}; +use alloc::sync::Arc; +use alloc::vec::Vec; + +/// Magic number for sanity check +const EFS_MAGIC: u32 = 0x3b800001; +/// The max number of direct inodes +const INODE_DIRECT_COUNT: usize = 28; +/// The max length of inode name +const NAME_LENGTH_LIMIT: usize = 27; +/// The max number of indirect1 inodes +const INODE_INDIRECT1_COUNT: usize = BLOCK_SZ / 4; +/// The max number of indirect2 inodes +const INODE_INDIRECT2_COUNT: usize = INODE_INDIRECT1_COUNT * INODE_INDIRECT1_COUNT; +/// The upper bound of direct inode index +const DIRECT_BOUND: usize = INODE_DIRECT_COUNT; +/// The upper bound of indirect1 inode index +const INDIRECT1_BOUND: usize = DIRECT_BOUND + INODE_INDIRECT1_COUNT; +/// The upper bound of indirect2 inode index +#[allow(unused)] +const INDIRECT2_BOUND: usize = INDIRECT1_BOUND + INODE_INDIRECT2_COUNT; + +/// Super block of a filesystem +#[repr(C)] +pub struct SuperBlock { + magic: u32, + pub total_blocks: u32, + pub inode_bitmap_blocks: u32, + pub inode_area_blocks: u32, + pub data_bitmap_blocks: u32, + pub data_area_blocks: u32, +} + +impl Debug for SuperBlock { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + f.debug_struct("SuperBlock") + .field("total_blocks", &self.total_blocks) + .field("inode_bitmap_blocks", &self.inode_bitmap_blocks) + .field("inode_area_blocks", &self.inode_area_blocks) + .field("data_bitmap_blocks", &self.data_bitmap_blocks) + .field("data_area_blocks", &self.data_area_blocks) + .finish() + } +} + +impl SuperBlock { + /// Initialize a super block + pub fn initialize( + &mut self, + total_blocks: u32, + inode_bitmap_blocks: u32, + inode_area_blocks: u32, + data_bitmap_blocks: u32, + data_area_blocks: u32, + ) { + *self = Self { + magic: EFS_MAGIC, + total_blocks, + inode_bitmap_blocks, + inode_area_blocks, + data_bitmap_blocks, + data_area_blocks, + } + } + /// Check if a super block is valid using efs magic + pub fn is_valid(&self) -> bool { + self.magic == EFS_MAGIC + } +} + +/// Type of a disk inode +#[derive(PartialEq)] +pub enum DiskInodeType { + File, + Directory, +} + +/// A indirect block +type IndirectBlock = [u32; BLOCK_SZ / 4]; +/// A data block +type DataBlock = [u8; BLOCK_SZ]; + +/// A disk inode +#[repr(C)] +pub struct DiskInode { + pub size: u32, + pub direct: [u32; INODE_DIRECT_COUNT], + pub indirect1: u32, + pub indirect2: u32, + type_: DiskInodeType, +} + +impl DiskInode { + /// Initialize a disk inode, as well as all direct inodes under it + /// indirect1 and indirect2 block are allocated only when they are needed + pub fn initialize(&mut self, type_: DiskInodeType) { + self.size = 0; + self.direct.iter_mut().for_each(|v| *v = 0); + self.indirect1 = 0; + self.indirect2 = 0; + self.type_ = type_; + } + /// Whether this inode is a directory + pub fn is_dir(&self) -> bool { + self.type_ == DiskInodeType::Directory + } + /// Whether this inode is a file + #[allow(unused)] + pub fn is_file(&self) -> bool { + self.type_ == DiskInodeType::File + } + /// Get the number of data blocks corresponding to size + pub fn data_blocks(&self) -> u32 { + Self::_data_blocks(self.size) + } + fn _data_blocks(size: u32) -> u32 { + (size + BLOCK_SZ as u32 - 1) / BLOCK_SZ as u32 + } + /// Get the number of data blocks required for the given size of data + pub fn total_blocks(size: u32) -> u32 { + let data_blocks = Self::_data_blocks(size) as usize; + let mut total = data_blocks as usize; + // indirect1 + if data_blocks > INODE_DIRECT_COUNT { + total += 1; + } + // indirect2 + if data_blocks > INDIRECT1_BOUND { + total += 1; + // sub indirect1 + total += (data_blocks - INDIRECT1_BOUND + INODE_INDIRECT1_COUNT - 1) / INODE_INDIRECT1_COUNT; + } + total as u32 + } + /// Get the number of data blocks that have to be allocated given the new size of data + pub fn blocks_num_needed(&self, new_size: u32) -> u32 { + assert!(new_size >= self.size); + Self::total_blocks(new_size) - Self::total_blocks(self.size) + } + /// Get id of block given inner id + pub fn get_block_id(&self, inner_id: u32, block_device: &Arc) -> u32 { + let inner_id = inner_id as usize; + if inner_id < INODE_DIRECT_COUNT { + self.direct[inner_id] + } else if inner_id < INDIRECT1_BOUND { + get_block_cache(self.indirect1 as usize, Arc::clone(block_device)) + .lock() + .read(0, |indirect_block: &IndirectBlock| { + indirect_block[inner_id - INODE_DIRECT_COUNT] + }) + } else { + let last = inner_id - INDIRECT1_BOUND; + let indirect1 = get_block_cache( + self.indirect2 as usize, + Arc::clone(block_device) + ) + .lock() + .read(0, |indirect2: &IndirectBlock| { + indirect2[last / INODE_INDIRECT1_COUNT] + }); + get_block_cache( + indirect1 as usize, + Arc::clone(block_device) + ) + .lock() + .read(0, |indirect1: &IndirectBlock| { + indirect1[last % INODE_INDIRECT1_COUNT] + }) + } + } + /// Inncrease the size of current disk inode + pub fn increase_size( + &mut self, + new_size: u32, + new_blocks: Vec, + block_device: &Arc, + ) { + let mut current_blocks = self.data_blocks(); + self.size = new_size; + let mut total_blocks = self.data_blocks(); + let mut new_blocks = new_blocks.into_iter(); + // fill direct + while current_blocks < total_blocks.min(INODE_DIRECT_COUNT as u32) { + self.direct[current_blocks as usize] = new_blocks.next().unwrap(); + current_blocks += 1; + } + // alloc indirect1 + if total_blocks > INODE_DIRECT_COUNT as u32{ + if current_blocks == INODE_DIRECT_COUNT as u32 { + self.indirect1 = new_blocks.next().unwrap(); + } + current_blocks -= INODE_DIRECT_COUNT as u32; + total_blocks -= INODE_DIRECT_COUNT as u32; + } else { + return; + } + // fill indirect1 + get_block_cache( + self.indirect1 as usize, + Arc::clone(block_device) + ) + .lock() + .modify(0, |indirect1: &mut IndirectBlock| { + while current_blocks < total_blocks.min(INODE_INDIRECT1_COUNT as u32) { + indirect1[current_blocks as usize] = new_blocks.next().unwrap(); + current_blocks += 1; + } + }); + // alloc indirect2 + if total_blocks > INODE_INDIRECT1_COUNT as u32 { + if current_blocks == INODE_INDIRECT1_COUNT as u32 { + self.indirect2 = new_blocks.next().unwrap(); + } + current_blocks -= INODE_INDIRECT1_COUNT as u32; + total_blocks -= INODE_INDIRECT1_COUNT as u32; + } else { + return; + } + // fill indirect2 from (a0, b0) -> (a1, b1) + let mut a0 = current_blocks as usize / INODE_INDIRECT1_COUNT; + let mut b0 = current_blocks as usize % INODE_INDIRECT1_COUNT; + let a1 = total_blocks as usize / INODE_INDIRECT1_COUNT; + let b1 = total_blocks as usize % INODE_INDIRECT1_COUNT; + // alloc low-level indirect1 + get_block_cache( + self.indirect2 as usize, + Arc::clone(block_device) + ) + .lock() + .modify(0, |indirect2: &mut IndirectBlock| { + while (a0 < a1) || (a0 == a1 && b0 < b1) { + if b0 == 0 { + indirect2[a0] = new_blocks.next().unwrap(); + } + // fill current + get_block_cache( + indirect2[a0] as usize, + Arc::clone(block_device) + ) + .lock() + .modify(0, |indirect1: &mut IndirectBlock| { + indirect1[b0] = new_blocks.next().unwrap(); + }); + // move to next + b0 += 1; + if b0 == INODE_INDIRECT1_COUNT { + b0 = 0; + a0 += 1; + } + } + }); + } + /// Clear size to zero and return blocks that should be deallocated + /// and clear the block contents to zero later + pub fn clear_size(&mut self, block_device: &Arc) -> Vec { + let mut v: Vec = Vec::new(); + let mut data_blocks = self.data_blocks() as usize; + self.size = 0; + let mut current_blocks = 0usize; + // direct + while current_blocks < data_blocks.min(INODE_DIRECT_COUNT) { + v.push(self.direct[current_blocks]); + self.direct[current_blocks] = 0; + current_blocks += 1; + } + // indirect1 block + if data_blocks > INODE_DIRECT_COUNT { + v.push(self.indirect1); + data_blocks -= INODE_DIRECT_COUNT; + current_blocks = 0; + } else { + return v; + } + // indirect1 + get_block_cache( + self.indirect1 as usize, + Arc::clone(block_device), + ) + .lock() + .modify(0, |indirect1: &mut IndirectBlock| { + while current_blocks < data_blocks.min(INODE_INDIRECT1_COUNT) { + v.push(indirect1[current_blocks]); + //indirect1[current_blocks] = 0; + current_blocks += 1; + } + }); + self.indirect1 = 0; + // indirect2 block + if data_blocks > INODE_INDIRECT1_COUNT { + v.push(self.indirect2); + data_blocks -= INODE_INDIRECT1_COUNT; + } else { + return v; + } + // indirect2 + assert!(data_blocks <= INODE_INDIRECT2_COUNT); + let a1 = data_blocks / INODE_INDIRECT1_COUNT; + let b1 = data_blocks % INODE_INDIRECT1_COUNT; + get_block_cache( + self.indirect2 as usize, + Arc::clone(block_device), + ) + .lock() + .modify(0, |indirect2: &mut IndirectBlock| { + // full indirect1 blocks + for i in 0..a1 { + v.push(indirect2[i]); + get_block_cache( + indirect2[i] as usize, + Arc::clone(block_device), + ) + .lock() + .modify(0, |indirect1: &mut IndirectBlock| { + for j in 0..INODE_INDIRECT1_COUNT { + v.push(indirect1[j]); + //indirect1[j] = 0; + } + }); + //indirect2[i] = 0; + } + // last indirect1 block + if b1 > 0 { + v.push(indirect2[a1]); + get_block_cache( + indirect2[a1] as usize, + Arc::clone(block_device), + ) + .lock() + .modify(0, |indirect1: &mut IndirectBlock| { + for j in 0..b1 { + v.push(indirect1[j]); + //indirect1[j] = 0; + } + }); + //indirect2[a1] = 0; + } + }); + self.indirect2 = 0; + v + } + /// Read data from current disk inode + pub fn read_at( + &self, + offset: usize, + buf: &mut [u8], + block_device: &Arc, + ) -> usize { + let mut start = offset; + let end = (offset + buf.len()).min(self.size as usize); + if start >= end { + return 0; + } + let mut start_block = start / BLOCK_SZ; + let mut read_size = 0usize; + loop { + // calculate end of current block + let mut end_current_block = (start / BLOCK_SZ + 1) * BLOCK_SZ; + end_current_block = end_current_block.min(end); + // read and update read size + let block_read_size = end_current_block - start; + let dst = &mut buf[read_size..read_size + block_read_size]; + get_block_cache( + self.get_block_id(start_block as u32, block_device) as usize, + Arc::clone(block_device), + ) + .lock() + .read(0, |data_block: &DataBlock| { + let src = &data_block[start % BLOCK_SZ..start % BLOCK_SZ + block_read_size]; + dst.copy_from_slice(src); + }); + read_size += block_read_size; + // move to next block + if end_current_block == end { break; } + start_block += 1; + start = end_current_block; + } + read_size + } + /// Write data into current disk inode + /// size must be adjusted properly beforehand + pub fn write_at( + &mut self, + offset: usize, + buf: &[u8], + block_device: &Arc, + ) -> usize { + let mut start = offset; + let end = (offset + buf.len()).min(self.size as usize); + assert!(start <= end); + let mut start_block = start / BLOCK_SZ; + let mut write_size = 0usize; + loop { + // calculate end of current block + let mut end_current_block = (start / BLOCK_SZ + 1) * BLOCK_SZ; + end_current_block = end_current_block.min(end); + // write and update write size + let block_write_size = end_current_block - start; + get_block_cache( + self.get_block_id(start_block as u32, block_device) as usize, + Arc::clone(block_device) + ) + .lock() + .modify(0, |data_block: &mut DataBlock| { + let src = &buf[write_size..write_size + block_write_size]; + let dst = &mut data_block[start % BLOCK_SZ..start % BLOCK_SZ + block_write_size]; + dst.copy_from_slice(src); + }); + write_size += block_write_size; + // move to next block + if end_current_block == end { break; } + start_block += 1; + start = end_current_block; + } + write_size + } +} + +/// A directory entry +#[repr(C)] +pub struct DirEntry { + name: [u8; NAME_LENGTH_LIMIT + 1], + inode_number: u32, +} + +/// Size of a directory entry +pub const DIRENT_SZ: usize = 32; + +impl DirEntry { + /// Create an empty directory entry + pub fn empty() -> Self { + Self { + name: [0u8; NAME_LENGTH_LIMIT + 1], + inode_number: 0, + } + } + /// Crate a directory entry from name and inode number + pub fn new(name: &str, inode_number: u32) -> Self { + let mut bytes = [0u8; NAME_LENGTH_LIMIT + 1]; + bytes[..name.len()].copy_from_slice(name.as_bytes()); + Self { + name: bytes, + inode_number, + } + } + /// Serialize into bytes + pub fn as_bytes(&self) -> &[u8] { + unsafe { + core::slice::from_raw_parts( + self as *const _ as usize as *const u8, + DIRENT_SZ, + ) + } + } + /// Serialize into mutable bytes + pub fn as_bytes_mut(&mut self) -> &mut [u8] { + unsafe { + core::slice::from_raw_parts_mut( + self as *mut _ as usize as *mut u8, + DIRENT_SZ, + ) + } + } + /// Get name of the entry + pub fn name(&self) -> &str { + let len = (0usize..).find(|i| self.name[*i] == 0).unwrap(); + core::str::from_utf8(&self.name[..len]).unwrap() + } + /// Get inode number of the entry + pub fn inode_number(&self) -> u32 { + self.inode_number + } +} diff --git a/easy-fs/src/lib.rs b/easy-fs/src/lib.rs new file mode 100644 index 0000000..b1b655d --- /dev/null +++ b/easy-fs/src/lib.rs @@ -0,0 +1,19 @@ +#![no_std] + +extern crate alloc; + +mod block_dev; +mod layout; +mod efs; +mod bitmap; +mod vfs; +mod block_cache; + +/// Use a block size of 512 bytes +pub const BLOCK_SZ: usize = 512; +pub use block_dev::BlockDevice; +pub use efs::EasyFileSystem; +pub use vfs::Inode; +use layout::*; +use bitmap::Bitmap; +use block_cache::{get_block_cache, block_cache_sync_all}; diff --git a/easy-fs/src/vfs.rs b/easy-fs/src/vfs.rs new file mode 100644 index 0000000..22ac0d8 --- /dev/null +++ b/easy-fs/src/vfs.rs @@ -0,0 +1,211 @@ +use super::{ + BlockDevice, + DiskInode, + DiskInodeType, + DirEntry, + EasyFileSystem, + DIRENT_SZ, + get_block_cache, + block_cache_sync_all, +}; +use alloc::sync::Arc; +use alloc::string::String; +use alloc::vec::Vec; +use spin::{Mutex, MutexGuard}; + +/// Virtual filesystem layer over easy-fs +pub struct Inode { + block_id: usize, + block_offset: usize, + fs: Arc>, + block_device: Arc, +} + +impl Inode { + /// Create a vfs inode + pub fn new( + block_id: u32, + block_offset: usize, + fs: Arc>, + block_device: Arc, + ) -> Self { + Self { + block_id: block_id as usize, + block_offset, + fs, + block_device, + } + } + /// Call a function over a disk inode to read it + fn read_disk_inode(&self, f: impl FnOnce(&DiskInode) -> V) -> V { + get_block_cache( + self.block_id, + Arc::clone(&self.block_device) + ).lock().read(self.block_offset, f) + } + /// Call a function over a disk inode to modify it + fn modify_disk_inode(&self, f: impl FnOnce(&mut DiskInode) -> V) -> V { + get_block_cache( + self.block_id, + Arc::clone(&self.block_device) + ).lock().modify(self.block_offset, f) + } + /// Find inode under a disk inode by name + fn find_inode_id( + &self, + name: &str, + disk_inode: &DiskInode, + ) -> Option { + // assert it is a directory + assert!(disk_inode.is_dir()); + let file_count = (disk_inode.size as usize) / DIRENT_SZ; + let mut dirent = DirEntry::empty(); + for i in 0..file_count { + assert_eq!( + disk_inode.read_at( + DIRENT_SZ * i, + dirent.as_bytes_mut(), + &self.block_device, + ), + DIRENT_SZ, + ); + if dirent.name() == name { + return Some(dirent.inode_number() as u32); + } + } + None + } + /// Find inode under current inode by name + pub fn find(&self, name: &str) -> Option> { + let fs = self.fs.lock(); + self.read_disk_inode(|disk_inode| { + self.find_inode_id(name, disk_inode) + .map(|inode_id| { + let (block_id, block_offset) = fs.get_disk_inode_pos(inode_id); + Arc::new(Self::new( + block_id, + block_offset, + self.fs.clone(), + self.block_device.clone(), + )) + }) + }) + } + /// Increase the size of a disk inode + fn increase_size( + &self, + new_size: u32, + disk_inode: &mut DiskInode, + fs: &mut MutexGuard, + ) { + if new_size < disk_inode.size { + return; + } + let blocks_needed = disk_inode.blocks_num_needed(new_size); + let mut v: Vec = Vec::new(); + for _ in 0..blocks_needed { + v.push(fs.alloc_data()); + } + disk_inode.increase_size(new_size, v, &self.block_device); + } + /// Create inode under current inode by name + pub fn create(&self, name: &str) -> Option> { + let mut fs = self.fs.lock(); + if self.modify_disk_inode(|root_inode| { + // assert it is a directory + assert!(root_inode.is_dir()); + // has the file been created? + self.find_inode_id(name, root_inode) + }).is_some() { + return None; + } + // create a new file + // alloc a inode with an indirect block + let new_inode_id = fs.alloc_inode(); + // initialize inode + let (new_inode_block_id, new_inode_block_offset) + = fs.get_disk_inode_pos(new_inode_id); + get_block_cache( + new_inode_block_id as usize, + Arc::clone(&self.block_device) + ).lock().modify(new_inode_block_offset, |new_inode: &mut DiskInode| { + new_inode.initialize(DiskInodeType::File); + }); + self.modify_disk_inode(|root_inode| { + // append file in the dirent + let file_count = (root_inode.size as usize) / DIRENT_SZ; + let new_size = (file_count + 1) * DIRENT_SZ; + // increase size + self.increase_size(new_size as u32, root_inode, &mut fs); + // write dirent + let dirent = DirEntry::new(name, new_inode_id); + root_inode.write_at( + file_count * DIRENT_SZ, + dirent.as_bytes(), + &self.block_device, + ); + }); + + let (block_id, block_offset) = fs.get_disk_inode_pos(new_inode_id); + block_cache_sync_all(); + // return inode + Some(Arc::new(Self::new( + block_id, + block_offset, + self.fs.clone(), + self.block_device.clone(), + ))) + // release efs lock automatically by compiler + } + /// List inodes under current inode + pub fn ls(&self) -> Vec { + let _fs = self.fs.lock(); + self.read_disk_inode(|disk_inode| { + let file_count = (disk_inode.size as usize) / DIRENT_SZ; + let mut v: Vec = Vec::new(); + for i in 0..file_count { + let mut dirent = DirEntry::empty(); + assert_eq!( + disk_inode.read_at( + i * DIRENT_SZ, + dirent.as_bytes_mut(), + &self.block_device, + ), + DIRENT_SZ, + ); + v.push(String::from(dirent.name())); + } + v + }) + } + /// Read data from current inode + pub fn read_at(&self, offset: usize, buf: &mut [u8]) -> usize { + let _fs = self.fs.lock(); + self.read_disk_inode(|disk_inode| { + disk_inode.read_at(offset, buf, &self.block_device) + }) + } + /// Write data to current inode + pub fn write_at(&self, offset: usize, buf: &[u8]) -> usize { + let mut fs = self.fs.lock(); + let size = self.modify_disk_inode(|disk_inode| { + self.increase_size((offset + buf.len()) as u32, disk_inode, &mut fs); + disk_inode.write_at(offset, buf, &self.block_device) + }); + block_cache_sync_all(); + size + } + /// Clear the data in current inode + pub fn clear(&self) { + let mut fs = self.fs.lock(); + self.modify_disk_inode(|disk_inode| { + let size = disk_inode.size; + let data_blocks_dealloc = disk_inode.clear_size(&self.block_device); + assert!(data_blocks_dealloc.len() == DiskInode::total_blocks(size) as usize); + for data_block in data_blocks_dealloc.into_iter() { + fs.dealloc_data(data_block); + } + }); + block_cache_sync_all(); + } +} diff --git a/os1/.cargo/config b/os1/.cargo/config new file mode 100644 index 0000000..4275fca --- /dev/null +++ b/os1/.cargo/config @@ -0,0 +1,7 @@ +[build] +target = "riscv64gc-unknown-none-elf" + +[target.riscv64gc-unknown-none-elf] +rustflags = [ + "-Clink-arg=-Tsrc/linker.ld", "-Cforce-frame-pointers=yes" +] diff --git a/os1/Cargo.toml b/os1/Cargo.toml new file mode 100644 index 0000000..ef61cb9 --- /dev/null +++ b/os1/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "os" +version = "0.1.0" +authors = ["Yifan Wu "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +log = "0.4" diff --git a/os1/Makefile b/os1/Makefile new file mode 100644 index 0000000..e3c1ded --- /dev/null +++ b/os1/Makefile @@ -0,0 +1,49 @@ +# Building +TARGET := riscv64gc-unknown-none-elf +MODE := release +KERNEL_ELF := target/$(TARGET)/$(MODE)/os +KERNEL_BIN := $(KERNEL_ELF).bin + +# BOARD +BOARD ?= qemu +SBI ?= rustsbi +BOOTLOADER := ../bootloader/$(SBI)-$(BOARD).bin + +# KERNEL ENTRY +KERNEL_ENTRY_PA := 0x80200000 + +# Binutils +OBJDUMP := rust-objdump --arch-name=riscv64 +OBJCOPY := rust-objcopy --binary-architecture=riscv64 + +build: env $(KERNEL_BIN) + +$(KERNEL_BIN): kernel + @$(OBJCOPY) $(KERNEL_ELF) --strip-all -O binary $@ + +env: + (rustup target list | grep "riscv64gc-unknown-none-elf (installed)") || rustup target add $(TARGET) + cargo install cargo-binutils --vers ~0.2 + rustup component add rust-src + rustup component add llvm-tools-preview + +kernel: + @cargo build --release + +clean: + @cargo clean + +run: build + @qemu-system-riscv64 \ + -machine virt \ + -nographic \ + -bios $(BOOTLOADER) \ + -device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY_PA) + +debug: build + @tmux new-session -d \ + "qemu-system-riscv64 -machine virt -nographic -bios $(BOOTLOADER) -device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY_PA) -s -S" && \ + tmux split-window -h "riscv64-unknown-elf-gdb -ex 'file $(KERNEL_ELF)' -ex 'set arch riscv:rv64' -ex 'target remote localhost:1234'" && \ + tmux -2 attach-session -d + +.PHONY: build env kernel clean run-inner diff --git a/os1/src/console.rs b/os1/src/console.rs new file mode 100644 index 0000000..632e662 --- /dev/null +++ b/os1/src/console.rs @@ -0,0 +1,37 @@ +/*! + +本模块实现了 print 和 println 宏。 + +*/ + +use crate::sbi::console_putchar; +use core::fmt::{self, Write}; + +struct Stdout; + +impl Write for Stdout { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + console_putchar(c as usize); + } + Ok(()) + } +} + +pub fn print(args: fmt::Arguments) { + Stdout.write_fmt(args).unwrap(); +} + +#[macro_export] +macro_rules! print { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!($fmt $(, $($arg)+)?)); + } +} + +#[macro_export] +macro_rules! println { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?)); + } +} diff --git a/os1/src/entry.asm b/os1/src/entry.asm new file mode 100644 index 0000000..9d2ff71 --- /dev/null +++ b/os1/src/entry.asm @@ -0,0 +1,12 @@ + .section .text.entry + .globl _start +_start: + la sp, boot_stack_top + call rust_main + + .section .bss.stack + .globl boot_stack +boot_stack: + .space 4096 * 16 + .globl boot_stack_top +boot_stack_top: \ No newline at end of file diff --git a/os1/src/lang_items.rs b/os1/src/lang_items.rs new file mode 100644 index 0000000..a6217a0 --- /dev/null +++ b/os1/src/lang_items.rs @@ -0,0 +1,17 @@ +use crate::sbi::shutdown; +use core::panic::PanicInfo; + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + if let Some(location) = info.location() { + println!( + "Panicked at {}:{} {}", + location.file(), + location.line(), + info.message().unwrap() + ); + } else { + println!("Panicked: {}", info.message().unwrap()); + } + shutdown() +} diff --git a/os1/src/link_app.S b/os1/src/link_app.S new file mode 100644 index 0000000..e69de29 diff --git a/os1/src/linker.ld b/os1/src/linker.ld new file mode 100644 index 0000000..8bcce1a --- /dev/null +++ b/os1/src/linker.ld @@ -0,0 +1,48 @@ +OUTPUT_ARCH(riscv) +ENTRY(_start) +BASE_ADDRESS = 0x80200000; + +SECTIONS +{ + . = BASE_ADDRESS; + skernel = .; + + stext = .; + .text : { + *(.text.entry) + *(.text .text.*) + } + + . = ALIGN(4K); + etext = .; + srodata = .; + .rodata : { + *(.rodata .rodata.*) + *(.srodata .srodata.*) + } + + . = ALIGN(4K); + erodata = .; + sdata = .; + .data : { + *(.data .data.*) + *(.sdata .sdata.*) + } + + . = ALIGN(4K); + edata = .; + .bss : { + *(.bss.stack) + sbss = .; + *(.bss .bss.*) + *(.sbss .sbss.*) + } + + . = ALIGN(4K); + ebss = .; + ekernel = .; + + /DISCARD/ : { + *(.eh_frame) + } +} \ No newline at end of file diff --git a/os1/src/logging.rs b/os1/src/logging.rs new file mode 100644 index 0000000..7b7cc56 --- /dev/null +++ b/os1/src/logging.rs @@ -0,0 +1,47 @@ +/*! + +本模块利用 log crate 为你提供了日志功能,使用方式见 main.rs. + +*/ + +use log::{self, Level, LevelFilter, Log, Metadata, Record}; + +struct SimpleLogger; + +impl Log for SimpleLogger { + fn enabled(&self, _metadata: &Metadata) -> bool { + true + } + fn log(&self, record: &Record) { + if !self.enabled(record.metadata()) { + return; + } + let color = match record.level() { + Level::Error => 31, // Red + Level::Warn => 93, // BrightYellow + Level::Info => 34, // Blue + Level::Debug => 32, // Green + Level::Trace => 90, // BrightBlack + }; + println!( + "\u{1B}[{}m[{:>5}] {}\u{1B}[0m", + color, + record.level(), + record.args(), + ); + } + fn flush(&self) {} +} + +pub fn init() { + static LOGGER: SimpleLogger = SimpleLogger; + log::set_logger(&LOGGER).unwrap(); + log::set_max_level(match option_env!("LOG") { + Some("ERROR") => LevelFilter::Error, + Some("WARN") => LevelFilter::Warn, + Some("INFO") => LevelFilter::Info, + Some("DEBUG") => LevelFilter::Debug, + Some("TRACE") => LevelFilter::Trace, + _ => LevelFilter::Off, + }); +} diff --git a/os1/src/main.rs b/os1/src/main.rs new file mode 100644 index 0000000..f3b68eb --- /dev/null +++ b/os1/src/main.rs @@ -0,0 +1,49 @@ +#![no_std] +#![no_main] +#![feature(panic_info_message)] + +use log::*; + +#[macro_use] +mod console; +mod lang_items; +mod logging; +mod sbi; + +core::arch::global_asm!(include_str!("entry.asm")); + +fn clear_bss() { + extern "C" { + fn sbss(); + fn ebss(); + } + (sbss as usize..ebss as usize).for_each(|a| unsafe { (a as *mut u8).write_volatile(0) }); +} + +#[no_mangle] +pub fn rust_main() -> ! { + extern "C" { + fn stext(); + fn etext(); + fn srodata(); + fn erodata(); + fn sdata(); + fn edata(); + fn sbss(); + fn ebss(); + fn boot_stack(); + fn boot_stack_top(); + } + clear_bss(); + logging::init(); + println!("Hello, world!"); + trace!(".text [{:#x}, {:#x})", stext as usize, etext as usize); + debug!(".rodata [{:#x}, {:#x})", srodata as usize, erodata as usize); + info!(".data [{:#x}, {:#x})", sdata as usize, edata as usize); + warn!( + "boot_stack [{:#x}, {:#x})", + boot_stack as usize, boot_stack_top as usize + ); + error!(".bss [{:#x}, {:#x})", sbss as usize, ebss as usize); + panic!("Shutdown machine!"); +} diff --git a/os1/src/sbi.rs b/os1/src/sbi.rs new file mode 100644 index 0000000..751a4d2 --- /dev/null +++ b/os1/src/sbi.rs @@ -0,0 +1,34 @@ +#![allow(unused)] + +const SBI_SET_TIMER: usize = 0; +const SBI_CONSOLE_PUTCHAR: usize = 1; +const SBI_CONSOLE_GETCHAR: usize = 2; +const SBI_SHUTDOWN: usize = 8; + +#[inline(always)] +fn sbi_call(which: usize, arg0: usize, arg1: usize, arg2: usize) -> usize { + let mut ret; + unsafe { + core::arch::asm!( + "ecall", + inlateout("x10") arg0 => ret, + in("x11") arg1, + in("x12") arg2, + in("x17") which, + ); + } + ret +} + +pub fn console_putchar(c: usize) { + sbi_call(SBI_CONSOLE_PUTCHAR, c, 0, 0); +} + +pub fn console_getchar() -> usize { + sbi_call(SBI_CONSOLE_GETCHAR, 0, 0, 0) +} + +pub fn shutdown() -> ! { + sbi_call(SBI_SHUTDOWN, 0, 0, 0); + panic!("It should shutdown!"); +} diff --git a/os2/.cargo/config b/os2/.cargo/config new file mode 100644 index 0000000..4275fca --- /dev/null +++ b/os2/.cargo/config @@ -0,0 +1,7 @@ +[build] +target = "riscv64gc-unknown-none-elf" + +[target.riscv64gc-unknown-none-elf] +rustflags = [ + "-Clink-arg=-Tsrc/linker.ld", "-Cforce-frame-pointers=yes" +] diff --git a/os2/Cargo.toml b/os2/Cargo.toml new file mode 100644 index 0000000..7ddc171 --- /dev/null +++ b/os2/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "os" +version = "0.1.0" +authors = ["Yifan Wu "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +lazy_static = { version = "1.4.0", features = ["spin_no_std"] } +log = "0.4" +riscv = { git = "https://gitee.com/rcore-os/riscv", features = ["inline-asm"] } diff --git a/os2/Makefile b/os2/Makefile new file mode 100644 index 0000000..7224b08 --- /dev/null +++ b/os2/Makefile @@ -0,0 +1,58 @@ +# Building +TARGET := riscv64gc-unknown-none-elf +MODE := release +KERNEL_ELF := target/$(TARGET)/$(MODE)/os +KERNEL_BIN := $(KERNEL_ELF).bin +KERNEL_ASM := $(KERNEL_ELF).asm + +# BOARD +BOARD ?= qemu +SBI ?= rustsbi +BOOTLOADER := ../bootloader/$(SBI)-$(BOARD).bin + +# KERNEL ENTRY +KERNEL_ENTRY_PA := 0x80200000 + +# Binutils +OBJDUMP := rust-objdump --arch-name=riscv64 +OBJCOPY := rust-objcopy --binary-architecture=riscv64 + +CHAPTER ?= 2 +TEST ?= $(CHAPTER) +BASE ?= 1 + +build: env $(KERNEL_BIN) + +$(KERNEL_BIN): kernel + @$(OBJCOPY) $(KERNEL_ELF) --strip-all -O binary $@ + +disasm: + @$(OBJDUMP) $(KERNEL_ELF) -S > $(KERNEL_ELF).asm + +env: + (rustup target list | grep "riscv64gc-unknown-none-elf (installed)") || rustup target add $(TARGET) + cargo install cargo-binutils --vers ~0.2 + rustup component add rust-src + rustup component add llvm-tools-preview + +kernel: + @make -C ../user build TEST=$(TEST) CHAPTER=$(CHAPTER) BASE=$(BASE) + @cargo build --release + +clean: + @cargo clean + +run: build + @qemu-system-riscv64 \ + -machine virt \ + -nographic \ + -bios $(BOOTLOADER) \ + -device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY_PA) + +debug: build + @tmux new-session -d \ + "qemu-system-riscv64 -machine virt -nographic -bios $(BOOTLOADER) -device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY_PA) -s -S" && \ + tmux split-window -h "riscv64-unknown-elf-gdb -ex 'file $(KERNEL_ELF)' -ex 'set arch riscv:rv64' -ex 'target remote localhost:1234'" && \ + tmux -2 attach-session -d + +.PHONY: build env kernel clean run-inner diff --git a/os2/build.rs b/os2/build.rs new file mode 100644 index 0000000..4a44c56 --- /dev/null +++ b/os2/build.rs @@ -0,0 +1,56 @@ +use std::fs::{read_dir, File}; +use std::io::{Result, Write}; + +fn main() { + println!("cargo:rerun-if-changed=../user/src/"); + println!("cargo:rerun-if-changed={}", TARGET_PATH); + insert_app_data().unwrap(); +} + +static TARGET_PATH: &str = "../user/build/bin/"; + +fn insert_app_data() -> Result<()> { + let mut f = File::create("src/link_app.S").unwrap(); + let mut apps: Vec<_> = read_dir("../user/build/bin/") + .unwrap() + .into_iter() + .map(|dir_entry| { + let mut name_with_ext = dir_entry.unwrap().file_name().into_string().unwrap(); + name_with_ext.drain(name_with_ext.find('.').unwrap()..name_with_ext.len()); + name_with_ext + }) + .collect(); + apps.sort(); + + writeln!( + f, + r#" + .align 3 + .section .data + .global _num_app +_num_app: + .quad {}"#, + apps.len() + )?; + + for i in 0..apps.len() { + writeln!(f, r#" .quad app_{}_start"#, i)?; + } + writeln!(f, r#" .quad app_{}_end"#, apps.len() - 1)?; + + for (idx, app) in apps.iter().enumerate() { + println!("app_{}: {}", idx, app); + writeln!( + f, + r#" + .section .data + .global app_{0}_start + .global app_{0}_end +app_{0}_start: + .incbin "{2}{1}.bin" +app_{0}_end:"#, + idx, app, TARGET_PATH + )?; + } + Ok(()) +} diff --git a/os2/src/batch.rs b/os2/src/batch.rs new file mode 100644 index 0000000..7f97793 --- /dev/null +++ b/os2/src/batch.rs @@ -0,0 +1,141 @@ +use crate::sync::UPSafeCell; +use crate::trap::TrapContext; +use lazy_static::*; + +const USER_STACK_SIZE: usize = 4096; +const KERNEL_STACK_SIZE: usize = 4096 * 2; +const MAX_APP_NUM: usize = 16; +const APP_BASE_ADDRESS: usize = 0x80400000; +const APP_SIZE_LIMIT: usize = 0x20000; + +#[repr(align(4096))] +struct KernelStack { + data: [u8; KERNEL_STACK_SIZE], +} + +#[repr(align(4096))] +struct UserStack { + data: [u8; USER_STACK_SIZE], +} + +static KERNEL_STACK: KernelStack = KernelStack { + data: [0; KERNEL_STACK_SIZE], +}; +static USER_STACK: UserStack = UserStack { + data: [0; USER_STACK_SIZE], +}; + +impl KernelStack { + fn get_sp(&self) -> usize { + self.data.as_ptr() as usize + KERNEL_STACK_SIZE + } + pub fn push_context(&self, cx: TrapContext) -> &'static mut TrapContext { + let cx_ptr = (self.get_sp() - core::mem::size_of::()) as *mut TrapContext; + unsafe { + *cx_ptr = cx; + } + unsafe { cx_ptr.as_mut().unwrap() } + } +} + +impl UserStack { + fn get_sp(&self) -> usize { + self.data.as_ptr() as usize + USER_STACK_SIZE + } +} + +struct AppManager { + num_app: usize, + current_app: usize, + app_start: [usize; MAX_APP_NUM + 1], +} + +impl AppManager { + pub fn print_app_info(&self) { + info!("[kernel] num_app = {}", self.num_app); + for i in 0..self.num_app { + info!( + "[kernel] app_{} [{:#x}, {:#x})", + i, + self.app_start[i], + self.app_start[i + 1] + ); + } + } + + unsafe fn load_app(&self, app_id: usize) { + if app_id >= self.num_app { + panic!("All applications completed!"); + } + info!("[kernel] Loading app_{}", app_id); + // clear icache + core::arch::asm!("fence.i"); + // clear app area + core::slice::from_raw_parts_mut(APP_BASE_ADDRESS as *mut u8, APP_SIZE_LIMIT).fill(0); + let app_src = core::slice::from_raw_parts( + self.app_start[app_id] as *const u8, + self.app_start[app_id + 1] - self.app_start[app_id], + ); + let app_dst = core::slice::from_raw_parts_mut(APP_BASE_ADDRESS as *mut u8, app_src.len()); + app_dst.copy_from_slice(app_src); + } + + pub fn get_current_app(&self) -> usize { + self.current_app + } + + pub fn move_to_next_app(&mut self) { + self.current_app += 1; + } +} + +lazy_static! { + static ref APP_MANAGER: UPSafeCell = unsafe { + UPSafeCell::new({ + extern "C" { + fn _num_app(); + } + let num_app_ptr = _num_app as usize as *const usize; + let num_app = num_app_ptr.read_volatile(); + let mut app_start: [usize; MAX_APP_NUM + 1] = [0; MAX_APP_NUM + 1]; + let app_start_raw: &[usize] = + core::slice::from_raw_parts(num_app_ptr.add(1), num_app + 1); + app_start[..=num_app].copy_from_slice(app_start_raw); + AppManager { + num_app, + current_app: 0, + app_start, + } + }) + }; +} + +pub fn init() { + print_app_info(); +} + +pub fn print_app_info() { + APP_MANAGER.exclusive_access().print_app_info(); +} + +pub fn run_next_app() -> ! { + let mut app_manager = APP_MANAGER.exclusive_access(); + let current_app = app_manager.get_current_app(); + unsafe { + app_manager.load_app(current_app); + } + app_manager.move_to_next_app(); + drop(app_manager); + // before this we have to drop local variables related to resources manually + // and release the resources + extern "C" { + fn __restore(cx_addr: usize); + } + unsafe { + __restore(KERNEL_STACK.push_context(TrapContext::app_init_context( + APP_BASE_ADDRESS, + USER_STACK.get_sp(), + )) as *const _ as usize); + } + panic!("Unreachable in batch::run_current_app!"); +} diff --git a/os2/src/console.rs b/os2/src/console.rs new file mode 100644 index 0000000..632e662 --- /dev/null +++ b/os2/src/console.rs @@ -0,0 +1,37 @@ +/*! + +本模块实现了 print 和 println 宏。 + +*/ + +use crate::sbi::console_putchar; +use core::fmt::{self, Write}; + +struct Stdout; + +impl Write for Stdout { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + console_putchar(c as usize); + } + Ok(()) + } +} + +pub fn print(args: fmt::Arguments) { + Stdout.write_fmt(args).unwrap(); +} + +#[macro_export] +macro_rules! print { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!($fmt $(, $($arg)+)?)); + } +} + +#[macro_export] +macro_rules! println { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?)); + } +} diff --git a/os2/src/entry.asm b/os2/src/entry.asm new file mode 100644 index 0000000..9d2ff71 --- /dev/null +++ b/os2/src/entry.asm @@ -0,0 +1,12 @@ + .section .text.entry + .globl _start +_start: + la sp, boot_stack_top + call rust_main + + .section .bss.stack + .globl boot_stack +boot_stack: + .space 4096 * 16 + .globl boot_stack_top +boot_stack_top: \ No newline at end of file diff --git a/os2/src/lang_items.rs b/os2/src/lang_items.rs new file mode 100644 index 0000000..a6217a0 --- /dev/null +++ b/os2/src/lang_items.rs @@ -0,0 +1,17 @@ +use crate::sbi::shutdown; +use core::panic::PanicInfo; + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + if let Some(location) = info.location() { + println!( + "Panicked at {}:{} {}", + location.file(), + location.line(), + info.message().unwrap() + ); + } else { + println!("Panicked: {}", info.message().unwrap()); + } + shutdown() +} diff --git a/os2/src/link_app.S b/os2/src/link_app.S new file mode 100644 index 0000000..e69de29 diff --git a/os2/src/linker.ld b/os2/src/linker.ld new file mode 100644 index 0000000..8bcce1a --- /dev/null +++ b/os2/src/linker.ld @@ -0,0 +1,48 @@ +OUTPUT_ARCH(riscv) +ENTRY(_start) +BASE_ADDRESS = 0x80200000; + +SECTIONS +{ + . = BASE_ADDRESS; + skernel = .; + + stext = .; + .text : { + *(.text.entry) + *(.text .text.*) + } + + . = ALIGN(4K); + etext = .; + srodata = .; + .rodata : { + *(.rodata .rodata.*) + *(.srodata .srodata.*) + } + + . = ALIGN(4K); + erodata = .; + sdata = .; + .data : { + *(.data .data.*) + *(.sdata .sdata.*) + } + + . = ALIGN(4K); + edata = .; + .bss : { + *(.bss.stack) + sbss = .; + *(.bss .bss.*) + *(.sbss .sbss.*) + } + + . = ALIGN(4K); + ebss = .; + ekernel = .; + + /DISCARD/ : { + *(.eh_frame) + } +} \ No newline at end of file diff --git a/os2/src/logging.rs b/os2/src/logging.rs new file mode 100644 index 0000000..7b7cc56 --- /dev/null +++ b/os2/src/logging.rs @@ -0,0 +1,47 @@ +/*! + +本模块利用 log crate 为你提供了日志功能,使用方式见 main.rs. + +*/ + +use log::{self, Level, LevelFilter, Log, Metadata, Record}; + +struct SimpleLogger; + +impl Log for SimpleLogger { + fn enabled(&self, _metadata: &Metadata) -> bool { + true + } + fn log(&self, record: &Record) { + if !self.enabled(record.metadata()) { + return; + } + let color = match record.level() { + Level::Error => 31, // Red + Level::Warn => 93, // BrightYellow + Level::Info => 34, // Blue + Level::Debug => 32, // Green + Level::Trace => 90, // BrightBlack + }; + println!( + "\u{1B}[{}m[{:>5}] {}\u{1B}[0m", + color, + record.level(), + record.args(), + ); + } + fn flush(&self) {} +} + +pub fn init() { + static LOGGER: SimpleLogger = SimpleLogger; + log::set_logger(&LOGGER).unwrap(); + log::set_max_level(match option_env!("LOG") { + Some("ERROR") => LevelFilter::Error, + Some("WARN") => LevelFilter::Warn, + Some("INFO") => LevelFilter::Info, + Some("DEBUG") => LevelFilter::Debug, + Some("TRACE") => LevelFilter::Trace, + _ => LevelFilter::Off, + }); +} diff --git a/os2/src/main.rs b/os2/src/main.rs new file mode 100644 index 0000000..cafaae9 --- /dev/null +++ b/os2/src/main.rs @@ -0,0 +1,40 @@ +#![no_std] +#![no_main] +#![feature(panic_info_message)] + +#[macro_use] +extern crate log; + +#[macro_use] +mod console; +mod batch; +mod lang_items; +mod logging; +mod sbi; +mod sync; +mod syscall; +mod trap; + +core::arch::global_asm!(include_str!("entry.asm")); +core::arch::global_asm!(include_str!("link_app.S")); + +fn clear_bss() { + extern "C" { + fn sbss(); + fn ebss(); + } + unsafe { + core::slice::from_raw_parts_mut(sbss as usize as *mut u8, ebss as usize - sbss as usize) + .fill(0); + } +} + +#[no_mangle] +pub fn rust_main() -> ! { + clear_bss(); + logging::init(); + println!("[kernel] Hello, world!"); + trap::init(); + batch::init(); + batch::run_next_app(); +} diff --git a/os2/src/sbi.rs b/os2/src/sbi.rs new file mode 100644 index 0000000..751a4d2 --- /dev/null +++ b/os2/src/sbi.rs @@ -0,0 +1,34 @@ +#![allow(unused)] + +const SBI_SET_TIMER: usize = 0; +const SBI_CONSOLE_PUTCHAR: usize = 1; +const SBI_CONSOLE_GETCHAR: usize = 2; +const SBI_SHUTDOWN: usize = 8; + +#[inline(always)] +fn sbi_call(which: usize, arg0: usize, arg1: usize, arg2: usize) -> usize { + let mut ret; + unsafe { + core::arch::asm!( + "ecall", + inlateout("x10") arg0 => ret, + in("x11") arg1, + in("x12") arg2, + in("x17") which, + ); + } + ret +} + +pub fn console_putchar(c: usize) { + sbi_call(SBI_CONSOLE_PUTCHAR, c, 0, 0); +} + +pub fn console_getchar() -> usize { + sbi_call(SBI_CONSOLE_GETCHAR, 0, 0, 0) +} + +pub fn shutdown() -> ! { + sbi_call(SBI_SHUTDOWN, 0, 0, 0); + panic!("It should shutdown!"); +} diff --git a/os2/src/sync/mod.rs b/os2/src/sync/mod.rs new file mode 100644 index 0000000..d1ce5bc --- /dev/null +++ b/os2/src/sync/mod.rs @@ -0,0 +1,3 @@ +mod up; + +pub use up::UPSafeCell; diff --git a/os2/src/sync/up.rs b/os2/src/sync/up.rs new file mode 100644 index 0000000..c7b2c9e --- /dev/null +++ b/os2/src/sync/up.rs @@ -0,0 +1,29 @@ +use core::cell::{RefCell, RefMut}; + +/// Wrap a static data structure inside it so that we are +/// able to access it without any `unsafe`. +/// +/// We should only use it in uniprocessor. +/// +/// In order to get mutable reference of inner data, call +/// `exclusive_access`. +pub struct UPSafeCell { + /// inner data + inner: RefCell, +} + +unsafe impl Sync for UPSafeCell {} + +impl UPSafeCell { + /// User is responsible to guarantee that inner struct is only used in + /// uniprocessor. + pub unsafe fn new(value: T) -> Self { + Self { + inner: RefCell::new(value), + } + } + /// Panic if the data has been borrowed. + pub fn exclusive_access(&self) -> RefMut<'_, T> { + self.inner.borrow_mut() + } +} diff --git a/os2/src/syscall/fs.rs b/os2/src/syscall/fs.rs new file mode 100644 index 0000000..3e38eae --- /dev/null +++ b/os2/src/syscall/fs.rs @@ -0,0 +1,15 @@ +const FD_STDOUT: usize = 1; + +pub fn sys_write(fd: usize, buf: *const u8, len: usize) -> isize { + match fd { + FD_STDOUT => { + let slice = unsafe { core::slice::from_raw_parts(buf, len) }; + let str = core::str::from_utf8(slice).unwrap(); + print!("{}", str); + len as isize + } + _ => { + panic!("Unsupported fd in sys_write!"); + } + } +} diff --git a/os2/src/syscall/mod.rs b/os2/src/syscall/mod.rs new file mode 100644 index 0000000..430af56 --- /dev/null +++ b/os2/src/syscall/mod.rs @@ -0,0 +1,16 @@ +const SYSCALL_WRITE: usize = 64; +const SYSCALL_EXIT: usize = 93; + +mod fs; +mod process; + +use fs::*; +use process::*; + +pub fn syscall(syscall_id: usize, args: [usize; 3]) -> isize { + match syscall_id { + SYSCALL_WRITE => sys_write(args[0], args[1] as *const u8, args[2]), + SYSCALL_EXIT => sys_exit(args[0] as i32), + _ => panic!("Unsupported syscall_id: {}", syscall_id), + } +} diff --git a/os2/src/syscall/process.rs b/os2/src/syscall/process.rs new file mode 100644 index 0000000..28caecd --- /dev/null +++ b/os2/src/syscall/process.rs @@ -0,0 +1,6 @@ +use crate::batch::run_next_app; + +pub fn sys_exit(exit_code: i32) -> ! { + info!("[kernel] Application exited with code {}", exit_code); + run_next_app() +} diff --git a/os2/src/trap/context.rs b/os2/src/trap/context.rs new file mode 100644 index 0000000..af5a53a --- /dev/null +++ b/os2/src/trap/context.rs @@ -0,0 +1,25 @@ +use riscv::register::sstatus::{self, Sstatus, SPP}; + +#[repr(C)] +pub struct TrapContext { + pub x: [usize; 32], + pub sstatus: Sstatus, + pub sepc: usize, +} + +impl TrapContext { + pub fn set_sp(&mut self, sp: usize) { + self.x[2] = sp; + } + pub fn app_init_context(entry: usize, sp: usize) -> Self { + let mut sstatus = sstatus::read(); + sstatus.set_spp(SPP::User); + let mut cx = Self { + x: [0; 32], + sstatus, + sepc: entry, + }; + cx.set_sp(sp); + cx + } +} diff --git a/os2/src/trap/mod.rs b/os2/src/trap/mod.rs new file mode 100644 index 0000000..c2cfcb4 --- /dev/null +++ b/os2/src/trap/mod.rs @@ -0,0 +1,50 @@ +mod context; + +use crate::batch::run_next_app; +use crate::syscall::syscall; +use riscv::register::{ + mtvec::TrapMode, + scause::{self, Exception, Trap}, + stval, stvec, +}; + +core::arch::global_asm!(include_str!("trap.S")); + +pub fn init() { + extern "C" { + fn __alltraps(); + } + unsafe { + stvec::write(__alltraps as usize, TrapMode::Direct); + } +} + +#[no_mangle] +pub fn trap_handler(cx: &mut TrapContext) -> &mut TrapContext { + let scause = scause::read(); + let stval = stval::read(); + match scause.cause() { + Trap::Exception(Exception::UserEnvCall) => { + cx.sepc += 4; + cx.x[10] = syscall(cx.x[17], [cx.x[10], cx.x[11], cx.x[12]]) as usize; + } + Trap::Exception(Exception::StoreFault) | Trap::Exception(Exception::StorePageFault) => { + error!("[kernel] PageFault in application, core dumped."); + run_next_app(); + } + Trap::Exception(Exception::IllegalInstruction) => { + error!("[kernel] IllegalInstruction in application, core dumped."); + run_next_app(); + } + _ => { + panic!( + "Unsupported trap {:?}, stval = {:#x}!", + scause.cause(), + stval + ); + } + } + cx +} + +pub use context::TrapContext; diff --git a/os2/src/trap/trap.S b/os2/src/trap/trap.S new file mode 100644 index 0000000..9d6967c --- /dev/null +++ b/os2/src/trap/trap.S @@ -0,0 +1,64 @@ +.altmacro +.macro SAVE_GP n + sd x\n, \n*8(sp) +.endm +.macro LOAD_GP n + ld x\n, \n*8(sp) +.endm + .section .text + .globl __alltraps + .globl __restore + .align 2 +__alltraps: + csrrw sp, sscratch, sp + # now sp->kernel stack, sscratch->user stack + # allocate a TrapContext on kernel stack + addi sp, sp, -34*8 + # save general-purpose registers + sd x1, 1*8(sp) + # skip sp(x2), we will save it later + sd x3, 3*8(sp) + # skip tp(x4), application does not use it + # save x5~x31 + .set n, 5 + .rept 27 + SAVE_GP %n + .set n, n+1 + .endr + # we can use t0/t1/t2 freely, because they were saved on kernel stack + csrr t0, sstatus + csrr t1, sepc + sd t0, 32*8(sp) + sd t1, 33*8(sp) + # read user stack from sscratch and save it on the kernel stack + csrr t2, sscratch + sd t2, 2*8(sp) + # set input argument of trap_handler(cx: &mut TrapContext) + mv a0, sp + call trap_handler + +__restore: + # case1: start running app by __restore + # case2: back to U after handling trap + mv sp, a0 + # now sp->kernel stack(after allocated), sscratch->user stack + # restore sstatus/sepc + ld t0, 32*8(sp) + ld t1, 33*8(sp) + ld t2, 2*8(sp) + csrw sstatus, t0 + csrw sepc, t1 + csrw sscratch, t2 + # restore general-purpuse registers except sp/tp + ld x1, 1*8(sp) + ld x3, 3*8(sp) + .set n, 5 + .rept 27 + LOAD_GP %n + .set n, n+1 + .endr + # release TrapContext on kernel stack + addi sp, sp, 34*8 + # now sp->kernel stack, sscratch->user stack + csrrw sp, sscratch, sp + sret diff --git a/os3/.cargo/config b/os3/.cargo/config new file mode 100644 index 0000000..4275fca --- /dev/null +++ b/os3/.cargo/config @@ -0,0 +1,7 @@ +[build] +target = "riscv64gc-unknown-none-elf" + +[target.riscv64gc-unknown-none-elf] +rustflags = [ + "-Clink-arg=-Tsrc/linker.ld", "-Cforce-frame-pointers=yes" +] diff --git a/os3/Cargo.toml b/os3/Cargo.toml new file mode 100644 index 0000000..7790c1a --- /dev/null +++ b/os3/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "os" +version = "0.1.0" +authors = ["Yifan Wu "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +buddy_system_allocator = "0.6" +lazy_static = { version = "1.4.0", features = ["spin_no_std"] } +log = "0.4" +riscv = { git = "https://gitee.com/rcore-os/riscv", features = ["inline-asm"] } diff --git a/os3/Makefile b/os3/Makefile new file mode 100644 index 0000000..1aefac3 --- /dev/null +++ b/os3/Makefile @@ -0,0 +1,59 @@ +# Building +TARGET := riscv64gc-unknown-none-elf +MODE := release +KERNEL_ELF := target/$(TARGET)/$(MODE)/os +KERNEL_BIN := $(KERNEL_ELF).bin +KERNEL_ASM := $(KERNEL_ELF).asm + +# BOARD +BOARD ?= qemu +SBI ?= rustsbi +BOOTLOADER := ../bootloader/$(SBI)-$(BOARD).bin + +# KERNEL ENTRY +KERNEL_ENTRY_PA := 0x80200000 + +# Binutils +OBJDUMP := rust-objdump --arch-name=riscv64 +OBJCOPY := rust-objcopy --binary-architecture=riscv64 + +CHAPTER ?= 3 +TEST ?= $(CHAPTER) +BASE ?= 1 + +build: env $(KERNEL_BIN) + +$(KERNEL_BIN): kernel + @$(OBJCOPY) $(KERNEL_ELF) --strip-all -O binary $@ + @$(OBJDUMP) $(KERNEL_ELF) -S > $(KERNEL_ELF).asm + +env: + (rustup target list | grep "riscv64gc-unknown-none-elf (installed)") || rustup target add $(TARGET) + cargo install cargo-binutils --vers ~0.2 + rustup component add rust-src + rustup component add llvm-tools-preview + +$(KERNEL_BIN): kernel + @$(OBJCOPY) $(KERNEL_ELF) --strip-all -O binary $@ + +kernel: + @make -C ../user build TEST=$(TEST) CHAPTER=$(CHAPTER) BASE=$(BASE) + @cargo build --release + +clean: + @cargo clean + +run: build + @qemu-system-riscv64 \ + -machine virt \ + -nographic \ + -bios $(BOOTLOADER) \ + -device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY_PA) + +debug: build + @tmux new-session -d \ + "qemu-system-riscv64 -machine virt -nographic -bios $(BOOTLOADER) -device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY_PA) -s -S" && \ + tmux split-window -h "riscv64-unknown-elf-gdb -ex 'file $(KERNEL_ELF)' -ex 'set arch riscv:rv64' -ex 'target remote localhost:1234'" && \ + tmux -2 attach-session -d + +.PHONY: build env kernel clean run-inner diff --git a/os3/build.rs b/os3/build.rs new file mode 100644 index 0000000..4a44c56 --- /dev/null +++ b/os3/build.rs @@ -0,0 +1,56 @@ +use std::fs::{read_dir, File}; +use std::io::{Result, Write}; + +fn main() { + println!("cargo:rerun-if-changed=../user/src/"); + println!("cargo:rerun-if-changed={}", TARGET_PATH); + insert_app_data().unwrap(); +} + +static TARGET_PATH: &str = "../user/build/bin/"; + +fn insert_app_data() -> Result<()> { + let mut f = File::create("src/link_app.S").unwrap(); + let mut apps: Vec<_> = read_dir("../user/build/bin/") + .unwrap() + .into_iter() + .map(|dir_entry| { + let mut name_with_ext = dir_entry.unwrap().file_name().into_string().unwrap(); + name_with_ext.drain(name_with_ext.find('.').unwrap()..name_with_ext.len()); + name_with_ext + }) + .collect(); + apps.sort(); + + writeln!( + f, + r#" + .align 3 + .section .data + .global _num_app +_num_app: + .quad {}"#, + apps.len() + )?; + + for i in 0..apps.len() { + writeln!(f, r#" .quad app_{}_start"#, i)?; + } + writeln!(f, r#" .quad app_{}_end"#, apps.len() - 1)?; + + for (idx, app) in apps.iter().enumerate() { + println!("app_{}: {}", idx, app); + writeln!( + f, + r#" + .section .data + .global app_{0}_start + .global app_{0}_end +app_{0}_start: + .incbin "{2}{1}.bin" +app_{0}_end:"#, + idx, app, TARGET_PATH + )?; + } + Ok(()) +} diff --git a/os3/src/config.rs b/os3/src/config.rs new file mode 100644 index 0000000..135382e --- /dev/null +++ b/os3/src/config.rs @@ -0,0 +1,8 @@ +pub const USER_STACK_SIZE: usize = 8192; +pub const KERNEL_STACK_SIZE: usize = 8192 * 2; +pub const KERNEL_HEAP_SIZE: usize = 0x20000; +pub const MAX_APP_NUM: usize = 16; +pub const APP_BASE_ADDRESS: usize = 0x80400000; +pub const APP_SIZE_LIMIT: usize = 0x20000; +pub const CLOCK_FREQ: usize = 12500000; +pub const MAX_SYSCALL_NUM: usize = 500; diff --git a/os3/src/console.rs b/os3/src/console.rs new file mode 100644 index 0000000..dda4911 --- /dev/null +++ b/os3/src/console.rs @@ -0,0 +1,31 @@ +use crate::sbi::console_putchar; +use core::fmt::{self, Write}; + +struct Stdout; + +impl Write for Stdout { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + console_putchar(c as usize); + } + Ok(()) + } +} + +pub fn print(args: fmt::Arguments) { + Stdout.write_fmt(args).unwrap(); +} + +#[macro_export] +macro_rules! print { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!($fmt $(, $($arg)+)?)); + } +} + +#[macro_export] +macro_rules! println { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?)); + } +} diff --git a/os3/src/entry.asm b/os3/src/entry.asm new file mode 100644 index 0000000..9d2ff71 --- /dev/null +++ b/os3/src/entry.asm @@ -0,0 +1,12 @@ + .section .text.entry + .globl _start +_start: + la sp, boot_stack_top + call rust_main + + .section .bss.stack + .globl boot_stack +boot_stack: + .space 4096 * 16 + .globl boot_stack_top +boot_stack_top: \ No newline at end of file diff --git a/os3/src/heap_alloc.rs b/os3/src/heap_alloc.rs new file mode 100644 index 0000000..82e0e45 --- /dev/null +++ b/os3/src/heap_alloc.rs @@ -0,0 +1,20 @@ +use crate::config::KERNEL_HEAP_SIZE; +use buddy_system_allocator::LockedHeap; + +#[global_allocator] +static HEAP_ALLOCATOR: LockedHeap = LockedHeap::empty(); + +static mut HEAP_SPACE: [u8; KERNEL_HEAP_SIZE] = [0; KERNEL_HEAP_SIZE]; + +pub fn init_heap() { + unsafe { + HEAP_ALLOCATOR + .lock() + .init(HEAP_SPACE.as_ptr() as usize, KERNEL_HEAP_SIZE); + } +} + +#[alloc_error_handler] +pub fn handle_alloc_error(layout: core::alloc::Layout) -> ! { + panic!("Heap allocation error, layout = {:?}", layout); +} diff --git a/os3/src/lang_items.rs b/os3/src/lang_items.rs new file mode 100644 index 0000000..b8335db --- /dev/null +++ b/os3/src/lang_items.rs @@ -0,0 +1,17 @@ +use crate::sbi::shutdown; +use core::panic::PanicInfo; + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + if let Some(location) = info.location() { + println!( + "Panicked at {}:{} {}", + location.file(), + location.line(), + info.message().unwrap() + ); + } else { + println!("[kernel] Panicked: {}", info.message().unwrap()); + } + shutdown() +} \ No newline at end of file diff --git a/os3/src/link_app.S b/os3/src/link_app.S new file mode 100644 index 0000000..e69de29 diff --git a/os3/src/linker.ld b/os3/src/linker.ld new file mode 100644 index 0000000..8bcce1a --- /dev/null +++ b/os3/src/linker.ld @@ -0,0 +1,48 @@ +OUTPUT_ARCH(riscv) +ENTRY(_start) +BASE_ADDRESS = 0x80200000; + +SECTIONS +{ + . = BASE_ADDRESS; + skernel = .; + + stext = .; + .text : { + *(.text.entry) + *(.text .text.*) + } + + . = ALIGN(4K); + etext = .; + srodata = .; + .rodata : { + *(.rodata .rodata.*) + *(.srodata .srodata.*) + } + + . = ALIGN(4K); + erodata = .; + sdata = .; + .data : { + *(.data .data.*) + *(.sdata .sdata.*) + } + + . = ALIGN(4K); + edata = .; + .bss : { + *(.bss.stack) + sbss = .; + *(.bss .bss.*) + *(.sbss .sbss.*) + } + + . = ALIGN(4K); + ebss = .; + ekernel = .; + + /DISCARD/ : { + *(.eh_frame) + } +} \ No newline at end of file diff --git a/os3/src/loader.rs b/os3/src/loader.rs new file mode 100644 index 0000000..b07958a --- /dev/null +++ b/os3/src/loader.rs @@ -0,0 +1,85 @@ +use crate::config::*; +use crate::trap::TrapContext; + +#[repr(align(4096))] +#[derive(Copy, Clone)] +struct KernelStack { + data: [u8; KERNEL_STACK_SIZE], +} + +#[repr(align(4096))] +#[derive(Copy, Clone)] +struct UserStack { + data: [u8; USER_STACK_SIZE], +} + +static KERNEL_STACK: [KernelStack; MAX_APP_NUM] = [KernelStack { + data: [0; KERNEL_STACK_SIZE], +}; MAX_APP_NUM]; + +static USER_STACK: [UserStack; MAX_APP_NUM] = [UserStack { + data: [0; USER_STACK_SIZE], +}; MAX_APP_NUM]; + +impl KernelStack { + fn get_sp(&self) -> usize { + self.data.as_ptr() as usize + KERNEL_STACK_SIZE + } + pub fn push_context(&self, trap_cx: TrapContext) -> usize { + let trap_cx_ptr = (self.get_sp() - core::mem::size_of::()) as *mut TrapContext; + unsafe { + *trap_cx_ptr = trap_cx; + } + trap_cx_ptr as usize + } +} + +impl UserStack { + fn get_sp(&self) -> usize { + self.data.as_ptr() as usize + USER_STACK_SIZE + } +} + +fn get_base_i(app_id: usize) -> usize { + APP_BASE_ADDRESS + app_id * APP_SIZE_LIMIT +} + +pub fn get_num_app() -> usize { + extern "C" { + fn _num_app(); + } + unsafe { (_num_app as usize as *const usize).read_volatile() } +} + +pub fn load_apps() { + extern "C" { + fn _num_app(); + } + let num_app_ptr = _num_app as usize as *const usize; + let num_app = get_num_app(); + let app_start = unsafe { core::slice::from_raw_parts(num_app_ptr.add(1), num_app + 1) }; + // clear i-cache first + unsafe { + core::arch::asm!("fence.i"); + } + // load apps + for i in 0..num_app { + let base_i = get_base_i(i); + // clear region + (base_i..base_i + APP_SIZE_LIMIT) + .for_each(|addr| unsafe { (addr as *mut u8).write_volatile(0) }); + // load app from data section to memory + let src = unsafe { + core::slice::from_raw_parts(app_start[i] as *const u8, app_start[i + 1] - app_start[i]) + }; + let dst = unsafe { core::slice::from_raw_parts_mut(base_i as *mut u8, src.len()) }; + dst.copy_from_slice(src); + } +} + +pub fn init_app_cx(app_id: usize) -> usize { + KERNEL_STACK[app_id].push_context(TrapContext::app_init_context( + get_base_i(app_id), + USER_STACK[app_id].get_sp(), + )) +} diff --git a/os3/src/logging.rs b/os3/src/logging.rs new file mode 100644 index 0000000..6f1a140 --- /dev/null +++ b/os3/src/logging.rs @@ -0,0 +1,41 @@ +use log::{self, Level, LevelFilter, Log, Metadata, Record}; + +struct SimpleLogger; + +impl Log for SimpleLogger { + fn enabled(&self, _metadata: &Metadata) -> bool { + true + } + fn log(&self, record: &Record) { + if !self.enabled(record.metadata()) { + return; + } + let color = match record.level() { + Level::Error => 31, // Red + Level::Warn => 93, // BrightYellow + Level::Info => 34, // Blue + Level::Debug => 32, // Green + Level::Trace => 90, // BrightBlack + }; + println!( + "\u{1B}[{}m[{:>5}] {}\u{1B}[0m", + color, + record.level(), + record.args(), + ); + } + fn flush(&self) {} +} + +pub fn init() { + static LOGGER: SimpleLogger = SimpleLogger; + log::set_logger(&LOGGER).unwrap(); + log::set_max_level(match option_env!("LOG") { + Some("ERROR") => LevelFilter::Error, + Some("WARN") => LevelFilter::Warn, + Some("INFO") => LevelFilter::Info, + Some("DEBUG") => LevelFilter::Debug, + Some("TRACE") => LevelFilter::Trace, + _ => LevelFilter::Off, + }); +} diff --git a/os3/src/main.rs b/os3/src/main.rs new file mode 100644 index 0000000..21315be --- /dev/null +++ b/os3/src/main.rs @@ -0,0 +1,51 @@ +#![no_std] +#![no_main] +#![feature(panic_info_message)] +#![feature(alloc_error_handler)] + +#[macro_use] +extern crate log; + +extern crate alloc; + +#[macro_use] +mod console; +mod config; +mod heap_alloc; +mod lang_items; +mod loader; +mod logging; +mod sbi; +mod sync; +mod syscall; +mod task; +mod timer; +mod trap; + +core::arch::global_asm!(include_str!("entry.asm")); +core::arch::global_asm!(include_str!("link_app.S")); + +fn clear_bss() { + extern "C" { + fn sbss(); + fn ebss(); + } + unsafe { + core::slice::from_raw_parts_mut(sbss as usize as *mut u8, ebss as usize - sbss as usize) + .fill(0); + } +} + +#[no_mangle] +pub fn rust_main() -> ! { + clear_bss(); + logging::init(); + println!("[kernel] Hello, world!"); + heap_alloc::init_heap(); + trap::init(); + loader::load_apps(); + trap::enable_timer_interrupt(); + timer::set_next_trigger(); + task::run_first_task(); + panic!("Unreachable in rust_main!"); +} diff --git a/os3/src/sbi.rs b/os3/src/sbi.rs new file mode 100644 index 0000000..6dcad4e --- /dev/null +++ b/os3/src/sbi.rs @@ -0,0 +1,38 @@ +#![allow(unused)] + +const SBI_SET_TIMER: usize = 0; +const SBI_CONSOLE_PUTCHAR: usize = 1; +const SBI_CONSOLE_GETCHAR: usize = 2; +const SBI_SHUTDOWN: usize = 8; + +#[inline(always)] +fn sbi_call(which: usize, arg0: usize, arg1: usize, arg2: usize) -> usize { + let mut ret; + unsafe { + core::arch::asm!( + "ecall", + inlateout("x10") arg0 => ret, + in("x11") arg1, + in("x12") arg2, + in("x17") which, + ); + } + ret +} + +pub fn set_timer(timer: usize) { + sbi_call(SBI_SET_TIMER, timer, 0, 0); +} + +pub fn console_putchar(c: usize) { + sbi_call(SBI_CONSOLE_PUTCHAR, c, 0, 0); +} + +pub fn console_getchar() -> usize { + sbi_call(SBI_CONSOLE_GETCHAR, 0, 0, 0) +} + +pub fn shutdown() -> ! { + sbi_call(SBI_SHUTDOWN, 0, 0, 0); + panic!("It should shutdown!"); +} diff --git a/os3/src/sync/README.md b/os3/src/sync/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os3/src/syscall/README.md b/os3/src/syscall/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os3/src/task/README.md b/os3/src/task/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os3/src/timer.rs b/os3/src/timer.rs new file mode 100644 index 0000000..8b908bc --- /dev/null +++ b/os3/src/timer.rs @@ -0,0 +1,18 @@ +use crate::config::CLOCK_FREQ; +use crate::sbi::set_timer; +use riscv::register::time; + +const TICKS_PER_SEC: usize = 100; +const MICRO_PER_SEC: usize = 1_000_000; + +pub fn get_time() -> usize { + time::read() +} + +pub fn get_time_us() -> usize { + time::read() / (CLOCK_FREQ / MICRO_PER_SEC) +} + +pub fn set_next_trigger() { + set_timer(get_time() + CLOCK_FREQ / TICKS_PER_SEC); +} diff --git a/os3/src/trap/README.md b/os3/src/trap/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os4/.cargo/config b/os4/.cargo/config new file mode 100644 index 0000000..4275fca --- /dev/null +++ b/os4/.cargo/config @@ -0,0 +1,7 @@ +[build] +target = "riscv64gc-unknown-none-elf" + +[target.riscv64gc-unknown-none-elf] +rustflags = [ + "-Clink-arg=-Tsrc/linker.ld", "-Cforce-frame-pointers=yes" +] diff --git a/os4/Cargo.toml b/os4/Cargo.toml new file mode 100644 index 0000000..e9bacac --- /dev/null +++ b/os4/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "os" +version = "0.1.0" +authors = ["Yifan Wu "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +bitflags = "1.2.1" +buddy_system_allocator = "0.6" +lazy_static = { version = "1.4.0", features = ["spin_no_std"] } +log = "0.4" +riscv = { git = "https://gitee.com/rcore-os/riscv", features = ["inline-asm"] } +spin = "0.9" +lock_api = "=0.4.6" +xmas-elf = "0.7.0" diff --git a/os4/Makefile b/os4/Makefile new file mode 100644 index 0000000..a6f3982 --- /dev/null +++ b/os4/Makefile @@ -0,0 +1,51 @@ +# Building +TARGET := riscv64gc-unknown-none-elf +MODE := release +KERNEL_ELF := target/$(TARGET)/$(MODE)/os +KERNEL_BIN := $(KERNEL_ELF).bin + +# BOARD +BOARD ?= qemu +SBI ?= rustsbi +BOOTLOADER := ../bootloader/$(SBI)-$(BOARD).bin + +# KERNEL ENTRY +KERNEL_ENTRY_PA := 0x80200000 + +# Binutils +OBJDUMP := rust-objdump --arch-name=riscv64 +OBJCOPY := rust-objcopy --binary-architecture=riscv64 + +TEST ?= 0 +build: env $(KERNEL_BIN) + +env: + (rustup target list | grep "riscv64gc-unknown-none-elf (installed)") || rustup target add $(TARGET) + cargo install cargo-binutils --vers ~0.2 + rustup component add rust-src + rustup component add llvm-tools-preview + +$(KERNEL_BIN): kernel + @$(OBJCOPY) $(KERNEL_ELF) --strip-all -O binary $@ + +kernel: + @cd ../user && make build TEST=$(TEST) + @cargo build --release + +clean: + @cargo clean + +run: build + @qemu-system-riscv64 \ + -machine virt \ + -nographic \ + -bios $(BOOTLOADER) \ + -device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY_PA) + +debug: build + @tmux new-session -d \ + "qemu-system-riscv64 -machine virt -nographic -bios $(BOOTLOADER) -device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY_PA) -s -S" && \ + tmux split-window -h "riscv64-unknown-elf-gdb -ex 'file $(KERNEL_ELF)' -ex 'set arch riscv:rv64' -ex 'target remote localhost:1234'" && \ + tmux -2 attach-session -d + +.PHONY: build env kernel clean run-inner diff --git a/os4/build.rs b/os4/build.rs new file mode 100644 index 0000000..2f109cb --- /dev/null +++ b/os4/build.rs @@ -0,0 +1,57 @@ +use std::fs::{read_dir, File}; +use std::io::{Result, Write}; + +fn main() { + println!("cargo:rerun-if-changed=../user/src/"); + println!("cargo:rerun-if-changed={}", TARGET_PATH); + insert_app_data().unwrap(); +} + +static TARGET_PATH: &str = "../user/build/elf/"; + +fn insert_app_data() -> Result<()> { + let mut f = File::create("src/link_app.S").unwrap(); + let mut apps: Vec<_> = read_dir("../user/build/elf/") + .unwrap() + .into_iter() + .map(|dir_entry| { + let mut name_with_ext = dir_entry.unwrap().file_name().into_string().unwrap(); + name_with_ext.drain(name_with_ext.find('.').unwrap()..name_with_ext.len()); + name_with_ext + }) + .collect(); + apps.sort(); + + writeln!( + f, + r#" + .align 3 + .section .data + .global _num_app +_num_app: + .quad {}"#, + apps.len() + )?; + + for i in 0..apps.len() { + writeln!(f, r#" .quad app_{}_start"#, i)?; + } + writeln!(f, r#" .quad app_{}_end"#, apps.len() - 1)?; + + for (idx, app) in apps.iter().enumerate() { + println!("app_{}: {}", idx, app); + writeln!( + f, + r#" + .section .data + .global app_{0}_start + .global app_{0}_end + .align 3 +app_{0}_start: + .incbin "{2}{1}.elf" +app_{0}_end:"#, + idx, app, TARGET_PATH + )?; + } + Ok(()) +} diff --git a/os4/src/config.rs b/os4/src/config.rs new file mode 100644 index 0000000..3fe8084 --- /dev/null +++ b/os4/src/config.rs @@ -0,0 +1,18 @@ +pub const USER_STACK_SIZE: usize = 4096 * 2; +pub const KERNEL_STACK_SIZE: usize = 4096 * 2; +pub const KERNEL_HEAP_SIZE: usize = 0x30_0000; +pub const MEMORY_END: usize = 0x88000000; +pub const PAGE_SIZE: usize = 0x1000; +pub const PAGE_SIZE_BITS: usize = 0xc; +pub const MAX_SYSCALL_NUM: usize = 500; + +pub const TRAMPOLINE: usize = usize::MAX - PAGE_SIZE + 1; +pub const TRAP_CONTEXT: usize = TRAMPOLINE - PAGE_SIZE; +/// Return (bottom, top) of a kernel stack in kernel space. +pub fn kernel_stack_position(app_id: usize) -> (usize, usize) { + let top = TRAMPOLINE - app_id * (KERNEL_STACK_SIZE + PAGE_SIZE); + let bottom = top - KERNEL_STACK_SIZE; + (bottom, top) +} + +pub const CLOCK_FREQ: usize = 12500000; diff --git a/os4/src/console.rs b/os4/src/console.rs new file mode 100644 index 0000000..27fc6a3 --- /dev/null +++ b/os4/src/console.rs @@ -0,0 +1,35 @@ +/*! + 本模块实现了 print 和 println 宏 +*/ + +use crate::sbi::console_putchar; +use core::fmt::{self, Write}; + +struct Stdout; + +impl Write for Stdout { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + console_putchar(c as usize); + } + Ok(()) + } +} + +pub fn print(args: fmt::Arguments) { + Stdout.write_fmt(args).unwrap(); +} + +#[macro_export] +macro_rules! print { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!($fmt $(, $($arg)+)?)); + } +} + +#[macro_export] +macro_rules! println { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?)); + } +} diff --git a/os4/src/entry.asm b/os4/src/entry.asm new file mode 100644 index 0000000..9d2ff71 --- /dev/null +++ b/os4/src/entry.asm @@ -0,0 +1,12 @@ + .section .text.entry + .globl _start +_start: + la sp, boot_stack_top + call rust_main + + .section .bss.stack + .globl boot_stack +boot_stack: + .space 4096 * 16 + .globl boot_stack_top +boot_stack_top: \ No newline at end of file diff --git a/os4/src/lang_items.rs b/os4/src/lang_items.rs new file mode 100644 index 0000000..26bd949 --- /dev/null +++ b/os4/src/lang_items.rs @@ -0,0 +1,17 @@ +use crate::sbi::shutdown; +use core::panic::PanicInfo; + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + if let Some(location) = info.location() { + println!( + "Panicked at {}:{} {}", + location.file(), + location.line(), + info.message().unwrap() + ); + } else { + println!("[kernel] Panicked: {}", info.message().unwrap()); + } + shutdown() +} diff --git a/os4/src/link_app.S b/os4/src/link_app.S new file mode 100644 index 0000000..e69de29 diff --git a/os4/src/linker.ld b/os4/src/linker.ld new file mode 100644 index 0000000..5baafbd --- /dev/null +++ b/os4/src/linker.ld @@ -0,0 +1,53 @@ +OUTPUT_ARCH(riscv) +ENTRY(_start) +BASE_ADDRESS = 0x80200000; + +SECTIONS +{ + . = BASE_ADDRESS; + skernel = .; + + stext = .; + .text : { + *(.text.entry) + . = ALIGN(4K); + strampoline = .; + *(.text.trampoline); + . = ALIGN(4K); + *(.text .text.*) + } + + . = ALIGN(4K); + etext = .; + srodata = .; + .rodata : { + *(.rodata .rodata.*) + *(.srodata .srodata.*) + } + + . = ALIGN(4K); + erodata = .; + sdata = .; + .data : { + *(.data .data.*) + *(.sdata .sdata.*) + } + + . = ALIGN(4K); + edata = .; + sbss_with_stack = .; + .bss : { + *(.bss.stack) + sbss = .; + *(.bss .bss.*) + *(.sbss .sbss.*) + } + + . = ALIGN(4K); + ebss = .; + ekernel = .; + + /DISCARD/ : { + *(.eh_frame) + } +} \ No newline at end of file diff --git a/os4/src/loader.rs b/os4/src/loader.rs new file mode 100644 index 0000000..1358c46 --- /dev/null +++ b/os4/src/loader.rs @@ -0,0 +1,22 @@ +pub fn get_num_app() -> usize { + extern "C" { + fn _num_app(); + } + unsafe { (_num_app as usize as *const usize).read_volatile() } +} + +pub fn get_app_data(app_id: usize) -> &'static [u8] { + extern "C" { + fn _num_app(); + } + let num_app_ptr = _num_app as usize as *const usize; + let num_app = get_num_app(); + let app_start = unsafe { core::slice::from_raw_parts(num_app_ptr.add(1), num_app + 1) }; + assert!(app_id < num_app); + unsafe { + core::slice::from_raw_parts( + app_start[app_id] as *const u8, + app_start[app_id + 1] - app_start[app_id], + ) + } +} diff --git a/os4/src/logging.rs b/os4/src/logging.rs new file mode 100644 index 0000000..6f1a140 --- /dev/null +++ b/os4/src/logging.rs @@ -0,0 +1,41 @@ +use log::{self, Level, LevelFilter, Log, Metadata, Record}; + +struct SimpleLogger; + +impl Log for SimpleLogger { + fn enabled(&self, _metadata: &Metadata) -> bool { + true + } + fn log(&self, record: &Record) { + if !self.enabled(record.metadata()) { + return; + } + let color = match record.level() { + Level::Error => 31, // Red + Level::Warn => 93, // BrightYellow + Level::Info => 34, // Blue + Level::Debug => 32, // Green + Level::Trace => 90, // BrightBlack + }; + println!( + "\u{1B}[{}m[{:>5}] {}\u{1B}[0m", + color, + record.level(), + record.args(), + ); + } + fn flush(&self) {} +} + +pub fn init() { + static LOGGER: SimpleLogger = SimpleLogger; + log::set_logger(&LOGGER).unwrap(); + log::set_max_level(match option_env!("LOG") { + Some("ERROR") => LevelFilter::Error, + Some("WARN") => LevelFilter::Warn, + Some("INFO") => LevelFilter::Info, + Some("DEBUG") => LevelFilter::Debug, + Some("TRACE") => LevelFilter::Trace, + _ => LevelFilter::Off, + }); +} diff --git a/os4/src/main.rs b/os4/src/main.rs new file mode 100644 index 0000000..9989a67 --- /dev/null +++ b/os4/src/main.rs @@ -0,0 +1,55 @@ +#![no_std] +#![no_main] +#![feature(panic_info_message)] +#![feature(alloc_error_handler)] + +#[macro_use] +extern crate bitflags; +#[macro_use] +extern crate log; + +extern crate alloc; + +#[macro_use] +mod console; +mod config; +mod lang_items; +mod loader; +mod logging; +mod mm; +mod sbi; +mod sync; +mod syscall; +mod task; +mod timer; +mod trap; + +core::arch::global_asm!(include_str!("entry.asm")); +core::arch::global_asm!(include_str!("link_app.S")); + +fn clear_bss() { + extern "C" { + fn sbss(); + fn ebss(); + } + unsafe { + core::slice::from_raw_parts_mut(sbss as usize as *mut u8, ebss as usize - sbss as usize) + .fill(0); + } +} + +#[no_mangle] +pub fn rust_main() -> ! { + clear_bss(); + logging::init(); + println!("[kernel] Hello, world!"); + mm::init(); + println!("[kernel] back to world!"); + mm::remap_test(); + trap::init(); + //trap::enable_interrupt(); + trap::enable_timer_interrupt(); + timer::set_next_trigger(); + task::run_first_task(); + panic!("Unreachable in rust_main!"); +} diff --git a/os4/src/mm/README.md b/os4/src/mm/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os4/src/sbi.rs b/os4/src/sbi.rs new file mode 100644 index 0000000..6dcad4e --- /dev/null +++ b/os4/src/sbi.rs @@ -0,0 +1,38 @@ +#![allow(unused)] + +const SBI_SET_TIMER: usize = 0; +const SBI_CONSOLE_PUTCHAR: usize = 1; +const SBI_CONSOLE_GETCHAR: usize = 2; +const SBI_SHUTDOWN: usize = 8; + +#[inline(always)] +fn sbi_call(which: usize, arg0: usize, arg1: usize, arg2: usize) -> usize { + let mut ret; + unsafe { + core::arch::asm!( + "ecall", + inlateout("x10") arg0 => ret, + in("x11") arg1, + in("x12") arg2, + in("x17") which, + ); + } + ret +} + +pub fn set_timer(timer: usize) { + sbi_call(SBI_SET_TIMER, timer, 0, 0); +} + +pub fn console_putchar(c: usize) { + sbi_call(SBI_CONSOLE_PUTCHAR, c, 0, 0); +} + +pub fn console_getchar() -> usize { + sbi_call(SBI_CONSOLE_GETCHAR, 0, 0, 0) +} + +pub fn shutdown() -> ! { + sbi_call(SBI_SHUTDOWN, 0, 0, 0); + panic!("It should shutdown!"); +} diff --git a/os4/src/sync/README.md b/os4/src/sync/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os4/src/syscall/README.md b/os4/src/syscall/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os4/src/task/README.md b/os4/src/task/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os4/src/timer.rs b/os4/src/timer.rs new file mode 100644 index 0000000..8b908bc --- /dev/null +++ b/os4/src/timer.rs @@ -0,0 +1,18 @@ +use crate::config::CLOCK_FREQ; +use crate::sbi::set_timer; +use riscv::register::time; + +const TICKS_PER_SEC: usize = 100; +const MICRO_PER_SEC: usize = 1_000_000; + +pub fn get_time() -> usize { + time::read() +} + +pub fn get_time_us() -> usize { + time::read() / (CLOCK_FREQ / MICRO_PER_SEC) +} + +pub fn set_next_trigger() { + set_timer(get_time() + CLOCK_FREQ / TICKS_PER_SEC); +} diff --git a/os4/src/trap/README.md b/os4/src/trap/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os5/.cargo/config b/os5/.cargo/config new file mode 100644 index 0000000..4275fca --- /dev/null +++ b/os5/.cargo/config @@ -0,0 +1,7 @@ +[build] +target = "riscv64gc-unknown-none-elf" + +[target.riscv64gc-unknown-none-elf] +rustflags = [ + "-Clink-arg=-Tsrc/linker.ld", "-Cforce-frame-pointers=yes" +] diff --git a/os5/Cargo.toml b/os5/Cargo.toml new file mode 100644 index 0000000..a9de084 --- /dev/null +++ b/os5/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "os" +version = "0.1.0" +authors = ["Yifan Wu "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +bitflags = "1.2.1" +buddy_system_allocator = "0.6" +lazy_static = { version = "1.4.0", features = ["spin_no_std"] } +log = "0.4" +riscv = { git = "https://gitee.com/rcore-os/riscv", features = ["inline-asm"] } +spin = "0.9" +xmas-elf = "0.7.0" +lock_api = "=0.4.6" diff --git a/os5/Makefile b/os5/Makefile new file mode 100644 index 0000000..0fd7fbe --- /dev/null +++ b/os5/Makefile @@ -0,0 +1,55 @@ +# Building +TARGET := riscv64gc-unknown-none-elf +MODE := release +KERNEL_ELF := target/$(TARGET)/$(MODE)/os +KERNEL_BIN := $(KERNEL_ELF).bin +KERNEL_ASM := $(KERNEL_ELF).asm + +# BOARD +BOARD ?= qemu +SBI ?= rustsbi +BOOTLOADER := ../bootloader/$(SBI)-$(BOARD).bin + +# KERNEL ENTRY +KERNEL_ENTRY_PA := 0x80200000 + +# Binutils +OBJDUMP := rust-objdump --arch-name=riscv64 +OBJCOPY := rust-objcopy --binary-architecture=riscv64 + +CHAPTER ?= 5 +TEST ?= $(CHAPTER) +BASE ?= 1 + +build: env $(KERNEL_BIN) + +env: + (rustup target list | grep "riscv64gc-unknown-none-elf (installed)") || rustup target add $(TARGET) + cargo install cargo-binutils --vers ~0.3 + rustup component add rust-src + rustup component add llvm-tools-preview + +$(KERNEL_BIN): kernel + @$(OBJCOPY) $(KERNEL_ELF) --strip-all -O binary $@ + +kernel: + @make -C ../user build TEST=$(TEST) CHAPTER=$(CHAPTER) BASE=$(BASE) + @cargo build --release + +clean: + @cargo clean + +run: build + @qemu-system-riscv64 \ + -machine virt \ + -nographic \ + -bios $(BOOTLOADER) \ + -device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY_PA) + +debug: build + @tmux new-session -d \ + "qemu-system-riscv64 -machine virt -nographic -bios $(BOOTLOADER) -device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY_PA) -s -S" && \ + tmux split-window -h "riscv64-unknown-elf-gdb -ex 'file $(KERNEL_ELF)' -ex 'set arch riscv:rv64' -ex 'target remote localhost:1234'" && \ + tmux -2 attach-session -d + +.PHONY: build env kernel clean run-inner \ No newline at end of file diff --git a/os5/build.rs b/os5/build.rs new file mode 100644 index 0000000..3f9d84d --- /dev/null +++ b/os5/build.rs @@ -0,0 +1,67 @@ +use std::fs::{read_dir, File}; +use std::io::{Result, Write}; + +fn main() { + println!("cargo:rerun-if-changed=../user/src/"); + println!("cargo:rerun-if-changed={}", TARGET_PATH); + insert_app_data().unwrap(); +} + +static TARGET_PATH: &str = "../user/build/elf/"; + +fn insert_app_data() -> Result<()> { + let mut f = File::create("src/link_app.S").unwrap(); + let mut apps: Vec<_> = read_dir("../user/build/elf/") + .unwrap() + .into_iter() + .map(|dir_entry| { + let mut name_with_ext = dir_entry.unwrap().file_name().into_string().unwrap(); + name_with_ext.drain(name_with_ext.find('.').unwrap()..name_with_ext.len()); + name_with_ext + }) + .collect(); + apps.sort(); + + writeln!( + f, + r#" + .align 3 + .section .data + .global _num_app +_num_app: + .quad {}"#, + apps.len() + )?; + + for i in 0..apps.len() { + writeln!(f, r#" .quad app_{}_start"#, i)?; + } + writeln!(f, r#" .quad app_{}_end"#, apps.len() - 1)?; + + writeln!( + f, + r#" + .global _app_names +_app_names:"# + )?; + for app in apps.iter() { + writeln!(f, r#" .string "{}""#, app)?; + } + + for (idx, app) in apps.iter().enumerate() { + println!("app_{}: {}", idx, app); + writeln!( + f, + r#" + .section .data + .global app_{0}_start + .global app_{0}_end + .align 3 +app_{0}_start: + .incbin "{2}{1}.elf" +app_{0}_end:"#, + idx, app, TARGET_PATH + )?; + } + Ok(()) +} diff --git a/os5/src/config.rs b/os5/src/config.rs new file mode 100644 index 0000000..a91541d --- /dev/null +++ b/os5/src/config.rs @@ -0,0 +1,12 @@ +pub const USER_STACK_SIZE: usize = 4096 * 2; +pub const KERNEL_STACK_SIZE: usize = 4096 * 2; +pub const KERNEL_HEAP_SIZE: usize = 0x30_0000; +pub const MEMORY_END: usize = 0x88000000; +pub const PAGE_SIZE: usize = 0x1000; +pub const PAGE_SIZE_BITS: usize = 0xc; +pub const MAX_SYSCALL_NUM: usize = 500; +pub const BIG_STRIDE: usize = usize::MAX; + +pub const TRAMPOLINE: usize = usize::MAX - PAGE_SIZE + 1; +pub const TRAP_CONTEXT: usize = TRAMPOLINE - PAGE_SIZE; +pub const CLOCK_FREQ: usize = 12500000; diff --git a/os5/src/console.rs b/os5/src/console.rs new file mode 100644 index 0000000..27fc6a3 --- /dev/null +++ b/os5/src/console.rs @@ -0,0 +1,35 @@ +/*! + 本模块实现了 print 和 println 宏 +*/ + +use crate::sbi::console_putchar; +use core::fmt::{self, Write}; + +struct Stdout; + +impl Write for Stdout { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + console_putchar(c as usize); + } + Ok(()) + } +} + +pub fn print(args: fmt::Arguments) { + Stdout.write_fmt(args).unwrap(); +} + +#[macro_export] +macro_rules! print { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!($fmt $(, $($arg)+)?)); + } +} + +#[macro_export] +macro_rules! println { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?)); + } +} diff --git a/os5/src/entry.asm b/os5/src/entry.asm new file mode 100644 index 0000000..9d2ff71 --- /dev/null +++ b/os5/src/entry.asm @@ -0,0 +1,12 @@ + .section .text.entry + .globl _start +_start: + la sp, boot_stack_top + call rust_main + + .section .bss.stack + .globl boot_stack +boot_stack: + .space 4096 * 16 + .globl boot_stack_top +boot_stack_top: \ No newline at end of file diff --git a/os5/src/lang_items.rs b/os5/src/lang_items.rs new file mode 100644 index 0000000..26bd949 --- /dev/null +++ b/os5/src/lang_items.rs @@ -0,0 +1,17 @@ +use crate::sbi::shutdown; +use core::panic::PanicInfo; + +#[panic_handler] +fn panic(info: &PanicInfo) -> ! { + if let Some(location) = info.location() { + println!( + "Panicked at {}:{} {}", + location.file(), + location.line(), + info.message().unwrap() + ); + } else { + println!("[kernel] Panicked: {}", info.message().unwrap()); + } + shutdown() +} diff --git a/os5/src/link_app.S b/os5/src/link_app.S new file mode 100644 index 0000000..e69de29 diff --git a/os5/src/linker.ld b/os5/src/linker.ld new file mode 100644 index 0000000..5baafbd --- /dev/null +++ b/os5/src/linker.ld @@ -0,0 +1,53 @@ +OUTPUT_ARCH(riscv) +ENTRY(_start) +BASE_ADDRESS = 0x80200000; + +SECTIONS +{ + . = BASE_ADDRESS; + skernel = .; + + stext = .; + .text : { + *(.text.entry) + . = ALIGN(4K); + strampoline = .; + *(.text.trampoline); + . = ALIGN(4K); + *(.text .text.*) + } + + . = ALIGN(4K); + etext = .; + srodata = .; + .rodata : { + *(.rodata .rodata.*) + *(.srodata .srodata.*) + } + + . = ALIGN(4K); + erodata = .; + sdata = .; + .data : { + *(.data .data.*) + *(.sdata .sdata.*) + } + + . = ALIGN(4K); + edata = .; + sbss_with_stack = .; + .bss : { + *(.bss.stack) + sbss = .; + *(.bss .bss.*) + *(.sbss .sbss.*) + } + + . = ALIGN(4K); + ebss = .; + ekernel = .; + + /DISCARD/ : { + *(.eh_frame) + } +} \ No newline at end of file diff --git a/os5/src/loader.rs b/os5/src/loader.rs new file mode 100644 index 0000000..6f41076 --- /dev/null +++ b/os5/src/loader.rs @@ -0,0 +1,64 @@ +use alloc::vec::Vec; +use lazy_static::*; + +pub fn get_num_app() -> usize { + extern "C" { + fn _num_app(); + } + unsafe { (_num_app as usize as *const usize).read_volatile() } +} + +pub fn get_app_data(app_id: usize) -> &'static [u8] { + extern "C" { + fn _num_app(); + } + let num_app_ptr = _num_app as usize as *const usize; + let num_app = get_num_app(); + let app_start = unsafe { core::slice::from_raw_parts(num_app_ptr.add(1), num_app + 1) }; + assert!(app_id < num_app); + unsafe { + core::slice::from_raw_parts( + app_start[app_id] as *const u8, + app_start[app_id + 1] - app_start[app_id], + ) + } +} + +lazy_static! { + static ref APP_NAMES: Vec<&'static str> = { + let num_app = get_num_app(); + extern "C" { + fn _app_names(); + } + let mut start = _app_names as usize as *const u8; + let mut v = Vec::new(); + unsafe { + for _ in 0..num_app { + let mut end = start; + while end.read_volatile() != b'\0' { + end = end.add(1); + } + let slice = core::slice::from_raw_parts(start, end as usize - start as usize); + let str = core::str::from_utf8(slice).unwrap(); + v.push(str); + start = end.add(1); + } + } + v + }; +} + +pub fn get_app_data_by_name(name: &str) -> Option<&'static [u8]> { + let num_app = get_num_app(); + (0..num_app) + .find(|&i| APP_NAMES[i] == name) + .map(get_app_data) +} + +pub fn list_apps() { + println!("/**** APPS ****"); + for app in APP_NAMES.iter() { + println!("{}", app); + } + println!("**************/"); +} diff --git a/os5/src/logging.rs b/os5/src/logging.rs new file mode 100644 index 0000000..6f1a140 --- /dev/null +++ b/os5/src/logging.rs @@ -0,0 +1,41 @@ +use log::{self, Level, LevelFilter, Log, Metadata, Record}; + +struct SimpleLogger; + +impl Log for SimpleLogger { + fn enabled(&self, _metadata: &Metadata) -> bool { + true + } + fn log(&self, record: &Record) { + if !self.enabled(record.metadata()) { + return; + } + let color = match record.level() { + Level::Error => 31, // Red + Level::Warn => 93, // BrightYellow + Level::Info => 34, // Blue + Level::Debug => 32, // Green + Level::Trace => 90, // BrightBlack + }; + println!( + "\u{1B}[{}m[{:>5}] {}\u{1B}[0m", + color, + record.level(), + record.args(), + ); + } + fn flush(&self) {} +} + +pub fn init() { + static LOGGER: SimpleLogger = SimpleLogger; + log::set_logger(&LOGGER).unwrap(); + log::set_max_level(match option_env!("LOG") { + Some("ERROR") => LevelFilter::Error, + Some("WARN") => LevelFilter::Warn, + Some("INFO") => LevelFilter::Info, + Some("DEBUG") => LevelFilter::Debug, + Some("TRACE") => LevelFilter::Trace, + _ => LevelFilter::Off, + }); +} diff --git a/os5/src/main.rs b/os5/src/main.rs new file mode 100644 index 0000000..b348880 --- /dev/null +++ b/os5/src/main.rs @@ -0,0 +1,56 @@ +#![no_std] +#![no_main] +#![feature(panic_info_message)] +#![feature(alloc_error_handler)] + +#[macro_use] +extern crate bitflags; +#[macro_use] +extern crate log; + +extern crate alloc; + +#[macro_use] +mod console; +mod config; +mod lang_items; +mod loader; +mod logging; +mod mm; +mod sbi; +mod sync; +mod syscall; +mod task; +mod timer; +mod trap; + +core::arch::global_asm!(include_str!("entry.asm")); +core::arch::global_asm!(include_str!("link_app.S")); + +fn clear_bss() { + extern "C" { + fn sbss(); + fn ebss(); + } + unsafe { + core::slice::from_raw_parts_mut(sbss as usize as *mut u8, ebss as usize - sbss as usize) + .fill(0); + } +} + +#[no_mangle] +pub fn rust_main() -> ! { + clear_bss(); + logging::init(); + println!("[kernel] Hello, world!"); + mm::init(); + mm::remap_test(); + task::add_initproc(); + info!("after initproc!"); + trap::init(); + trap::enable_timer_interrupt(); + timer::set_next_trigger(); + loader::list_apps(); + task::run_tasks(); + panic!("Unreachable in rust_main!"); +} diff --git a/os5/src/mm/README.md b/os5/src/mm/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os5/src/sbi.rs b/os5/src/sbi.rs new file mode 100644 index 0000000..6dcad4e --- /dev/null +++ b/os5/src/sbi.rs @@ -0,0 +1,38 @@ +#![allow(unused)] + +const SBI_SET_TIMER: usize = 0; +const SBI_CONSOLE_PUTCHAR: usize = 1; +const SBI_CONSOLE_GETCHAR: usize = 2; +const SBI_SHUTDOWN: usize = 8; + +#[inline(always)] +fn sbi_call(which: usize, arg0: usize, arg1: usize, arg2: usize) -> usize { + let mut ret; + unsafe { + core::arch::asm!( + "ecall", + inlateout("x10") arg0 => ret, + in("x11") arg1, + in("x12") arg2, + in("x17") which, + ); + } + ret +} + +pub fn set_timer(timer: usize) { + sbi_call(SBI_SET_TIMER, timer, 0, 0); +} + +pub fn console_putchar(c: usize) { + sbi_call(SBI_CONSOLE_PUTCHAR, c, 0, 0); +} + +pub fn console_getchar() -> usize { + sbi_call(SBI_CONSOLE_GETCHAR, 0, 0, 0) +} + +pub fn shutdown() -> ! { + sbi_call(SBI_SHUTDOWN, 0, 0, 0); + panic!("It should shutdown!"); +} diff --git a/os5/src/sync/README.md b/os5/src/sync/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os5/src/syscall/README.md b/os5/src/syscall/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os5/src/task/README.md b/os5/src/task/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os5/src/timer.rs b/os5/src/timer.rs new file mode 100644 index 0000000..8b908bc --- /dev/null +++ b/os5/src/timer.rs @@ -0,0 +1,18 @@ +use crate::config::CLOCK_FREQ; +use crate::sbi::set_timer; +use riscv::register::time; + +const TICKS_PER_SEC: usize = 100; +const MICRO_PER_SEC: usize = 1_000_000; + +pub fn get_time() -> usize { + time::read() +} + +pub fn get_time_us() -> usize { + time::read() / (CLOCK_FREQ / MICRO_PER_SEC) +} + +pub fn set_next_trigger() { + set_timer(get_time() + CLOCK_FREQ / TICKS_PER_SEC); +} diff --git a/os5/src/trap/README.md b/os5/src/trap/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os6/.cargo/config b/os6/.cargo/config new file mode 100644 index 0000000..4275fca --- /dev/null +++ b/os6/.cargo/config @@ -0,0 +1,7 @@ +[build] +target = "riscv64gc-unknown-none-elf" + +[target.riscv64gc-unknown-none-elf] +rustflags = [ + "-Clink-arg=-Tsrc/linker.ld", "-Cforce-frame-pointers=yes" +] diff --git a/os6/Cargo.toml b/os6/Cargo.toml new file mode 100644 index 0000000..d0d9e54 --- /dev/null +++ b/os6/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "os" +version = "0.1.0" +authors = ["Yifan Wu "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +bitflags = "1.2.1" +buddy_system_allocator = "0.6" +lazy_static = { version = "1.4.0", features = ["spin_no_std"] } +log = "0.4" +riscv = { git = "https://gitee.com/rcore-os/riscv", features = ["inline-asm"] } +lock_api = "=0.4.6" +xmas-elf = "0.7.0" +virtio-drivers = { git = "https://gitee.com/rcore-os/virtio-drivers" } +easy-fs = { path = "../easy-fs" } diff --git a/os6/Makefile b/os6/Makefile new file mode 100644 index 0000000..98e8087 --- /dev/null +++ b/os6/Makefile @@ -0,0 +1,64 @@ +# Building +TARGET := riscv64gc-unknown-none-elf +MODE := release +KERNEL_ELF := target/$(TARGET)/$(MODE)/os +KERNEL_BIN := $(KERNEL_ELF).bin +KERNEL_ASM := $(KERNEL_ELF).asm +FS_IMG := ../user/target/$(TARGET)/$(MODE)/fs.img +APPS := ../user/src/bin/* + +# BOARD +BOARD ?= qemu +SBI ?= rustsbi +BOOTLOADER := ../bootloader/$(SBI)-$(BOARD).bin + +# KERNEL ENTRY +KERNEL_ENTRY_PA := 0x80200000 + +# Binutils +OBJDUMP := rust-objdump --arch-name=riscv64 +OBJCOPY := rust-objcopy --binary-architecture=riscv64 + +CHAPTER ?= 6 +TEST ?= $(CHAPTER) +BASE ?= 1 + +build: env $(KERNEL_BIN) fs-img + +fs-img: $(APPS) + @make -C ../user build TEST=$(TEST) CHAPTER=$(CHAPTER) BASE=$(BASE) + @cd ../easy-fs-fuse && cargo run --release -- -s ../user/build/app/ -t ../user/target/riscv64gc-unknown-none-elf/release/ + +env: + (rustup target list | grep "riscv64gc-unknown-none-elf (installed)") || rustup target add $(TARGET) + cargo install cargo-binutils --vers ~0.3 + rustup component add rust-src + rustup component add llvm-tools-preview + +$(KERNEL_BIN): kernel + @$(OBJCOPY) $(KERNEL_ELF) --strip-all -O binary $@ + +kernel: + @make -C ../user build TEST=$(TEST) CHAPTER=$(CHAPTER) BASE=$(BASE) + @cargo build --release + +clean: + @cargo clean + @cd ../user && make clean + +run: build + @qemu-system-riscv64 \ + -machine virt \ + -nographic \ + -bios $(BOOTLOADER) \ + -device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY_PA) \ + -drive file=$(FS_IMG),if=none,format=raw,id=x0 \ + -device virtio-blk-device,drive=x0,bus=virtio-mmio-bus.0 + +debug: build + @tmux new-session -d \ + "qemu-system-riscv64 -machine virt -nographic -bios $(BOOTLOADER) -device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY_PA) -drive file=$(FS_IMG),if=none,format=raw,id=x0 -device virtio-blk-device,drive=x0,bus=virtio-mmio-bus.0 -s -S" && \ + tmux split-window -h "riscv64-unknown-elf-gdb -ex 'file $(KERNEL_ELF)' -ex 'set arch riscv:rv64' -ex 'target remote localhost:1234'" && \ + tmux -2 attach-session -d + +.PHONY: build env kernel clean fs-img diff --git a/os6/build.rs b/os6/build.rs new file mode 100644 index 0000000..5529b4f --- /dev/null +++ b/os6/build.rs @@ -0,0 +1,6 @@ +static TARGET_PATH: &str = "../user/target/riscv64gc-unknown-none-elf/release/"; + +fn main() { + println!("cargo:rerun-if-changed=../user/src/"); + println!("cargo:rerun-if-changed={}", TARGET_PATH); +} diff --git a/os6/src/config.rs b/os6/src/config.rs new file mode 100644 index 0000000..851df0a --- /dev/null +++ b/os6/src/config.rs @@ -0,0 +1,16 @@ +//! Constants used in rCore + +pub const USER_STACK_SIZE: usize = 4096 * 2; +pub const KERNEL_STACK_SIZE: usize = 4096 * 2; +pub const KERNEL_HEAP_SIZE: usize = 0x20_0000; +pub const MEMORY_END: usize = 0x88000000; +pub const PAGE_SIZE: usize = 0x1000; +pub const PAGE_SIZE_BITS: usize = 0xc; +pub const MAX_SYSCALL_NUM: usize = 500; + +pub const TRAMPOLINE: usize = usize::MAX - PAGE_SIZE + 1; +pub const TRAP_CONTEXT: usize = TRAMPOLINE - PAGE_SIZE; +pub const CLOCK_FREQ: usize = 12500000; +pub const MMIO: &[(usize, usize)] = &[ + (0x10001000, 0x1000), +]; diff --git a/os6/src/console.rs b/os6/src/console.rs new file mode 100644 index 0000000..a23a0e0 --- /dev/null +++ b/os6/src/console.rs @@ -0,0 +1,130 @@ +//! SBI console driver, for text output + +use crate::sbi::console_putchar; +use core::fmt::{self, Write}; + +struct Stdout; + +impl Write for Stdout { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + console_putchar(c as usize); + } + Ok(()) + } +} + +pub fn print(args: fmt::Arguments) { + Stdout.write_fmt(args).unwrap(); +} + +#[macro_export] +/// print string macro +macro_rules! print { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!($fmt $(, $($arg)+)?)); + } +} + +#[macro_export] +/// println string macro +macro_rules! println { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?)); + } +} + +/* +以下代码提供了与颜色相关的 ANSI 转义字符,以及彩色输出可以使用的函数与宏。 + +可以使用它们,甚至扩展它们,来提升开发体验和显示效果。 +*/ + +// 使用 ANSI 转义字符来加上颜色 +#[macro_export] +macro_rules! colorize { + ($content: ident, $foreground_color: ident) => { + format_args!("\u{1B}[{}m{}\u{1B}[0m", $foreground_color as u8, $content) + }; + ($content: ident, $foreground_color: ident, $background_color: ident) => { + format_args!( + "\u{1B}[{}m\u{1B}[{}m{}\u{1B}[0m", + $foreground_color.into(), + $background_color.into(), + $content + ) + }; +} + +pub fn print_colorized( + args: fmt::Arguments, + foreground_color: impl Into, + background_color: impl Into, +) { + Stdout + .write_fmt(colorize!(args, foreground_color, background_color)) + .unwrap(); +} + +#[macro_export] +macro_rules! print_colorized { + ($fmt: literal, $foreground_color: expr, $background_color: expr $(, $($arg: tt)+)?) => { + $crate::console::print_colorized(format_args!($fmt $(, $($arg)+)?), $foreground_color as u8, $background_color as u8); + }; +} + +#[macro_export] +macro_rules! println_colorized { + ($fmt: literal, $foreground_color: expr, $background_color: expr $(, $($arg: tt)+)?) => { + $crate::console::print_colorized(format_args!(concat!($fmt, "\n") $(, $($arg)+)?), $foreground_color as u8, $background_color as u8); + } +} + +#[allow(dead_code)] +pub enum ANSICON { + Reset = 0, + Bold = 1, + Underline = 4, + Blink = 5, + Reverse = 7, + FgBlack = 30, + FgRed = 31, + FgGreen = 32, + FgYellow = 33, + FgBlue = 34, + FgMagenta = 35, + FgCyan = 36, + FgWhite = 37, + FgDefault = 39, + FgLightGray = 90, + FgLightRed = 91, + FgLightGreen = 92, + FgLightYellow = 93, + FgLightBlue = 94, + FgLightMagenta = 95, + FgLightCyan = 96, + FgLightWhite = 97, + BgBlack = 40, + BgRed = 41, + BgGreen = 42, + BgYellow = 43, + BgBlue = 44, + BgMagenta = 45, + BgCyan = 46, + BgWhite = 47, + BgDefault = 49, + BgLightGray = 100, + BgLightRed = 101, + BgLightGreen = 102, + BgLightYellow = 103, + BgLightBlue = 104, + BgLightMagenta = 105, + BgLightCyan = 106, + BgLightWhite = 107, +} + +impl From for u8 { + fn from(con: ANSICON) -> Self { + con as Self + } +} diff --git a/os6/src/drivers/block/mod.rs b/os6/src/drivers/block/mod.rs new file mode 100644 index 0000000..e3a6345 --- /dev/null +++ b/os6/src/drivers/block/mod.rs @@ -0,0 +1,24 @@ +mod virtio_blk; + +use lazy_static::*; +use alloc::sync::Arc; +use easy_fs::BlockDevice; +type BlockDeviceImpl = virtio_blk::VirtIOBlock; + +lazy_static! { + pub static ref BLOCK_DEVICE: Arc = Arc::new(BlockDeviceImpl::new()); +} + +#[allow(unused)] +pub fn block_device_test() { + let block_device = BLOCK_DEVICE.clone(); + let mut write_buffer = [0u8; 512]; + let mut read_buffer = [0u8; 512]; + for i in 0..512 { + for byte in write_buffer.iter_mut() { *byte = i as u8; } + block_device.write_block(i as usize, &write_buffer); + block_device.read_block(i as usize, &mut read_buffer); + assert_eq!(write_buffer, read_buffer); + } + println!("block device test passed!"); +} \ No newline at end of file diff --git a/os6/src/drivers/block/virtio_blk.rs b/os6/src/drivers/block/virtio_blk.rs new file mode 100644 index 0000000..c9956f5 --- /dev/null +++ b/os6/src/drivers/block/virtio_blk.rs @@ -0,0 +1,84 @@ + +use virtio_drivers::{VirtIOBlk, VirtIOHeader}; +use crate::mm::{ + PhysAddr, + VirtAddr, + frame_alloc, + frame_dealloc, + PhysPageNum, + FrameTracker, + PageTable, + StepByOne, + kernel_token, +}; +use super::BlockDevice; +use crate::sync::UPSafeCell; +use alloc::vec::Vec; +use lazy_static::*; + +#[allow(unused)] +const VIRTIO0: usize = 0x10001000; + +pub struct VirtIOBlock(UPSafeCell>); + +lazy_static! { + static ref QUEUE_FRAMES: UPSafeCell> = unsafe { + UPSafeCell::new(Vec::new()) + }; +} + +impl BlockDevice for VirtIOBlock { + fn read_block(&self, block_id: usize, buf: &mut [u8]) { + self.0.exclusive_access() + .read_block(block_id, buf) + .expect("Error when reading VirtIOBlk"); + } + fn write_block(&self, block_id: usize, buf: &[u8]) { + self.0.exclusive_access() + .write_block(block_id, buf) + .expect("Error when writing VirtIOBlk"); + } +} + +impl VirtIOBlock { + #[allow(unused)] + pub fn new() -> Self { + unsafe { + Self(UPSafeCell::new(VirtIOBlk::new( + &mut *(VIRTIO0 as *mut VirtIOHeader) + ).unwrap())) + } + } +} + +#[no_mangle] +pub extern "C" fn virtio_dma_alloc(pages: usize) -> PhysAddr { + let mut ppn_base = PhysPageNum(0); + for i in 0..pages { + let frame = frame_alloc().unwrap(); + if i == 0 { ppn_base = frame.ppn; } + assert_eq!(frame.ppn.0, ppn_base.0 + i); + QUEUE_FRAMES.exclusive_access().push(frame); + } + ppn_base.into() +} + +#[no_mangle] +pub extern "C" fn virtio_dma_dealloc(pa: PhysAddr, pages: usize) -> i32 { + let mut ppn_base: PhysPageNum = pa.into(); + for _ in 0..pages { + frame_dealloc(ppn_base); + ppn_base.step(); + } + 0 +} + +#[no_mangle] +pub extern "C" fn virtio_phys_to_virt(paddr: PhysAddr) -> VirtAddr { + VirtAddr(paddr.0) +} + +#[no_mangle] +pub extern "C" fn virtio_virt_to_phys(vaddr: VirtAddr) -> PhysAddr { + PageTable::from_token(kernel_token()).translate_va(vaddr).unwrap() +} diff --git a/os6/src/drivers/mod.rs b/os6/src/drivers/mod.rs new file mode 100644 index 0000000..43a6f54 --- /dev/null +++ b/os6/src/drivers/mod.rs @@ -0,0 +1,3 @@ +mod block; + +pub use block::BLOCK_DEVICE; diff --git a/os6/src/entry.asm b/os6/src/entry.asm new file mode 100644 index 0000000..9d2ff71 --- /dev/null +++ b/os6/src/entry.asm @@ -0,0 +1,12 @@ + .section .text.entry + .globl _start +_start: + la sp, boot_stack_top + call rust_main + + .section .bss.stack + .globl boot_stack +boot_stack: + .space 4096 * 16 + .globl boot_stack_top +boot_stack_top: \ No newline at end of file diff --git a/os6/src/fs/README.md b/os6/src/fs/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os6/src/lang_items.rs b/os6/src/lang_items.rs new file mode 100644 index 0000000..e52afff --- /dev/null +++ b/os6/src/lang_items.rs @@ -0,0 +1,29 @@ +//! The panic handler + +use crate::console::ANSICON; +use crate::sbi::shutdown; + +use core::panic::PanicInfo; + +#[panic_handler] +/// panic handler +fn panic(info: &PanicInfo) -> ! { + if let Some(location) = info.location() { + println_colorized!( + "[kernel] Panicked at {}:{} {}", + ANSICON::FgRed, + ANSICON::BgDefault, + location.file(), + location.line(), + info.message().unwrap() + ); + } else { + println_colorized!( + "[kernel] Panicked: {}", + ANSICON::FgRed, + ANSICON::BgDefault, + info.message().unwrap() + ); + } + shutdown() +} diff --git a/os6/src/link_app.S b/os6/src/link_app.S new file mode 100644 index 0000000..32748e6 --- /dev/null +++ b/os6/src/link_app.S @@ -0,0 +1,140 @@ + + .align 3 + .section .data + .global _num_app +_num_app: + .quad 13 + .quad app_0_start + .quad app_1_start + .quad app_2_start + .quad app_3_start + .quad app_4_start + .quad app_5_start + .quad app_6_start + .quad app_7_start + .quad app_8_start + .quad app_9_start + .quad app_10_start + .quad app_11_start + .quad app_12_start + .quad app_12_end + + .global _app_names +_app_names: + .string "ch2b_bad_address" + .string "ch2b_bad_instructions" + .string "ch2b_bad_register" + .string "ch2b_hello_world" + .string "ch2b_power_3" + .string "ch2b_power_5" + .string "ch2b_power_7" + .string "ch3_taskinfo" + .string "ch3b_sleep" + .string "ch3b_sleep1" + .string "ch3b_yield0" + .string "ch3b_yield1" + .string "ch3b_yield2" + + .section .data + .global app_0_start + .global app_0_end + .align 3 +app_0_start: + .incbin "../ci-user/user/build/bin/ch2b_bad_address.bin" +app_0_end: + + .section .data + .global app_1_start + .global app_1_end + .align 3 +app_1_start: + .incbin "../ci-user/user/build/bin/ch2b_bad_instructions.bin" +app_1_end: + + .section .data + .global app_2_start + .global app_2_end + .align 3 +app_2_start: + .incbin "../ci-user/user/build/bin/ch2b_bad_register.bin" +app_2_end: + + .section .data + .global app_3_start + .global app_3_end + .align 3 +app_3_start: + .incbin "../ci-user/user/build/bin/ch2b_hello_world.bin" +app_3_end: + + .section .data + .global app_4_start + .global app_4_end + .align 3 +app_4_start: + .incbin "../ci-user/user/build/bin/ch2b_power_3.bin" +app_4_end: + + .section .data + .global app_5_start + .global app_5_end + .align 3 +app_5_start: + .incbin "../ci-user/user/build/bin/ch2b_power_5.bin" +app_5_end: + + .section .data + .global app_6_start + .global app_6_end + .align 3 +app_6_start: + .incbin "../ci-user/user/build/bin/ch2b_power_7.bin" +app_6_end: + + .section .data + .global app_7_start + .global app_7_end + .align 3 +app_7_start: + .incbin "../ci-user/user/build/bin/ch3_taskinfo.bin" +app_7_end: + + .section .data + .global app_8_start + .global app_8_end + .align 3 +app_8_start: + .incbin "../ci-user/user/build/bin/ch3b_sleep.bin" +app_8_end: + + .section .data + .global app_9_start + .global app_9_end + .align 3 +app_9_start: + .incbin "../ci-user/user/build/bin/ch3b_sleep1.bin" +app_9_end: + + .section .data + .global app_10_start + .global app_10_end + .align 3 +app_10_start: + .incbin "../ci-user/user/build/bin/ch3b_yield0.bin" +app_10_end: + + .section .data + .global app_11_start + .global app_11_end + .align 3 +app_11_start: + .incbin "../ci-user/user/build/bin/ch3b_yield1.bin" +app_11_end: + + .section .data + .global app_12_start + .global app_12_end + .align 3 +app_12_start: + .incbin "../ci-user/user/build/bin/ch3b_yield2.bin" +app_12_end: diff --git a/os6/src/linker.ld b/os6/src/linker.ld new file mode 100644 index 0000000..5baafbd --- /dev/null +++ b/os6/src/linker.ld @@ -0,0 +1,53 @@ +OUTPUT_ARCH(riscv) +ENTRY(_start) +BASE_ADDRESS = 0x80200000; + +SECTIONS +{ + . = BASE_ADDRESS; + skernel = .; + + stext = .; + .text : { + *(.text.entry) + . = ALIGN(4K); + strampoline = .; + *(.text.trampoline); + . = ALIGN(4K); + *(.text .text.*) + } + + . = ALIGN(4K); + etext = .; + srodata = .; + .rodata : { + *(.rodata .rodata.*) + *(.srodata .srodata.*) + } + + . = ALIGN(4K); + erodata = .; + sdata = .; + .data : { + *(.data .data.*) + *(.sdata .sdata.*) + } + + . = ALIGN(4K); + edata = .; + sbss_with_stack = .; + .bss : { + *(.bss.stack) + sbss = .; + *(.bss .bss.*) + *(.sbss .sbss.*) + } + + . = ALIGN(4K); + ebss = .; + ekernel = .; + + /DISCARD/ : { + *(.eh_frame) + } +} \ No newline at end of file diff --git a/os6/src/logging.rs b/os6/src/logging.rs new file mode 100644 index 0000000..e12448e --- /dev/null +++ b/os6/src/logging.rs @@ -0,0 +1,45 @@ +//! Global logger + +use log::{self, Level, LevelFilter, Log, Metadata, Record}; + +/// a simple logger +struct SimpleLogger; + +impl Log for SimpleLogger { + fn enabled(&self, _metadata: &Metadata) -> bool { + true + } + fn log(&self, record: &Record) { + if !self.enabled(record.metadata()) { + return; + } + let color = match record.level() { + Level::Error => 31, // Red + Level::Warn => 93, // BrightYellow + Level::Info => 34, // Blue + Level::Debug => 32, // Green + Level::Trace => 90, // BrightBlack + }; + println!( + "\u{1B}[{}m[{:>5}] {}\u{1B}[0m", + color, + record.level(), + record.args(), + ); + } + fn flush(&self) {} +} + +/// initiate logger +pub fn init() { + static LOGGER: SimpleLogger = SimpleLogger; + log::set_logger(&LOGGER).unwrap(); + log::set_max_level(match option_env!("LOG") { + Some("ERROR") => LevelFilter::Error, + Some("WARN") => LevelFilter::Warn, + Some("INFO") => LevelFilter::Info, + Some("DEBUG") => LevelFilter::Debug, + Some("TRACE") => LevelFilter::Trace, + _ => LevelFilter::Off, + }); +} diff --git a/os6/src/main.rs b/os6/src/main.rs new file mode 100644 index 0000000..8036bca --- /dev/null +++ b/os6/src/main.rs @@ -0,0 +1,74 @@ +//! The main module and entrypoint +//! +//! Various facilities of the kernels are implemented as submodules. The most +//! important ones are: +//! +//! - [`trap`]: Handles all cases of switching from userspace to the kernel +//! - [`task`]: Task management +//! - [`syscall`]: System call handling and implementation +//! +//! The operating system also starts in this module. Kernel code starts +//! executing from `entry.asm`, after which [`rust_main()`] is called to +//! initialize various pieces of functionality. (See its source code for +//! details.) +//! +//! We then call [`task::run_first_task()`] and for the first time go to +//! userspace. + +#![no_std] +#![no_main] +#![feature(panic_info_message)] +#![feature(alloc_error_handler)] + +#[macro_use] +extern crate bitflags; +#[macro_use] +extern crate log; + +extern crate alloc; + +#[macro_use] +mod console; +mod config; +mod lang_items; +mod logging; +mod mm; +mod sbi; +mod sync; +mod syscall; +mod task; +mod timer; +mod trap; +mod drivers; +mod fs; + +core::arch::global_asm!(include_str!("entry.asm")); + +/// clear BSS segment +fn clear_bss() { + extern "C" { + fn sbss(); + fn ebss(); + } + unsafe { + core::slice::from_raw_parts_mut(sbss as usize as *mut u8, ebss as usize - sbss as usize) + .fill(0); + } +} + +#[no_mangle] +/// the rust entry-point of os +pub fn rust_main() -> ! { + clear_bss(); + logging::init(); + println!("[kernel] Hello, world!"); + mm::init(); + mm::remap_test(); + trap::init(); + trap::enable_timer_interrupt(); + timer::set_next_trigger(); + fs::list_apps(); + task::add_initproc(); + task::run_tasks(); + panic!("Unreachable in rust_main!"); +} diff --git a/os6/src/mm/README.md b/os6/src/mm/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os6/src/sbi.rs b/os6/src/sbi.rs new file mode 100644 index 0000000..4af7620 --- /dev/null +++ b/os6/src/sbi.rs @@ -0,0 +1,45 @@ +//! SBI call wrappers + +#![allow(unused)] + +const SBI_SET_TIMER: usize = 0; +const SBI_CONSOLE_PUTCHAR: usize = 1; +const SBI_CONSOLE_GETCHAR: usize = 2; +const SBI_SHUTDOWN: usize = 8; + +#[inline(always)] +/// general sbi call +fn sbi_call(which: usize, arg0: usize, arg1: usize, arg2: usize) -> usize { + let mut ret; + unsafe { + core::arch::asm!( + "ecall", + inlateout("x10") arg0 => ret, + in("x11") arg1, + in("x12") arg2, + in("x17") which, + ); + } + ret +} + +/// use sbi call to set timer +pub fn set_timer(timer: usize) { + sbi_call(SBI_SET_TIMER, timer, 0, 0); +} + +/// use sbi call to putchar in console (qemu uart handler) +pub fn console_putchar(c: usize) { + sbi_call(SBI_CONSOLE_PUTCHAR, c, 0, 0); +} + +/// use sbi call to getchar from console (qemu uart handler) +pub fn console_getchar() -> usize { + sbi_call(SBI_CONSOLE_GETCHAR, 0, 0, 0) +} + +/// use sbi call to shutdown the kernel +pub fn shutdown() -> ! { + sbi_call(SBI_SHUTDOWN, 0, 0, 0); + panic!("It should shutdown!"); +} diff --git a/os6/src/sync/README.md b/os6/src/sync/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os6/src/syscall/README.md b/os6/src/syscall/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os6/src/task/README.md b/os6/src/task/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os6/src/timer.rs b/os6/src/timer.rs new file mode 100644 index 0000000..4f40494 --- /dev/null +++ b/os6/src/timer.rs @@ -0,0 +1,23 @@ +//! RISC-V timer-related functionality + +use crate::config::CLOCK_FREQ; +use crate::sbi::set_timer; +use riscv::register::time; + +const TICKS_PER_SEC: usize = 100; +const MICRO_PER_SEC: usize = 1_000_000; + +/// read the `mtime` register +pub fn get_time() -> usize { + time::read() +} + +/// get current time in microseconds +pub fn get_time_us() -> usize { + time::read() / (CLOCK_FREQ / MICRO_PER_SEC) +} + +/// set the next timer interrupt +pub fn set_next_trigger() { + set_timer(get_time() + CLOCK_FREQ / TICKS_PER_SEC); +} diff --git a/os6/src/trap/README.md b/os6/src/trap/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os7/.cargo/config b/os7/.cargo/config new file mode 100644 index 0000000..4275fca --- /dev/null +++ b/os7/.cargo/config @@ -0,0 +1,7 @@ +[build] +target = "riscv64gc-unknown-none-elf" + +[target.riscv64gc-unknown-none-elf] +rustflags = [ + "-Clink-arg=-Tsrc/linker.ld", "-Cforce-frame-pointers=yes" +] diff --git a/os7/Cargo.toml b/os7/Cargo.toml new file mode 100644 index 0000000..d0d9e54 --- /dev/null +++ b/os7/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "os" +version = "0.1.0" +authors = ["Yifan Wu "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +bitflags = "1.2.1" +buddy_system_allocator = "0.6" +lazy_static = { version = "1.4.0", features = ["spin_no_std"] } +log = "0.4" +riscv = { git = "https://gitee.com/rcore-os/riscv", features = ["inline-asm"] } +lock_api = "=0.4.6" +xmas-elf = "0.7.0" +virtio-drivers = { git = "https://gitee.com/rcore-os/virtio-drivers" } +easy-fs = { path = "../easy-fs" } diff --git a/os7/Makefile b/os7/Makefile new file mode 100644 index 0000000..facaf77 --- /dev/null +++ b/os7/Makefile @@ -0,0 +1,64 @@ +# Building +TARGET := riscv64gc-unknown-none-elf +MODE := release +KERNEL_ELF := target/$(TARGET)/$(MODE)/os +KERNEL_BIN := $(KERNEL_ELF).bin +KERNEL_ASM := $(KERNEL_ELF).asm +FS_IMG := ../user/target/$(TARGET)/$(MODE)/fs.img +APPS := ../user/src/bin/* + +# BOARD +BOARD ?= qemu +SBI ?= rustsbi +BOOTLOADER := ../bootloader/$(SBI)-$(BOARD).bin + +# KERNEL ENTRY +KERNEL_ENTRY_PA := 0x80200000 + +# Binutils +OBJDUMP := rust-objdump --arch-name=riscv64 +OBJCOPY := rust-objcopy --binary-architecture=riscv64 + +CHAPTER ?= 7 +TEST ?= $(CHAPTER) +BASE ?= 1 + +build: env $(KERNEL_BIN) fs-img + +fs-img: $(APPS) + @make -C ../user build TEST=$(TEST) CHAPTER=$(CHAPTER) BASE=$(BASE) + @cd ../easy-fs-fuse && cargo run --release -- -s ../user/build/app/ -t ../user/target/riscv64gc-unknown-none-elf/release/ + +env: + (rustup target list | grep "riscv64gc-unknown-none-elf (installed)") || rustup target add $(TARGET) + cargo install cargo-binutils --vers ~0.3 + rustup component add rust-src + rustup component add llvm-tools-preview + +$(KERNEL_BIN): kernel + @$(OBJCOPY) $(KERNEL_ELF) --strip-all -O binary $@ + +kernel: + @make -C ../user build TEST=$(TEST) CHAPTER=$(CHAPTER) BASE=$(BASE) + @cargo build --release + +clean: + @cargo clean + @cd ../user && make clean + +run: build + @qemu-system-riscv64 \ + -machine virt \ + -nographic \ + -bios $(BOOTLOADER) \ + -device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY_PA) \ + -drive file=$(FS_IMG),if=none,format=raw,id=x0 \ + -device virtio-blk-device,drive=x0,bus=virtio-mmio-bus.0 + +debug: build + @tmux new-session -d \ + "qemu-system-riscv64 -machine virt -nographic -bios $(BOOTLOADER) -device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY_PA) -drive file=$(FS_IMG),if=none,format=raw,id=x0 -device virtio-blk-device,drive=x0,bus=virtio-mmio-bus.0 -s -S" && \ + tmux split-window -h "riscv64-unknown-elf-gdb -ex 'file $(KERNEL_ELF)' -ex 'set arch riscv:rv64' -ex 'target remote localhost:1234'" && \ + tmux -2 attach-session -d + +.PHONY: build env kernel clean fs-img diff --git a/os7/build.rs b/os7/build.rs new file mode 100644 index 0000000..5529b4f --- /dev/null +++ b/os7/build.rs @@ -0,0 +1,6 @@ +static TARGET_PATH: &str = "../user/target/riscv64gc-unknown-none-elf/release/"; + +fn main() { + println!("cargo:rerun-if-changed=../user/src/"); + println!("cargo:rerun-if-changed={}", TARGET_PATH); +} diff --git a/os7/src/config.rs b/os7/src/config.rs new file mode 100644 index 0000000..851df0a --- /dev/null +++ b/os7/src/config.rs @@ -0,0 +1,16 @@ +//! Constants used in rCore + +pub const USER_STACK_SIZE: usize = 4096 * 2; +pub const KERNEL_STACK_SIZE: usize = 4096 * 2; +pub const KERNEL_HEAP_SIZE: usize = 0x20_0000; +pub const MEMORY_END: usize = 0x88000000; +pub const PAGE_SIZE: usize = 0x1000; +pub const PAGE_SIZE_BITS: usize = 0xc; +pub const MAX_SYSCALL_NUM: usize = 500; + +pub const TRAMPOLINE: usize = usize::MAX - PAGE_SIZE + 1; +pub const TRAP_CONTEXT: usize = TRAMPOLINE - PAGE_SIZE; +pub const CLOCK_FREQ: usize = 12500000; +pub const MMIO: &[(usize, usize)] = &[ + (0x10001000, 0x1000), +]; diff --git a/os7/src/console.rs b/os7/src/console.rs new file mode 100644 index 0000000..a23a0e0 --- /dev/null +++ b/os7/src/console.rs @@ -0,0 +1,130 @@ +//! SBI console driver, for text output + +use crate::sbi::console_putchar; +use core::fmt::{self, Write}; + +struct Stdout; + +impl Write for Stdout { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + console_putchar(c as usize); + } + Ok(()) + } +} + +pub fn print(args: fmt::Arguments) { + Stdout.write_fmt(args).unwrap(); +} + +#[macro_export] +/// print string macro +macro_rules! print { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!($fmt $(, $($arg)+)?)); + } +} + +#[macro_export] +/// println string macro +macro_rules! println { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?)); + } +} + +/* +以下代码提供了与颜色相关的 ANSI 转义字符,以及彩色输出可以使用的函数与宏。 + +可以使用它们,甚至扩展它们,来提升开发体验和显示效果。 +*/ + +// 使用 ANSI 转义字符来加上颜色 +#[macro_export] +macro_rules! colorize { + ($content: ident, $foreground_color: ident) => { + format_args!("\u{1B}[{}m{}\u{1B}[0m", $foreground_color as u8, $content) + }; + ($content: ident, $foreground_color: ident, $background_color: ident) => { + format_args!( + "\u{1B}[{}m\u{1B}[{}m{}\u{1B}[0m", + $foreground_color.into(), + $background_color.into(), + $content + ) + }; +} + +pub fn print_colorized( + args: fmt::Arguments, + foreground_color: impl Into, + background_color: impl Into, +) { + Stdout + .write_fmt(colorize!(args, foreground_color, background_color)) + .unwrap(); +} + +#[macro_export] +macro_rules! print_colorized { + ($fmt: literal, $foreground_color: expr, $background_color: expr $(, $($arg: tt)+)?) => { + $crate::console::print_colorized(format_args!($fmt $(, $($arg)+)?), $foreground_color as u8, $background_color as u8); + }; +} + +#[macro_export] +macro_rules! println_colorized { + ($fmt: literal, $foreground_color: expr, $background_color: expr $(, $($arg: tt)+)?) => { + $crate::console::print_colorized(format_args!(concat!($fmt, "\n") $(, $($arg)+)?), $foreground_color as u8, $background_color as u8); + } +} + +#[allow(dead_code)] +pub enum ANSICON { + Reset = 0, + Bold = 1, + Underline = 4, + Blink = 5, + Reverse = 7, + FgBlack = 30, + FgRed = 31, + FgGreen = 32, + FgYellow = 33, + FgBlue = 34, + FgMagenta = 35, + FgCyan = 36, + FgWhite = 37, + FgDefault = 39, + FgLightGray = 90, + FgLightRed = 91, + FgLightGreen = 92, + FgLightYellow = 93, + FgLightBlue = 94, + FgLightMagenta = 95, + FgLightCyan = 96, + FgLightWhite = 97, + BgBlack = 40, + BgRed = 41, + BgGreen = 42, + BgYellow = 43, + BgBlue = 44, + BgMagenta = 45, + BgCyan = 46, + BgWhite = 47, + BgDefault = 49, + BgLightGray = 100, + BgLightRed = 101, + BgLightGreen = 102, + BgLightYellow = 103, + BgLightBlue = 104, + BgLightMagenta = 105, + BgLightCyan = 106, + BgLightWhite = 107, +} + +impl From for u8 { + fn from(con: ANSICON) -> Self { + con as Self + } +} diff --git a/os7/src/drivers/block/mod.rs b/os7/src/drivers/block/mod.rs new file mode 100644 index 0000000..e3a6345 --- /dev/null +++ b/os7/src/drivers/block/mod.rs @@ -0,0 +1,24 @@ +mod virtio_blk; + +use lazy_static::*; +use alloc::sync::Arc; +use easy_fs::BlockDevice; +type BlockDeviceImpl = virtio_blk::VirtIOBlock; + +lazy_static! { + pub static ref BLOCK_DEVICE: Arc = Arc::new(BlockDeviceImpl::new()); +} + +#[allow(unused)] +pub fn block_device_test() { + let block_device = BLOCK_DEVICE.clone(); + let mut write_buffer = [0u8; 512]; + let mut read_buffer = [0u8; 512]; + for i in 0..512 { + for byte in write_buffer.iter_mut() { *byte = i as u8; } + block_device.write_block(i as usize, &write_buffer); + block_device.read_block(i as usize, &mut read_buffer); + assert_eq!(write_buffer, read_buffer); + } + println!("block device test passed!"); +} \ No newline at end of file diff --git a/os7/src/drivers/block/virtio_blk.rs b/os7/src/drivers/block/virtio_blk.rs new file mode 100644 index 0000000..c9956f5 --- /dev/null +++ b/os7/src/drivers/block/virtio_blk.rs @@ -0,0 +1,84 @@ + +use virtio_drivers::{VirtIOBlk, VirtIOHeader}; +use crate::mm::{ + PhysAddr, + VirtAddr, + frame_alloc, + frame_dealloc, + PhysPageNum, + FrameTracker, + PageTable, + StepByOne, + kernel_token, +}; +use super::BlockDevice; +use crate::sync::UPSafeCell; +use alloc::vec::Vec; +use lazy_static::*; + +#[allow(unused)] +const VIRTIO0: usize = 0x10001000; + +pub struct VirtIOBlock(UPSafeCell>); + +lazy_static! { + static ref QUEUE_FRAMES: UPSafeCell> = unsafe { + UPSafeCell::new(Vec::new()) + }; +} + +impl BlockDevice for VirtIOBlock { + fn read_block(&self, block_id: usize, buf: &mut [u8]) { + self.0.exclusive_access() + .read_block(block_id, buf) + .expect("Error when reading VirtIOBlk"); + } + fn write_block(&self, block_id: usize, buf: &[u8]) { + self.0.exclusive_access() + .write_block(block_id, buf) + .expect("Error when writing VirtIOBlk"); + } +} + +impl VirtIOBlock { + #[allow(unused)] + pub fn new() -> Self { + unsafe { + Self(UPSafeCell::new(VirtIOBlk::new( + &mut *(VIRTIO0 as *mut VirtIOHeader) + ).unwrap())) + } + } +} + +#[no_mangle] +pub extern "C" fn virtio_dma_alloc(pages: usize) -> PhysAddr { + let mut ppn_base = PhysPageNum(0); + for i in 0..pages { + let frame = frame_alloc().unwrap(); + if i == 0 { ppn_base = frame.ppn; } + assert_eq!(frame.ppn.0, ppn_base.0 + i); + QUEUE_FRAMES.exclusive_access().push(frame); + } + ppn_base.into() +} + +#[no_mangle] +pub extern "C" fn virtio_dma_dealloc(pa: PhysAddr, pages: usize) -> i32 { + let mut ppn_base: PhysPageNum = pa.into(); + for _ in 0..pages { + frame_dealloc(ppn_base); + ppn_base.step(); + } + 0 +} + +#[no_mangle] +pub extern "C" fn virtio_phys_to_virt(paddr: PhysAddr) -> VirtAddr { + VirtAddr(paddr.0) +} + +#[no_mangle] +pub extern "C" fn virtio_virt_to_phys(vaddr: VirtAddr) -> PhysAddr { + PageTable::from_token(kernel_token()).translate_va(vaddr).unwrap() +} diff --git a/os7/src/drivers/mod.rs b/os7/src/drivers/mod.rs new file mode 100644 index 0000000..43a6f54 --- /dev/null +++ b/os7/src/drivers/mod.rs @@ -0,0 +1,3 @@ +mod block; + +pub use block::BLOCK_DEVICE; diff --git a/os7/src/entry.asm b/os7/src/entry.asm new file mode 100644 index 0000000..9d2ff71 --- /dev/null +++ b/os7/src/entry.asm @@ -0,0 +1,12 @@ + .section .text.entry + .globl _start +_start: + la sp, boot_stack_top + call rust_main + + .section .bss.stack + .globl boot_stack +boot_stack: + .space 4096 * 16 + .globl boot_stack_top +boot_stack_top: \ No newline at end of file diff --git a/os7/src/fs/README.md b/os7/src/fs/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os7/src/lang_items.rs b/os7/src/lang_items.rs new file mode 100644 index 0000000..e52afff --- /dev/null +++ b/os7/src/lang_items.rs @@ -0,0 +1,29 @@ +//! The panic handler + +use crate::console::ANSICON; +use crate::sbi::shutdown; + +use core::panic::PanicInfo; + +#[panic_handler] +/// panic handler +fn panic(info: &PanicInfo) -> ! { + if let Some(location) = info.location() { + println_colorized!( + "[kernel] Panicked at {}:{} {}", + ANSICON::FgRed, + ANSICON::BgDefault, + location.file(), + location.line(), + info.message().unwrap() + ); + } else { + println_colorized!( + "[kernel] Panicked: {}", + ANSICON::FgRed, + ANSICON::BgDefault, + info.message().unwrap() + ); + } + shutdown() +} diff --git a/os7/src/link_app.S b/os7/src/link_app.S new file mode 100644 index 0000000..32748e6 --- /dev/null +++ b/os7/src/link_app.S @@ -0,0 +1,140 @@ + + .align 3 + .section .data + .global _num_app +_num_app: + .quad 13 + .quad app_0_start + .quad app_1_start + .quad app_2_start + .quad app_3_start + .quad app_4_start + .quad app_5_start + .quad app_6_start + .quad app_7_start + .quad app_8_start + .quad app_9_start + .quad app_10_start + .quad app_11_start + .quad app_12_start + .quad app_12_end + + .global _app_names +_app_names: + .string "ch2b_bad_address" + .string "ch2b_bad_instructions" + .string "ch2b_bad_register" + .string "ch2b_hello_world" + .string "ch2b_power_3" + .string "ch2b_power_5" + .string "ch2b_power_7" + .string "ch3_taskinfo" + .string "ch3b_sleep" + .string "ch3b_sleep1" + .string "ch3b_yield0" + .string "ch3b_yield1" + .string "ch3b_yield2" + + .section .data + .global app_0_start + .global app_0_end + .align 3 +app_0_start: + .incbin "../ci-user/user/build/bin/ch2b_bad_address.bin" +app_0_end: + + .section .data + .global app_1_start + .global app_1_end + .align 3 +app_1_start: + .incbin "../ci-user/user/build/bin/ch2b_bad_instructions.bin" +app_1_end: + + .section .data + .global app_2_start + .global app_2_end + .align 3 +app_2_start: + .incbin "../ci-user/user/build/bin/ch2b_bad_register.bin" +app_2_end: + + .section .data + .global app_3_start + .global app_3_end + .align 3 +app_3_start: + .incbin "../ci-user/user/build/bin/ch2b_hello_world.bin" +app_3_end: + + .section .data + .global app_4_start + .global app_4_end + .align 3 +app_4_start: + .incbin "../ci-user/user/build/bin/ch2b_power_3.bin" +app_4_end: + + .section .data + .global app_5_start + .global app_5_end + .align 3 +app_5_start: + .incbin "../ci-user/user/build/bin/ch2b_power_5.bin" +app_5_end: + + .section .data + .global app_6_start + .global app_6_end + .align 3 +app_6_start: + .incbin "../ci-user/user/build/bin/ch2b_power_7.bin" +app_6_end: + + .section .data + .global app_7_start + .global app_7_end + .align 3 +app_7_start: + .incbin "../ci-user/user/build/bin/ch3_taskinfo.bin" +app_7_end: + + .section .data + .global app_8_start + .global app_8_end + .align 3 +app_8_start: + .incbin "../ci-user/user/build/bin/ch3b_sleep.bin" +app_8_end: + + .section .data + .global app_9_start + .global app_9_end + .align 3 +app_9_start: + .incbin "../ci-user/user/build/bin/ch3b_sleep1.bin" +app_9_end: + + .section .data + .global app_10_start + .global app_10_end + .align 3 +app_10_start: + .incbin "../ci-user/user/build/bin/ch3b_yield0.bin" +app_10_end: + + .section .data + .global app_11_start + .global app_11_end + .align 3 +app_11_start: + .incbin "../ci-user/user/build/bin/ch3b_yield1.bin" +app_11_end: + + .section .data + .global app_12_start + .global app_12_end + .align 3 +app_12_start: + .incbin "../ci-user/user/build/bin/ch3b_yield2.bin" +app_12_end: diff --git a/os7/src/linker.ld b/os7/src/linker.ld new file mode 100644 index 0000000..5baafbd --- /dev/null +++ b/os7/src/linker.ld @@ -0,0 +1,53 @@ +OUTPUT_ARCH(riscv) +ENTRY(_start) +BASE_ADDRESS = 0x80200000; + +SECTIONS +{ + . = BASE_ADDRESS; + skernel = .; + + stext = .; + .text : { + *(.text.entry) + . = ALIGN(4K); + strampoline = .; + *(.text.trampoline); + . = ALIGN(4K); + *(.text .text.*) + } + + . = ALIGN(4K); + etext = .; + srodata = .; + .rodata : { + *(.rodata .rodata.*) + *(.srodata .srodata.*) + } + + . = ALIGN(4K); + erodata = .; + sdata = .; + .data : { + *(.data .data.*) + *(.sdata .sdata.*) + } + + . = ALIGN(4K); + edata = .; + sbss_with_stack = .; + .bss : { + *(.bss.stack) + sbss = .; + *(.bss .bss.*) + *(.sbss .sbss.*) + } + + . = ALIGN(4K); + ebss = .; + ekernel = .; + + /DISCARD/ : { + *(.eh_frame) + } +} \ No newline at end of file diff --git a/os7/src/logging.rs b/os7/src/logging.rs new file mode 100644 index 0000000..e12448e --- /dev/null +++ b/os7/src/logging.rs @@ -0,0 +1,45 @@ +//! Global logger + +use log::{self, Level, LevelFilter, Log, Metadata, Record}; + +/// a simple logger +struct SimpleLogger; + +impl Log for SimpleLogger { + fn enabled(&self, _metadata: &Metadata) -> bool { + true + } + fn log(&self, record: &Record) { + if !self.enabled(record.metadata()) { + return; + } + let color = match record.level() { + Level::Error => 31, // Red + Level::Warn => 93, // BrightYellow + Level::Info => 34, // Blue + Level::Debug => 32, // Green + Level::Trace => 90, // BrightBlack + }; + println!( + "\u{1B}[{}m[{:>5}] {}\u{1B}[0m", + color, + record.level(), + record.args(), + ); + } + fn flush(&self) {} +} + +/// initiate logger +pub fn init() { + static LOGGER: SimpleLogger = SimpleLogger; + log::set_logger(&LOGGER).unwrap(); + log::set_max_level(match option_env!("LOG") { + Some("ERROR") => LevelFilter::Error, + Some("WARN") => LevelFilter::Warn, + Some("INFO") => LevelFilter::Info, + Some("DEBUG") => LevelFilter::Debug, + Some("TRACE") => LevelFilter::Trace, + _ => LevelFilter::Off, + }); +} diff --git a/os7/src/main.rs b/os7/src/main.rs new file mode 100644 index 0000000..8036bca --- /dev/null +++ b/os7/src/main.rs @@ -0,0 +1,74 @@ +//! The main module and entrypoint +//! +//! Various facilities of the kernels are implemented as submodules. The most +//! important ones are: +//! +//! - [`trap`]: Handles all cases of switching from userspace to the kernel +//! - [`task`]: Task management +//! - [`syscall`]: System call handling and implementation +//! +//! The operating system also starts in this module. Kernel code starts +//! executing from `entry.asm`, after which [`rust_main()`] is called to +//! initialize various pieces of functionality. (See its source code for +//! details.) +//! +//! We then call [`task::run_first_task()`] and for the first time go to +//! userspace. + +#![no_std] +#![no_main] +#![feature(panic_info_message)] +#![feature(alloc_error_handler)] + +#[macro_use] +extern crate bitflags; +#[macro_use] +extern crate log; + +extern crate alloc; + +#[macro_use] +mod console; +mod config; +mod lang_items; +mod logging; +mod mm; +mod sbi; +mod sync; +mod syscall; +mod task; +mod timer; +mod trap; +mod drivers; +mod fs; + +core::arch::global_asm!(include_str!("entry.asm")); + +/// clear BSS segment +fn clear_bss() { + extern "C" { + fn sbss(); + fn ebss(); + } + unsafe { + core::slice::from_raw_parts_mut(sbss as usize as *mut u8, ebss as usize - sbss as usize) + .fill(0); + } +} + +#[no_mangle] +/// the rust entry-point of os +pub fn rust_main() -> ! { + clear_bss(); + logging::init(); + println!("[kernel] Hello, world!"); + mm::init(); + mm::remap_test(); + trap::init(); + trap::enable_timer_interrupt(); + timer::set_next_trigger(); + fs::list_apps(); + task::add_initproc(); + task::run_tasks(); + panic!("Unreachable in rust_main!"); +} diff --git a/os7/src/mm/README.md b/os7/src/mm/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os7/src/sbi.rs b/os7/src/sbi.rs new file mode 100644 index 0000000..4af7620 --- /dev/null +++ b/os7/src/sbi.rs @@ -0,0 +1,45 @@ +//! SBI call wrappers + +#![allow(unused)] + +const SBI_SET_TIMER: usize = 0; +const SBI_CONSOLE_PUTCHAR: usize = 1; +const SBI_CONSOLE_GETCHAR: usize = 2; +const SBI_SHUTDOWN: usize = 8; + +#[inline(always)] +/// general sbi call +fn sbi_call(which: usize, arg0: usize, arg1: usize, arg2: usize) -> usize { + let mut ret; + unsafe { + core::arch::asm!( + "ecall", + inlateout("x10") arg0 => ret, + in("x11") arg1, + in("x12") arg2, + in("x17") which, + ); + } + ret +} + +/// use sbi call to set timer +pub fn set_timer(timer: usize) { + sbi_call(SBI_SET_TIMER, timer, 0, 0); +} + +/// use sbi call to putchar in console (qemu uart handler) +pub fn console_putchar(c: usize) { + sbi_call(SBI_CONSOLE_PUTCHAR, c, 0, 0); +} + +/// use sbi call to getchar from console (qemu uart handler) +pub fn console_getchar() -> usize { + sbi_call(SBI_CONSOLE_GETCHAR, 0, 0, 0) +} + +/// use sbi call to shutdown the kernel +pub fn shutdown() -> ! { + sbi_call(SBI_SHUTDOWN, 0, 0, 0); + panic!("It should shutdown!"); +} diff --git a/os7/src/sync/README.md b/os7/src/sync/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os7/src/syscall/README.md b/os7/src/syscall/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os7/src/task/README.md b/os7/src/task/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os7/src/timer.rs b/os7/src/timer.rs new file mode 100644 index 0000000..4f40494 --- /dev/null +++ b/os7/src/timer.rs @@ -0,0 +1,23 @@ +//! RISC-V timer-related functionality + +use crate::config::CLOCK_FREQ; +use crate::sbi::set_timer; +use riscv::register::time; + +const TICKS_PER_SEC: usize = 100; +const MICRO_PER_SEC: usize = 1_000_000; + +/// read the `mtime` register +pub fn get_time() -> usize { + time::read() +} + +/// get current time in microseconds +pub fn get_time_us() -> usize { + time::read() / (CLOCK_FREQ / MICRO_PER_SEC) +} + +/// set the next timer interrupt +pub fn set_next_trigger() { + set_timer(get_time() + CLOCK_FREQ / TICKS_PER_SEC); +} diff --git a/os7/src/trap/README.md b/os7/src/trap/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os8/.cargo/config b/os8/.cargo/config new file mode 100644 index 0000000..4275fca --- /dev/null +++ b/os8/.cargo/config @@ -0,0 +1,7 @@ +[build] +target = "riscv64gc-unknown-none-elf" + +[target.riscv64gc-unknown-none-elf] +rustflags = [ + "-Clink-arg=-Tsrc/linker.ld", "-Cforce-frame-pointers=yes" +] diff --git a/os8/Cargo.toml b/os8/Cargo.toml new file mode 100644 index 0000000..d0d9e54 --- /dev/null +++ b/os8/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "os" +version = "0.1.0" +authors = ["Yifan Wu "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +bitflags = "1.2.1" +buddy_system_allocator = "0.6" +lazy_static = { version = "1.4.0", features = ["spin_no_std"] } +log = "0.4" +riscv = { git = "https://gitee.com/rcore-os/riscv", features = ["inline-asm"] } +lock_api = "=0.4.6" +xmas-elf = "0.7.0" +virtio-drivers = { git = "https://gitee.com/rcore-os/virtio-drivers" } +easy-fs = { path = "../easy-fs" } diff --git a/os8/Makefile b/os8/Makefile new file mode 100644 index 0000000..7c3c6eb --- /dev/null +++ b/os8/Makefile @@ -0,0 +1,64 @@ +# Building +TARGET := riscv64gc-unknown-none-elf +MODE := release +KERNEL_ELF := target/$(TARGET)/$(MODE)/os +KERNEL_BIN := $(KERNEL_ELF).bin +KERNEL_ASM := $(KERNEL_ELF).asm +FS_IMG := ../user/target/$(TARGET)/$(MODE)/fs.img +APPS := ../user/src/bin/* + +# BOARD +BOARD ?= qemu +SBI ?= rustsbi +BOOTLOADER := ../bootloader/$(SBI)-$(BOARD).bin + +# KERNEL ENTRY +KERNEL_ENTRY_PA := 0x80200000 + +# Binutils +OBJDUMP := rust-objdump --arch-name=riscv64 +OBJCOPY := rust-objcopy --binary-architecture=riscv64 + +CHAPTER ?= 8 +TEST ?= $(CHAPTER) +BASE ?= 1 + +build: env $(KERNEL_BIN) fs-img + +fs-img: $(APPS) + @make -C ../user build TEST=$(TEST) CHAPTER=$(CHAPTER) BASE=$(BASE) + @cd ../easy-fs-fuse && cargo run --release -- -s ../user/build/app/ -t ../user/target/riscv64gc-unknown-none-elf/release/ + +env: + (rustup target list | grep "riscv64gc-unknown-none-elf (installed)") || rustup target add $(TARGET) + cargo install cargo-binutils --vers ~0.3 + rustup component add rust-src + rustup component add llvm-tools-preview + +$(KERNEL_BIN): kernel + @$(OBJCOPY) $(KERNEL_ELF) --strip-all -O binary $@ + +kernel: + @make -C ../user build TEST=$(TEST) CHAPTER=$(CHAPTER) BASE=$(BASE) + @cargo build --release + +clean: + @cargo clean + @cd ../user && make clean + +run: build + @qemu-system-riscv64 \ + -machine virt \ + -nographic \ + -bios $(BOOTLOADER) \ + -device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY_PA) \ + -drive file=$(FS_IMG),if=none,format=raw,id=x0 \ + -device virtio-blk-device,drive=x0,bus=virtio-mmio-bus.0 + +debug: build + @tmux new-session -d \ + "qemu-system-riscv64 -machine virt -nographic -bios $(BOOTLOADER) -device loader,file=$(KERNEL_BIN),addr=$(KERNEL_ENTRY_PA) -drive file=$(FS_IMG),if=none,format=raw,id=x0 -device virtio-blk-device,drive=x0,bus=virtio-mmio-bus.0 -s -S" && \ + tmux split-window -h "riscv64-unknown-elf-gdb -ex 'file $(KERNEL_ELF)' -ex 'set arch riscv:rv64' -ex 'target remote localhost:1234'" && \ + tmux -2 attach-session -d + +.PHONY: build env kernel clean fs-img diff --git a/os8/build.rs b/os8/build.rs new file mode 100644 index 0000000..5529b4f --- /dev/null +++ b/os8/build.rs @@ -0,0 +1,6 @@ +static TARGET_PATH: &str = "../user/target/riscv64gc-unknown-none-elf/release/"; + +fn main() { + println!("cargo:rerun-if-changed=../user/src/"); + println!("cargo:rerun-if-changed={}", TARGET_PATH); +} diff --git a/os8/src/config.rs b/os8/src/config.rs new file mode 100644 index 0000000..8562cd6 --- /dev/null +++ b/os8/src/config.rs @@ -0,0 +1,14 @@ +//! Constants used in rCore + +pub const USER_STACK_SIZE: usize = 4096 * 2; +pub const KERNEL_STACK_SIZE: usize = 4096 * 2; +pub const KERNEL_HEAP_SIZE: usize = 0x30_0000; +pub const MEMORY_END: usize = 0x88000000; +pub const PAGE_SIZE: usize = 0x1000; +pub const PAGE_SIZE_BITS: usize = 0xc; +pub const MAX_SYSCALL_NUM: usize = 500; + +pub const TRAMPOLINE: usize = usize::MAX - PAGE_SIZE + 1; +pub const TRAP_CONTEXT: usize = TRAMPOLINE - PAGE_SIZE; +pub const CLOCK_FREQ: usize = 12500000; +pub const MMIO: &[(usize, usize)] = &[(0x10001000, 0x1000)]; diff --git a/os8/src/console.rs b/os8/src/console.rs new file mode 100644 index 0000000..a23a0e0 --- /dev/null +++ b/os8/src/console.rs @@ -0,0 +1,130 @@ +//! SBI console driver, for text output + +use crate::sbi::console_putchar; +use core::fmt::{self, Write}; + +struct Stdout; + +impl Write for Stdout { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + console_putchar(c as usize); + } + Ok(()) + } +} + +pub fn print(args: fmt::Arguments) { + Stdout.write_fmt(args).unwrap(); +} + +#[macro_export] +/// print string macro +macro_rules! print { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!($fmt $(, $($arg)+)?)); + } +} + +#[macro_export] +/// println string macro +macro_rules! println { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?)); + } +} + +/* +以下代码提供了与颜色相关的 ANSI 转义字符,以及彩色输出可以使用的函数与宏。 + +可以使用它们,甚至扩展它们,来提升开发体验和显示效果。 +*/ + +// 使用 ANSI 转义字符来加上颜色 +#[macro_export] +macro_rules! colorize { + ($content: ident, $foreground_color: ident) => { + format_args!("\u{1B}[{}m{}\u{1B}[0m", $foreground_color as u8, $content) + }; + ($content: ident, $foreground_color: ident, $background_color: ident) => { + format_args!( + "\u{1B}[{}m\u{1B}[{}m{}\u{1B}[0m", + $foreground_color.into(), + $background_color.into(), + $content + ) + }; +} + +pub fn print_colorized( + args: fmt::Arguments, + foreground_color: impl Into, + background_color: impl Into, +) { + Stdout + .write_fmt(colorize!(args, foreground_color, background_color)) + .unwrap(); +} + +#[macro_export] +macro_rules! print_colorized { + ($fmt: literal, $foreground_color: expr, $background_color: expr $(, $($arg: tt)+)?) => { + $crate::console::print_colorized(format_args!($fmt $(, $($arg)+)?), $foreground_color as u8, $background_color as u8); + }; +} + +#[macro_export] +macro_rules! println_colorized { + ($fmt: literal, $foreground_color: expr, $background_color: expr $(, $($arg: tt)+)?) => { + $crate::console::print_colorized(format_args!(concat!($fmt, "\n") $(, $($arg)+)?), $foreground_color as u8, $background_color as u8); + } +} + +#[allow(dead_code)] +pub enum ANSICON { + Reset = 0, + Bold = 1, + Underline = 4, + Blink = 5, + Reverse = 7, + FgBlack = 30, + FgRed = 31, + FgGreen = 32, + FgYellow = 33, + FgBlue = 34, + FgMagenta = 35, + FgCyan = 36, + FgWhite = 37, + FgDefault = 39, + FgLightGray = 90, + FgLightRed = 91, + FgLightGreen = 92, + FgLightYellow = 93, + FgLightBlue = 94, + FgLightMagenta = 95, + FgLightCyan = 96, + FgLightWhite = 97, + BgBlack = 40, + BgRed = 41, + BgGreen = 42, + BgYellow = 43, + BgBlue = 44, + BgMagenta = 45, + BgCyan = 46, + BgWhite = 47, + BgDefault = 49, + BgLightGray = 100, + BgLightRed = 101, + BgLightGreen = 102, + BgLightYellow = 103, + BgLightBlue = 104, + BgLightMagenta = 105, + BgLightCyan = 106, + BgLightWhite = 107, +} + +impl From for u8 { + fn from(con: ANSICON) -> Self { + con as Self + } +} diff --git a/os8/src/drivers/block/mod.rs b/os8/src/drivers/block/mod.rs new file mode 100644 index 0000000..e3a6345 --- /dev/null +++ b/os8/src/drivers/block/mod.rs @@ -0,0 +1,24 @@ +mod virtio_blk; + +use lazy_static::*; +use alloc::sync::Arc; +use easy_fs::BlockDevice; +type BlockDeviceImpl = virtio_blk::VirtIOBlock; + +lazy_static! { + pub static ref BLOCK_DEVICE: Arc = Arc::new(BlockDeviceImpl::new()); +} + +#[allow(unused)] +pub fn block_device_test() { + let block_device = BLOCK_DEVICE.clone(); + let mut write_buffer = [0u8; 512]; + let mut read_buffer = [0u8; 512]; + for i in 0..512 { + for byte in write_buffer.iter_mut() { *byte = i as u8; } + block_device.write_block(i as usize, &write_buffer); + block_device.read_block(i as usize, &mut read_buffer); + assert_eq!(write_buffer, read_buffer); + } + println!("block device test passed!"); +} \ No newline at end of file diff --git a/os8/src/drivers/block/virtio_blk.rs b/os8/src/drivers/block/virtio_blk.rs new file mode 100644 index 0000000..c9956f5 --- /dev/null +++ b/os8/src/drivers/block/virtio_blk.rs @@ -0,0 +1,84 @@ + +use virtio_drivers::{VirtIOBlk, VirtIOHeader}; +use crate::mm::{ + PhysAddr, + VirtAddr, + frame_alloc, + frame_dealloc, + PhysPageNum, + FrameTracker, + PageTable, + StepByOne, + kernel_token, +}; +use super::BlockDevice; +use crate::sync::UPSafeCell; +use alloc::vec::Vec; +use lazy_static::*; + +#[allow(unused)] +const VIRTIO0: usize = 0x10001000; + +pub struct VirtIOBlock(UPSafeCell>); + +lazy_static! { + static ref QUEUE_FRAMES: UPSafeCell> = unsafe { + UPSafeCell::new(Vec::new()) + }; +} + +impl BlockDevice for VirtIOBlock { + fn read_block(&self, block_id: usize, buf: &mut [u8]) { + self.0.exclusive_access() + .read_block(block_id, buf) + .expect("Error when reading VirtIOBlk"); + } + fn write_block(&self, block_id: usize, buf: &[u8]) { + self.0.exclusive_access() + .write_block(block_id, buf) + .expect("Error when writing VirtIOBlk"); + } +} + +impl VirtIOBlock { + #[allow(unused)] + pub fn new() -> Self { + unsafe { + Self(UPSafeCell::new(VirtIOBlk::new( + &mut *(VIRTIO0 as *mut VirtIOHeader) + ).unwrap())) + } + } +} + +#[no_mangle] +pub extern "C" fn virtio_dma_alloc(pages: usize) -> PhysAddr { + let mut ppn_base = PhysPageNum(0); + for i in 0..pages { + let frame = frame_alloc().unwrap(); + if i == 0 { ppn_base = frame.ppn; } + assert_eq!(frame.ppn.0, ppn_base.0 + i); + QUEUE_FRAMES.exclusive_access().push(frame); + } + ppn_base.into() +} + +#[no_mangle] +pub extern "C" fn virtio_dma_dealloc(pa: PhysAddr, pages: usize) -> i32 { + let mut ppn_base: PhysPageNum = pa.into(); + for _ in 0..pages { + frame_dealloc(ppn_base); + ppn_base.step(); + } + 0 +} + +#[no_mangle] +pub extern "C" fn virtio_phys_to_virt(paddr: PhysAddr) -> VirtAddr { + VirtAddr(paddr.0) +} + +#[no_mangle] +pub extern "C" fn virtio_virt_to_phys(vaddr: VirtAddr) -> PhysAddr { + PageTable::from_token(kernel_token()).translate_va(vaddr).unwrap() +} diff --git a/os8/src/drivers/mod.rs b/os8/src/drivers/mod.rs new file mode 100644 index 0000000..43a6f54 --- /dev/null +++ b/os8/src/drivers/mod.rs @@ -0,0 +1,3 @@ +mod block; + +pub use block::BLOCK_DEVICE; diff --git a/os8/src/entry.asm b/os8/src/entry.asm new file mode 100644 index 0000000..9d2ff71 --- /dev/null +++ b/os8/src/entry.asm @@ -0,0 +1,12 @@ + .section .text.entry + .globl _start +_start: + la sp, boot_stack_top + call rust_main + + .section .bss.stack + .globl boot_stack +boot_stack: + .space 4096 * 16 + .globl boot_stack_top +boot_stack_top: \ No newline at end of file diff --git a/os8/src/fs/README.md b/os8/src/fs/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os8/src/lang_items.rs b/os8/src/lang_items.rs new file mode 100644 index 0000000..e52afff --- /dev/null +++ b/os8/src/lang_items.rs @@ -0,0 +1,29 @@ +//! The panic handler + +use crate::console::ANSICON; +use crate::sbi::shutdown; + +use core::panic::PanicInfo; + +#[panic_handler] +/// panic handler +fn panic(info: &PanicInfo) -> ! { + if let Some(location) = info.location() { + println_colorized!( + "[kernel] Panicked at {}:{} {}", + ANSICON::FgRed, + ANSICON::BgDefault, + location.file(), + location.line(), + info.message().unwrap() + ); + } else { + println_colorized!( + "[kernel] Panicked: {}", + ANSICON::FgRed, + ANSICON::BgDefault, + info.message().unwrap() + ); + } + shutdown() +} diff --git a/os8/src/link_app.S b/os8/src/link_app.S new file mode 100644 index 0000000..32748e6 --- /dev/null +++ b/os8/src/link_app.S @@ -0,0 +1,140 @@ + + .align 3 + .section .data + .global _num_app +_num_app: + .quad 13 + .quad app_0_start + .quad app_1_start + .quad app_2_start + .quad app_3_start + .quad app_4_start + .quad app_5_start + .quad app_6_start + .quad app_7_start + .quad app_8_start + .quad app_9_start + .quad app_10_start + .quad app_11_start + .quad app_12_start + .quad app_12_end + + .global _app_names +_app_names: + .string "ch2b_bad_address" + .string "ch2b_bad_instructions" + .string "ch2b_bad_register" + .string "ch2b_hello_world" + .string "ch2b_power_3" + .string "ch2b_power_5" + .string "ch2b_power_7" + .string "ch3_taskinfo" + .string "ch3b_sleep" + .string "ch3b_sleep1" + .string "ch3b_yield0" + .string "ch3b_yield1" + .string "ch3b_yield2" + + .section .data + .global app_0_start + .global app_0_end + .align 3 +app_0_start: + .incbin "../ci-user/user/build/bin/ch2b_bad_address.bin" +app_0_end: + + .section .data + .global app_1_start + .global app_1_end + .align 3 +app_1_start: + .incbin "../ci-user/user/build/bin/ch2b_bad_instructions.bin" +app_1_end: + + .section .data + .global app_2_start + .global app_2_end + .align 3 +app_2_start: + .incbin "../ci-user/user/build/bin/ch2b_bad_register.bin" +app_2_end: + + .section .data + .global app_3_start + .global app_3_end + .align 3 +app_3_start: + .incbin "../ci-user/user/build/bin/ch2b_hello_world.bin" +app_3_end: + + .section .data + .global app_4_start + .global app_4_end + .align 3 +app_4_start: + .incbin "../ci-user/user/build/bin/ch2b_power_3.bin" +app_4_end: + + .section .data + .global app_5_start + .global app_5_end + .align 3 +app_5_start: + .incbin "../ci-user/user/build/bin/ch2b_power_5.bin" +app_5_end: + + .section .data + .global app_6_start + .global app_6_end + .align 3 +app_6_start: + .incbin "../ci-user/user/build/bin/ch2b_power_7.bin" +app_6_end: + + .section .data + .global app_7_start + .global app_7_end + .align 3 +app_7_start: + .incbin "../ci-user/user/build/bin/ch3_taskinfo.bin" +app_7_end: + + .section .data + .global app_8_start + .global app_8_end + .align 3 +app_8_start: + .incbin "../ci-user/user/build/bin/ch3b_sleep.bin" +app_8_end: + + .section .data + .global app_9_start + .global app_9_end + .align 3 +app_9_start: + .incbin "../ci-user/user/build/bin/ch3b_sleep1.bin" +app_9_end: + + .section .data + .global app_10_start + .global app_10_end + .align 3 +app_10_start: + .incbin "../ci-user/user/build/bin/ch3b_yield0.bin" +app_10_end: + + .section .data + .global app_11_start + .global app_11_end + .align 3 +app_11_start: + .incbin "../ci-user/user/build/bin/ch3b_yield1.bin" +app_11_end: + + .section .data + .global app_12_start + .global app_12_end + .align 3 +app_12_start: + .incbin "../ci-user/user/build/bin/ch3b_yield2.bin" +app_12_end: diff --git a/os8/src/linker.ld b/os8/src/linker.ld new file mode 100644 index 0000000..5baafbd --- /dev/null +++ b/os8/src/linker.ld @@ -0,0 +1,53 @@ +OUTPUT_ARCH(riscv) +ENTRY(_start) +BASE_ADDRESS = 0x80200000; + +SECTIONS +{ + . = BASE_ADDRESS; + skernel = .; + + stext = .; + .text : { + *(.text.entry) + . = ALIGN(4K); + strampoline = .; + *(.text.trampoline); + . = ALIGN(4K); + *(.text .text.*) + } + + . = ALIGN(4K); + etext = .; + srodata = .; + .rodata : { + *(.rodata .rodata.*) + *(.srodata .srodata.*) + } + + . = ALIGN(4K); + erodata = .; + sdata = .; + .data : { + *(.data .data.*) + *(.sdata .sdata.*) + } + + . = ALIGN(4K); + edata = .; + sbss_with_stack = .; + .bss : { + *(.bss.stack) + sbss = .; + *(.bss .bss.*) + *(.sbss .sbss.*) + } + + . = ALIGN(4K); + ebss = .; + ekernel = .; + + /DISCARD/ : { + *(.eh_frame) + } +} \ No newline at end of file diff --git a/os8/src/logging.rs b/os8/src/logging.rs new file mode 100644 index 0000000..e12448e --- /dev/null +++ b/os8/src/logging.rs @@ -0,0 +1,45 @@ +//! Global logger + +use log::{self, Level, LevelFilter, Log, Metadata, Record}; + +/// a simple logger +struct SimpleLogger; + +impl Log for SimpleLogger { + fn enabled(&self, _metadata: &Metadata) -> bool { + true + } + fn log(&self, record: &Record) { + if !self.enabled(record.metadata()) { + return; + } + let color = match record.level() { + Level::Error => 31, // Red + Level::Warn => 93, // BrightYellow + Level::Info => 34, // Blue + Level::Debug => 32, // Green + Level::Trace => 90, // BrightBlack + }; + println!( + "\u{1B}[{}m[{:>5}] {}\u{1B}[0m", + color, + record.level(), + record.args(), + ); + } + fn flush(&self) {} +} + +/// initiate logger +pub fn init() { + static LOGGER: SimpleLogger = SimpleLogger; + log::set_logger(&LOGGER).unwrap(); + log::set_max_level(match option_env!("LOG") { + Some("ERROR") => LevelFilter::Error, + Some("WARN") => LevelFilter::Warn, + Some("INFO") => LevelFilter::Info, + Some("DEBUG") => LevelFilter::Debug, + Some("TRACE") => LevelFilter::Trace, + _ => LevelFilter::Off, + }); +} diff --git a/os8/src/main.rs b/os8/src/main.rs new file mode 100644 index 0000000..8036bca --- /dev/null +++ b/os8/src/main.rs @@ -0,0 +1,74 @@ +//! The main module and entrypoint +//! +//! Various facilities of the kernels are implemented as submodules. The most +//! important ones are: +//! +//! - [`trap`]: Handles all cases of switching from userspace to the kernel +//! - [`task`]: Task management +//! - [`syscall`]: System call handling and implementation +//! +//! The operating system also starts in this module. Kernel code starts +//! executing from `entry.asm`, after which [`rust_main()`] is called to +//! initialize various pieces of functionality. (See its source code for +//! details.) +//! +//! We then call [`task::run_first_task()`] and for the first time go to +//! userspace. + +#![no_std] +#![no_main] +#![feature(panic_info_message)] +#![feature(alloc_error_handler)] + +#[macro_use] +extern crate bitflags; +#[macro_use] +extern crate log; + +extern crate alloc; + +#[macro_use] +mod console; +mod config; +mod lang_items; +mod logging; +mod mm; +mod sbi; +mod sync; +mod syscall; +mod task; +mod timer; +mod trap; +mod drivers; +mod fs; + +core::arch::global_asm!(include_str!("entry.asm")); + +/// clear BSS segment +fn clear_bss() { + extern "C" { + fn sbss(); + fn ebss(); + } + unsafe { + core::slice::from_raw_parts_mut(sbss as usize as *mut u8, ebss as usize - sbss as usize) + .fill(0); + } +} + +#[no_mangle] +/// the rust entry-point of os +pub fn rust_main() -> ! { + clear_bss(); + logging::init(); + println!("[kernel] Hello, world!"); + mm::init(); + mm::remap_test(); + trap::init(); + trap::enable_timer_interrupt(); + timer::set_next_trigger(); + fs::list_apps(); + task::add_initproc(); + task::run_tasks(); + panic!("Unreachable in rust_main!"); +} diff --git a/os8/src/mm/README.md b/os8/src/mm/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os8/src/sbi.rs b/os8/src/sbi.rs new file mode 100644 index 0000000..4af7620 --- /dev/null +++ b/os8/src/sbi.rs @@ -0,0 +1,45 @@ +//! SBI call wrappers + +#![allow(unused)] + +const SBI_SET_TIMER: usize = 0; +const SBI_CONSOLE_PUTCHAR: usize = 1; +const SBI_CONSOLE_GETCHAR: usize = 2; +const SBI_SHUTDOWN: usize = 8; + +#[inline(always)] +/// general sbi call +fn sbi_call(which: usize, arg0: usize, arg1: usize, arg2: usize) -> usize { + let mut ret; + unsafe { + core::arch::asm!( + "ecall", + inlateout("x10") arg0 => ret, + in("x11") arg1, + in("x12") arg2, + in("x17") which, + ); + } + ret +} + +/// use sbi call to set timer +pub fn set_timer(timer: usize) { + sbi_call(SBI_SET_TIMER, timer, 0, 0); +} + +/// use sbi call to putchar in console (qemu uart handler) +pub fn console_putchar(c: usize) { + sbi_call(SBI_CONSOLE_PUTCHAR, c, 0, 0); +} + +/// use sbi call to getchar from console (qemu uart handler) +pub fn console_getchar() -> usize { + sbi_call(SBI_CONSOLE_GETCHAR, 0, 0, 0) +} + +/// use sbi call to shutdown the kernel +pub fn shutdown() -> ! { + sbi_call(SBI_SHUTDOWN, 0, 0, 0); + panic!("It should shutdown!"); +} diff --git a/os8/src/sync/README.md b/os8/src/sync/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os8/src/syscall/README.md b/os8/src/syscall/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os8/src/task/README.md b/os8/src/task/README.md new file mode 100644 index 0000000..e69de29 diff --git a/os8/src/timer.rs b/os8/src/timer.rs new file mode 100644 index 0000000..b2fd8eb --- /dev/null +++ b/os8/src/timer.rs @@ -0,0 +1,83 @@ +//! RISC-V timer-related functionality + +use crate::config::CLOCK_FREQ; +use crate::sbi::set_timer; +use crate::sync::UPSafeCell; +use crate::task::{add_task, TaskControlBlock}; +use alloc::collections::BinaryHeap; +use alloc::sync::Arc; +use core::cmp::Ordering; +use lazy_static::*; +use riscv::register::time; + +const TICKS_PER_SEC: usize = 100; +const MILLI_PER_SEC: usize = 1_000; +const MICRO_PER_SEC: usize = 1_000_000; + +/// read the `mtime` register +pub fn get_time() -> usize { + time::read() +} + +/// get current time in microseconds +pub fn get_time_us() -> usize { + time::read() / (CLOCK_FREQ / MICRO_PER_SEC) +} + +/// get current time in milliseconds +pub fn get_time_ms() -> usize { + time::read() / (CLOCK_FREQ / MILLI_PER_SEC) +} + +/// set the next timer interrupt +pub fn set_next_trigger() { + set_timer(get_time() + CLOCK_FREQ / TICKS_PER_SEC); +} + +pub struct TimerCondVar { + pub expire_ms: usize, + pub task: Arc, +} + +impl PartialEq for TimerCondVar { + fn eq(&self, other: &Self) -> bool { + self.expire_ms == other.expire_ms + } +} +impl Eq for TimerCondVar {} +impl PartialOrd for TimerCondVar { + fn partial_cmp(&self, other: &Self) -> Option { + let a = -(self.expire_ms as isize); + let b = -(other.expire_ms as isize); + Some(a.cmp(&b)) + } +} + +impl Ord for TimerCondVar { + fn cmp(&self, other: &Self) -> Ordering { + self.partial_cmp(other).unwrap() + } +} + +lazy_static! { + static ref TIMERS: UPSafeCell> = + unsafe { UPSafeCell::new(BinaryHeap::::new()) }; +} + +pub fn add_timer(expire_ms: usize, task: Arc) { + let mut timers = TIMERS.exclusive_access(); + timers.push(TimerCondVar { expire_ms, task }); +} + +pub fn check_timer() { + let current_ms = get_time_ms(); + let mut timers = TIMERS.exclusive_access(); + while let Some(timer) = timers.peek() { + if timer.expire_ms <= current_ms { + add_task(Arc::clone(&timer.task)); + timers.pop(); + } else { + break; + } + } +} diff --git a/os8/src/trap/README.md b/os8/src/trap/README.md new file mode 100644 index 0000000..e69de29 diff --git a/reports/lab1.md b/reports/lab1.md new file mode 100644 index 0000000..e69de29 diff --git a/reports/lab2.md b/reports/lab2.md new file mode 100644 index 0000000..e69de29 diff --git a/reports/lab3.md b/reports/lab3.md new file mode 100644 index 0000000..e69de29 diff --git a/reports/lab4.md b/reports/lab4.md new file mode 100644 index 0000000..e69de29 diff --git a/reports/lab5.md b/reports/lab5.md new file mode 100644 index 0000000..e69de29 diff --git a/rust-toolchain b/rust-toolchain new file mode 100644 index 0000000..289fc8e --- /dev/null +++ b/rust-toolchain @@ -0,0 +1 @@ +nightly-2022-04-11 \ No newline at end of file