From 7c1679774c01810ff1a8aa5bcad03b32e1c411e7 Mon Sep 17 00:00:00 2001 From: Yu Chen Date: Mon, 27 Jun 2022 21:48:28 +0800 Subject: [PATCH] init version --- .gitignore | 9 + LICENSE | 674 ++++++++++++++++++++++++++++ Makefile | 58 +++ bootloader/rustsbi-qemu.bin | Bin 0 -> 43568 bytes easy-fs-fuse/Cargo.toml | 12 + easy-fs-fuse/src/main.rs | 155 +++++++ easy-fs/.gitignore | 3 + easy-fs/Cargo.toml | 11 + easy-fs/src/bitmap.rs | 77 ++++ easy-fs/src/block_cache.rs | 144 ++++++ easy-fs/src/block_dev.rs | 8 + easy-fs/src/efs.rs | 164 +++++++ easy-fs/src/layout.rs | 477 ++++++++++++++++++++ easy-fs/src/lib.rs | 19 + easy-fs/src/vfs.rs | 211 +++++++++ os1/.cargo/config | 7 + os1/Cargo.toml | 10 + os1/Makefile | 49 ++ os1/src/console.rs | 37 ++ os1/src/entry.asm | 12 + os1/src/lang_items.rs | 17 + os1/src/link_app.S | 0 os1/src/linker.ld | 48 ++ os1/src/logging.rs | 47 ++ os1/src/main.rs | 49 ++ os1/src/sbi.rs | 34 ++ os2/.cargo/config | 7 + os2/Cargo.toml | 12 + os2/Makefile | 58 +++ os2/build.rs | 56 +++ os2/src/batch.rs | 141 ++++++ os2/src/console.rs | 37 ++ os2/src/entry.asm | 12 + os2/src/lang_items.rs | 17 + os2/src/link_app.S | 0 os2/src/linker.ld | 48 ++ os2/src/logging.rs | 47 ++ os2/src/main.rs | 40 ++ os2/src/sbi.rs | 34 ++ os2/src/sync/mod.rs | 3 + os2/src/sync/up.rs | 29 ++ os2/src/syscall/fs.rs | 15 + os2/src/syscall/mod.rs | 16 + os2/src/syscall/process.rs | 6 + os2/src/trap/context.rs | 25 ++ os2/src/trap/mod.rs | 50 +++ os2/src/trap/trap.S | 64 +++ os3/.cargo/config | 7 + os3/Cargo.toml | 13 + os3/Makefile | 59 +++ os3/build.rs | 56 +++ os3/src/config.rs | 8 + os3/src/console.rs | 31 ++ os3/src/entry.asm | 12 + os3/src/heap_alloc.rs | 20 + os3/src/lang_items.rs | 17 + os3/src/link_app.S | 0 os3/src/linker.ld | 48 ++ os3/src/loader.rs | 85 ++++ os3/src/logging.rs | 41 ++ os3/src/main.rs | 51 +++ os3/src/sbi.rs | 38 ++ os3/src/sync/README.md | 0 os3/src/syscall/README.md | 0 os3/src/task/README.md | 0 os3/src/timer.rs | 18 + os3/src/trap/README.md | 0 os4/.cargo/config | 7 + os4/Cargo.toml | 17 + os4/Makefile | 51 +++ os4/build.rs | 57 +++ os4/src/config.rs | 18 + os4/src/console.rs | 35 ++ os4/src/entry.asm | 12 + os4/src/lang_items.rs | 17 + os4/src/link_app.S | 0 os4/src/linker.ld | 53 +++ os4/src/loader.rs | 22 + os4/src/logging.rs | 41 ++ os4/src/main.rs | 55 +++ os4/src/mm/README.md | 0 os4/src/sbi.rs | 38 ++ os4/src/sync/README.md | 0 os4/src/syscall/README.md | 0 os4/src/task/README.md | 0 os4/src/timer.rs | 18 + os4/src/trap/README.md | 0 os5/.cargo/config | 7 + os5/Cargo.toml | 17 + os5/Makefile | 55 +++ os5/build.rs | 67 +++ os5/src/config.rs | 12 + os5/src/console.rs | 35 ++ os5/src/entry.asm | 12 + os5/src/lang_items.rs | 17 + os5/src/link_app.S | 0 os5/src/linker.ld | 53 +++ os5/src/loader.rs | 64 +++ os5/src/logging.rs | 41 ++ os5/src/main.rs | 56 +++ os5/src/mm/README.md | 0 os5/src/sbi.rs | 38 ++ os5/src/sync/README.md | 0 os5/src/syscall/README.md | 0 os5/src/task/README.md | 0 os5/src/timer.rs | 18 + os5/src/trap/README.md | 0 os6/.cargo/config | 7 + os6/Cargo.toml | 18 + os6/Makefile | 64 +++ os6/build.rs | 6 + os6/src/config.rs | 16 + os6/src/console.rs | 130 ++++++ os6/src/drivers/block/mod.rs | 24 + os6/src/drivers/block/virtio_blk.rs | 84 ++++ os6/src/drivers/mod.rs | 3 + os6/src/entry.asm | 12 + os6/src/fs/README.md | 0 os6/src/lang_items.rs | 29 ++ os6/src/link_app.S | 140 ++++++ os6/src/linker.ld | 53 +++ os6/src/logging.rs | 45 ++ os6/src/main.rs | 74 +++ os6/src/mm/README.md | 0 os6/src/sbi.rs | 45 ++ os6/src/sync/README.md | 0 os6/src/syscall/README.md | 0 os6/src/task/README.md | 0 os6/src/timer.rs | 23 + os6/src/trap/README.md | 0 os7/.cargo/config | 7 + os7/Cargo.toml | 18 + os7/Makefile | 64 +++ os7/build.rs | 6 + os7/src/config.rs | 16 + os7/src/console.rs | 130 ++++++ os7/src/drivers/block/mod.rs | 24 + os7/src/drivers/block/virtio_blk.rs | 84 ++++ os7/src/drivers/mod.rs | 3 + os7/src/entry.asm | 12 + os7/src/fs/README.md | 0 os7/src/lang_items.rs | 29 ++ os7/src/link_app.S | 140 ++++++ os7/src/linker.ld | 53 +++ os7/src/logging.rs | 45 ++ os7/src/main.rs | 74 +++ os7/src/mm/README.md | 0 os7/src/sbi.rs | 45 ++ os7/src/sync/README.md | 0 os7/src/syscall/README.md | 0 os7/src/task/README.md | 0 os7/src/timer.rs | 23 + os7/src/trap/README.md | 0 os8/.cargo/config | 7 + os8/Cargo.toml | 18 + os8/Makefile | 64 +++ os8/build.rs | 6 + os8/src/config.rs | 14 + os8/src/console.rs | 130 ++++++ os8/src/drivers/block/mod.rs | 24 + os8/src/drivers/block/virtio_blk.rs | 84 ++++ os8/src/drivers/mod.rs | 3 + os8/src/entry.asm | 12 + os8/src/fs/README.md | 0 os8/src/lang_items.rs | 29 ++ os8/src/link_app.S | 140 ++++++ os8/src/linker.ld | 53 +++ os8/src/logging.rs | 45 ++ os8/src/main.rs | 74 +++ os8/src/mm/README.md | 0 os8/src/sbi.rs | 45 ++ os8/src/sync/README.md | 0 os8/src/syscall/README.md | 0 os8/src/task/README.md | 0 os8/src/timer.rs | 83 ++++ os8/src/trap/README.md | 0 reports/lab1.md | 0 reports/lab2.md | 0 reports/lab3.md | 0 reports/lab4.md | 0 reports/lab5.md | 0 rust-toolchain | 1 + 182 files changed, 6864 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 bootloader/rustsbi-qemu.bin create mode 100644 easy-fs-fuse/Cargo.toml create mode 100644 easy-fs-fuse/src/main.rs create mode 100644 easy-fs/.gitignore create mode 100644 easy-fs/Cargo.toml create mode 100644 easy-fs/src/bitmap.rs create mode 100644 easy-fs/src/block_cache.rs create mode 100644 easy-fs/src/block_dev.rs create mode 100644 easy-fs/src/efs.rs create mode 100644 easy-fs/src/layout.rs create mode 100644 easy-fs/src/lib.rs create mode 100644 easy-fs/src/vfs.rs create mode 100644 os1/.cargo/config create mode 100644 os1/Cargo.toml create mode 100644 os1/Makefile create mode 100644 os1/src/console.rs create mode 100644 os1/src/entry.asm create mode 100644 os1/src/lang_items.rs create mode 100644 os1/src/link_app.S create mode 100644 os1/src/linker.ld create mode 100644 os1/src/logging.rs create mode 100644 os1/src/main.rs create mode 100644 os1/src/sbi.rs create mode 100644 os2/.cargo/config create mode 100644 os2/Cargo.toml create mode 100644 os2/Makefile create mode 100644 os2/build.rs create mode 100644 os2/src/batch.rs create mode 100644 os2/src/console.rs create mode 100644 os2/src/entry.asm create mode 100644 os2/src/lang_items.rs create mode 100644 os2/src/link_app.S create mode 100644 os2/src/linker.ld create mode 100644 os2/src/logging.rs create mode 100644 os2/src/main.rs create mode 100644 os2/src/sbi.rs create mode 100644 os2/src/sync/mod.rs create mode 100644 os2/src/sync/up.rs create mode 100644 os2/src/syscall/fs.rs create mode 100644 os2/src/syscall/mod.rs create mode 100644 os2/src/syscall/process.rs create mode 100644 os2/src/trap/context.rs create mode 100644 os2/src/trap/mod.rs create mode 100644 os2/src/trap/trap.S create mode 100644 os3/.cargo/config create mode 100644 os3/Cargo.toml create mode 100644 os3/Makefile create mode 100644 os3/build.rs create mode 100644 os3/src/config.rs create mode 100644 os3/src/console.rs create mode 100644 os3/src/entry.asm create mode 100644 os3/src/heap_alloc.rs create mode 100644 os3/src/lang_items.rs create mode 100644 os3/src/link_app.S create mode 100644 os3/src/linker.ld create mode 100644 os3/src/loader.rs create mode 100644 os3/src/logging.rs create mode 100644 os3/src/main.rs create mode 100644 os3/src/sbi.rs create mode 100644 os3/src/sync/README.md create mode 100644 os3/src/syscall/README.md create mode 100644 os3/src/task/README.md create mode 100644 os3/src/timer.rs create mode 100644 os3/src/trap/README.md create mode 100644 os4/.cargo/config create mode 100644 os4/Cargo.toml create mode 100644 os4/Makefile create mode 100644 os4/build.rs create mode 100644 os4/src/config.rs create mode 100644 os4/src/console.rs create mode 100644 os4/src/entry.asm create mode 100644 os4/src/lang_items.rs create mode 100644 os4/src/link_app.S create mode 100644 os4/src/linker.ld create mode 100644 os4/src/loader.rs create mode 100644 os4/src/logging.rs create mode 100644 os4/src/main.rs create mode 100644 os4/src/mm/README.md create mode 100644 os4/src/sbi.rs create mode 100644 os4/src/sync/README.md create mode 100644 os4/src/syscall/README.md create mode 100644 os4/src/task/README.md create mode 100644 os4/src/timer.rs create mode 100644 os4/src/trap/README.md create mode 100644 os5/.cargo/config create mode 100644 os5/Cargo.toml create mode 100644 os5/Makefile create mode 100644 os5/build.rs create mode 100644 os5/src/config.rs create mode 100644 os5/src/console.rs create mode 100644 os5/src/entry.asm create mode 100644 os5/src/lang_items.rs create mode 100644 os5/src/link_app.S create mode 100644 os5/src/linker.ld create mode 100644 os5/src/loader.rs create mode 100644 os5/src/logging.rs create mode 100644 os5/src/main.rs create mode 100644 os5/src/mm/README.md create mode 100644 os5/src/sbi.rs create mode 100644 os5/src/sync/README.md create mode 100644 os5/src/syscall/README.md create mode 100644 os5/src/task/README.md create mode 100644 os5/src/timer.rs create mode 100644 os5/src/trap/README.md create mode 100644 os6/.cargo/config create mode 100644 os6/Cargo.toml create mode 100644 os6/Makefile create mode 100644 os6/build.rs create mode 100644 os6/src/config.rs create mode 100644 os6/src/console.rs create mode 100644 os6/src/drivers/block/mod.rs create mode 100644 os6/src/drivers/block/virtio_blk.rs create mode 100644 os6/src/drivers/mod.rs create mode 100644 os6/src/entry.asm create mode 100644 os6/src/fs/README.md create mode 100644 os6/src/lang_items.rs create mode 100644 os6/src/link_app.S create mode 100644 os6/src/linker.ld create mode 100644 os6/src/logging.rs create mode 100644 os6/src/main.rs create mode 100644 os6/src/mm/README.md create mode 100644 os6/src/sbi.rs create mode 100644 os6/src/sync/README.md create mode 100644 os6/src/syscall/README.md create mode 100644 os6/src/task/README.md create mode 100644 os6/src/timer.rs create mode 100644 os6/src/trap/README.md create mode 100644 os7/.cargo/config create mode 100644 os7/Cargo.toml create mode 100644 os7/Makefile create mode 100644 os7/build.rs create mode 100644 os7/src/config.rs create mode 100644 os7/src/console.rs create mode 100644 os7/src/drivers/block/mod.rs create mode 100644 os7/src/drivers/block/virtio_blk.rs create mode 100644 os7/src/drivers/mod.rs create mode 100644 os7/src/entry.asm create mode 100644 os7/src/fs/README.md create mode 100644 os7/src/lang_items.rs create mode 100644 os7/src/link_app.S create mode 100644 os7/src/linker.ld create mode 100644 os7/src/logging.rs create mode 100644 os7/src/main.rs create mode 100644 os7/src/mm/README.md create mode 100644 os7/src/sbi.rs create mode 100644 os7/src/sync/README.md create mode 100644 os7/src/syscall/README.md create mode 100644 os7/src/task/README.md create mode 100644 os7/src/timer.rs create mode 100644 os7/src/trap/README.md create mode 100644 os8/.cargo/config create mode 100644 os8/Cargo.toml create mode 100644 os8/Makefile create mode 100644 os8/build.rs create mode 100644 os8/src/config.rs create mode 100644 os8/src/console.rs create mode 100644 os8/src/drivers/block/mod.rs create mode 100644 os8/src/drivers/block/virtio_blk.rs create mode 100644 os8/src/drivers/mod.rs create mode 100644 os8/src/entry.asm create mode 100644 os8/src/fs/README.md create mode 100644 os8/src/lang_items.rs create mode 100644 os8/src/link_app.S create mode 100644 os8/src/linker.ld create mode 100644 os8/src/logging.rs create mode 100644 os8/src/main.rs create mode 100644 os8/src/mm/README.md create mode 100644 os8/src/sbi.rs create mode 100644 os8/src/sync/README.md create mode 100644 os8/src/syscall/README.md create mode 100644 os8/src/task/README.md create mode 100644 os8/src/timer.rs create mode 100644 os8/src/trap/README.md create mode 100644 reports/lab1.md create mode 100644 reports/lab2.md create mode 100644 reports/lab3.md create mode 100644 reports/lab4.md create mode 100644 reports/lab5.md create mode 100644 rust-toolchain 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 0000000000000000000000000000000000000000..9822f54e58daad6d5fa47ac4b9b51061dbad1a4a GIT binary patch literal 43568 zcmdS?e_Rwt(g2M2%rLVH0xk~Af@p%0McqdcT>+KE2aU5tqF&+!yxeoif#YH@q9QED z5^zKt z3w7xPx?bsvtI+k;Ds_WWPQk7ls#V#0HNXW+yZ77s)SP`#`l8G2 zLjjzwZI2M?)^$|^E#Pxak?NGH@-f`Puw8_EGD1ZE`x0e3voZ(rSS(qZoj^@d_**M| ziuB}88AK>6fLO$|`*%<24eFaZc;8S}YfZbo^JMqw-uk|G2HzW6(PnTbcCGDMcQd*F zmv^2XzS`E|zTS1C=bM`Y{omdh8NM|WEy@ZUT}C;xlx zZ*TlIAT>W1A^dMwCet^wH=;YSb8Wl5n4$#~S!^vRMw3w#Ss5?(=v3C!KiSVoujIW2 zWiiJyb-q%|je{C!Im>hm*Kv|;TK@sx{U44VDqjTn-pO%6^++(Bsi;T!L3uCDpG5~c zcAiIhUpo>mqnrEQ-uL>f{@|Y5aY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>` z`0_v~1VO1(6~*lmNg@h0D2e;Z1@inDLAsta>VmaJ6l9|5VvPt-cJMt@w2+&{tRYEc zf|_Y}N-n6IC{83Zpyfr;0re^(UeGFv@b_OxzNnJVX|oYHz)Vd|h1b5whvX*s6(^{r zoF~cTSD;@IZ?U`O%ZNW^64X+Y+@Mh*Q>AehqD~_Y(Px7@i8M&GA+2Nwk<{Tvs}hn< zk`>AFyhH2 zndn-c)#xRwC^@0A;g6pI_ri2=1hiag1q0CDFw&?g0`-7rmO!S<3+S~|93eoRWs9nc z$|(6pNeIXul_ZmN3rPV@X@(XHj94;N7L+zcXiOXxY?dJ;OyC!*h+rQH&00jSXe-jR z7!!m>MoPg%`;?~FUt_5P)4>BQB`}%uobPOUe`tB_(%W_vJvvk1{+&&qdyHRSH2m4e z>|Z^W`_j}skMo?UrKkt0I zH}}nDqPJ-5GjILxQ~Qtq>Am-S55Lp%RMAu*+Se;W|;H59=v^TVJY)gL|$JU9"] +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