Initial commit

This commit is contained in:
github-classroom[bot]
2022-06-29 12:24:12 +00:00
commit 4dfe17a1b1
867 changed files with 57359 additions and 0 deletions

35
.github/workflows/deployguide.yml vendored Normal file
View File

@@ -0,0 +1,35 @@
name: Deploy Guide
on:
push:
branches: [main]
jobs:
deploy-doc:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
with:
python-version: "3.8.10"
- name: Install dependencies
run: |
cd guide
pip install -r requirements.txt
- name: build doc
run: |
cd guide
make html
- name: create .nojekyll
run: |
cd guide
touch build/html/.nojekyll
- name: Push to gh-pages
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./guide/build/html

8
.gitignore vendored Normal file
View File

@@ -0,0 +1,8 @@
.vscode
.idea
Cargo.lock
target
os/src/link_app.S
os/last-*
tools
workplace/

674
LICENSE Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

180
Makefile Normal file
View File

@@ -0,0 +1,180 @@
DOCKER_NAME ?= dinghao188/rcore-tutorial
DIR := workplace
.PHONY: docker build_docker
test: test3 test4 test5 test6 test7 test8
lab1: test3
lab2: test4
lab3: test5
lab4: test6 test7
lab5: 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}
export PATH=$PATH:$HOME/qemu-7.0.0
export PATH=$PATH:$HOME/qemu-7.0.0/riscv64-softmmu
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} .
setupclassroom_test1:
mkdir -p .github/classroom/
mkdir -p .github/workflows/
touch .github/.keep
cp scripts/autograding-test1.json .github/classroom/autograding.json
cp scripts/classroom.yml .github/workflows/classroom.yml
git add .github/classroom/autograding.json
git add .github/workflows/classroom.yml
git add .github/.keep
git commit -m"update classroom.yml .keep autograding.json for classroom CI test"
git push
setupclassroom_test2:
mkdir -p .github/classroom/
mkdir -p .github/workflows/
touch .github/.keep
cp scripts/autograding-test2.json .github/classroom/autograding.json
cp scripts/classroom.yml .github/workflows/classroom.yml
git add .github/classroom/autograding.json
git add .github/workflows/classroom.yml
git add .github/.keep
git commit -m"update classroom.yml .keep autograding.json for classroom CI test"
git push
setupclassroom_test3:
mkdir -p .github/classroom/
mkdir -p .github/workflows/
touch .github/.keep
cp scripts/autograding-test3.json .github/classroom/autograding.json
cp scripts/classroom.yml .github/workflows/classroom.yml
git add .github/classroom/autograding.json
git add .github/workflows/classroom.yml
git add .github/.keep
git commit -m"update classroom.yml .keep autograding.json for classroom CI test"
git push
setupclassroom_test4:
mkdir -p .github/classroom/
mkdir -p .github/workflows/
touch .github/.keep
cp scripts/autograding-test4.json .github/classroom/autograding.json
cp scripts/classroom.yml .github/workflows/classroom.yml
git add .github/classroom/autograding.json
git add .github/workflows/classroom.yml
git add .github/.keep
git commit -m"update classroom.yml .keep autograding.json for classroom CI test"
git push
setupclassroom_test5:
mkdir -p .github/classroom/
mkdir -p .github/workflows/
touch .github/.keep
cp scripts/autograding-test5.json .github/classroom/autograding.json
cp scripts/classroom.yml .github/workflows/classroom.yml
git add .github/classroom/autograding.json
git add .github/workflows/classroom.yml
git add .github/.keep
git commit -m"update classroom.yml .keep autograding.json for classroom CI test"
git push
setupclassroom_test6:
mkdir -p .github/classroom/
mkdir -p .github/workflows/
touch .github/.keep
cp scripts/autograding-test6.json .github/classroom/autograding.json
cp scripts/classroom.yml .github/workflows/classroom.yml
git add .github/classroom/autograding.json
git add .github/workflows/classroom.yml
git add .github/.keep
git commit -m"update classroom.yml .keep autograding.json for classroom CI test"
git push
setupclassroom_test7:
mkdir -p .github/classroom/
mkdir -p .github/workflows/
touch .github/.keep
cp scripts/autograding-test7.json .github/classroom/autograding.json
cp scripts/classroom.yml .github/workflows/classroom.yml
git add .github/classroom/autograding.json
git add .github/workflows/classroom.yml
git add .github/.keep
git commit -m"update classroom.yml .keep autograding.json for classroom CI test"
git push
setupclassroom_test8:
mkdir -p .github/classroom/
mkdir -p .github/workflows/
touch .github/.keep
cp scripts/autograding-test8.json .github/classroom/autograding.json
cp scripts/classroom.yml .github/workflows/classroom.yml
git add .github/classroom/autograding.json
git add .github/workflows/classroom.yml
git add .github/.keep
git commit -m"update classroom.yml .keep autograding.json for classroom CI test"
git push
# setupenv:
# sudo apt-get update
# sudo apt-get install -y curl wget autoconf automake autotools-dev curl libmpc-dev libmpfr-dev libgmp-dev gawk build-essential bison flex texinfo gperf libtool patchutils bc xz-utils zlib1g-dev libexpat-dev pkg-config libglib2.0-dev libpixman-1-dev git tmux python3
# curl https://sh.rustup.rs -sSf > $RUSTUP && chmod +x $RUSTUP
# $RUSTUP -y --default-toolchain nightly-2022-04-11 --profile minimal
# cd $HOME
# wget https://download.qemu.org/qemu-7.0.0.tar.xz
# tar xvJf qemu-7.0.0.tar.xz
# cd qemu-7.0.0
# ./configure --target-list=riscv64-softmmu
# make install

48
README.md Normal file
View File

@@ -0,0 +1,48 @@
# Open-Source OS Training Comp 2022
Welcome to Open-Source OS Training Comp 20222022年开源操作系统训练营.
## Scheduling
- NOTICE current [**SCHEDULING**](./scheduling.md)2022年开源操作系统训练营的计划安排!
## History
- [open-source os training comp 2021](https://github.com/rcore-os/rCore/wiki/os-tutorial-summer-of-code-2021)
- [open-source os training comp 2020](https://github.com/rcore-os/rCore/wiki/os-tutorial-summer-of-code-2020)
## Guide
- Guide deployed version can be found [here](https://learningos.github.io/rust-based-os-comp2022/)精简OS实验指导
- [rCore Tutorial v3 Guide](https://rcore-os.github.io/rCore-Tutorial-Book-v3/) (2022春季OS课程讲义)
- [OS Course Slides in 2022 spring](https://learningos.github.io/os-lectures/)(2022春季OS课程Slides)
First, you can read [Guide](https://learningos.github.io/rust-based-os-comp2022/) to:
- (Important) `git clone` this repo.
- (Important) setup development environment.
- (Important) setup classroom CI by `make setupclassroom` (if you using githubclassroom to devel labs)
- analyze and try os1 and os2 labs.
- (Option) you can [use github classroom&code space to develop all os labs](https://learningos.github.io/rust-based-os-comp2022/chapter1/0intro.html#id4) just in a net browser.
## os reference framework
The 'os[1-8]-ref' are the 'os[1-8]' reference frameworks. You can read and copy some codes into os[1-8]
## kernel labs
There are two simple practice work, and five kernel labs.
登录github.com点击并打开下面的lab0~lab5的github classroom的链接后点击醒目绿色按钮"Accept this assignment"选择接受github就为你创建了一个对应实验的git repo
According to the [Guide](https://learningos.github.io/rust-based-os-comp2022/), write os codes for:
- [lab0-0 setup env in 'os1' DIR](https://classroom.github.com/a/hnoWuKGF) [Important NOTICE](https://learningos.github.io/rust-based-os-comp2022/chapter1/0intro.html#id4)
- [lab0-1 try something in os2 in 'os2' DIR](https://classroom.github.com/a/UEOvz4qO) [Important NOTICE](https://learningos.github.io/rust-based-os-comp2022/chapter2/0intro.html#id3)
- [lab1 in 'os3' DIR](https://classroom.github.com/a/s1v7GyJM) [Important NOTICE](https://learningos.github.io/rust-based-os-comp2022/chapter3/0intro.html#id3)
- [lab2 in 'os4' DIR](https://classroom.github.com/a/ghbB1wYX) [Important NOTICE](https://learningos.github.io/rust-based-os-comp2022/chapter4/0intro.html#id3)
- [lab3 in 'os5' DIR](https://classroom.github.com/a/RxB6h4-x) [Important NOTICE](https://learningos.github.io/rust-based-os-comp2022/chapter5/0intro.html#id3)
- [lab4 in 'os6' DIR](https://classroom.github.com/a/94eMW8zi) [Important NOTICE](https://learningos.github.io/rust-based-os-comp2022/chapter6/0intro.html#id3)
- [lab5 in 'os8' DIR](https://classroom.github.com/a/zqGJEPK-) [Important NOTICE](https://learningos.github.io/rust-based-os-comp2022/chapter8/0intro.html#id5)
## Check your results
- lab1: `make test3` for lab1
- lab2: `make test4` for lab2
- lab3: `make test5` for lab3
- lab4: `make test6` && `make test7` for lab4
- lab5: `make test8` for lab5
## Send issues
If you meet any problems or some difficulties, please send issues to [Issues in rust-based-os-comp2022](https://github.com/LearningOS/rust-based-os-comp2022/issues)

BIN
bootloader/rustsbi-qemu.bin Normal file

Binary file not shown.

6
ci-user/.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
user/target
user/build
user/Cargo.lock
user/.idea
.idea
__pycache__

61
ci-user/.gitlab-ci.yml Normal file
View File

@@ -0,0 +1,61 @@
default:
image: zhanghx0905/rcore-ci
stages:
- build
build-ch2-job:
stage: build
script:
- cd user && make all CHAPTER=2
artifacts:
paths:
- user/build/bin/*.bin
build-ch3_0-job:
stage: build
script:
- cd user && make all CHAPTER=3_0
artifacts:
paths:
- user/build/bin/*.bin
build-ch3_1-job:
stage: build
script:
- cd user && make all CHAPTER=3_1
artifacts:
paths:
- user/build/bin/*.bin
build-ch4-job:
stage: build
script:
- cd user && make all CHAPTER=4
artifacts:
paths:
- user/build/elf/*.elf
build-ch5-job:
stage: build
script:
- cd user && make all CHAPTER=5
artifacts:
paths:
- user/build/elf/*.elf
build-ch6-job:
stage: build
script:
- cd user && make all CHAPTER=6
artifacts:
paths:
- user/build/elf/*.elf
build-ch7-job:
stage: build
script:
- cd user && make all CHAPTER=7
artifacts:
paths:
- user/build/elf/*.elf

48
ci-user/Makefile Normal file
View File

@@ -0,0 +1,48 @@
RAND := $(shell awk 'BEGIN{srand();printf("%d", 65536*rand())}')
CHAPTER ?=
ifeq ($(CHAPTER), 3)
LAB := 1
else ifeq ($(CHAPTER), 4)
LAB := 2
else ifeq ($(CHAPTER), 5)
INITPROC := 1
LAB := 3
else ifeq ($(CHAPTER), 6)
INITPROC := 1
LAB := 4
else ifeq ($(CHAPTER), 7)
INITPROC := 1
LAB := 4
else ifeq ($(CHAPTER), 8)
INITPROC := 1
LAB := 5
endif
randomize:
find user/src/bin -name "*.rs" | xargs sed -i 's/OK/OK$(RAND)/g'
find user/src/bin -name "*.rs" | xargs sed -i 's/passed/passed$(RAND)/g'
find check -name "*.py" | xargs sed -i 's/OK/OK$(RAND)/g'
find check -name "*.py" | xargs sed -i 's/passed/passed$(RAND)/g'
test: randomize
python3 overwrite.py $(CHAPTER)
make -C user build BASE=2 TEST=$(CHAPTER) CHAPTER=$(CHAPTER)
ifdef INITPROC
cp -f user/build/elf/ch$(CHAPTER)_usertest.elf user/build/elf/ch$(CHAPTER)b_initproc.elf
endif
make -C ../os run | tee stdout-ch$(CHAPTER)
python3 check/ch$(CHAPTER).py < stdout-ch$(CHAPTER)
ifdef LAB
@for i in $(shell seq $(LAB)); do \
if ! [ -f ../reports/lab$$i.pdf -o -f ../reports/lab$$i.md ]; then \
echo "Report for lab$$i needed. Add your report to reports/lab$$i.pdf or reports/lab$$i.md" ; \
exit 1 ; \
else \
echo "Report for lab$$i found." ; \
fi; \
done
endif
.PHONY: test randomize

67
ci-user/README.md Normal file
View File

@@ -0,0 +1,67 @@
## rCore_tutorial_v3 TESTS
本项目用于为 rCore 实验进行 CI 测试,在 user 目录下 `make all CHAPTER=x` 可获得第 x 章的测例。
- 可选项 2, 3_0, 3_2, 4, 5, 6, 7。
**重要**-加载地址更新:
- chapter2 所有程序加载位置位于 0x80400000与示例代码一致。
- chapter3 测试程序分为 3 批,每一批的地址都为 0x80400000 + id\*0x20000id 为程序在这一批中的序号。每一批都与参考代码一致,请分别测试。
- chapter4-7 所有程序加载位置位于 0x0与示例代码一致。
可以在 `user/build/asm` 目录下查看汇编来确认加载地址。
**测例更新**
- 一部分无用测例已删除,包括 ch2_helloworld, ch3_1_yield 等。
- sleep 测例被转移到第四章
- ch4 之后不再测试 write1
rust 的把user测例分散到了各个branch里当时想的是尽量把测试的过程屏蔽掉现在看确实不便于管理这学期就先这样算了.
### 各章的测例
#### ch3
test1write0 write1
test2setprio
test3stride的六个测例
#### ch4
test1sleep0 sleep1 测试 sys_time
test2map0123 unmap12 测试 map unmap 实现
#### ch5 6 7 8
```rust
"test_sleep\0",
"test_sleep1\0",
"test_mmap0\0",
"test_mmap1\0",
"test_mmap2\0",
"test_mmap3\0",
"test_unmap\0",
"test_unmap2\0",
"test_spawn0\0",
"test_spawn1\0",
// ch6
"test_mail0\0",
"test_mail1\0",
"test_mail2\0",
"test_mail3\0",
// ch7
"test_file0\0",
"test_file1\0",
"test_file2\0",
// ch8
...
```
share mem 的测例放着就行。
ch8 先不管。

46
ci-user/check/base.py Normal file
View File

@@ -0,0 +1,46 @@
import sys
import re
import ch5_1
def test(expected, not_expected=[]):
output = sys.stdin.read(1000000)
count = 0
total = len(expected) + len(not_expected)
for pattern in expected:
if re.search(pattern, output):
count += 1
print(f'\033[92m[PASS]\033[0m found <{pattern}>')
else:
print(f'\033[91m[FAIL]\033[0m not found <{pattern}>')
for pattern in not_expected:
if not re.search(pattern, output):
count += 1
print(f'\033[92m[PASS]\033[0m not found <{pattern}>')
else:
print(f'\033[91m[FAIL]\033[0m found <{pattern}>')
print('\nTest passed: %d/%d' % (count, total))
assert count == total
# test stride
if re.search(ch5_1.PATTERN, output):
ch5_1.stride_test(re.compile(ch5_1.PATTERN).findall(output))
# def test_str(expected):
# output = sys.stdin.read(1000000)
# count = 0
# total = len(expected)
# for pattern in expected:
# if output.find(pattern) != -1:
# count += 1
# print('\033[92m[PASS]\033[0m', pattern)
# else:
# print('\033[91m[FAIL]\033[0m', pattern)
# print('\nTest passed: %d/%d' % (count, total))
# assert count == total

14
ci-user/check/ch1.py Normal file
View File

@@ -0,0 +1,14 @@
import base
EXPECTED = [
"Hello, world!",
]
TEMP = []
NOT_EXPECTED = [
"FAIL: T.T",
]
if __name__ == "__main__":
base.test(EXPECTED + TEMP, NOT_EXPECTED)

17
ci-user/check/ch2.py Normal file
View File

@@ -0,0 +1,17 @@
import base
EXPECTED = [
"Hello, world from user mode program!",
"Test power_3 OK!",
"Test power_5 OK!",
"Test power_7 OK!",
]
TEMP = []
NOT_EXPECTED = [
"FAIL: T.T",
]
if __name__ == "__main__":
base.test(EXPECTED + TEMP, NOT_EXPECTED)

21
ci-user/check/ch3.py Normal file
View File

@@ -0,0 +1,21 @@
import base
from ch2 import EXPECTED, NOT_EXPECTED
EXPECTED += [
r"get_time OK! (\d+)",
"Test sleep OK!",
r"current time_msec = (\d+)",
r"time_msec = (\d+) after sleeping (\d+) ticks, delta = (\d+)ms!",
"Test sleep1 passed!",
"Test write A OK!",
"Test write B OK!",
"Test write C OK!",
]
EXPECTED += [
"string from task info test",
"Test task info OK!",
]
if __name__ == "__main__":
base.test(EXPECTED, NOT_EXPECTED)

18
ci-user/check/ch4.py Normal file
View File

@@ -0,0 +1,18 @@
import base
from ch3 import EXPECTED, NOT_EXPECTED
EXPECTED += [
"Test 04_1 OK!",
"Test 04_4 test OK!",
"Test 04_5 ummap OK!",
"Test 04_6 ummap2 OK!",
]
NOT_EXPECTED += [
"Should cause error, Test 04_2 fail!",
"Should cause error, Test 04_3 fail!",
]
if __name__ == "__main__":
base.test(EXPECTED, NOT_EXPECTED)

22
ci-user/check/ch5.py Normal file
View File

@@ -0,0 +1,22 @@
import base
from ch4 import EXPECTED, NOT_EXPECTED
EXPECTED += [
r"Test getpid OK! pid = (\d+)",
"Test spawn0 OK!",
"Test wait OK!",
"Test waitpid OK!",
"Test set_priority OK!",
]
EXPECTED = list(set(EXPECTED) - set([
"string from task info test",
"Test task info OK!",
]))
TEMP = [
# "ch5 Usertests passed!",
]
if __name__ == '__main__':
base.test(EXPECTED + TEMP, NOT_EXPECTED)

15
ci-user/check/ch5_1.py Normal file
View File

@@ -0,0 +1,15 @@
PATTERN = r"ratio = (\d+)"
def stride_test(result):
assert len(result) == 6
factors = [int(i) for i in result]
print('\nstride ratio =', factors)
if max(factors) / min(factors) < 1.5:
print('\033[92m[PASS]\033[0m Stride Test')
print('\nTest passed: 1/1')
else:
print('\033[91m[FAIL]\033[0m Stride Test')
print('\nTest passed: 0/1')
assert max(factors) / min(factors) < 1.5

20
ci-user/check/ch6.py Normal file
View File

@@ -0,0 +1,20 @@
import base
from ch5 import EXPECTED, NOT_EXPECTED
EXPECTED += [
"Test file0 OK!",
"Test fstat OK!",
"Test link OK!",
"Test mass open/unlink OK!"
]
EXPECTED = list(set(EXPECTED) - set([
"Test set_priority OK!"
]))
TEMP = [
# "ch6 Usertests passed!",
]
if __name__ == '__main__':
base.test(EXPECTED + TEMP, NOT_EXPECTED)

4
ci-user/check/ch7.py Normal file
View File

@@ -0,0 +1,4 @@
import base
if __name__ == '__main__':
base.test([], [])

42
ci-user/check/ch8.py Normal file
View File

@@ -0,0 +1,42 @@
import base
from ch5 import NOT_EXPECTED
EXPECTED = [
# ch2b
"Hello, world from user mode program!",
"Test power_3 OK!",
"Test power_5 OK!",
"Test power_7 OK!",
# ch3b
r"get_time OK! (\d+)",
"Test sleep OK!",
r"current time_msec = (\d+)",
r"time_msec = (\d+) after sleeping (\d+) ticks, delta = (\d+)ms!",
"Test sleep1 passed!",
"Test write A OK!",
"Test write B OK!",
"Test write C OK!",
# ch5b
"forktest2 test passed!",
# ch6b
"file_test passed!",
# ch7b
"pipetest passed!",
# ch8b
"mpsc_sem passed!",
"philosopher dining problem with mutex test passed!",
"race adder using spin mutex test passed!",
"sync_sem passed!",
"test_condvar passed!",
"threads with arg test passed!",
"threads test passed!",
# ch8
"deadlock test mutex 1 OK!",
"deadlock test semaphore 1 OK!",
"deadlock test semaphore 2 OK!",
"ch8 Usertests passed!",
]
if __name__ == "__main__":
base.test(EXPECTED, NOT_EXPECTED)

28
ci-user/overwrite.py Normal file
View File

@@ -0,0 +1,28 @@
import argparse
import os
parser = argparse.ArgumentParser()
parser.add_argument("chapter", type=int)
chapter = parser.parse_args().chapter
if 5 >= chapter >= 4:
os.system("cp overwrite/build-elf.rs ../os/build.rs")
elif chapter < 4:
os.system("cp overwrite/build-bin.rs ../os/build.rs")
if chapter <= 5:
os.system("cp overwrite/Makefile-ch3 ../os/Makefile")
elif chapter <= 6:
os.system("cp overwrite/Makefile-ch6 ../os/Makefile")
os.system("cp overwrite/easy-fs-fuse.rs ../easy-fs-fuse/src/main.rs")
elif chapter <= 8:
os.system("cp overwrite/Makefile-ch6 ../os/Makefile")
os.system("cp overwrite/easy-fs-fuse-ch7.rs ../easy-fs-fuse/src/main.rs")
lines = []
with open("../os/Cargo.toml", 'r') as f:
for line in f.readlines():
processed = line.replace(' git = "https://github.com/rcore-os/riscv"', ' path = "../ci-user/riscv" ')
lines.append(processed)
with open("../os/Cargo.toml", 'w+') as f:
f.writelines(lines)

View File

@@ -0,0 +1,24 @@
# Building
TARGET := riscv64gc-unknown-none-elf
MODE := release
KERNEL_ELF := target/$(TARGET)/$(MODE)/os
# BOARD
BOARD ?= qemu
SBI ?= rustsbi
BOOTLOADER := ../bootloader/$(SBI)-$(BOARD).bin
kernel:
cargo build --release
clean:
cargo clean
run: kernel
timeout --foreground 30s qemu-system-riscv64 \
-machine virt \
-nographic \
-bios $(BOOTLOADER) \
-kernel $(KERNEL_ELF)
.PHONY: build kernel clean run

View File

@@ -0,0 +1,24 @@
# Building
TARGET := riscv64gc-unknown-none-elf
MODE := release
KERNEL_ELF := target/$(TARGET)/$(MODE)/os
# BOARD
BOARD ?= qemu
SBI ?= rustsbi
BOOTLOADER := ../bootloader/$(SBI)-$(BOARD).bin
kernel:
cargo build --release
clean:
cargo clean
run: kernel
timeout --foreground 40s qemu-system-riscv64 \
-machine virt \
-nographic \
-bios $(BOOTLOADER) \
-kernel $(KERNEL_ELF)
.PHONY: build kernel clean run

View File

@@ -0,0 +1,31 @@
# Building
TARGET := riscv64gc-unknown-none-elf
MODE := release
KERNEL_ELF := target/$(TARGET)/$(MODE)/os
FS_IMG := ../ci-user/user/build/fs.img
# BOARD
BOARD ?= qemu
SBI ?= rustsbi
BOOTLOADER := ../bootloader/$(SBI)-$(BOARD).bin
fsimg:
cd ../easy-fs-fuse && cargo run --release -- \
-s ../ci-user/user/build/elf \
-o $(FS_IMG)
kernel: fsimg
cargo build --release
clean:
cargo clean
run: kernel
timeout --foreground 30s qemu-system-riscv64 \
-machine virt \
-nographic \
-bios $(BOOTLOADER) \
-kernel $(KERNEL_ELF) \
-drive file=$(FS_IMG),if=none,format=raw,id=x0 \
-device virtio-blk-device,drive=x0,bus=virtio-mmio-bus.0
.PHONY: build kernel clean run

View File

@@ -0,0 +1,56 @@
use std::io::{Result, Write};
use std::fs::{File, read_dir};
fn main() {
println!("cargo:rerun-if-changed=../ci-user/user/src/");
println!("cargo:rerun-if-changed={}", TARGET_PATH);
insert_app_data().unwrap();
}
static TARGET_PATH: &str = "../ci-user/user/build/bin/";
fn insert_app_data() -> Result<()> {
let mut f = File::create("src/link_app.S").unwrap();
let mut apps: Vec<_> = read_dir("../ci-user/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)?;
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}.bin"
app_{0}_end:"#, idx, app, TARGET_PATH)?;
}
Ok(())
}

View File

@@ -0,0 +1,56 @@
use std::io::{Result, Write};
use std::fs::{File, read_dir};
fn main() {
println!("cargo:rerun-if-changed=../ci-user/user/src/");
println!("cargo:rerun-if-changed={}", TARGET_PATH);
insert_app_data().unwrap();
}
static TARGET_PATH: &str = "../ci-user/user/build/elf/";
fn insert_app_data() -> Result<()> {
let mut f = File::create("src/link_app.S").unwrap();
let mut apps: Vec<_> = read_dir("../ci-user/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(())
}

View File

@@ -0,0 +1,82 @@
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;
const BLOCK_SZ: usize = 512;
struct BlockFile(Mutex<File>);
impl BlockDevice for BlockFile {
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!");
}
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!");
}
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"),
)
.arg(
Arg::with_name("output")
.short("o")
.long("output")
.takes_value(true)
.help("Output file path"),
)
.get_matches();
let src_path = matches.value_of("source").unwrap();
let output_path = matches.value_of("output").unwrap();
println!("src_path = {}\noutput_path = {}", src_path, output_path);
let block_file = Arc::new(BlockFile(Mutex::new({
let f = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(output_path)?;
f.set_len(16384 * 512).unwrap();
f
})));
// 4MiB, at most 4095 files
let efs = EasyFileSystem::create(block_file.clone(), 16384, 1);
let root_inode = Arc::new(EasyFileSystem::root_inode(&efs));
for dir_entry in read_dir(src_path).unwrap() {
let dir_entry = dir_entry.unwrap();
let path = dir_entry.path();
// load app data from host file system
let mut host_file = File::open(&path).unwrap();
let mut all_data: Vec<u8> = Vec::new();
host_file.read_to_end(&mut all_data).unwrap();
// create a file in easy-fs
let name = path.file_stem().unwrap().to_str().unwrap();
let inode = root_inode.create(name).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(())
}

View File

@@ -0,0 +1,82 @@
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;
const BLOCK_SZ: usize = 512;
struct BlockFile(Mutex<File>);
impl BlockDevice for BlockFile {
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!");
}
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!");
}
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"),
)
.arg(
Arg::with_name("output")
.short("o")
.long("output")
.takes_value(true)
.help("Output file path"),
)
.get_matches();
let src_path = matches.value_of("source").unwrap();
let output_path = matches.value_of("output").unwrap();
println!("src_path = {}\noutput_path = {}", src_path, output_path);
let block_file = Arc::new(BlockFile(Mutex::new({
let f = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(output_path)?;
f.set_len(14000 * 512).unwrap();
f
})));
// 4MiB, at most 4095 files
let efs = EasyFileSystem::create(block_file.clone(), 14000, 1);
let root_inode = Arc::new(EasyFileSystem::root_inode(&efs));
for dir_entry in read_dir(src_path).unwrap() {
let dir_entry = dir_entry.unwrap();
let path = dir_entry.path();
// load app data from host file system
let mut host_file = File::open(&path).unwrap();
let mut all_data: Vec<u8> = Vec::new();
host_file.read_to_end(&mut all_data).unwrap();
// create a file in easy-fs
let name = path.file_stem().unwrap().to_str().unwrap();
let inode = root_inode.create(name).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(())
}

5
ci-user/riscv/.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
Cargo.lock
target/
bin/*.after
bin/*.before
bin/*.o

51
ci-user/riscv/.travis.yml Normal file
View File

@@ -0,0 +1,51 @@
language: rust
env:
- TARGET=x86_64-unknown-linux-gnu
- TARGET=riscv32imac-unknown-none-elf
- TARGET=riscv64imac-unknown-none-elf
- TARGET=riscv64gc-unknown-none-elf
rust:
- nightly
- stable
- 1.42.0 # MSRV
if: (branch = staging OR branch = trying OR branch = master) OR (type = pull_request AND branch = master)
matrix:
allow_failures:
- rust: nightly
include:
- env: CHECK_BLOBS=1
rust:
language: bash
if: (branch = staging OR branch = trying OR branch = master) OR (type = pull_request AND branch = master)
- env: RUSTFMT=1
rust: stable
if: (branch = staging OR branch = trying OR branch = master) OR (type = pull_request AND branch = master)
install:
- ci/install.sh
script:
- ci/script.sh
cache:
cargo: true
directories:
- gcc
branches:
only:
- master
- staging
- trying
notifications:
email:
on_success: never

View File

@@ -0,0 +1,45 @@
# Change Log
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).
## [Unreleased]
## [v0.6.0] - 2020-06-20
### Changed
- `Mtvec::trap_mode()`, `Stvec::trap_mode()` and `Utvec::trap_mode()` functions now return `Option<TrapMode>` (breaking change)
- Updated Minimum Supported Rust Version to 1.42.0
- Use `llvm_asm!` instead of `asm!`
### Removed
- vexriscv-specific registers were moved to the `vexriscv` crate
## [v0.5.6] - 2020-03-14
### Added
- Added vexriscv-specific registers
## [v0.5.5] - 2020-02-28
### Added
- Added `riscv32i-unknown-none-elf` target support
- Added user trap setup and handling registers
- Added write methods for the `mip` and `satp` registers
- Added `mideleg` register
- Added Changelog
### Changed
- Fixed MSRV by restricting the upper bound of `bare-metal` version
[Unreleased]: https://github.com/rust-embedded/riscv/compare/v0.6.0...HEAD
[v0.6.0]: https://github.com/rust-embedded/riscv/compare/v0.5.6...v0.6.0
[v0.5.6]: https://github.com/rust-embedded/riscv/compare/v0.5.5...v0.5.6
[v0.5.5]: https://github.com/rust-embedded/riscv/compare/v0.5.4...v0.5.5

View File

@@ -0,0 +1,37 @@
# The Rust Code of Conduct
## Conduct
**Contact**: [RISC-V team](https://github.com/rust-embedded/wg#the-riscv-team)
* We are committed to providing a friendly, safe and welcoming environment for all, regardless of level of experience, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, nationality, or other similar characteristic.
* On IRC, please avoid using overtly sexual nicknames or other nicknames that might detract from a friendly, safe and welcoming environment for all.
* Please be kind and courteous. There's no need to be mean or rude.
* Respect that people have differences of opinion and that every design or implementation choice carries a trade-off and numerous costs. There is seldom a right answer.
* Please keep unstructured critique to a minimum. If you have solid ideas you want to experiment with, make a fork and see how it works.
* We will exclude you from interaction if you insult, demean or harass anyone. That is not welcome behavior. We interpret the term "harassment" as including the definition in the [Citizen Code of Conduct](http://citizencodeofconduct.org/); if you have any lack of clarity about what might be included in that concept, please read their definition. In particular, we don't tolerate behavior that excludes people in socially marginalized groups.
* Private harassment is also unacceptable. No matter who you are, if you feel you have been or are being harassed or made uncomfortable by a community member, please contact one of the channel ops or any of the [RISC-V team][team] immediately. Whether you're a regular contributor or a newcomer, we care about making this community a safe place for you and we've got your back.
* Likewise any spamming, trolling, flaming, baiting or other attention-stealing behavior is not welcome.
## Moderation
These are the policies for upholding our community's standards of conduct.
1. Remarks that violate the Rust standards of conduct, including hateful, hurtful, oppressive, or exclusionary remarks, are not allowed. (Cursing is allowed, but never targeting another user, and never in a hateful manner.)
2. Remarks that moderators find inappropriate, whether listed in the code of conduct or not, are also not allowed.
3. Moderators will first respond to such remarks with a warning.
4. If the warning is unheeded, the user will be "kicked," i.e., kicked out of the communication channel to cool off.
5. If the user comes back and continues to make trouble, they will be banned, i.e., indefinitely excluded.
6. Moderators may choose at their discretion to un-ban the user if it was a first offense and they offer the offended party a genuine apology.
7. If a moderator bans someone and you think it was unjustified, please take it up with that moderator, or with a different moderator, **in private**. Complaints about bans in-channel are not allowed.
8. Moderators are held to a higher standard than other community members. If a moderator creates an inappropriate situation, they should expect less leeway than others.
In the Rust community we strive to go the extra step to look out for each other. Don't just aim to be technically unimpeachable, try to be your best self. In particular, avoid flirting with offensive or sensitive issues, particularly if they're off-topic; this all too often leads to unnecessary fights, hurt feelings, and damaged trust; worse, it can drive people away from the community entirely.
And if someone takes issue with something you said or did, resist the urge to be defensive. Just stop doing what it was they complained about and apologize. Even if you feel you were misinterpreted or unfairly accused, chances are good there was something you could've communicated better — remember that it's your responsibility to make your fellow Rustaceans comfortable. Everyone wants to get along and we are all here first and foremost because we want to talk about cool technology. You will find that people will be eager to assume good intent and forgive as long as you earn their trust.
The enforcement policies listed above apply to all official embedded WG venues; including official IRC channels (#rust-embedded); GitHub repositories under rust-embedded; and all forums under rust-embedded.org (forum.rust-embedded.org).
*Adapted from the [Node.js Policy on Trolling](http://blog.izs.me/post/30036893703/policy-on-trolling) as well as the [Contributor Covenant v1.3.0](https://www.contributor-covenant.org/version/1/3/0/).*
[team]: https://github.com/rust-embedded/wg#the-riscv-team

21
ci-user/riscv/Cargo.toml Normal file
View File

@@ -0,0 +1,21 @@
[package]
name = "riscv"
version = "0.6.0"
repository = "https://github.com/rust-embedded/riscv"
authors = ["The RISC-V Team <risc-v@teams.rust-embedded.org>"]
categories = ["embedded", "hardware-support", "no-std"]
description = "Low level access to RISC-V processors"
keywords = ["riscv", "register", "peripheral"]
license = "ISC"
[dependencies]
bare-metal = "0.2.5"
bitflags = "1.0"
bit_field = "0.10.0"
log = "0.4"
[build-dependencies]
riscv-target = "0.1.2"
[features]
inline-asm = []

41
ci-user/riscv/README.md Normal file
View File

@@ -0,0 +1,41 @@
[![crates.io](https://img.shields.io/crates/d/riscv.svg)](https://crates.io/crates/riscv)
[![crates.io](https://img.shields.io/crates/v/riscv.svg)](https://crates.io/crates/riscv)
[![Build Status](https://travis-ci.org/rust-embedded/riscv.svg?branch=master)](https://travis-ci.org/rust-embedded/riscv)
# `riscv`
> Low level access to RISC-V processors
This project is developed and maintained by the [RISC-V team][team].
## [Documentation](https://docs.rs/crate/riscv)
## Minimum Supported Rust Version (MSRV)
This crate is guaranteed to compile on stable Rust 1.42.0 and up. It *might*
compile with older versions but that may change in any new patch release.
## License
Copyright 2019-2020 [RISC-V team][team]
Permission to use, copy, modify, and/or distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright notice
and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
## Code of Conduct
Contribution to this crate is organized under the terms of the [Rust Code of
Conduct][CoC], the maintainer of this crate, the [RISC-V team][team], promises
to intervene to uphold that code of conduct.
[CoC]: CODE_OF_CONDUCT.md
[team]: https://github.com/rust-embedded/wg#the-riscv-team

454
ci-user/riscv/asm.S Normal file
View File

@@ -0,0 +1,454 @@
#include "asm.h"
.section .text.__ebreak
.global __ebreak
__ebreak:
ebreak
ret
.section .text.__wfi
.global __wfi
__wfi:
wfi
ret
.section .text.__sfence_vma_all
.global __sfence_vma_all
__sfence_vma_all:
sfence.vma
ret
.section .text.__sfence_vma
.global __sfence_vma
__sfence_vma:
sfence.vma a0, a1
ret
// RISC-V hypervisor instructions.
// The switch for enabling LLVM support for asm generation.
// #define LLVM_RISCV_HYPERVISOR_EXTENSION_SUPPORT
.section .text.__hfence_gvma
.global __hfence_gvma
__hfence_gvma:
#ifdef LLVM_RISCV_HYPERVISOR_EXTENSION_SUPPORT
hfence.gvma a0, a1
#else
.word 1656029299
#endif
ret
.section .text.__hfence_vvma
.global __hfence_vvma
__hfence_vvma:
#ifdef LLVM_RISCV_HYPERVISOR_EXTENSION_SUPPORT
hfence.vvma a0, a1
#else
.word 582287475
#endif
ret
.section .text.__hlv_b
.global __hlv_b
__hlv_b:
#ifdef LLVM_RISCV_HYPERVISOR_EXTENSION_SUPPORT
hlv.b a0, a0
#else
.word 1610958195
#endif
ret
.section .text.__hlv_bu
.global __hlv_bu
__hlv_bu:
#ifdef LLVM_RISCV_HYPERVISOR_EXTENSION_SUPPORT
hlv.bu a0, a0
#else
.word 1612006771
#endif
ret
.section .text.__hlv_h
.global __hlv_h
__hlv_h:
#ifdef LLVM_RISCV_HYPERVISOR_EXTENSION_SUPPORT
hlv.h a0, a0
#else
.word 1678067059
#endif
ret
.section .text.__hlv_hu
.global __hlv_hu
__hlv_hu:
#ifdef LLVM_RISCV_HYPERVISOR_EXTENSION_SUPPORT
hlv.hu a0, a0
#else
.word 1679115635
#endif
ret
.section .text.__hlvx_hu
.global __hlvx_hu
__hlvx_hu:
#ifdef LLVM_RISCV_HYPERVISOR_EXTENSION_SUPPORT
hlvx.hu a0, a0
#else
.word 1681212787
#endif
ret
.section .text.__hlv_w
.global __hlv_w
__hlv_w:
#ifdef LLVM_RISCV_HYPERVISOR_EXTENSION_SUPPORT
hlv.w a0, a0
#else
.word 1745175923
#endif
ret
.section .text.__hlvx_wu
.global __hlvx_wu
__hlvx_wu:
#ifdef LLVM_RISCV_HYPERVISOR_EXTENSION_SUPPORT
hlvx.wu a0, a0
#else
.word 1748321651
#endif
ret
.section .text.__hsv_b
.global __hsv_b
__hsv_b:
#ifdef LLVM_RISCV_HYPERVISOR_EXTENSION_SUPPORT
hsv.b a0, a1
#else
.word 1656045683
#endif
ret
.section .text.__hsv_h
.global __hsv_h
__hsv_h:
#ifdef LLVM_RISCV_HYPERVISOR_EXTENSION_SUPPORT
hsv.h a0, a1
#else
.word 1723154547
#endif
ret
.section .text.__hsv_w
.global __hsv_w
__hsv_w:
#ifdef LLVM_RISCV_HYPERVISOR_EXTENSION_SUPPORT
hsv.w a0, a1
#else
.word 1790263411
#endif
ret
.section .text.__hlv_wu
.global __hlv_wu
__hlv_wu:
#ifdef LLVM_RISCV_HYPERVISOR_EXTENSION_SUPPORT
hlv.wu a0, a0
#else
.word 1746224499
#endif
ret
.section .text.__hlv_d
.global __hlv_d
__hlv_d:
#ifdef LLVM_RISCV_HYPERVISOR_EXTENSION_SUPPORT
hlv.d a0, a0
#else
.word 1812284787
#endif
ret
.section .text.__hsv_d
.global __hsv_d
__hsv_d:
#ifdef LLVM_RISCV_HYPERVISOR_EXTENSION_SUPPORT
hsv.d a0, a1
#else
.word 1857372275
#endif
ret
// User Trap Setup
RW(0x000, ustatus) // User status register
RW(0x004, uie) // User interrupt-enable register
RW(0x005, utvec) // User trap handler base address
// User Trap Handling
RW(0x040, uscratch) // Scratch register for user trap handlers
RW(0x041, uepc) // User exception program counter
RW(0x042, ucause) // User trap cause
RW(0x043, utval) // User bad address or instruction
RW(0x044, uip) // User interrupt pending
// User Floating-Point CSRs
RW(0x001, fflags) // Floating-Point Accrued Exceptions
RW(0x002, frm) // Floating-Point Dynamic Rounding Mode
RW(0x003, fcsr) // Floating-Point Control and Status Register (frm + fflags)
// User Counter/Timers
RO( 0xC00, cycle) // Cycle counter for RDCYCLE instruction
RO( 0xC01, time) // Timer for RDTIME instruction
RO( 0xC02, instret) // Instructions-retired counter for RDINSTRET instruction
RO( 0xC03, hpmcounter3) // Performance-monitoring counter
RO( 0xC04, hpmcounter4) // Performance-monitoring counter
RO( 0xC05, hpmcounter5) // Performance-monitoring counter
RO( 0xC06, hpmcounter6) // Performance-monitoring counter
RO( 0xC07, hpmcounter7) // Performance-monitoring counter
RO( 0xC08, hpmcounter8) // Performance-monitoring counter
RO( 0xC09, hpmcounter9) // Performance-monitoring counter
RO( 0xC0A, hpmcounter10) // Performance-monitoring counter
RO( 0xC0B, hpmcounter11) // Performance-monitoring counter
RO( 0xC0C, hpmcounter12) // Performance-monitoring counter
RO( 0xC0D, hpmcounter13) // Performance-monitoring counter
RO( 0xC0E, hpmcounter14) // Performance-monitoring counter
RO( 0xC0F, hpmcounter15) // Performance-monitoring counter
RO( 0xC10, hpmcounter16) // Performance-monitoring counter
RO( 0xC11, hpmcounter17) // Performance-monitoring counter
RO( 0xC12, hpmcounter18) // Performance-monitoring counter
RO( 0xC13, hpmcounter19) // Performance-monitoring counter
RO( 0xC14, hpmcounter20) // Performance-monitoring counter
RO( 0xC15, hpmcounter21) // Performance-monitoring counter
RO( 0xC16, hpmcounter22) // Performance-monitoring counter
RO( 0xC17, hpmcounter23) // Performance-monitoring counter
RO( 0xC18, hpmcounter24) // Performance-monitoring counter
RO( 0xC19, hpmcounter25) // Performance-monitoring counter
RO( 0xC1A, hpmcounter26) // Performance-monitoring counter
RO( 0xC1B, hpmcounter27) // Performance-monitoring counter
RO( 0xC1C, hpmcounter28) // Performance-monitoring counter
RO( 0xC1D, hpmcounter29) // Performance-monitoring counter
RO( 0xC1E, hpmcounter30) // Performance-monitoring counter
RO( 0xC1F, hpmcounter31) // Performance-monitoring counter
RO32(0xC80, cycleh) // Upper 32 bits of cycle, RV32I only
RO32(0xC81, timeh) // Upper 32 bits of time, RV32I only
RO32(0xC82, instreth) // Upper 32 bits of instret, RV32I only
RO32(0xC83, hpmcounter3h) // Upper 32 bits of hpmcounter3, RV32I only
RO32(0xC84, hpmcounter4h)
RO32(0xC85, hpmcounter5h)
RO32(0xC86, hpmcounter6h)
RO32(0xC87, hpmcounter7h)
RO32(0xC88, hpmcounter8h)
RO32(0xC89, hpmcounter9h)
RO32(0xC8A, hpmcounter10h)
RO32(0xC8B, hpmcounter11h)
RO32(0xC8C, hpmcounter12h)
RO32(0xC8D, hpmcounter13h)
RO32(0xC8E, hpmcounter14h)
RO32(0xC8F, hpmcounter15h)
RO32(0xC90, hpmcounter16h)
RO32(0xC91, hpmcounter17h)
RO32(0xC92, hpmcounter18h)
RO32(0xC93, hpmcounter19h)
RO32(0xC94, hpmcounter20h)
RO32(0xC95, hpmcounter21h)
RO32(0xC96, hpmcounter22h)
RO32(0xC97, hpmcounter23h)
RO32(0xC98, hpmcounter24h)
RO32(0xC99, hpmcounter25h)
RO32(0xC9A, hpmcounter26h)
RO32(0xC9B, hpmcounter27h)
RO32(0xC9C, hpmcounter28h)
RO32(0xC9D, hpmcounter29h)
RO32(0xC9E, hpmcounter30h)
RO32(0xC9F, hpmcounter31h)
// Supervisor Trap Setup
RW(0x100, sstatus) // Supervisor status register
RW(0x102, sedeleg) // Supervisor exception delegation register
RW(0x103, sideleg) // Supervisor interrupt delegation register
RW(0x104, sie) // Supervisor interrupt-enable register
RW(0x105, stvec) // Supervisor trap handler base address
RW(0x106, scounteren) // Supervisor counter enable
// Supervisor Trap Handling
RW(0x140, sscratch) // Scratch register for supervisor trap handlers
RW(0x141, sepc) // Supervisor exception program counter
RW(0x142, scause) // Supervisor trap cause
RW(0x143, stval) // Supervisor bad address or instruction
RW(0x144, sip) // Supervisor interrupt pending
// Supervisor Protection and Translation
RW(0x180, satp) // Supervisor address translation and protection
// Machine Information Registers
RO(0xF11, mvendorid) // Vendor ID
RO(0xF12, marchid) // Architecture ID
RO(0xF13, mimpid) // Implementation ID
RO(0xF14, mhartid) // Hardware thread ID
// Machine Trap Setup
RW(0x300, mstatus) // Machine status register
RW(0x301, misa) // ISA and extensions
RW(0x302, medeleg) // Machine exception delegation register
RW(0x303, mideleg) // Machine interrupt delegation register
RW(0x304, mie) // Machine interrupt-enable register
RW(0x305, mtvec) // Machine trap handler base address
RW(0x306, mcounteren) // Machine counter enable
// Machine Trap Handling
RW(0x340, mscratch) // Scratch register for machine trap handlers
RW(0x341, mepc) // Machine exception program counter
RW(0x342, mcause) // Machine trap cause
RW(0x343, mtval) // Machine bad address or instruction
RW(0x344, mip) // Machine interrupt pending
// Machine Protection and Translation
RW( 0x3A0, pmpcfg0) // Physical memory protection configuration
RW32(0x3A1, pmpcfg1) // Physical memory protection configuration, RV32 only
RW( 0x3A2, pmpcfg2) // Physical memory protection configuration
RW32(0x3A3, pmpcfg3) // Physical memory protection configuration, RV32 only
RW( 0x3B0, pmpaddr0) // Physical memory protection address register
RW( 0x3B1, pmpaddr1) // Physical memory protection address register
RW( 0x3B2, pmpaddr2) // Physical memory protection address register
RW( 0x3B3, pmpaddr3) // Physical memory protection address register
RW( 0x3B4, pmpaddr4) // Physical memory protection address register
RW( 0x3B5, pmpaddr5) // Physical memory protection address register
RW( 0x3B6, pmpaddr6) // Physical memory protection address register
RW( 0x3B7, pmpaddr7) // Physical memory protection address register
RW( 0x3B8, pmpaddr8) // Physical memory protection address register
RW( 0x3B9, pmpaddr9) // Physical memory protection address register
RW( 0x3BA, pmpaddr10) // Physical memory protection address register
RW( 0x3BB, pmpaddr11) // Physical memory protection address register
RW( 0x3BC, pmpaddr12) // Physical memory protection address register
RW( 0x3BD, pmpaddr13) // Physical memory protection address register
RW( 0x3BE, pmpaddr14) // Physical memory protection address register
RW( 0x3BF, pmpaddr15) // Physical memory protection address register
// Machine Counter/Timers
RO( 0xB00, mcycle) // Machine cycle counter
RO( 0xB02, minstret) // Machine instructions-retired counter
RO( 0xB03, mhpmcounter3) // Machine performance-monitoring counter
RO( 0xB04, mhpmcounter4) // Machine performance-monitoring counter
RO( 0xB05, mhpmcounter5) // Machine performance-monitoring counter
RO( 0xB06, mhpmcounter6) // Machine performance-monitoring counter
RO( 0xB07, mhpmcounter7) // Machine performance-monitoring counter
RO( 0xB08, mhpmcounter8) // Machine performance-monitoring counter
RO( 0xB09, mhpmcounter9) // Machine performance-monitoring counter
RO( 0xB0A, mhpmcounter10) // Machine performance-monitoring counter
RO( 0xB0B, mhpmcounter11) // Machine performance-monitoring counter
RO( 0xB0C, mhpmcounter12) // Machine performance-monitoring counter
RO( 0xB0D, mhpmcounter13) // Machine performance-monitoring counter
RO( 0xB0E, mhpmcounter14) // Machine performance-monitoring counter
RO( 0xB0F, mhpmcounter15) // Machine performance-monitoring counter
RO( 0xB10, mhpmcounter16) // Machine performance-monitoring counter
RO( 0xB11, mhpmcounter17) // Machine performance-monitoring counter
RO( 0xB12, mhpmcounter18) // Machine performance-monitoring counter
RO( 0xB13, mhpmcounter19) // Machine performance-monitoring counter
RO( 0xB14, mhpmcounter20) // Machine performance-monitoring counter
RO( 0xB15, mhpmcounter21) // Machine performance-monitoring counter
RO( 0xB16, mhpmcounter22) // Machine performance-monitoring counter
RO( 0xB17, mhpmcounter23) // Machine performance-monitoring counter
RO( 0xB18, mhpmcounter24) // Machine performance-monitoring counter
RO( 0xB19, mhpmcounter25) // Machine performance-monitoring counter
RO( 0xB1A, mhpmcounter26) // Machine performance-monitoring counter
RO( 0xB1B, mhpmcounter27) // Machine performance-monitoring counter
RO( 0xB1C, mhpmcounter28) // Machine performance-monitoring counter
RO( 0xB1D, mhpmcounter29) // Machine performance-monitoring counter
RO( 0xB1E, mhpmcounter30) // Machine performance-monitoring counter
RO( 0xB1F, mhpmcounter31) // Machine performance-monitoring counter
RO32(0xB80, mcycleh) // Upper 32 bits of mcycle, RV32I only
RO32(0xB82, minstreth) // Upper 32 bits of minstret, RV32I only
RO32(0xB83, mhpmcounter3h) // Upper 32 bits of mhpmcounter3, RV32I only
RO32(0xB84, mhpmcounter4h)
RO32(0xB85, mhpmcounter5h)
RO32(0xB86, mhpmcounter6h)
RO32(0xB87, mhpmcounter7h)
RO32(0xB88, mhpmcounter8h)
RO32(0xB89, mhpmcounter9h)
RO32(0xB8A, mhpmcounter10h)
RO32(0xB8B, mhpmcounter11h)
RO32(0xB8C, mhpmcounter12h)
RO32(0xB8D, mhpmcounter13h)
RO32(0xB8E, mhpmcounter14h)
RO32(0xB8F, mhpmcounter15h)
RO32(0xB90, mhpmcounter16h)
RO32(0xB91, mhpmcounter17h)
RO32(0xB92, mhpmcounter18h)
RO32(0xB93, mhpmcounter19h)
RO32(0xB94, mhpmcounter20h)
RO32(0xB95, mhpmcounter21h)
RO32(0xB96, mhpmcounter22h)
RO32(0xB97, mhpmcounter23h)
RO32(0xB98, mhpmcounter24h)
RO32(0xB99, mhpmcounter25h)
RO32(0xB9A, mhpmcounter26h)
RO32(0xB9B, mhpmcounter27h)
RO32(0xB9C, mhpmcounter28h)
RO32(0xB9D, mhpmcounter29h)
RO32(0xB9E, mhpmcounter30h)
RO32(0xB9F, mhpmcounter31h)
RW(0x323, mhpmevent3) // Machine performance-monitoring event selector
RW(0x324, mhpmevent4) // Machine performance-monitoring event selector
RW(0x325, mhpmevent5) // Machine performance-monitoring event selector
RW(0x326, mhpmevent6) // Machine performance-monitoring event selector
RW(0x327, mhpmevent7) // Machine performance-monitoring event selector
RW(0x328, mhpmevent8) // Machine performance-monitoring event selector
RW(0x329, mhpmevent9) // Machine performance-monitoring event selector
RW(0x32A, mhpmevent10) // Machine performance-monitoring event selector
RW(0x32B, mhpmevent11) // Machine performance-monitoring event selector
RW(0x32C, mhpmevent12) // Machine performance-monitoring event selector
RW(0x32D, mhpmevent13) // Machine performance-monitoring event selector
RW(0x32E, mhpmevent14) // Machine performance-monitoring event selector
RW(0x32F, mhpmevent15) // Machine performance-monitoring event selector
RW(0x330, mhpmevent16) // Machine performance-monitoring event selector
RW(0x331, mhpmevent17) // Machine performance-monitoring event selector
RW(0x332, mhpmevent18) // Machine performance-monitoring event selector
RW(0x333, mhpmevent19) // Machine performance-monitoring event selector
RW(0x334, mhpmevent20) // Machine performance-monitoring event selector
RW(0x335, mhpmevent21) // Machine performance-monitoring event selector
RW(0x336, mhpmevent22) // Machine performance-monitoring event selector
RW(0x337, mhpmevent23) // Machine performance-monitoring event selector
RW(0x338, mhpmevent24) // Machine performance-monitoring event selector
RW(0x339, mhpmevent25) // Machine performance-monitoring event selector
RW(0x33A, mhpmevent26) // Machine performance-monitoring event selector
RW(0x33B, mhpmevent27) // Machine performance-monitoring event selector
RW(0x33C, mhpmevent28) // Machine performance-monitoring event selector
RW(0x33D, mhpmevent29) // Machine performance-monitoring event selector
RW(0x33E, mhpmevent30) // Machine performance-monitoring event selector
RW(0x33F, mhpmevent31) // Machine performance-monitoring event selector
// Debug/Trace Registers (shared with Debug Mode)
RW(0x7A0, tselect) // Debug/Trace trigger register select
RW(0x7A1, tdata1) // First Debug/Trace trigger data register
RW(0x7A2, tdata2) // Second Debug/Trace trigger data register
RW(0x7A3, tdata3) // Third Debug/Trace trigger data register
// Debug Mode Registers
RW(0x7B0, dcsr) // Debug control and status register
RW(0x7B1, dpc) // Debug PC
RW(0x7B2, dscratch) // Debug scratch register
// Hypervisor Trap Setup
RW(0x600, hstatus) // Hypervisor status register
RW(0x602, hedeleg) // Hypervisor exception delegation register
RW(0x603, hideleg) // Hypervisor interrupt delegation register
RW(0x604, hie) // Hypervisor interrupt-enable register
RW(0x606, hcounteren) // Hypervisor counter enable
RW(0x607, hgeie) // Hypervisor guest external interrupt-enable register
// Hypervisor Trap Handling
RW(0x643, htval) // Hypervisor bad guest physical address
RW(0x644, hip) // Hypervisor interrupt pending
RW(0x645, hvip) // Hypervisor virtual interrupt pending
RW(0x64a, htinst) // Hypervisor trap instruction (transformed)
RW(0xe12, hgeip) // Hypervisor guest external interrupt pending
// Hypervisor Protection and Translation
RO(0x680, hgatp) // Hypervisor guest address translation and protection
// Debug/Trace Registers
RW(0x6a8, hcontext) // Hypervisor-mode context register
// Hypervisor Counter/Timer Virtualization Registers
RW(0x605, htimedelta) // Delta for VS/VU-mode timer
RW32(0x615, htimedeltah) // Upper 32 bits of {\tt htimedelta}, RV32 only
// Virtual Supervisor Registers
RW(0x200, vsstatus) // Virtual supervisor status register
RW(0x204, vsie) // Virtual supervisor interrupt-enable register
RW(0x205, vstvec) // Virtual supervisor trap handler base address
RW(0x240, vsscratch) // Virtual supervisor scratch register
RW(0x241, vsepc) // Virtual supervisor exception program counter
RW(0x242, vscause) // Virtual supervisor trap cause
RW(0x243, vstval) // Virtual supervisor bad address or instruction
RW(0x244, vsip) // Virtual supervisor interrupt pending
RW(0x280, vsatp) // Virtual supervisor address translation and protection

48
ci-user/riscv/asm.h Normal file
View File

@@ -0,0 +1,48 @@
#ifndef __ASM_H
#define __ASM_H
#define REG_READ(name, offset) \
.section .text.__read_ ## name; \
.global __read_ ## name; \
__read_ ## name: \
csrrs a0, offset, x0; \
ret
#define REG_WRITE(name, offset) \
.section .text.__write_ ## name; \
.global __write_ ## name; \
__write_ ## name: \
csrrw x0, offset, a0; \
ret
#define REG_SET(name, offset) \
.section .text.__set_ ## name; \
.global __set_ ## name; \
__set_ ## name: \
csrrs x0, offset, a0; \
ret
#define REG_CLEAR(name, offset) \
.section .text.__clear_ ## name; \
.global __clear_ ## name; \
__clear_ ## name: \
csrrc x0, offset, a0; \
ret
#define REG_READ_WRITE(name, offset) REG_READ(name, offset); REG_WRITE(name, offset)
#define REG_SET_CLEAR(name, offset) REG_SET(name, offset); REG_CLEAR(name, offset)
#define RW(offset, name) REG_READ_WRITE(name, offset); REG_SET_CLEAR(name, offset)
#define RO(offset, name) REG_READ(name, offset)
#if __riscv_xlen == 32
#define RW32(offset, name) RW(offset, name)
#define RO32(offset, name) RO(offset, name)
#else
#define RW32(offset, name)
#define RO32(offset, name)
#endif
#endif /* __ASM_H */

View File

@@ -0,0 +1,20 @@
New-Item -Force -Name bin -Type Directory
# remove existing blobs because otherwise this will append object files to the old blobs
Remove-Item -Force bin/*.a
$crate = "riscv"
riscv64-unknown-elf-gcc -c -mabi=ilp32 -march=rv32i asm.S -o bin/$crate.o
riscv64-unknown-elf-ar crs bin/riscv32i-unknown-none-elf.a bin/$crate.o
riscv64-unknown-elf-gcc -c -mabi=ilp32 -march=rv32ic asm.S -o bin/$crate.o
riscv64-unknown-elf-ar crs bin/riscv32ic-unknown-none-elf.a bin/$crate.o
riscv64-unknown-elf-gcc -c -mabi=lp64 -march=rv64i asm.S -o bin/$crate.o
riscv64-unknown-elf-ar crs bin/riscv64i-unknown-none-elf.a bin/$crate.o
riscv64-unknown-elf-gcc -c -mabi=lp64 -march=rv64ic asm.S -o bin/$crate.o
riscv64-unknown-elf-ar crs bin/riscv64ic-unknown-none-elf.a bin/$crate.o
Remove-Item bin/$crate.o

22
ci-user/riscv/assemble.sh Executable file
View File

@@ -0,0 +1,22 @@
#!/bin/bash
set -euxo pipefail
crate=riscv
# remove existing blobs because otherwise this will append object files to the old blobs
rm -f bin/*.a
riscv64-unknown-elf-gcc -c -mabi=ilp32 -march=rv32i asm.S -o bin/$crate.o
ar crs bin/riscv32i-unknown-none-elf.a bin/$crate.o
riscv64-unknown-elf-gcc -c -mabi=ilp32 -march=rv32ic asm.S -o bin/$crate.o
ar crs bin/riscv32ic-unknown-none-elf.a bin/$crate.o
riscv64-unknown-elf-gcc -c -mabi=lp64 -march=rv64i asm.S -o bin/$crate.o
ar crs bin/riscv64i-unknown-none-elf.a bin/$crate.o
riscv64-unknown-elf-gcc -c -mabi=lp64 -march=rv64ic asm.S -o bin/$crate.o
ar crs bin/riscv64ic-unknown-none-elf.a bin/$crate.o
rm bin/$crate.o

35
ci-user/riscv/build.rs Normal file
View File

@@ -0,0 +1,35 @@
extern crate riscv_target;
use riscv_target::Target;
use std::path::PathBuf;
use std::{env, fs};
fn main() {
let target = env::var("TARGET").unwrap();
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let name = env::var("CARGO_PKG_NAME").unwrap();
if target.starts_with("riscv") && env::var_os("CARGO_FEATURE_INLINE_ASM").is_none() {
let mut target = Target::from_target_str(&target);
target.retain_extensions("ic");
let target = target.to_string();
fs::copy(
format!("bin/{}.a", target),
out_dir.join(format!("lib{}.a", name)),
)
.unwrap();
println!("cargo:rustc-link-lib=static={}", name);
println!("cargo:rustc-link-search={}", out_dir.display());
}
if target.contains("riscv32") {
println!("cargo:rustc-cfg=riscv");
println!("cargo:rustc-cfg=riscv32");
} else if target.contains("riscv64") {
println!("cargo:rustc-cfg=riscv");
println!("cargo:rustc-cfg=riscv64");
}
}

21
ci-user/riscv/check-blobs.sh Executable file
View File

@@ -0,0 +1,21 @@
#!/bin/bash
# Checks that the blobs are up to date with the committed assembly files
set -euxo pipefail
for lib in $(ls bin/*.a); do
filename=$(basename $lib)
riscv64-unknown-elf-objdump -Cd $lib > bin/${filename%.a}.before
done
./assemble.sh
for lib in $(ls bin/*.a); do
filename=$(basename $lib)
riscv64-unknown-elf-objdump -Cd $lib > bin/${filename%.a}.after
done
for cksum in $(ls bin/*.after); do
diff -u $cksum ${cksum%.after}.before
done

View File

@@ -0,0 +1,8 @@
#!/bin/bash
rustc generator.rs
rm -f ../src/register/hypervisorx64/mod.rs;
for i in *.txt; do
./generator <$i > ../src/register/hypervisorx64/`basename -s .txt $i`.rs;
echo "pub mod $(basename -s .txt $i);" >> ../src/register/hypervisorx64/mod.rs;
done
rm -f generator

View File

@@ -0,0 +1,312 @@
use std::fmt::*;
macro_rules! as_str_polyfill {
($x: expr, $r: expr) => {{
let mut y = $x.clone();
if let Some(x) = y.next() {
$r.split_at(x.as_ptr() as usize - $r.as_ptr() as usize).1
} else {
""
}
}};
}
#[derive(Debug, Clone)]
struct EnumerationDescriptor<'a> {
enumerations: Vec<(&'a str, usize)>,
}
impl<'a> EnumerationDescriptor<'a> {
pub fn parse(enums: &'a str) -> Self {
let mut counter = 0;
let list = enums.split(";");
let mut e = Vec::new();
for tup in list {
let mut t = tup.split("=");
let n = t.next().unwrap();
if let Some(new_id) = t.next() {
counter = new_id.parse().unwrap();
}
e.push((n, counter));
counter += 1;
}
EnumerationDescriptor { enumerations: e }
}
fn generate_enum(&self, name: &str) -> String {
let mut ret = String::new();
write!(
&mut ret,
"#[derive(Copy, Clone, Debug)]
#[repr(usize)]
"
)
.unwrap();
write!(&mut ret, "pub enum {}{{\n", name).unwrap();
let mut branches = String::new();
for e in self.enumerations.iter() {
write!(&mut ret, " {} = {},\n", e.0, e.1).unwrap();
write!(&mut branches, " {} => Self::{},\n", e.1, e.0).unwrap();
}
write!(
&mut ret,
"}}
impl {}{{
fn from(x: usize)->Self{{
match x{{
{} _ => unreachable!()
}}
}}
}}
",
name, branches
)
.unwrap();
return ret;
}
}
#[derive(Debug, Clone)]
struct BitFieldDescriptor<'a> {
name: &'a str,
description: &'a str,
lo: usize,
hi: usize,
ed: Option<(&'a str, EnumerationDescriptor<'a>)>,
}
impl<'a> BitFieldDescriptor<'a> {
pub fn parse(desc: &'a str) -> Self {
let mut parts = desc.split(",");
let name = parts.next().unwrap();
let hi = parts.next().unwrap().parse::<usize>().unwrap();
let lo = parts.next().unwrap().parse::<usize>().unwrap();
let (lo, hi) = if lo < hi { (lo, hi) } else { (hi, lo) };
let use_enum = parts.next().unwrap();
let ed = if use_enum != "number" {
let opts = parts.next().unwrap();
Some((use_enum, EnumerationDescriptor::parse(opts)))
} else {
None
};
let description = as_str_polyfill!(parts, desc);
BitFieldDescriptor {
name,
lo,
hi,
description,
ed,
}
}
pub fn generate_enum(&self) -> Option<String> {
if let Some((n, e)) = &self.ed {
Some(e.generate_enum(n))
} else {
None
}
}
pub fn flag_type(&self) -> &str {
if let Some((n, _)) = self.ed {
n
} else {
if self.lo == self.hi {
"bool"
} else {
"usize"
}
}
}
fn mask(&self) -> String {
format!("{}", (1usize << (self.hi - self.lo + 1)) - 1)
}
fn getter(&self) -> String {
if self.lo == self.hi {
return format!("self.bits.get_bit({})", self.lo);
} else if self.flag_type() != "usize" {
return format!(
"{}::from(self.bits.get_bits({}..{}))",
self.flag_type(),
self.lo,
self.hi + 1
);
} else {
return format!("self.bits.get_bits({}..{})", self.lo, self.hi + 1);
}
}
fn setter(&self) -> String {
if self.lo == self.hi {
return format!("self.bits.set_bit({}, val);", self.lo);
} else if self.flag_type() != "usize" {
return format!(
"self.bits.set_bits({}..{}, val as usize);",
self.lo,
self.hi + 1
);
} else {
return format!("self.bits.set_bits({}..{}, val);", self.lo, self.hi + 1);
}
}
fn generate_read_write(&self) -> String {
format!(
" /// {}
#[inline]
pub fn {}(&self)->{}{{
{}
}}
#[inline]
pub fn set_{}(&mut self, val: {}){{
{}
}}\n",
self.description,
self.name,
self.flag_type(),
self.getter(),
self.name,
self.flag_type(),
self.setter()
)
}
fn generate_bit_set(&self) -> String {
format!(
" pub fn set_{}()->bool{{
unsafe {{csr::csrrc({}) & {} !=0}}
}}
pub fn clear_{}()->bool{{
unsafe {{csr::csrrs({}) & {} !=0 }}
}}\n",
self.name,
1usize << self.lo,
1usize << self.lo,
self.name,
1usize << self.lo,
1usize << self.lo
)
}
fn generate_bitops(&self) -> String {
format!(
" set_clear_csr!(
///{}
, set_{}, clear_{}, 1 << {});\n",
self.description, self.name, self.name, self.lo
)
}
}
#[derive(Debug, Clone)]
struct CSRDescriptor<'a> {
name: &'a str,
id: usize,
description: &'a str,
bfs: Vec<BitFieldDescriptor<'a>>,
}
impl<'a> CSRDescriptor<'a> {
fn canonical_name(&self) -> String {
self.name.to_lowercase()
}
pub fn parse(d: &'a str) -> Self {
let mut parts = d.split("\n");
let name = parts.next().unwrap();
let id = parts.next().unwrap().parse::<usize>().unwrap();
let mut bfs = Vec::new();
while let Some(x) = parts.next() {
if x == "end" {
break;
} else {
bfs.push(BitFieldDescriptor::parse(x));
}
}
CSRDescriptor {
name,
id,
description: as_str_polyfill!(parts, d),
bfs,
}
}
pub fn generate(&self) -> String {
let mut trait_impls = String::new();
let mut bit_sets = String::new();
let mut enums = String::new();
for bf in self.bfs.iter() {
if bf.lo == bf.hi {
write!(&mut bit_sets, "{}", bf.generate_bitops()).unwrap();
//write!(&mut trait_impls, "{}",bf.generate_bit_set()).unwrap();
}
write!(&mut trait_impls, "{}", bf.generate_read_write()).unwrap();
if let Some(x) = bf.generate_enum() {
write!(&mut enums, "{}", x).unwrap();
}
}
if &trait_impls == "" && &bit_sets == "" {
format!(
"
//! {}
read_csr_as_usize!({}, __read_{});
write_csr_as_usize!({}, __write_{});
",
self.description,
self.id,
self.canonical_name(),
self.id,
self.canonical_name()
)
} else {
format!(
"
//! {}
use bit_field::BitField;
#[derive(Copy, Clone, Debug)]
pub struct {}{{\n bits: usize,\n}}
impl {}{{
#[inline]
pub fn bits(&self) -> usize{{
return self.bits;
}}
#[inline]
pub fn from_bits(x: usize) -> Self{{
return {}{{bits: x}};
}}
#[inline]
pub unsafe fn write(&self){{
_write(self.bits);
}}
{}
}}
read_csr_as!({}, {}, __read_{});
write_csr!({}, __write_{});
set!({}, __set_{});
clear!({}, __clear_{});
// bit ops
{}
// enums
{}
",
self.description,
self.name,
self.name,
self.name,
trait_impls,
self.name,
self.id,
self.canonical_name(),
self.id,
self.canonical_name(),
self.id,
self.canonical_name(),
self.id,
self.canonical_name(),
bit_sets,
enums,
)
}
}
}
fn main() {
use std::io::Read;
let mut buffer = String::new();
std::io::stdin().read_to_string(&mut buffer).unwrap();
let csr = CSRDescriptor::parse(&buffer);
println!("{}", csr.generate());
}

View File

@@ -0,0 +1,36 @@
Hcounteren
3602
cy,0,0,number,
tm,1,1,number,
ir,2,2,number,
hpm3,3,3,number,
hpm4,4,4,number,
hpm5,5,5,number,
hpm6,6,6,number,
hpm7,7,7,number,
hpm8,8,8,number,
hpm9,9,9,number,
hpm10,10,10,number,
hpm11,11,11,number,
hpm12,12,12,number,
hpm13,13,13,number,
hpm14,14,14,number,
hpm15,15,15,number,
hpm16,16,16,number,
hpm17,17,17,number,
hpm18,18,18,number,
hpm19,19,19,number,
hpm20,20,20,number,
hpm21,21,21,number,
hpm22,22,22,number,
hpm23,23,23,number,
hpm24,24,24,number,
hpm25,25,25,number,
hpm26,26,26,number,
hpm27,27,27,number,
hpm28,28,28,number,
hpm29,29,29,number,
hpm30,30,30,number,
hpm31,31,31,number,
end
Hypervisor Guest External Interrupt Pending Register.

View File

@@ -0,0 +1,16 @@
Hedeleg
1538
ex0,0,0,number,Instruction address misaligned
ex1,1,1,number,Instruction access fault
ex2,2,2,number,Illegal instruction
ex3,3,3,number,Breakpoint
ex4,4,4,number,Load address misaligned
ex5,5,5,number,Load access fault
ex6,6,6,number,Store/AMO address misaligned
ex7,7,7,number,Store/AMO access fault
ex8,8,8,number,Environment call from U-mode or VU-mode
ex12,12,12,number,Instruction page fault
ex13,13,13,number,Load page fault
ex15,15,15,number,Store/AMO page fault
end
Hypervisor Exception Delegation Register.

View File

@@ -0,0 +1,7 @@
Hgatp
1664
mode,63,60,HgatpValues,Bare=0;Sv39x4=8;Sv48x4=9,Guest address translation mode.
vmid,57,44,number,Virtual machine ID.
ppn,43,0,number,Physical Page Number for root page table.
end
Hypervisor Guest Address Translation and Protection Register.

View File

@@ -0,0 +1,4 @@
Hgeie
1543
end
Hypervisor Guest External Interrupt Enable Register.

View File

@@ -0,0 +1,4 @@
Hgeip
3602
end
Hypervisor Guest External Interrupt Pending Register.

View File

@@ -0,0 +1,7 @@
Hideleg
1539
sip,2,2,number,Software Interrupt
tip,6,6,number,Timer Interrupt
eip,10,10,number,External Interrupt
end
Hypervisor Interrupt Delegation Register.

View File

@@ -0,0 +1,8 @@
Hie
1540
vssie,2,2,number,Software Interrupt
vstie,6,6,number,Timer Interrupt
vseie,10,10,number,External Interrupt
sgeie,12,12,number,Guest External Interrupt
end
Hypervisor Interrupt Enable Register.

View File

@@ -0,0 +1,8 @@
Hip
1604
vssip,2,2,number,Software Interrupt
vstip,6,6,number,Timer Interrupt
vseip,10,10,number,External Interrupt
sgeip,12,12,number,Guest External Interrupt
end
Hypervisor Interrupt Pending Register.

View File

@@ -0,0 +1,14 @@
Hstatus
1536
vsxl,33,32,VsxlValues,Vsxl32=1;Vsxl64;Vsxl128,Effective XLEN for VM.
vtsr,22,22,number,TSR for VM.
vtw,21,21,number,TW for VM.
vtvm,20,20,number,TVM for VM.
vgein,17,12,number,Virtual Guest External Interrupt Number.
hu,9,9,number,Hypervisor User mode.
spvp,8,8,number,Supervisor Previous Virtual Privilege.
spv,7,7,number,Supervisor Previous Virtualization mode.
gva,6,6,number,Guest Virtual Address.
vsbe,5,5,number,VS access endianness.
end
HStatus Register.

View File

@@ -0,0 +1,5 @@
Htimedelta
1541
end
Hypervisor Time Delta Register.
read_composite_csr!(super::htimedeltah::read(), read());

View File

@@ -0,0 +1,4 @@
Htimedeltah
1557
end
Hypervisor Time Delta Register.

View File

@@ -0,0 +1,4 @@
Htinst
1610
end
Hypervisor Trap Instruction Register.

View File

@@ -0,0 +1,4 @@
Htval
1603
end
Hypervisor Trap Value Register.

View File

@@ -0,0 +1,7 @@
Hvip
1605
vssip,2,2,number,Software Interrupt
vstip,6,6,number,Timer Interrupt
vseip,10,10,number,External Interrupt
end
Hypervisor Virtual Interrupt Pending Register.

View File

@@ -0,0 +1,7 @@
Vsatp
640
mode,63,60,HgatpValues,Bare=0;Sv39x4=8;Sv48x4=9,Guest address translation mode.
asid,59,44,number,ASID.
ppn,43,0,number,Physical Page Number for root page table.
end
Virtual Supervisor Guest Address Translation and Protection Register.

View File

@@ -0,0 +1,6 @@
Vscause
578
interrupt,63,63,number,Is cause interrupt.
code,62,0,number,Exception code
end
Virtual Supervisor Cause Register.

View File

@@ -0,0 +1,4 @@
Vsepc
577
end
Virtual Supervisor Exception Program Counter.

View File

@@ -0,0 +1,7 @@
Vsie
516
ssie,1,1,number,Software Interrupt
stie,5,5,number,Timer Interrupt
seie,9,9,number,External Interrupt
end
Virtual Supevisor Interrupt Enable Register.

View File

@@ -0,0 +1,7 @@
Vsip
580
ssip,1,1,number,Software Interrupt
stip,5,5,number,Timer Interrupt
seip,9,9,number,External Interrupt
end
Virtual Supevisor Interrupt Pending Register.

View File

@@ -0,0 +1,4 @@
Vsscratch
576
end
Virtual Supervisor Scratch Register.

View File

@@ -0,0 +1,14 @@
Vsstatus
512
sd,63,60,number,
uxl,33,32,UxlValues,Uxl32=1;Uxl64;Uxl128,Effective User XLEN.
mxr,19,19,number,
sum,18,18,number,
xs,16,15,number,
fs,14,13,number,
spp,8,8,number,
ube,6,6,number,
spie,5,5,number,
sie,1,1,number,
end
Hypervisor Guest External Interrupt Pending Register.

View File

@@ -0,0 +1,4 @@
Vstval
579
end
Virtual Supervisor Trap Value Register.

View File

@@ -0,0 +1,6 @@
Vstvec
517
base,63,2,number,
mode,1,0,number,
end
Virtual Supervisor Trap Vector Base Address Register.

View File

@@ -0,0 +1,211 @@
use super::*;
use bit_field::BitField;
use core::convert::TryInto;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct GPAddrSv32X4(u64);
impl Address for GPAddrSv32X4 {
fn new(addr: usize) -> Self {
Self::new_u64(addr as u64)
}
fn as_usize(&self) -> usize {
self.0 as usize
}
fn page_number(&self) -> usize {
self.0.get_bits(12..34) as usize
}
fn page_offset(&self) -> usize {
self.0.get_bits(0..12) as usize
}
fn to_4k_aligned(&self) -> Self {
GPAddrSv32X4((self.0 >> 12) << 12)
}
}
impl VirtualAddress for GPAddrSv32X4 {
unsafe fn as_mut<'a, 'b, T>(&'a self) -> &'b mut T {
&mut *(self.0 as *mut T)
}
}
impl AddressL2 for GPAddrSv32X4 {
fn p2_index(&self) -> usize {
self.0.get_bits(22..34) as usize
}
fn p1_index(&self) -> usize {
self.0.get_bits(12..22) as usize
}
fn from_page_table_indices(p2_index: usize, p1_index: usize, offset: usize) -> Self {
let p2_index = p2_index as u64;
let p1_index = p1_index as u64;
let offset = offset as u64;
assert!(p2_index.get_bits(12..) == 0, "p2_index exceeding 12 bits");
assert!(p1_index.get_bits(10..) == 0, "p1_index exceeding 10 bits");
assert!(offset.get_bits(12..) == 0, "offset exceeding 12 bits");
GPAddrSv32X4::new_u64((p2_index << 22) | (p1_index << 12) | offset)
}
}
impl AddressX64 for GPAddrSv32X4 {
fn new_u64(addr: u64) -> Self {
assert!(
addr.get_bits(34..64) == 0,
"Sv32x4 does not allow pa 34..64!=0"
);
GPAddrSv32X4(addr)
}
fn as_u64(&self) -> u64 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct GPAddrSv39X4(u64);
impl Address for GPAddrSv39X4 {
fn new(addr: usize) -> Self {
GPAddrSv39X4(addr.try_into().unwrap())
}
fn as_usize(&self) -> usize {
self.0 as usize
}
fn page_number(&self) -> usize {
self.0.get_bits(12..41) as usize
}
fn page_offset(&self) -> usize {
self.0.get_bits(0..12) as usize
}
fn to_4k_aligned(&self) -> Self {
GPAddrSv39X4((self.0 >> 12) << 12)
}
}
impl VirtualAddress for GPAddrSv39X4 {
unsafe fn as_mut<'a, 'b, T>(&'a self) -> &'b mut T {
&mut *(self.0 as *mut T)
}
}
impl AddressL3 for GPAddrSv39X4 {
fn p3_index(&self) -> usize {
self.0.get_bits(30..41) as usize
}
fn p2_index(&self) -> usize {
self.0.get_bits(21..30) as usize
}
fn p1_index(&self) -> usize {
self.0.get_bits(12..21) as usize
}
fn from_page_table_indices(
p3_index: usize,
p2_index: usize,
p1_index: usize,
offset: usize,
) -> Self {
let p3_index = p3_index as u64;
let p2_index = p2_index as u64;
let p1_index = p1_index as u64;
let offset = offset as u64;
assert!(p3_index.get_bits(11..) == 0, "p3_index exceeding 11 bits");
assert!(p2_index.get_bits(9..) == 0, "p2_index exceeding 9 bits");
assert!(p1_index.get_bits(9..) == 0, "p1_index exceeding 9 bits");
assert!(offset.get_bits(12..) == 0, "offset exceeding 12 bits");
GPAddrSv39X4::new_u64(
(p3_index << 12 << 9 << 9) | (p2_index << 12 << 9) | (p1_index << 12) | offset,
)
}
}
impl AddressX64 for GPAddrSv39X4 {
fn new_u64(addr: u64) -> Self {
assert!(
addr.get_bits(41..64) == 0,
"Sv39x4 does not allow pa 41..64!=0"
);
GPAddrSv39X4(addr)
}
fn as_u64(&self) -> u64 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct GPAddrSv48X4(u64);
impl Address for GPAddrSv48X4 {
fn new(addr: usize) -> Self {
GPAddrSv48X4(addr.try_into().unwrap())
}
fn as_usize(&self) -> usize {
self.0 as usize
}
fn page_number(&self) -> usize {
self.0.get_bits(12..50) as usize
}
fn page_offset(&self) -> usize {
self.0.get_bits(0..12) as usize
}
fn to_4k_aligned(&self) -> Self {
GPAddrSv48X4((self.0 >> 12) << 12)
}
}
impl VirtualAddress for GPAddrSv48X4 {
unsafe fn as_mut<'a, 'b, T>(&'a self) -> &'b mut T {
&mut *(self.0 as *mut T)
}
}
impl AddressL4 for GPAddrSv48X4 {
fn p4_index(&self) -> usize {
self.0.get_bits(39..50) as usize
}
fn p3_index(&self) -> usize {
self.0.get_bits(30..39) as usize
}
fn p2_index(&self) -> usize {
self.0.get_bits(21..30) as usize
}
fn p1_index(&self) -> usize {
self.0.get_bits(12..21) as usize
}
fn from_page_table_indices(
p4_index: usize,
p3_index: usize,
p2_index: usize,
p1_index: usize,
offset: usize,
) -> Self {
let p4_index = p4_index as u64;
let p3_index = p3_index as u64;
let p2_index = p2_index as u64;
let p1_index = p1_index as u64;
let offset = offset as u64;
assert!(p4_index.get_bits(11..) == 0, "p4_index exceeding 11 bits");
assert!(p3_index.get_bits(9..) == 0, "p3_index exceeding 9 bits");
assert!(p2_index.get_bits(9..) == 0, "p2_index exceeding 9 bits");
assert!(p1_index.get_bits(9..) == 0, "p1_index exceeding 9 bits");
assert!(offset.get_bits(12..) == 0, "offset exceeding 12 bits");
GPAddrSv48X4::new_u64(
(p4_index << 12 << 9 << 9 << 9)
| (p3_index << 12 << 9 << 9)
| (p2_index << 12 << 9)
| (p1_index << 12)
| offset,
)
}
}
impl AddressX64 for GPAddrSv48X4 {
fn new_u64(addr: u64) -> Self {
assert!(
addr.get_bits(50..64) == 0,
"Sv48x4 does not allow pa 50..64!=0"
);
GPAddrSv48X4(addr)
}
fn as_u64(&self) -> u64 {
self.0
}
}

View File

@@ -0,0 +1,98 @@
pub trait Address: core::fmt::Debug + Copy + Clone + PartialEq + Eq + PartialOrd + Ord {
fn new(addr: usize) -> Self;
fn page_number(&self) -> usize;
fn page_offset(&self) -> usize;
fn to_4k_aligned(&self) -> Self;
fn as_usize(&self) -> usize;
}
pub trait VirtualAddress: Address {
unsafe fn as_mut<'a, 'b, T>(&'a self) -> &'b mut T;
}
pub trait AddressX32: Address {
fn new_u32(addr: u32) -> Self;
fn as_u32(&self) -> u32;
}
pub trait AddressX64: Address {
fn new_u64(addr: u64) -> Self;
fn as_u64(&self) -> u64;
}
pub trait PhysicalAddress: AddressX64 {}
pub trait AddressL3: Address {
fn p3_index(&self) -> usize;
fn p2_index(&self) -> usize;
fn p1_index(&self) -> usize;
fn from_page_table_indices(
p3_index: usize,
p2_index: usize,
p1_index: usize,
offset: usize,
) -> Self;
}
pub trait AddressL4: Address {
fn p4_index(&self) -> usize;
fn p3_index(&self) -> usize;
fn p2_index(&self) -> usize;
fn p1_index(&self) -> usize;
fn from_page_table_indices(
p4_index: usize,
p3_index: usize,
p2_index: usize,
p1_index: usize,
offset: usize,
) -> Self;
}
pub trait AddressL2: Address {
fn p2_index(&self) -> usize;
fn p1_index(&self) -> usize;
fn from_page_table_indices(p2_index: usize, p1_index: usize, offset: usize) -> Self;
}
pub mod gpax4;
pub mod page;
pub mod sv32;
pub mod sv39;
pub mod sv48;
pub use self::gpax4::*;
pub use self::page::*;
pub use self::sv32::*;
pub use self::sv39::*;
pub use self::sv48::*;
#[macro_export]
macro_rules! use_sv32 {
() => {
pub type VirtAddr = VirtAddrSv32;
pub type PhysAddr = PhysAddrSv32;
pub type Page = PageWith<VirtAddr>;
pub type Frame = FrameWith<PhysAddr>;
};
}
#[macro_export]
macro_rules! use_sv39 {
() => {
pub type VirtAddr = VirtAddrSv39;
pub type PhysAddr = PhysAddrSv39;
pub type Page = PageWith<VirtAddr>;
pub type Frame = FrameWith<PhysAddr>;
};
}
#[macro_export]
macro_rules! use_sv48 {
() => {
pub type VirtAddr = VirtAddrSv48;
pub type PhysAddr = PhysAddrSv48;
pub type Page = PageWith<VirtAddr>;
pub type Frame = FrameWith<PhysAddr>;
};
}
#[cfg(target_arch = "riscv64")]
use_sv48!();
#[cfg(target_arch = "riscv32")]
use_sv32!();

View File

@@ -0,0 +1,174 @@
pub use super::*;
pub use bit_field::BitField;
pub trait PageWithL4 {
fn p4_index(&self) -> usize;
fn p3_index(&self) -> usize;
fn p2_index(&self) -> usize;
fn p1_index(&self) -> usize;
fn from_page_table_indices(
p4_index: usize,
p3_index: usize,
p2_index: usize,
p1_index: usize,
) -> Self;
}
pub trait PageWithL3 {
fn p3_index(&self) -> usize;
fn p2_index(&self) -> usize;
fn p1_index(&self) -> usize;
fn from_page_table_indices(p3_index: usize, p2_index: usize, p1_index: usize) -> Self;
}
pub trait PageWithL2 {
fn p2_index(&self) -> usize;
fn p1_index(&self) -> usize;
fn from_page_table_indices(p2_index: usize, p1_index: usize) -> Self;
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct PageWith<T: VirtualAddress>(T);
impl<T: AddressL4 + VirtualAddress> PageWithL4 for PageWith<T> {
fn p4_index(&self) -> usize {
self.0.p4_index()
}
fn p3_index(&self) -> usize {
self.0.p3_index()
}
fn p2_index(&self) -> usize {
self.0.p2_index()
}
fn p1_index(&self) -> usize {
self.0.p1_index()
}
fn from_page_table_indices(
p4_index: usize,
p3_index: usize,
p2_index: usize,
p1_index: usize,
) -> Self {
PageWith::of_addr(T::from_page_table_indices(
p4_index, p3_index, p2_index, p1_index, 0,
))
}
}
impl<T: AddressL3 + VirtualAddress> PageWithL3 for PageWith<T> {
fn p3_index(&self) -> usize {
self.0.p3_index()
}
fn p2_index(&self) -> usize {
self.0.p2_index()
}
fn p1_index(&self) -> usize {
self.0.p1_index()
}
fn from_page_table_indices(p3_index: usize, p2_index: usize, p1_index: usize) -> Self {
PageWith::of_addr(T::from_page_table_indices(p3_index, p2_index, p1_index, 0))
}
}
impl<T: AddressL2 + VirtualAddress> PageWithL2 for PageWith<T> {
fn p2_index(&self) -> usize {
self.0.p2_index()
}
fn p1_index(&self) -> usize {
self.0.p1_index()
}
fn from_page_table_indices(p2_index: usize, p1_index: usize) -> Self {
PageWith::of_addr(T::from_page_table_indices(p2_index, p1_index, 0))
}
}
impl<T: VirtualAddress> PageWith<T> {
pub fn of_addr(addr: T) -> Self {
PageWith(addr.to_4k_aligned())
}
pub fn of_vpn(vpn: usize) -> Self {
PageWith(T::new(vpn << 12))
}
pub fn start_address(&self) -> T {
self.0.clone()
}
pub fn number(&self) -> usize {
self.0.page_number()
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct FrameWith<T: PhysicalAddress>(T);
impl<T: AddressL4 + PhysicalAddress> PageWithL4 for FrameWith<T> {
fn p4_index(&self) -> usize {
self.0.p4_index()
}
fn p3_index(&self) -> usize {
self.0.p3_index()
}
fn p2_index(&self) -> usize {
self.0.p2_index()
}
fn p1_index(&self) -> usize {
self.0.p1_index()
}
fn from_page_table_indices(
p4_index: usize,
p3_index: usize,
p2_index: usize,
p1_index: usize,
) -> Self {
FrameWith::of_addr(T::from_page_table_indices(
p4_index, p3_index, p2_index, p1_index, 0,
))
}
}
impl<T: AddressL3 + PhysicalAddress> PageWithL3 for FrameWith<T> {
fn p3_index(&self) -> usize {
self.0.p3_index()
}
fn p2_index(&self) -> usize {
self.0.p2_index()
}
fn p1_index(&self) -> usize {
self.0.p1_index()
}
fn from_page_table_indices(p3_index: usize, p2_index: usize, p1_index: usize) -> Self {
FrameWith::of_addr(T::from_page_table_indices(p3_index, p2_index, p1_index, 0))
}
}
impl<T: AddressL2 + PhysicalAddress> PageWithL2 for FrameWith<T> {
fn p2_index(&self) -> usize {
self.0.p2_index()
}
fn p1_index(&self) -> usize {
self.0.p1_index()
}
fn from_page_table_indices(p2_index: usize, p1_index: usize) -> Self {
FrameWith::of_addr(T::from_page_table_indices(p2_index, p1_index, 0))
}
}
impl<T: PhysicalAddress> FrameWith<T> {
pub fn of_addr(addr: T) -> Self {
FrameWith(addr.to_4k_aligned())
}
#[inline(always)]
pub fn of_ppn(ppn: usize) -> Self {
FrameWith(T::new_u64((ppn as u64) << 12))
}
pub fn start_address(&self) -> T {
self.0.clone()
}
pub fn number(&self) -> usize {
self.0.page_number()
}
pub unsafe fn as_kernel_mut<'a, 'b, U>(&'a self, linear_offset: u64) -> &'b mut U {
&mut *(((self.0).as_u64() + linear_offset) as *mut U)
}
}

View File

@@ -0,0 +1,91 @@
use super::*;
use bit_field::BitField;
use core::convert::TryInto;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct VirtAddrSv32(u32);
impl Address for VirtAddrSv32 {
fn new(addr: usize) -> Self {
VirtAddrSv32(addr.try_into().unwrap())
}
fn as_usize(&self) -> usize {
self.0 as usize
}
fn page_number(&self) -> usize {
self.0.get_bits(12..32) as usize
}
fn page_offset(&self) -> usize {
self.0.get_bits(0..12) as usize
}
fn to_4k_aligned(&self) -> Self {
VirtAddrSv32((self.0 >> 12) << 12)
}
}
impl VirtualAddress for VirtAddrSv32 {
unsafe fn as_mut<'a, 'b, T>(&'a self) -> &'b mut T {
&mut *(self.0 as *mut T)
}
}
impl AddressL2 for VirtAddrSv32 {
fn p2_index(&self) -> usize {
self.0.get_bits(22..32) as usize
}
fn p1_index(&self) -> usize {
self.0.get_bits(12..22) as usize
}
fn from_page_table_indices(p2_index: usize, p1_index: usize, offset: usize) -> Self {
assert!(p2_index.get_bits(10..) == 0, "p2_index exceeding 10 bits");
assert!(p1_index.get_bits(10..) == 0, "p1_index exceeding 10 bits");
assert!(offset.get_bits(12..) == 0, "offset exceeding 12 bits");
VirtAddrSv32::new((p2_index << 22) | (p1_index << 12) | offset)
}
}
impl AddressX32 for VirtAddrSv32 {
fn new_u32(addr: u32) -> Self {
VirtAddrSv32(addr)
}
fn as_u32(&self) -> u32 {
self.0
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct PhysAddrSv32(u64);
impl Address for PhysAddrSv32 {
fn new(addr: usize) -> Self {
Self::new_u64(addr as u64)
}
fn as_usize(&self) -> usize {
assert!(
self.0.get_bits(32..34) == 0,
"Downcasting an Sv32 pa >4GB (32..34!=0) will cause address loss."
);
self.0 as usize
}
fn page_number(&self) -> usize {
self.0.get_bits(12..34) as usize
}
fn page_offset(&self) -> usize {
self.0.get_bits(0..12) as usize
}
fn to_4k_aligned(&self) -> Self {
PhysAddrSv32((self.0 >> 12) << 12)
}
}
impl AddressX64 for PhysAddrSv32 {
fn new_u64(addr: u64) -> Self {
assert!(
addr.get_bits(34..64) == 0,
"Sv32 does not allow pa 34..64!=0"
);
PhysAddrSv32(addr)
}
fn as_u64(&self) -> u64 {
self.0
}
}
impl PhysicalAddress for PhysAddrSv32 {}

View File

@@ -0,0 +1,115 @@
use super::*;
use bit_field::BitField;
use core::convert::TryInto;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct VirtAddrSv39(u64);
impl VirtualAddress for VirtAddrSv39 {
unsafe fn as_mut<'a, 'b, T>(&'a self) -> &'b mut T {
&mut *(self.0 as *mut T)
}
}
impl Address for VirtAddrSv39 {
fn new(addr: usize) -> Self {
Self::new_u64(addr as u64)
}
fn as_usize(&self) -> usize {
self.0.try_into().unwrap()
}
fn page_number(&self) -> usize {
self.0.get_bits(12..39).try_into().unwrap()
}
fn page_offset(&self) -> usize {
self.0.get_bits(0..12) as usize
}
fn to_4k_aligned(&self) -> Self {
VirtAddrSv39((self.0 >> 12) << 12)
}
}
impl AddressL3 for VirtAddrSv39 {
fn p3_index(&self) -> usize {
self.0.get_bits(30..39) as usize
}
fn p2_index(&self) -> usize {
self.0.get_bits(21..30) as usize
}
fn p1_index(&self) -> usize {
self.0.get_bits(12..21) as usize
}
fn from_page_table_indices(
p3_index: usize,
p2_index: usize,
p1_index: usize,
offset: usize,
) -> Self {
let p3_index = p3_index as u64;
let p2_index = p2_index as u64;
let p1_index = p1_index as u64;
let offset = offset as u64;
assert!(p3_index.get_bits(11..) == 0, "p3_index exceeding 11 bits");
assert!(p2_index.get_bits(9..) == 0, "p2_index exceeding 9 bits");
assert!(p1_index.get_bits(9..) == 0, "p1_index exceeding 9 bits");
assert!(offset.get_bits(12..) == 0, "offset exceeding 12 bits");
let mut addr =
(p3_index << 12 << 9 << 9) | (p2_index << 12 << 9) | (p1_index << 12) | offset;
if addr.get_bit(38) {
addr.set_bits(39..64, (1 << (64 - 39)) - 1);
} else {
addr.set_bits(39..64, 0x0000);
}
VirtAddrSv39::new_u64(addr)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct PhysAddrSv39(u64);
impl Address for PhysAddrSv39 {
fn new(addr: usize) -> Self {
Self::new_u64(addr as u64)
}
fn as_usize(&self) -> usize {
self.0.try_into().unwrap()
}
fn page_number(&self) -> usize {
self.0.get_bits(12..56) as usize
}
fn page_offset(&self) -> usize {
self.0.get_bits(0..12) as usize
}
fn to_4k_aligned(&self) -> Self {
PhysAddrSv39((self.0 >> 12) << 12)
}
}
impl AddressX64 for VirtAddrSv39 {
fn new_u64(addr: u64) -> Self {
if addr.get_bit(38) {
assert!(
addr.get_bits(39..64) == (1 << (64 - 39)) - 1,
"va 39..64 is not sext"
);
} else {
assert!(addr.get_bits(39..64) == 0x0000, "va 39..64 is not sext");
}
VirtAddrSv39(addr as u64)
}
fn as_u64(&self) -> u64 {
self.0
}
}
impl AddressX64 for PhysAddrSv39 {
fn new_u64(addr: u64) -> Self {
assert!(
addr.get_bits(56..64) == 0,
"Sv39 does not allow pa 56..64!=0"
);
PhysAddrSv39(addr)
}
fn as_u64(&self) -> u64 {
self.0
}
}
impl PhysicalAddress for PhysAddrSv39 {}

View File

@@ -0,0 +1,125 @@
use super::*;
use bit_field::BitField;
use core::convert::TryInto;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct VirtAddrSv48(u64);
impl VirtualAddress for VirtAddrSv48 {
unsafe fn as_mut<'a, 'b, T>(&'a self) -> &'b mut T {
&mut *(self.0 as *mut T)
}
}
impl Address for VirtAddrSv48 {
fn new(addr: usize) -> Self {
Self::new_u64(addr as u64)
}
fn as_usize(&self) -> usize {
self.0.try_into().unwrap()
}
fn page_number(&self) -> usize {
self.0.get_bits(12..48).try_into().unwrap()
}
fn page_offset(&self) -> usize {
self.0.get_bits(0..12) as usize
}
fn to_4k_aligned(&self) -> Self {
VirtAddrSv48((self.0 >> 12) << 12)
}
}
impl AddressL4 for VirtAddrSv48 {
fn p4_index(&self) -> usize {
self.0.get_bits(39..48) as usize
}
fn p3_index(&self) -> usize {
self.0.get_bits(30..39) as usize
}
fn p2_index(&self) -> usize {
self.0.get_bits(21..30) as usize
}
fn p1_index(&self) -> usize {
self.0.get_bits(12..21) as usize
}
fn from_page_table_indices(
p4_index: usize,
p3_index: usize,
p2_index: usize,
p1_index: usize,
offset: usize,
) -> Self {
let p4_index = p4_index as u64;
let p3_index = p3_index as u64;
let p2_index = p2_index as u64;
let p1_index = p1_index as u64;
let offset = offset as u64;
assert!(p4_index.get_bits(9..) == 0, "p4_index exceeding 9 bits");
assert!(p3_index.get_bits(9..) == 0, "p3_index exceeding 9 bits");
assert!(p2_index.get_bits(9..) == 0, "p2_index exceeding 9 bits");
assert!(p1_index.get_bits(9..) == 0, "p1_index exceeding 9 bits");
assert!(offset.get_bits(12..) == 0, "offset exceeding 12 bits");
let mut addr = (p4_index << 12 << 9 << 9 << 9)
| (p3_index << 12 << 9 << 9)
| (p2_index << 12 << 9)
| (p1_index << 12)
| offset;
if addr.get_bit(47) {
addr.set_bits(48..64, (1 << (64 - 48)) - 1);
} else {
addr.set_bits(48..64, 0x0000);
}
VirtAddrSv48::new_u64(addr)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct PhysAddrSv48(u64);
impl Address for PhysAddrSv48 {
fn new(addr: usize) -> Self {
Self::new_u64(addr as u64)
}
fn as_usize(&self) -> usize {
self.0.try_into().unwrap()
}
fn page_number(&self) -> usize {
self.0.get_bits(12..56) as usize
}
fn page_offset(&self) -> usize {
self.0.get_bits(0..12) as usize
}
fn to_4k_aligned(&self) -> Self {
PhysAddrSv48((self.0 >> 12) << 12)
}
}
impl AddressX64 for VirtAddrSv48 {
fn new_u64(addr: u64) -> Self {
if addr.get_bit(47) {
assert!(
addr.get_bits(48..64) == (1 << (64 - 48)) - 1,
"va 48..64 is not sext"
);
} else {
assert!(addr.get_bits(48..64) == 0x0000, "va 48..64 is not sext");
}
VirtAddrSv48(addr as u64)
}
fn as_u64(&self) -> u64 {
self.0
}
}
impl AddressX64 for PhysAddrSv48 {
fn new_u64(addr: u64) -> Self {
assert!(
addr.get_bits(56..64) == 0,
"Sv48 does not allow pa 56..64!=0"
);
PhysAddrSv48(addr)
}
fn as_u64(&self) -> u64 {
self.0
}
}
impl PhysicalAddress for PhysAddrSv48 {}

152
ci-user/riscv/src/asm.rs Normal file
View File

@@ -0,0 +1,152 @@
//! Assembly instructions
macro_rules! instruction {
($(#[$attr:meta])*, $fnname:ident, $asm:expr, $asm_fn:ident) => (
$(#[$attr])*
#[inline]
pub unsafe fn $fnname() {
match () {
#[cfg(all(riscv, feature = "inline-asm"))]
() => asm!($asm),
#[cfg(all(riscv, not(feature = "inline-asm")))]
() => {
extern "C" {
fn $asm_fn();
}
$asm_fn();
}
#[cfg(not(riscv))]
() => unimplemented!(),
}
}
)
}
instruction!(
/// `EBREAK` instruction wrapper
///
/// Generates a breakpoint exception.
, ebreak, "ebreak", __ebreak);
instruction!(
/// `WFI` instruction wrapper
///
/// Provides a hint to the implementation that the current hart can be stalled until an interrupt might need servicing.
/// The WFI instruction is just a hint, and a legal implementation is to implement WFI as a NOP.
, wfi, "wfi", __wfi);
instruction!(
/// `SFENCE.VMA` instruction wrapper (all address spaces and page table levels)
///
/// Synchronizes updates to in-memory memory-management data structures with current execution.
/// Instruction execution causes implicit reads and writes to these data structures; however, these implicit references
/// are ordinarily not ordered with respect to loads and stores in the instruction stream.
/// Executing an `SFENCE.VMA` instruction guarantees that any stores in the instruction stream prior to the
/// `SFENCE.VMA` are ordered before all implicit references subsequent to the `SFENCE.VMA`.
, sfence_vma_all, "sfence.vma", __sfence_vma_all);
/// `SFENCE.VMA` instruction wrapper
///
/// Synchronizes updates to in-memory memory-management data structures with current execution.
/// Instruction execution causes implicit reads and writes to these data structures; however, these implicit references
/// are ordinarily not ordered with respect to loads and stores in the instruction stream.
/// Executing an `SFENCE.VMA` instruction guarantees that any stores in the instruction stream prior to the
/// `SFENCE.VMA` are ordered before all implicit references subsequent to the `SFENCE.VMA`.
#[inline]
#[allow(unused_variables)]
pub unsafe fn sfence_vma(asid: usize, addr: usize) {
match () {
#[cfg(all(riscv, feature = "inline-asm"))]
() => asm!("sfence.vma {0}, {1}", in(reg) asid, in(reg) addr),
#[cfg(all(riscv, not(feature = "inline-asm")))]
() => {
extern "C" {
fn __sfence_vma(asid: usize, addr: usize);
}
__sfence_vma(asid, addr);
}
#[cfg(not(riscv))]
() => unimplemented!(),
}
}
mod hypervisor_extension {
// Generating instructions for Hypervisor extension.
// There are two kinds of instructions: rs1/rs2 type and rs1/rd type.
// Also special register handling is required before LLVM could generate inline assembly for extended instructions.
macro_rules! instruction_hypervisor_extension {
(RS1_RS2, $(#[$attr:meta])*, $fnname:ident, $asm:expr, $asm_fn:ident) => (
$(#[$attr])*
#[inline]
#[allow(unused_variables)]
pub unsafe fn $fnname(rs1: usize, rs2: usize) {
match () {
#[cfg(all(riscv, feature = "inline-asm"))]
// Since LLVM does not recognize the two registers, we assume they are placed in a0 and a1, correspondingly.
() => asm!($asm, in("x10") rs1, in("x11") rs2),
#[cfg(all(riscv, not(feature = "inline-asm")))]
() => {
extern "C" {
fn $asm_fn(rs1: usize, rs2: usize);
}
$asm_fn(rs1, rs2);
}
#[cfg(not(riscv))]
() => unimplemented!(),
}
}
);
(RS1_RD, $(#[$attr:meta])*, $fnname:ident, $asm:expr, $asm_fn:ident) => (
$(#[$attr])*
#[inline]
#[allow(unused_variables)]
pub unsafe fn $fnname(rs1: usize)->usize {
match () {
#[cfg(all(riscv, feature = "inline-asm"))]
() => {
let mut result : usize;
asm!($asm, inlateout("x10") rs1 => result);
return result;
}
#[cfg(all(riscv, not(feature = "inline-asm")))]
() => {
extern "C" {
fn $asm_fn(rs1: usize)->usize;
}
return $asm_fn(rs1);
}
#[cfg(not(riscv))]
() => unimplemented!(),
}
}
)
}
instruction_hypervisor_extension!(RS1_RS2,,hfence_gvma,".word 1656029299",__hfence_gvma);
instruction_hypervisor_extension!(RS1_RS2,,hfence_vvma,".word 582287475",__hfence_vvma);
instruction_hypervisor_extension!(RS1_RD,,hlv_b,".word 1610958195",__hlv_b);
instruction_hypervisor_extension!(RS1_RD,,hlv_bu,".word 1612006771",__hlv_bu);
instruction_hypervisor_extension!(RS1_RD,,hlv_h,".word 1678067059",__hlv_h);
instruction_hypervisor_extension!(RS1_RD,,hlv_hu,".word 1679115635",__hlv_hu);
instruction_hypervisor_extension!(RS1_RD,,hlvx_hu,".word 1681212787",__hlvx_hu);
instruction_hypervisor_extension!(RS1_RD,,hlv_w,".word 1745175923",__hlv_w);
instruction_hypervisor_extension!(RS1_RD,,hlvx_wu,".word 1748321651",__hlvx_wu);
instruction_hypervisor_extension!(RS1_RS2,,hsv_b,".word 1656045683",__hsv_b);
instruction_hypervisor_extension!(RS1_RS2,,hsv_h,".word 1723154547",__hsv_h);
instruction_hypervisor_extension!(RS1_RS2,,hsv_w,".word 1790263411",__hsv_w);
instruction_hypervisor_extension!(RS1_RD,,hlv_wu,".word 1746224499",__hlv_wu);
instruction_hypervisor_extension!(RS1_RD,,hlv_d,".word 1812284787",__hlv_d);
instruction_hypervisor_extension!(RS1_RS2,,hsv_d,".word 1857372275",__hsv_d);
}
pub use self::hypervisor_extension::*;

View File

@@ -0,0 +1,58 @@
//! Interrupts
// NOTE: Adapted from cortex-m/src/interrupt.rs
pub use bare_metal::{CriticalSection, Mutex, Nr};
use register::mstatus;
/// Disables all interrupts
#[inline]
pub unsafe fn disable() {
match () {
#[cfg(riscv)]
() => mstatus::clear_mie(),
#[cfg(not(riscv))]
() => unimplemented!(),
}
}
/// Enables all the interrupts
///
/// # Safety
///
/// - Do not call this function inside an `interrupt::free` critical section
#[inline]
pub unsafe fn enable() {
match () {
#[cfg(riscv)]
() => mstatus::set_mie(),
#[cfg(not(riscv))]
() => unimplemented!(),
}
}
/// Execute closure `f` in an interrupt-free context.
///
/// This as also known as a "critical section".
pub fn free<F, R>(f: F) -> R
where
F: FnOnce(&CriticalSection) -> R,
{
let mstatus = mstatus::read();
// disable interrupts
unsafe {
disable();
}
let r = f(unsafe { &CriticalSection::new() });
// If the interrupts were active before our `disable` call, then re-enable
// them. Otherwise, keep them disabled
if mstatus.mie() {
unsafe {
enable();
}
}
r
}

27
ci-user/riscv/src/lib.rs Normal file
View File

@@ -0,0 +1,27 @@
//! Low level access to RISC-V processors
//!
//! # Minimum Supported Rust Version (MSRV)
//!
//! This crate is guaranteed to compile on stable Rust 1.42 and up. It *might*
//! compile with older versions but that may change in any new patch release.
//!
//! # Features
//!
//! This crate provides:
//!
//! - Access to core registers like `mstatus` or `mcause`.
//! - Interrupt manipulation mechanisms.
//! - Wrappers around assembly instructions like `WFI`.
#![no_std]
#![cfg_attr(feature = "inline-asm", feature(asm))]
extern crate bare_metal;
#[macro_use]
extern crate bitflags;
extern crate bit_field;
pub mod addr;
pub mod asm;
pub mod interrupt;
pub mod paging;
pub mod register;

View File

@@ -0,0 +1,40 @@
//! Traits for abstracting away frame allocation and deallocation.
use addr::*;
/// A trait for types that can allocate a frame of memory.
pub trait FrameAllocatorFor<P: PhysicalAddress> {
/// Allocate a frame of the appropriate size and return it if possible.
fn alloc(&mut self) -> Option<FrameWith<P>>;
}
/// A trait for types that can deallocate a frame of memory.
pub trait FrameDeallocatorFor<P: PhysicalAddress> {
/// Deallocate the given frame of memory.
fn dealloc(&mut self, frame: FrameWith<P>);
}
/// Polyfill for default use cases.
#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
pub trait FrameAllocator {
fn alloc(&mut self) -> Option<Frame>;
}
#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
pub trait FrameDeallocator {
fn dealloc(&mut self, frame: Frame);
}
#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
impl<T: FrameAllocator> FrameAllocatorFor<PhysAddr> for T {
#[inline]
fn alloc(&mut self) -> Option<Frame> {
FrameAllocator::alloc(self)
}
}
#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
impl<T: FrameDeallocator> FrameDeallocatorFor<PhysAddr> for T {
#[inline]
fn dealloc(&mut self, frame: Frame) {
FrameDeallocator::dealloc(self, frame)
}
}

View File

@@ -0,0 +1,136 @@
use super::frame_alloc::*;
use super::page_table::*;
use addr::*;
pub trait Mapper {
type P: PhysicalAddress;
type V: VirtualAddress;
type MapperFlush: MapperFlushable;
type Entry: PTE;
/// Creates a new mapping in the page table.
///
/// This function might need additional physical frames to create new page tables. These
/// frames are allocated from the `allocator` argument. At most three frames are required.
fn map_to(
&mut self,
page: PageWith<Self::V>,
frame: FrameWith<Self::P>,
flags: PageTableFlags,
allocator: &mut impl FrameAllocatorFor<<Self as Mapper>::P>,
) -> Result<Self::MapperFlush, MapToError>;
/// Removes a mapping from the page table and returns the frame that used to be mapped.
///
/// Note that no page tables or pages are deallocated.
fn unmap(
&mut self,
page: PageWith<Self::V>,
) -> Result<(FrameWith<Self::P>, Self::MapperFlush), UnmapError<<Self as Mapper>::P>>;
/// Get the reference of the specified `page` entry
fn ref_entry(&mut self, page: PageWith<Self::V>) -> Result<&mut Self::Entry, FlagUpdateError>;
/// Updates the flags of an existing mapping.
fn update_flags(
&mut self,
page: PageWith<Self::V>,
flags: PageTableFlags,
) -> Result<Self::MapperFlush, FlagUpdateError> {
self.ref_entry(page).map(|e| {
e.set(e.frame::<Self::P>(), flags);
Self::MapperFlush::new(page)
})
}
/// Return the frame that the specified page is mapped to.
fn translate_page(&mut self, page: PageWith<Self::V>) -> Option<FrameWith<Self::P>> {
match self.ref_entry(page) {
Ok(e) => {
if e.is_unused() {
None
} else {
Some(e.frame())
}
}
Err(_) => None,
}
}
/// Maps the given frame to the virtual page with the same address.
fn identity_map(
&mut self,
frame: FrameWith<Self::P>,
flags: PageTableFlags,
allocator: &mut impl FrameAllocatorFor<<Self as Mapper>::P>,
) -> Result<Self::MapperFlush, MapToError> {
let page = PageWith::of_addr(Self::V::new(frame.start_address().as_usize()));
self.map_to(page, frame, flags, allocator)
}
}
pub trait MapperFlushable {
/// Create a new flush promise
fn new<T: VirtualAddress>(page: PageWith<T>) -> Self;
/// Flush the page from the TLB to ensure that the newest mapping is used.
fn flush(self);
/// Don't flush the TLB and silence the “must be used” warning.
fn ignore(self);
}
#[must_use = "Page Table changes must be flushed or ignored."]
pub struct MapperFlush(usize);
impl MapperFlushable for MapperFlush {
fn new<T: VirtualAddress>(page: PageWith<T>) -> Self {
MapperFlush(page.start_address().as_usize())
}
fn flush(self) {
unsafe {
crate::asm::sfence_vma(0, self.0);
}
}
fn ignore(self) {}
}
/// This error is returned from `map_to` and similar methods.
#[derive(Debug)]
pub enum MapToError {
/// An additional frame was needed for the mapping process, but the frame allocator
/// returned `None`.
FrameAllocationFailed,
/// An upper level page table entry has the `HUGE_PAGE` flag set, which means that the
/// given page is part of an already mapped huge page.
ParentEntryHugePage,
/// The given page is already mapped to a physical frame.
PageAlreadyMapped,
}
/// An error indicating that an `unmap` call failed.
#[derive(Debug)]
pub enum UnmapError<P: PhysicalAddress> {
/// An upper level page table entry has the `HUGE_PAGE` flag set, which means that the
/// given page is part of a huge page and can't be freed individually.
ParentEntryHugePage,
/// The given page is not mapped to a physical frame.
PageNotMapped,
/// The page table entry for the given page points to an invalid physical address.
InvalidFrameAddress(P),
}
/// An error indicating that an `update_flags` call failed.
#[derive(Debug)]
pub enum FlagUpdateError {
/// The given page is not mapped to a physical frame.
PageNotMapped,
}
pub trait MapperExt {
type Page;
type Frame;
}
impl<T: Mapper> MapperExt for T {
type Page = PageWith<<T as Mapper>::V>;
type Frame = FrameWith<<T as Mapper>::P>;
}

View File

@@ -0,0 +1,13 @@
mod frame_alloc;
mod mapper;
mod multi_level;
mod multi_level_x4;
mod page_table;
mod page_table_x4;
pub use self::frame_alloc::*;
pub use self::mapper::*;
pub use self::multi_level::*;
pub use self::multi_level_x4::*;
pub use self::page_table::*;
pub use self::page_table_x4::*;

View File

@@ -0,0 +1,354 @@
use super::frame_alloc::*;
use super::mapper::*;
use super::page_table::{PageTableFlags as F, *};
use crate::addr::*;
use core::marker::PhantomData;
/// This struct is a two level page table with `Mapper` trait implemented.
pub struct Rv32PageTableWith<'a, V: VirtualAddress + AddressL2, FL: MapperFlushable> {
root_table: &'a mut PageTableX32,
linear_offset: u64, // VA = PA + linear_offset
phantom: PhantomData<(V, FL)>,
}
impl<'a, V: VirtualAddress + AddressL2, FL: MapperFlushable> Rv32PageTableWith<'a, V, FL> {
pub fn new(table: &'a mut PageTableX32, linear_offset: usize) -> Self {
Rv32PageTableWith {
root_table: table,
linear_offset: linear_offset as u64,
phantom: PhantomData,
}
}
fn create_p1_if_not_exist(
&mut self,
p2_index: usize,
allocator: &mut impl FrameAllocatorFor<<Self as Mapper>::P>,
) -> Result<&mut PageTableX32, MapToError> {
if self.root_table[p2_index].is_unused() {
let frame = allocator.alloc().ok_or(MapToError::FrameAllocationFailed)?;
self.root_table[p2_index].set(frame.clone(), F::VALID);
let p1_table: &mut PageTableX32 = unsafe { frame.as_kernel_mut(self.linear_offset) };
p1_table.zero();
Ok(p1_table)
} else {
let frame = self.root_table[p2_index].frame::<PhysAddrSv32>();
let p1_table: &mut PageTableX32 = unsafe { frame.as_kernel_mut(self.linear_offset) };
Ok(p1_table)
}
}
}
impl<'a, V: VirtualAddress + AddressL2, FL: MapperFlushable> Mapper
for Rv32PageTableWith<'a, V, FL>
{
type P = PhysAddrSv32;
type V = V;
type MapperFlush = FL;
type Entry = PageTableEntryX32;
fn map_to(
&mut self,
page: <Self as MapperExt>::Page,
frame: <Self as MapperExt>::Frame,
flags: PageTableFlags,
allocator: &mut impl FrameAllocatorFor<<Self as Mapper>::P>,
) -> Result<Self::MapperFlush, MapToError> {
let p1_table = self.create_p1_if_not_exist(page.p2_index(), allocator)?;
if !p1_table[page.p1_index()].is_unused() {
return Err(MapToError::PageAlreadyMapped);
}
p1_table[page.p1_index()].set(frame, flags);
Ok(Self::MapperFlush::new(page))
}
fn unmap(
&mut self,
page: <Self as MapperExt>::Page,
) -> Result<(<Self as MapperExt>::Frame, Self::MapperFlush), UnmapError<<Self as Mapper>::P>>
{
if self.root_table[page.p2_index()].is_unused() {
return Err(UnmapError::PageNotMapped);
}
let p1_frame = self.root_table[page.p2_index()].frame::<PhysAddrSv32>();
let p1_table: &mut PageTableX32 = unsafe { p1_frame.as_kernel_mut(self.linear_offset) };
let p1_entry = &mut p1_table[page.p1_index()];
if !p1_entry.flags().contains(F::VALID) {
return Err(UnmapError::PageNotMapped);
}
let frame = p1_entry.frame();
p1_entry.set_unused();
Ok((frame, Self::MapperFlush::new(page)))
}
fn ref_entry(
&mut self,
page: <Self as MapperExt>::Page,
) -> Result<&mut PageTableEntryX32, FlagUpdateError> {
if self.root_table[page.p2_index()].is_unused() {
return Err(FlagUpdateError::PageNotMapped);
}
let p1_frame = self.root_table[page.p2_index()].frame::<PhysAddrSv32>();
let p1_table: &mut PageTableX32 = unsafe { p1_frame.as_kernel_mut(self.linear_offset) };
Ok(&mut p1_table[page.p1_index()])
}
}
/// This struct is a three level page table with `Mapper` trait implemented.
pub struct Rv39PageTableWith<'a, V: VirtualAddress + AddressL3, FL: MapperFlushable> {
root_table: &'a mut PageTableX64,
linear_offset: u64, // VA = PA + linear_offset
phantom: PhantomData<(V, FL)>,
}
impl<'a, V: VirtualAddress + AddressL3, FL: MapperFlushable> Rv39PageTableWith<'a, V, FL> {
pub fn new(table: &'a mut PageTableX64, linear_offset: usize) -> Self {
Rv39PageTableWith {
root_table: table,
linear_offset: linear_offset as u64,
phantom: PhantomData,
}
}
fn create_p1_if_not_exist(
&mut self,
p3_index: usize,
p2_index: usize,
allocator: &mut impl FrameAllocatorFor<<Self as Mapper>::P>,
) -> Result<&mut PageTableX64, MapToError> {
let p2_table = if self.root_table[p3_index].is_unused() {
let frame = allocator.alloc().ok_or(MapToError::FrameAllocationFailed)?;
self.root_table[p3_index].set(frame.clone(), F::VALID);
let p2_table: &mut PageTableX64 = unsafe { frame.as_kernel_mut(self.linear_offset) };
p2_table.zero();
p2_table
} else {
let frame = self.root_table[p3_index].frame::<PhysAddrSv39>();
unsafe { frame.as_kernel_mut(self.linear_offset) }
};
if p2_table[p2_index].is_unused() {
let frame = allocator.alloc().ok_or(MapToError::FrameAllocationFailed)?;
p2_table[p2_index].set(frame.clone(), F::VALID);
let p1_table: &mut PageTableX64 = unsafe { frame.as_kernel_mut(self.linear_offset) };
p1_table.zero();
Ok(p1_table)
} else {
let frame = p2_table[p2_index].frame::<PhysAddrSv39>();
let p1_table: &mut PageTableX64 = unsafe { frame.as_kernel_mut(self.linear_offset) };
Ok(p1_table)
}
}
}
impl<'a, V: VirtualAddress + AddressL3, FL: MapperFlushable> Mapper
for Rv39PageTableWith<'a, V, FL>
{
type P = PhysAddrSv39;
type V = V;
type MapperFlush = FL;
type Entry = PageTableEntryX64;
fn map_to(
&mut self,
page: <Self as MapperExt>::Page,
frame: <Self as MapperExt>::Frame,
flags: PageTableFlags,
allocator: &mut impl FrameAllocatorFor<<Self as Mapper>::P>,
) -> Result<Self::MapperFlush, MapToError> {
let p1_table = self.create_p1_if_not_exist(page.p3_index(), page.p2_index(), allocator)?;
if !p1_table[page.p1_index()].is_unused() {
return Err(MapToError::PageAlreadyMapped);
}
p1_table[page.p1_index()].set(frame, flags);
Ok(Self::MapperFlush::new(page))
}
fn unmap(
&mut self,
page: <Self as MapperExt>::Page,
) -> Result<(<Self as MapperExt>::Frame, Self::MapperFlush), UnmapError<<Self as Mapper>::P>>
{
if self.root_table[page.p3_index()].is_unused() {
return Err(UnmapError::PageNotMapped);
}
let p2_frame = self.root_table[page.p3_index()].frame::<PhysAddrSv39>();
let p2_table: &mut PageTableX64 = unsafe { p2_frame.as_kernel_mut(self.linear_offset) };
if p2_table[page.p2_index()].is_unused() {
return Err(UnmapError::PageNotMapped);
}
let p1_frame = p2_table[page.p2_index()].frame::<PhysAddrSv39>();
let p1_table: &mut PageTableX64 = unsafe { p1_frame.as_kernel_mut(self.linear_offset) };
let p1_entry = &mut p1_table[page.p1_index()];
if !p1_entry.flags().contains(F::VALID) {
return Err(UnmapError::PageNotMapped);
}
let frame = p1_entry.frame();
p1_entry.set_unused();
Ok((frame, Self::MapperFlush::new(page)))
}
fn ref_entry(
&mut self,
page: <Self as MapperExt>::Page,
) -> Result<&mut PageTableEntryX64, FlagUpdateError> {
if self.root_table[page.p3_index()].is_unused() {
return Err(FlagUpdateError::PageNotMapped);
}
let p2_frame = self.root_table[page.p3_index()].frame::<PhysAddrSv39>();
let p2_table: &mut PageTableX64 = unsafe { p2_frame.as_kernel_mut(self.linear_offset) };
if p2_table[page.p2_index()].is_unused() {
return Err(FlagUpdateError::PageNotMapped);
}
let p1_frame = p2_table[page.p2_index()].frame::<PhysAddrSv39>();
let p1_table: &mut PageTableX64 = unsafe { p1_frame.as_kernel_mut(self.linear_offset) };
Ok(&mut p1_table[page.p1_index()])
}
}
/// This struct is a four level page table with `Mapper` trait implemented.
pub struct Rv48PageTableWith<'a, V: VirtualAddress + AddressL4, FL: MapperFlushable> {
root_table: &'a mut PageTableX64,
linear_offset: u64, // VA = PA + linear_offset
phantom: PhantomData<(V, FL)>,
}
impl<'a, V: VirtualAddress + AddressL4, FL: MapperFlushable> Rv48PageTableWith<'a, V, FL> {
pub fn new(table: &'a mut PageTableX64, linear_offset: usize) -> Self {
Rv48PageTableWith {
root_table: table,
linear_offset: linear_offset as u64,
phantom: PhantomData,
}
}
fn create_p1_if_not_exist(
&mut self,
p4_index: usize,
p3_index: usize,
p2_index: usize,
allocator: &mut impl FrameAllocatorFor<<Self as Mapper>::P>,
) -> Result<&mut PageTableX64, MapToError> {
let p3_table = if self.root_table[p4_index].is_unused() {
let frame = allocator.alloc().ok_or(MapToError::FrameAllocationFailed)?;
self.root_table[p4_index].set(frame.clone(), F::VALID);
let p3_table: &mut PageTableX64 = unsafe { frame.as_kernel_mut(self.linear_offset) };
p3_table.zero();
p3_table
} else {
let frame = self.root_table[p4_index].frame::<PhysAddrSv48>();
unsafe { frame.as_kernel_mut(self.linear_offset) }
};
let p2_table = if p3_table[p3_index].is_unused() {
let frame = allocator.alloc().ok_or(MapToError::FrameAllocationFailed)?;
p3_table[p3_index].set(frame.clone(), F::VALID);
let p2_table: &mut PageTableX64 = unsafe { frame.as_kernel_mut(self.linear_offset) };
p2_table.zero();
p2_table
} else {
let frame = p3_table[p3_index].frame::<PhysAddrSv48>();
unsafe { frame.as_kernel_mut(self.linear_offset) }
};
if p2_table[p2_index].is_unused() {
let frame = allocator.alloc().ok_or(MapToError::FrameAllocationFailed)?;
p2_table[p2_index].set(frame.clone(), F::VALID);
let p1_table: &mut PageTableX64 = unsafe { frame.as_kernel_mut(self.linear_offset) };
p1_table.zero();
Ok(p1_table)
} else {
let frame = p2_table[p2_index].frame::<PhysAddrSv48>();
let p1_table: &mut PageTableX64 = unsafe { frame.as_kernel_mut(self.linear_offset) };
Ok(p1_table)
}
}
}
impl<'a, V: VirtualAddress + AddressL4, FL: MapperFlushable> Mapper
for Rv48PageTableWith<'a, V, FL>
{
type P = PhysAddrSv48;
type V = V;
type MapperFlush = FL;
type Entry = PageTableEntryX64;
fn map_to(
&mut self,
page: <Self as MapperExt>::Page,
frame: <Self as MapperExt>::Frame,
flags: PageTableFlags,
allocator: &mut impl FrameAllocatorFor<<Self as Mapper>::P>,
) -> Result<Self::MapperFlush, MapToError> {
let p1_table = self.create_p1_if_not_exist(
page.p4_index(),
page.p3_index(),
page.p2_index(),
allocator,
)?;
if !p1_table[page.p1_index()].is_unused() {
return Err(MapToError::PageAlreadyMapped);
}
p1_table[page.p1_index()].set(frame, flags);
Ok(Self::MapperFlush::new(page))
}
fn unmap(
&mut self,
page: <Self as MapperExt>::Page,
) -> Result<(<Self as MapperExt>::Frame, Self::MapperFlush), UnmapError<<Self as Mapper>::P>>
{
if self.root_table[page.p4_index()].is_unused() {
return Err(UnmapError::PageNotMapped);
}
let p3_frame = self.root_table[page.p4_index()].frame::<PhysAddrSv48>();
let p3_table: &mut PageTableX64 = unsafe { p3_frame.as_kernel_mut(self.linear_offset) };
if p3_table[page.p3_index()].is_unused() {
return Err(UnmapError::PageNotMapped);
}
let p2_frame = p3_table[page.p3_index()].frame::<PhysAddrSv48>();
let p2_table: &mut PageTableX64 = unsafe { p2_frame.as_kernel_mut(self.linear_offset) };
if p2_table[page.p2_index()].is_unused() {
return Err(UnmapError::PageNotMapped);
}
let p1_frame = p2_table[page.p2_index()].frame::<PhysAddrSv48>();
let p1_table: &mut PageTableX64 = unsafe { p1_frame.as_kernel_mut(self.linear_offset) };
let p1_entry = &mut p1_table[page.p1_index()];
if !p1_entry.flags().contains(F::VALID) {
return Err(UnmapError::PageNotMapped);
}
let frame = p1_entry.frame::<PhysAddrSv48>();
p1_entry.set_unused();
Ok((frame, Self::MapperFlush::new(page)))
}
fn ref_entry(
&mut self,
page: <Self as MapperExt>::Page,
) -> Result<&mut PageTableEntryX64, FlagUpdateError> {
if self.root_table[page.p4_index()].is_unused() {
return Err(FlagUpdateError::PageNotMapped);
}
let p3_frame = self.root_table[page.p4_index()].frame::<PhysAddrSv48>();
let p3_table: &mut PageTableX64 = unsafe { p3_frame.as_kernel_mut(self.linear_offset) };
if p3_table[page.p3_index()].is_unused() {
return Err(FlagUpdateError::PageNotMapped);
}
let p2_frame = p3_table[page.p3_index()].frame::<PhysAddrSv48>();
let p2_table: &mut PageTableX64 = unsafe { p2_frame.as_kernel_mut(self.linear_offset) };
if p2_table[page.p2_index()].is_unused() {
return Err(FlagUpdateError::PageNotMapped);
}
let p1_frame = p2_table[page.p2_index()].frame::<PhysAddrSv48>();
let p1_table: &mut PageTableX64 = unsafe { p1_frame.as_kernel_mut(self.linear_offset) };
Ok(&mut p1_table[page.p1_index()])
}
}
pub type Rv32PageTable<'a> = Rv32PageTableWith<'a, VirtAddrSv32, MapperFlush>;
pub type Rv39PageTable<'a> = Rv39PageTableWith<'a, VirtAddrSv39, MapperFlush>;
pub type Rv48PageTable<'a> = Rv48PageTableWith<'a, VirtAddrSv48, MapperFlush>;

View File

@@ -0,0 +1,42 @@
use crate::addr::*;
use crate::asm::{hfence_gvma, hfence_vvma};
use crate::paging::mapper::MapperFlushable;
use crate::paging::multi_level::Rv32PageTableWith;
use crate::paging::multi_level::{Rv39PageTableWith, Rv48PageTableWith};
#[must_use = "Guest Physical Address Table changes must be flushed or ignored."]
pub struct MapperFlushGPA(usize);
impl MapperFlushable for MapperFlushGPA {
fn new<T: VirtualAddress>(page: PageWith<T>) -> Self {
MapperFlushGPA(page.start_address().as_usize())
}
fn flush(self) {
unsafe {
hfence_gvma(self.0, 0);
}
}
fn ignore(self) {}
}
#[must_use = "Guest Page Table changes must be flushed or ignored."]
pub struct MapperFlushGPT(usize);
impl MapperFlushable for MapperFlushGPT {
fn new<T: VirtualAddress>(page: PageWith<T>) -> Self {
MapperFlushGPT(page.start_address().as_usize())
}
fn flush(self) {
unsafe {
hfence_vvma(self.0, 0);
}
}
fn ignore(self) {}
}
pub type Rv32PageTableX4<'a> = Rv32PageTableWith<'a, GPAddrSv32X4, MapperFlushGPA>;
pub type Rv39PageTableX4<'a> = Rv39PageTableWith<'a, GPAddrSv39X4, MapperFlushGPA>;
pub type Rv48PageTableX4<'a> = Rv48PageTableWith<'a, GPAddrSv48X4, MapperFlushGPA>;
pub type Rv32PageTableGuest<'a> = Rv32PageTableWith<'a, VirtAddrSv32, MapperFlushGPT>;
pub type Rv39PageTableGuest<'a> = Rv39PageTableWith<'a, VirtAddrSv39, MapperFlushGPT>;
pub type Rv48PageTableGuest<'a> = Rv48PageTableWith<'a, VirtAddrSv48, MapperFlushGPT>;

View File

@@ -0,0 +1,252 @@
use addr::*;
use core::convert::TryInto;
use core::fmt::{Debug, Error, Formatter};
use core::marker::PhantomData;
use core::ops::{Index, IndexMut};
pub type Entries32 = [PageTableEntryX32; RV32_ENTRY_COUNT];
pub type Entries64 = [PageTableEntryX64; RV64_ENTRY_COUNT];
// To avoid const generic.
pub trait PTEIterableSlice<T> {
fn to_pte_slice<'a>(&'a self) -> &'a [T];
fn to_pte_slice_mut<'a>(&'a mut self) -> &'a mut [T];
fn pte_index(&self, index: usize) -> &T;
fn pte_index_mut(&mut self, index: usize) -> &mut T;
}
impl PTEIterableSlice<PageTableEntryX32> for Entries32 {
fn to_pte_slice(&self) -> &[PageTableEntryX32] {
self
}
fn to_pte_slice_mut(&mut self) -> &mut [PageTableEntryX32] {
self
}
fn pte_index(&self, index: usize) -> &PageTableEntryX32 {
&self[index]
}
fn pte_index_mut(&mut self, index: usize) -> &mut PageTableEntryX32 {
&mut self[index]
}
}
impl PTEIterableSlice<PageTableEntryX64> for Entries64 {
fn to_pte_slice(&self) -> &[PageTableEntryX64] {
self
}
fn to_pte_slice_mut(&mut self) -> &mut [PageTableEntryX64] {
self
}
fn pte_index(&self, index: usize) -> &PageTableEntryX64 {
&self[index]
}
fn pte_index_mut(&mut self, index: usize) -> &mut PageTableEntryX64 {
&mut self[index]
}
}
#[repr(C)]
pub struct PageTableWith<T: PTEIterableSlice<E>, E: PTE> {
entries: T,
phantom: PhantomData<E>,
}
impl<T: PTEIterableSlice<E>, E: PTE> PageTableWith<T, E> {
/// Clears all entries.
pub fn zero(&mut self) {
for entry in self.entries.to_pte_slice_mut().iter_mut() {
entry.set_unused();
}
}
}
impl<T: PTEIterableSlice<E>, E: PTE> Index<usize> for PageTableWith<T, E> {
type Output = E;
fn index(&self, index: usize) -> &Self::Output {
self.entries.pte_index(index)
}
}
impl<T: PTEIterableSlice<E>, E: PTE> IndexMut<usize> for PageTableWith<T, E> {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
self.entries.pte_index_mut(index)
}
}
impl<T: PTEIterableSlice<E>, E: PTE + Debug> Debug for PageTableWith<T, E> {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
f.debug_map()
.entries(
self.entries
.to_pte_slice()
.iter()
.enumerate()
.filter(|p| !p.1.is_unused()),
)
.finish()
}
}
pub trait PTE {
fn is_unused(&self) -> bool;
fn set_unused(&mut self);
fn flags(&self) -> PageTableFlags;
fn ppn(&self) -> usize;
fn ppn_u64(&self) -> u64;
fn addr<T: PhysicalAddress>(&self) -> T;
fn frame<T: PhysicalAddress>(&self) -> FrameWith<T>;
fn set<T: PhysicalAddress>(&mut self, frame: FrameWith<T>, flags: PageTableFlags);
fn flags_mut(&mut self) -> &mut PageTableFlags;
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct PageTableEntryX32(u32);
impl PTE for PageTableEntryX32 {
fn is_unused(&self) -> bool {
self.0 == 0
}
fn set_unused(&mut self) {
self.0 = 0;
}
fn flags(&self) -> PageTableFlags {
PageTableFlags::from_bits_truncate(self.0 as usize)
}
fn ppn(&self) -> usize {
self.ppn_u64().try_into().unwrap()
}
fn ppn_u64(&self) -> u64 {
(self.0 >> 10) as u64
}
fn addr<T: PhysicalAddress>(&self) -> T {
T::new_u64((self.ppn() as u64) << 12)
}
fn frame<T: PhysicalAddress>(&self) -> FrameWith<T> {
FrameWith::of_addr(self.addr())
}
fn set<T: PhysicalAddress>(&mut self, frame: FrameWith<T>, mut flags: PageTableFlags) {
// U540 will raise page fault when accessing page with A=0 or D=0
flags |= EF::ACCESSED | EF::DIRTY;
self.0 = ((frame.number() << 10) | flags.bits()) as u32;
}
fn flags_mut(&mut self) -> &mut PageTableFlags {
unsafe { &mut *(self as *mut _ as *mut PageTableFlags) }
}
}
impl Debug for PageTableEntryX32 {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
f.debug_struct("PageTableEntryX32")
.field("frame", &self.frame::<PhysAddrSv32>())
.field("flags", &self.flags())
.finish()
}
}
#[derive(Copy, Clone)]
pub struct PageTableEntryX64(u64);
impl PTE for PageTableEntryX64 {
fn is_unused(&self) -> bool {
self.0 == 0
}
fn set_unused(&mut self) {
self.0 = 0;
}
fn flags(&self) -> PageTableFlags {
PageTableFlags::from_bits_truncate(self.0 as usize)
}
fn ppn(&self) -> usize {
self.ppn_u64().try_into().unwrap()
}
fn ppn_u64(&self) -> u64 {
(self.0 >> 10) as u64
}
fn addr<T: PhysicalAddress>(&self) -> T {
T::new_u64((self.ppn() as u64) << 12)
}
fn frame<T: PhysicalAddress>(&self) -> FrameWith<T> {
FrameWith::of_addr(self.addr())
}
fn set<T: PhysicalAddress>(&mut self, frame: FrameWith<T>, mut flags: PageTableFlags) {
// U540 will raise page fault when accessing page with A=0 or D=0
flags |= EF::ACCESSED | EF::DIRTY;
self.0 = ((frame.number() << 10) | flags.bits()) as u64;
}
fn flags_mut(&mut self) -> &mut PageTableFlags {
unsafe { &mut *(self as *mut _ as *mut PageTableFlags) }
}
}
pub struct PageTableEntryX64Printer<'a, P: PhysicalAddress>(
&'a PageTableEntryX64,
PhantomData<*const P>,
);
impl<'a, P: PhysicalAddress> Debug for PageTableEntryX64Printer<'a, P> {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
f.debug_struct("PageTableEntryX64")
.field("frame", &self.0.frame::<P>())
.field("flags", &self.0.flags())
.finish()
}
}
impl PageTableEntryX64 {
pub fn debug_sv39<'a>(&'a self) -> PageTableEntryX64Printer<'a, PhysAddrSv39> {
PageTableEntryX64Printer(self, PhantomData)
}
pub fn debug_sv48<'a>(&'a self) -> PageTableEntryX64Printer<'a, PhysAddrSv48> {
PageTableEntryX64Printer(self, PhantomData)
}
}
impl Debug for PageTableEntryX64 {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
self.debug_sv48().fmt(f)
}
}
pub const RV64_ENTRY_COUNT: usize = 1 << 9;
pub const RV32_ENTRY_COUNT: usize = 1 << 10;
#[cfg(riscv64)]
pub const ENTRY_COUNT: usize = RV64_ENTRY_COUNT;
#[cfg(riscv32)]
pub const ENTRY_COUNT: usize = RV32_ENTRY_COUNT;
#[cfg(riscv64)]
pub type PageTableEntry = PageTableEntryX64;
#[cfg(riscv32)]
pub type PageTableEntry = PageTableEntryX32;
#[cfg(riscv64)]
pub type Entries = Entries64;
#[cfg(riscv32)]
pub type Entries = Entries32;
#[cfg(not(any(riscv32, riscv64)))]
pub const ENTRY_COUNT: usize = 1 << 0;
#[cfg(not(any(riscv32, riscv64)))]
pub type Entries = Entries64;
pub type PageTableX32 = PageTableWith<Entries32, PageTableEntryX32>;
pub type PageTableX64 = PageTableWith<Entries64, PageTableEntryX64>;
#[cfg(riscv64)]
pub type PageTable = PageTableX64;
#[cfg(riscv32)]
pub type PageTable = PageTableX32;
bitflags! {
/// Possible flags for a page table entry.
pub struct PageTableFlags: usize {
const VALID = 1 << 0;
const READABLE = 1 << 1;
const WRITABLE = 1 << 2;
const EXECUTABLE = 1 << 3;
const USER = 1 << 4;
const GLOBAL = 1 << 5;
const ACCESSED = 1 << 6;
const DIRTY = 1 << 7;
const RESERVED1 = 1 << 8;
const RESERVED2 = 1 << 9;
}
}
type EF = PageTableFlags;

View File

@@ -0,0 +1,44 @@
/// This file is for Hypervisor-related x4 page tables, including Sv32x4, Sv39x4 and Sv48x4.
/// In fact, these x4 page tables are Phys-to-Phys page tables from GPAs to real PAs.
use super::page_table::{
PTEIterableSlice, PageTableEntryX32, PageTableEntryX64, PageTableWith, RV32_ENTRY_COUNT,
RV64_ENTRY_COUNT,
};
// The root page table is 4 times larger.
pub const RV32_X4_ENTRY_COUNT: usize = RV32_ENTRY_COUNT << 2;
pub const RV64_X4_ENTRY_COUNT: usize = RV64_ENTRY_COUNT << 2;
pub type Entries32X4 = [PageTableEntryX32; RV32_X4_ENTRY_COUNT];
pub type Entries64X4 = [PageTableEntryX64; RV64_X4_ENTRY_COUNT];
impl PTEIterableSlice<PageTableEntryX32> for Entries32X4 {
fn to_pte_slice(&self) -> &[PageTableEntryX32] {
self
}
fn to_pte_slice_mut(&mut self) -> &mut [PageTableEntryX32] {
self
}
fn pte_index(&self, index: usize) -> &PageTableEntryX32 {
&self[index]
}
fn pte_index_mut(&mut self, index: usize) -> &mut PageTableEntryX32 {
&mut self[index]
}
}
impl PTEIterableSlice<PageTableEntryX64> for Entries64X4 {
fn to_pte_slice(&self) -> &[PageTableEntryX64] {
self
}
fn to_pte_slice_mut(&mut self) -> &mut [PageTableEntryX64] {
self
}
fn pte_index(&self, index: usize) -> &PageTableEntryX64 {
&self[index]
}
fn pte_index_mut(&mut self, index: usize) -> &mut PageTableEntryX64 {
&mut self[index]
}
}
pub type PageTable32X4 = PageTableWith<Entries32X4, PageTableEntryX32>;
pub type PageTable64X4 = PageTableWith<Entries64X4, PageTableEntryX64>;

View File

@@ -0,0 +1,134 @@
//! Floating-point control and status register
use bit_field::BitField;
/// Floating-point control and status register
#[derive(Clone, Copy, Debug)]
pub struct FCSR {
bits: u32,
}
/// Accrued Exception Flags
#[derive(Clone, Copy, Debug)]
pub struct Flags(u32);
/// Accrued Exception Flag
#[derive(Clone, Copy, Debug)]
pub enum Flag {
/// Inexact
NX = 0b00001,
/// Underflow
UF = 0b00010,
/// Overflow
OF = 0b00100,
/// Divide by Zero
DZ = 0b01000,
/// Invalid Operation
NV = 0b10000,
}
impl Flags {
/// Inexact
#[inline]
pub fn nx(&self) -> bool {
self.0.get_bit(0)
}
/// Underflow
#[inline]
pub fn uf(&self) -> bool {
self.0.get_bit(1)
}
/// Overflow
#[inline]
pub fn of(&self) -> bool {
self.0.get_bit(2)
}
/// Divide by Zero
#[inline]
pub fn dz(&self) -> bool {
self.0.get_bit(3)
}
/// Invalid Operation
#[inline]
pub fn nv(&self) -> bool {
self.0.get_bit(4)
}
}
/// Rounding Mode
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RoundingMode {
RoundToNearestEven = 0b000,
RoundTowardsZero = 0b001,
RoundDown = 0b010,
RoundUp = 0b011,
RoundToNearestMaxMagnitude = 0b100,
Invalid = 0b111,
}
impl FCSR {
/// Returns the contents of the register as raw bits
pub fn bits(&self) -> u32 {
self.bits
}
/// Accrued Exception Flags
#[inline]
pub fn fflags(&self) -> Flags {
Flags(self.bits.get_bits(0..5))
}
/// Rounding Mode
#[inline]
pub fn frm(&self) -> RoundingMode {
match self.bits.get_bits(5..8) {
0b000 => RoundingMode::RoundToNearestEven,
0b001 => RoundingMode::RoundTowardsZero,
0b010 => RoundingMode::RoundDown,
0b011 => RoundingMode::RoundUp,
0b100 => RoundingMode::RoundToNearestMaxMagnitude,
_ => RoundingMode::Invalid,
}
}
}
read_csr!(0x003, __read_fcsr);
write_csr!(0x003, __write_fcsr);
clear!(0x003, __clear_fcsr);
/// Reads the CSR
#[inline]
pub fn read() -> FCSR {
FCSR {
bits: unsafe { _read() as u32 },
}
}
/// Writes the CSR
#[inline]
pub unsafe fn set_rounding_mode(frm: RoundingMode) {
let old = read();
let bits = ((frm as u32) << 5) | old.fflags().0;
_write(bits as usize);
}
/// Resets `fflags` field bits
#[inline]
pub unsafe fn clear_flags() {
let mask = 0b11111;
_clear(mask);
}
/// Resets `fflags` field bit
#[inline]
pub unsafe fn clear_flag(flag: Flag) {
_clear(flag as usize);
}

View File

@@ -0,0 +1,82 @@
macro_rules! reg {
(
$addr:expr, $csrl:ident, $csrh:ident, $readf:ident, $writef:ident
) => {
/// Performance-monitoring counter
pub mod $csrl {
read_csr_as_usize!($addr, $readf);
read_composite_csr!(super::$csrh::read(), read());
}
}
}
macro_rules! regh {
(
$addr:expr, $csrh:ident, $readf:ident, $writef:ident
) => {
/// Upper 32 bits of performance-monitoring counter (RV32I only)
pub mod $csrh {
read_csr_as_usize_rv32!($addr, $readf);
}
}
}
reg!(0xC03, hpmcounter3, hpmcounter3h, __read_hpmcounter3, __write_hpmcounter3);
reg!(0xC04, hpmcounter4, hpmcounter4h, __read_hpmcounter4, __write_hpmcounter4);
reg!(0xC05, hpmcounter5, hpmcounter5h, __read_hpmcounter5, __write_hpmcounter5);
reg!(0xC06, hpmcounter6, hpmcounter6h, __read_hpmcounter6, __write_hpmcounter6);
reg!(0xC07, hpmcounter7, hpmcounter7h, __read_hpmcounter7, __write_hpmcounter7);
reg!(0xC08, hpmcounter8, hpmcounter8h, __read_hpmcounter8, __write_hpmcounter8);
reg!(0xC09, hpmcounter9, hpmcounter9h, __read_hpmcounter9, __write_hpmcounter9);
reg!(0xC0A, hpmcounter10, hpmcounter10h, __read_hpmcounter10, __write_hpmcounter10);
reg!(0xC0B, hpmcounter11, hpmcounter11h, __read_hpmcounter11, __write_hpmcounter11);
reg!(0xC0C, hpmcounter12, hpmcounter12h, __read_hpmcounter12, __write_hpmcounter12);
reg!(0xC0D, hpmcounter13, hpmcounter13h, __read_hpmcounter13, __write_hpmcounter13);
reg!(0xC0E, hpmcounter14, hpmcounter14h, __read_hpmcounter14, __write_hpmcounter14);
reg!(0xC0F, hpmcounter15, hpmcounter15h, __read_hpmcounter15, __write_hpmcounter15);
reg!(0xC10, hpmcounter16, hpmcounter16h, __read_hpmcounter16, __write_hpmcounter16);
reg!(0xC11, hpmcounter17, hpmcounter17h, __read_hpmcounter17, __write_hpmcounter17);
reg!(0xC12, hpmcounter18, hpmcounter18h, __read_hpmcounter18, __write_hpmcounter18);
reg!(0xC13, hpmcounter19, hpmcounter19h, __read_hpmcounter19, __write_hpmcounter19);
reg!(0xC14, hpmcounter20, hpmcounter20h, __read_hpmcounter20, __write_hpmcounter20);
reg!(0xC15, hpmcounter21, hpmcounter21h, __read_hpmcounter21, __write_hpmcounter21);
reg!(0xC16, hpmcounter22, hpmcounter22h, __read_hpmcounter22, __write_hpmcounter22);
reg!(0xC17, hpmcounter23, hpmcounter23h, __read_hpmcounter23, __write_hpmcounter23);
reg!(0xC18, hpmcounter24, hpmcounter24h, __read_hpmcounter24, __write_hpmcounter24);
reg!(0xC19, hpmcounter25, hpmcounter25h, __read_hpmcounter25, __write_hpmcounter25);
reg!(0xC1A, hpmcounter26, hpmcounter26h, __read_hpmcounter26, __write_hpmcounter26);
reg!(0xC1B, hpmcounter27, hpmcounter27h, __read_hpmcounter27, __write_hpmcounter27);
reg!(0xC1C, hpmcounter28, hpmcounter28h, __read_hpmcounter28, __write_hpmcounter28);
reg!(0xC1D, hpmcounter29, hpmcounter29h, __read_hpmcounter29, __write_hpmcounter29);
reg!(0xC1E, hpmcounter30, hpmcounter30h, __read_hpmcounter30, __write_hpmcounter30);
reg!(0xC1F, hpmcounter31, hpmcounter31h, __read_hpmcounter31, __write_hpmcounter31);
regh!(0xC83, hpmcounter3h, __read_hpmcounter3h, __write_hpmcounter3h);
regh!(0xC84, hpmcounter4h, __read_hpmcounter4h, __write_hpmcounter4h);
regh!(0xC85, hpmcounter5h, __read_hpmcounter5h, __write_hpmcounter5h);
regh!(0xC86, hpmcounter6h, __read_hpmcounter6h, __write_hpmcounter6h);
regh!(0xC87, hpmcounter7h, __read_hpmcounter7h, __write_hpmcounter7h);
regh!(0xC88, hpmcounter8h, __read_hpmcounter8h, __write_hpmcounter8h);
regh!(0xC89, hpmcounter9h, __read_hpmcounter9h, __write_hpmcounter9h);
regh!(0xC8A, hpmcounter10h, __read_hpmcounter10h, __write_hpmcounter10h);
regh!(0xC8B, hpmcounter11h, __read_hpmcounter11h, __write_hpmcounter11h);
regh!(0xC8C, hpmcounter12h, __read_hpmcounter12h, __write_hpmcounter12h);
regh!(0xC8D, hpmcounter13h, __read_hpmcounter13h, __write_hpmcounter13h);
regh!(0xC8E, hpmcounter14h, __read_hpmcounter14h, __write_hpmcounter14h);
regh!(0xC8F, hpmcounter15h, __read_hpmcounter15h, __write_hpmcounter15h);
regh!(0xC90, hpmcounter16h, __read_hpmcounter16h, __write_hpmcounter16h);
regh!(0xC91, hpmcounter17h, __read_hpmcounter17h, __write_hpmcounter17h);
regh!(0xC92, hpmcounter18h, __read_hpmcounter18h, __write_hpmcounter18h);
regh!(0xC93, hpmcounter19h, __read_hpmcounter19h, __write_hpmcounter19h);
regh!(0xC94, hpmcounter20h, __read_hpmcounter20h, __write_hpmcounter20h);
regh!(0xC95, hpmcounter21h, __read_hpmcounter21h, __write_hpmcounter21h);
regh!(0xC96, hpmcounter22h, __read_hpmcounter22h, __write_hpmcounter22h);
regh!(0xC97, hpmcounter23h, __read_hpmcounter23h, __write_hpmcounter23h);
regh!(0xC98, hpmcounter24h, __read_hpmcounter24h, __write_hpmcounter24h);
regh!(0xC99, hpmcounter25h, __read_hpmcounter25h, __write_hpmcounter25h);
regh!(0xC9A, hpmcounter26h, __read_hpmcounter26h, __write_hpmcounter26h);
regh!(0xC9B, hpmcounter27h, __read_hpmcounter27h, __write_hpmcounter27h);
regh!(0xC9C, hpmcounter28h, __read_hpmcounter28h, __write_hpmcounter28h);
regh!(0xC9D, hpmcounter29h, __read_hpmcounter29h, __write_hpmcounter29h);
regh!(0xC9E, hpmcounter30h, __read_hpmcounter30h, __write_hpmcounter30h);
regh!(0xC9F, hpmcounter31h, __read_hpmcounter31h, __write_hpmcounter31h);

View File

@@ -0,0 +1,413 @@
//! Hypervisor Guest External Interrupt Pending Register.
use bit_field::BitField;
#[derive(Copy, Clone, Debug)]
pub struct Hcounteren {
bits: usize,
}
impl Hcounteren {
#[inline]
pub fn bits(&self) -> usize {
return self.bits;
}
#[inline]
pub fn from_bits(x: usize) -> Self {
return Hcounteren { bits: x };
}
#[inline]
pub unsafe fn write(&self) {
_write(self.bits);
}
///
#[inline]
pub fn cy(&self) -> bool {
self.bits.get_bit(0)
}
#[inline]
pub fn set_cy(&mut self, val: bool) {
self.bits.set_bit(0, val);
}
///
#[inline]
pub fn tm(&self) -> bool {
self.bits.get_bit(1)
}
#[inline]
pub fn set_tm(&mut self, val: bool) {
self.bits.set_bit(1, val);
}
///
#[inline]
pub fn ir(&self) -> bool {
self.bits.get_bit(2)
}
#[inline]
pub fn set_ir(&mut self, val: bool) {
self.bits.set_bit(2, val);
}
///
#[inline]
pub fn hpm3(&self) -> bool {
self.bits.get_bit(3)
}
#[inline]
pub fn set_hpm3(&mut self, val: bool) {
self.bits.set_bit(3, val);
}
///
#[inline]
pub fn hpm4(&self) -> bool {
self.bits.get_bit(4)
}
#[inline]
pub fn set_hpm4(&mut self, val: bool) {
self.bits.set_bit(4, val);
}
///
#[inline]
pub fn hpm5(&self) -> bool {
self.bits.get_bit(5)
}
#[inline]
pub fn set_hpm5(&mut self, val: bool) {
self.bits.set_bit(5, val);
}
///
#[inline]
pub fn hpm6(&self) -> bool {
self.bits.get_bit(6)
}
#[inline]
pub fn set_hpm6(&mut self, val: bool) {
self.bits.set_bit(6, val);
}
///
#[inline]
pub fn hpm7(&self) -> bool {
self.bits.get_bit(7)
}
#[inline]
pub fn set_hpm7(&mut self, val: bool) {
self.bits.set_bit(7, val);
}
///
#[inline]
pub fn hpm8(&self) -> bool {
self.bits.get_bit(8)
}
#[inline]
pub fn set_hpm8(&mut self, val: bool) {
self.bits.set_bit(8, val);
}
///
#[inline]
pub fn hpm9(&self) -> bool {
self.bits.get_bit(9)
}
#[inline]
pub fn set_hpm9(&mut self, val: bool) {
self.bits.set_bit(9, val);
}
///
#[inline]
pub fn hpm10(&self) -> bool {
self.bits.get_bit(10)
}
#[inline]
pub fn set_hpm10(&mut self, val: bool) {
self.bits.set_bit(10, val);
}
///
#[inline]
pub fn hpm11(&self) -> bool {
self.bits.get_bit(11)
}
#[inline]
pub fn set_hpm11(&mut self, val: bool) {
self.bits.set_bit(11, val);
}
///
#[inline]
pub fn hpm12(&self) -> bool {
self.bits.get_bit(12)
}
#[inline]
pub fn set_hpm12(&mut self, val: bool) {
self.bits.set_bit(12, val);
}
///
#[inline]
pub fn hpm13(&self) -> bool {
self.bits.get_bit(13)
}
#[inline]
pub fn set_hpm13(&mut self, val: bool) {
self.bits.set_bit(13, val);
}
///
#[inline]
pub fn hpm14(&self) -> bool {
self.bits.get_bit(14)
}
#[inline]
pub fn set_hpm14(&mut self, val: bool) {
self.bits.set_bit(14, val);
}
///
#[inline]
pub fn hpm15(&self) -> bool {
self.bits.get_bit(15)
}
#[inline]
pub fn set_hpm15(&mut self, val: bool) {
self.bits.set_bit(15, val);
}
///
#[inline]
pub fn hpm16(&self) -> bool {
self.bits.get_bit(16)
}
#[inline]
pub fn set_hpm16(&mut self, val: bool) {
self.bits.set_bit(16, val);
}
///
#[inline]
pub fn hpm17(&self) -> bool {
self.bits.get_bit(17)
}
#[inline]
pub fn set_hpm17(&mut self, val: bool) {
self.bits.set_bit(17, val);
}
///
#[inline]
pub fn hpm18(&self) -> bool {
self.bits.get_bit(18)
}
#[inline]
pub fn set_hpm18(&mut self, val: bool) {
self.bits.set_bit(18, val);
}
///
#[inline]
pub fn hpm19(&self) -> bool {
self.bits.get_bit(19)
}
#[inline]
pub fn set_hpm19(&mut self, val: bool) {
self.bits.set_bit(19, val);
}
///
#[inline]
pub fn hpm20(&self) -> bool {
self.bits.get_bit(20)
}
#[inline]
pub fn set_hpm20(&mut self, val: bool) {
self.bits.set_bit(20, val);
}
///
#[inline]
pub fn hpm21(&self) -> bool {
self.bits.get_bit(21)
}
#[inline]
pub fn set_hpm21(&mut self, val: bool) {
self.bits.set_bit(21, val);
}
///
#[inline]
pub fn hpm22(&self) -> bool {
self.bits.get_bit(22)
}
#[inline]
pub fn set_hpm22(&mut self, val: bool) {
self.bits.set_bit(22, val);
}
///
#[inline]
pub fn hpm23(&self) -> bool {
self.bits.get_bit(23)
}
#[inline]
pub fn set_hpm23(&mut self, val: bool) {
self.bits.set_bit(23, val);
}
///
#[inline]
pub fn hpm24(&self) -> bool {
self.bits.get_bit(24)
}
#[inline]
pub fn set_hpm24(&mut self, val: bool) {
self.bits.set_bit(24, val);
}
///
#[inline]
pub fn hpm25(&self) -> bool {
self.bits.get_bit(25)
}
#[inline]
pub fn set_hpm25(&mut self, val: bool) {
self.bits.set_bit(25, val);
}
///
#[inline]
pub fn hpm26(&self) -> bool {
self.bits.get_bit(26)
}
#[inline]
pub fn set_hpm26(&mut self, val: bool) {
self.bits.set_bit(26, val);
}
///
#[inline]
pub fn hpm27(&self) -> bool {
self.bits.get_bit(27)
}
#[inline]
pub fn set_hpm27(&mut self, val: bool) {
self.bits.set_bit(27, val);
}
///
#[inline]
pub fn hpm28(&self) -> bool {
self.bits.get_bit(28)
}
#[inline]
pub fn set_hpm28(&mut self, val: bool) {
self.bits.set_bit(28, val);
}
///
#[inline]
pub fn hpm29(&self) -> bool {
self.bits.get_bit(29)
}
#[inline]
pub fn set_hpm29(&mut self, val: bool) {
self.bits.set_bit(29, val);
}
///
#[inline]
pub fn hpm30(&self) -> bool {
self.bits.get_bit(30)
}
#[inline]
pub fn set_hpm30(&mut self, val: bool) {
self.bits.set_bit(30, val);
}
///
#[inline]
pub fn hpm31(&self) -> bool {
self.bits.get_bit(31)
}
#[inline]
pub fn set_hpm31(&mut self, val: bool) {
self.bits.set_bit(31, val);
}
}
read_csr_as!(Hcounteren, 3602, __read_hcounteren);
write_csr!(3602, __write_hcounteren);
set!(3602, __set_hcounteren);
clear!(3602, __clear_hcounteren);
// bit ops
set_clear_csr!(
///
, set_cy, clear_cy, 1 << 0);
set_clear_csr!(
///
, set_tm, clear_tm, 1 << 1);
set_clear_csr!(
///
, set_ir, clear_ir, 1 << 2);
set_clear_csr!(
///
, set_hpm3, clear_hpm3, 1 << 3);
set_clear_csr!(
///
, set_hpm4, clear_hpm4, 1 << 4);
set_clear_csr!(
///
, set_hpm5, clear_hpm5, 1 << 5);
set_clear_csr!(
///
, set_hpm6, clear_hpm6, 1 << 6);
set_clear_csr!(
///
, set_hpm7, clear_hpm7, 1 << 7);
set_clear_csr!(
///
, set_hpm8, clear_hpm8, 1 << 8);
set_clear_csr!(
///
, set_hpm9, clear_hpm9, 1 << 9);
set_clear_csr!(
///
, set_hpm10, clear_hpm10, 1 << 10);
set_clear_csr!(
///
, set_hpm11, clear_hpm11, 1 << 11);
set_clear_csr!(
///
, set_hpm12, clear_hpm12, 1 << 12);
set_clear_csr!(
///
, set_hpm13, clear_hpm13, 1 << 13);
set_clear_csr!(
///
, set_hpm14, clear_hpm14, 1 << 14);
set_clear_csr!(
///
, set_hpm15, clear_hpm15, 1 << 15);
set_clear_csr!(
///
, set_hpm16, clear_hpm16, 1 << 16);
set_clear_csr!(
///
, set_hpm17, clear_hpm17, 1 << 17);
set_clear_csr!(
///
, set_hpm18, clear_hpm18, 1 << 18);
set_clear_csr!(
///
, set_hpm19, clear_hpm19, 1 << 19);
set_clear_csr!(
///
, set_hpm20, clear_hpm20, 1 << 20);
set_clear_csr!(
///
, set_hpm21, clear_hpm21, 1 << 21);
set_clear_csr!(
///
, set_hpm22, clear_hpm22, 1 << 22);
set_clear_csr!(
///
, set_hpm23, clear_hpm23, 1 << 23);
set_clear_csr!(
///
, set_hpm24, clear_hpm24, 1 << 24);
set_clear_csr!(
///
, set_hpm25, clear_hpm25, 1 << 25);
set_clear_csr!(
///
, set_hpm26, clear_hpm26, 1 << 26);
set_clear_csr!(
///
, set_hpm27, clear_hpm27, 1 << 27);
set_clear_csr!(
///
, set_hpm28, clear_hpm28, 1 << 28);
set_clear_csr!(
///
, set_hpm29, clear_hpm29, 1 << 29);
set_clear_csr!(
///
, set_hpm30, clear_hpm30, 1 << 30);
set_clear_csr!(
///
, set_hpm31, clear_hpm31, 1 << 31);
// enums

View File

@@ -0,0 +1,173 @@
//! Hypervisor Exception Delegation Register.
use bit_field::BitField;
#[derive(Copy, Clone, Debug)]
pub struct Hedeleg {
bits: usize,
}
impl Hedeleg {
#[inline]
pub fn bits(&self) -> usize {
return self.bits;
}
#[inline]
pub fn from_bits(x: usize) -> Self {
return Hedeleg { bits: x };
}
#[inline]
pub unsafe fn write(&self) {
_write(self.bits);
}
/// Instruction address misaligned
#[inline]
pub fn ex0(&self) -> bool {
self.bits.get_bit(0)
}
#[inline]
pub fn set_ex0(&mut self, val: bool) {
self.bits.set_bit(0, val);
}
/// Instruction access fault
#[inline]
pub fn ex1(&self) -> bool {
self.bits.get_bit(1)
}
#[inline]
pub fn set_ex1(&mut self, val: bool) {
self.bits.set_bit(1, val);
}
/// Illegal instruction
#[inline]
pub fn ex2(&self) -> bool {
self.bits.get_bit(2)
}
#[inline]
pub fn set_ex2(&mut self, val: bool) {
self.bits.set_bit(2, val);
}
/// Breakpoint
#[inline]
pub fn ex3(&self) -> bool {
self.bits.get_bit(3)
}
#[inline]
pub fn set_ex3(&mut self, val: bool) {
self.bits.set_bit(3, val);
}
/// Load address misaligned
#[inline]
pub fn ex4(&self) -> bool {
self.bits.get_bit(4)
}
#[inline]
pub fn set_ex4(&mut self, val: bool) {
self.bits.set_bit(4, val);
}
/// Load access fault
#[inline]
pub fn ex5(&self) -> bool {
self.bits.get_bit(5)
}
#[inline]
pub fn set_ex5(&mut self, val: bool) {
self.bits.set_bit(5, val);
}
/// Store/AMO address misaligned
#[inline]
pub fn ex6(&self) -> bool {
self.bits.get_bit(6)
}
#[inline]
pub fn set_ex6(&mut self, val: bool) {
self.bits.set_bit(6, val);
}
/// Store/AMO access fault
#[inline]
pub fn ex7(&self) -> bool {
self.bits.get_bit(7)
}
#[inline]
pub fn set_ex7(&mut self, val: bool) {
self.bits.set_bit(7, val);
}
/// Environment call from U-mode or VU-mode
#[inline]
pub fn ex8(&self) -> bool {
self.bits.get_bit(8)
}
#[inline]
pub fn set_ex8(&mut self, val: bool) {
self.bits.set_bit(8, val);
}
/// Instruction page fault
#[inline]
pub fn ex12(&self) -> bool {
self.bits.get_bit(12)
}
#[inline]
pub fn set_ex12(&mut self, val: bool) {
self.bits.set_bit(12, val);
}
/// Load page fault
#[inline]
pub fn ex13(&self) -> bool {
self.bits.get_bit(13)
}
#[inline]
pub fn set_ex13(&mut self, val: bool) {
self.bits.set_bit(13, val);
}
/// Store/AMO page fault
#[inline]
pub fn ex15(&self) -> bool {
self.bits.get_bit(15)
}
#[inline]
pub fn set_ex15(&mut self, val: bool) {
self.bits.set_bit(15, val);
}
}
read_csr_as!(Hedeleg, 1538, __read_hedeleg);
write_csr!(1538, __write_hedeleg);
set!(1538, __set_hedeleg);
clear!(1538, __clear_hedeleg);
// bit ops
set_clear_csr!(
///Instruction address misaligned
, set_ex0, clear_ex0, 1 << 0);
set_clear_csr!(
///Instruction access fault
, set_ex1, clear_ex1, 1 << 1);
set_clear_csr!(
///Illegal instruction
, set_ex2, clear_ex2, 1 << 2);
set_clear_csr!(
///Breakpoint
, set_ex3, clear_ex3, 1 << 3);
set_clear_csr!(
///Load address misaligned
, set_ex4, clear_ex4, 1 << 4);
set_clear_csr!(
///Load access fault
, set_ex5, clear_ex5, 1 << 5);
set_clear_csr!(
///Store/AMO address misaligned
, set_ex6, clear_ex6, 1 << 6);
set_clear_csr!(
///Store/AMO access fault
, set_ex7, clear_ex7, 1 << 7);
set_clear_csr!(
///Environment call from U-mode or VU-mode
, set_ex8, clear_ex8, 1 << 8);
set_clear_csr!(
///Instruction page fault
, set_ex12, clear_ex12, 1 << 12);
set_clear_csr!(
///Load page fault
, set_ex13, clear_ex13, 1 << 13);
set_clear_csr!(
///Store/AMO page fault
, set_ex15, clear_ex15, 1 << 15);
// enums

View File

@@ -0,0 +1,73 @@
//! Hypervisor Guest Address Translation and Protection Register.
use bit_field::BitField;
#[derive(Copy, Clone, Debug)]
pub struct Hgatp {
bits: usize,
}
impl Hgatp {
#[inline]
pub fn bits(&self) -> usize {
return self.bits;
}
#[inline]
pub fn from_bits(x: usize) -> Self {
return Hgatp { bits: x };
}
#[inline]
pub unsafe fn write(&self) {
_write(self.bits);
}
/// Guest address translation mode.
#[inline]
pub fn mode(&self) -> HgatpValues {
HgatpValues::from(self.bits.get_bits(60..64))
}
#[inline]
pub fn set_mode(&mut self, val: HgatpValues) {
self.bits.set_bits(60..64, val as usize);
}
/// Virtual machine ID.
#[inline]
pub fn vmid(&self) -> usize {
self.bits.get_bits(44..58)
}
#[inline]
pub fn set_vmid(&mut self, val: usize) {
self.bits.set_bits(44..58, val);
}
/// Physical Page Number for root page table.
#[inline]
pub fn ppn(&self) -> usize {
self.bits.get_bits(0..44)
}
#[inline]
pub fn set_ppn(&mut self, val: usize) {
self.bits.set_bits(0..44, val);
}
}
read_csr_as!(Hgatp, 1664, __read_hgatp);
write_csr!(1664, __write_hgatp);
set!(1664, __set_hgatp);
clear!(1664, __clear_hgatp);
// bit ops
// enums
#[derive(Copy, Clone, Debug)]
#[repr(usize)]
pub enum HgatpValues {
Bare = 0,
Sv39x4 = 8,
Sv48x4 = 9,
}
impl HgatpValues {
fn from(x: usize) -> Self {
match x {
0 => Self::Bare,
8 => Self::Sv39x4,
9 => Self::Sv48x4,
_ => unreachable!(),
}
}
}

View File

@@ -0,0 +1,3 @@
//! Hypervisor Guest External Interrupt Enable Register.
read_csr_as_usize!(1543, __read_hgeie);
write_csr_as_usize!(1543, __write_hgeie);

View File

@@ -0,0 +1,3 @@
//! Hypervisor Guest External Interrupt Pending Register.
read_csr_as_usize!(3602, __read_hgeip);
write_csr_as_usize!(3602, __write_hgeip);

View File

@@ -0,0 +1,65 @@
//! Hypervisor Interrupt Delegation Register.
use bit_field::BitField;
#[derive(Copy, Clone, Debug)]
pub struct Hideleg {
bits: usize,
}
impl Hideleg {
#[inline]
pub fn bits(&self) -> usize {
return self.bits;
}
#[inline]
pub fn from_bits(x: usize) -> Self {
return Hideleg { bits: x };
}
#[inline]
pub unsafe fn write(&self) {
_write(self.bits);
}
/// Software Interrupt
#[inline]
pub fn sip(&self) -> bool {
self.bits.get_bit(2)
}
#[inline]
pub fn set_sip(&mut self, val: bool) {
self.bits.set_bit(2, val);
}
/// Timer Interrupt
#[inline]
pub fn tip(&self) -> bool {
self.bits.get_bit(6)
}
#[inline]
pub fn set_tip(&mut self, val: bool) {
self.bits.set_bit(6, val);
}
/// External Interrupt
#[inline]
pub fn eip(&self) -> bool {
self.bits.get_bit(10)
}
#[inline]
pub fn set_eip(&mut self, val: bool) {
self.bits.set_bit(10, val);
}
}
read_csr_as!(Hideleg, 1539, __read_hideleg);
write_csr!(1539, __write_hideleg);
set!(1539, __set_hideleg);
clear!(1539, __clear_hideleg);
// bit ops
set_clear_csr!(
///Software Interrupt
, set_sip, clear_sip, 1 << 2);
set_clear_csr!(
///Timer Interrupt
, set_tip, clear_tip, 1 << 6);
set_clear_csr!(
///External Interrupt
, set_eip, clear_eip, 1 << 10);
// enums

View File

@@ -0,0 +1,77 @@
//! Hypervisor Interrupt Enable Register.
use bit_field::BitField;
#[derive(Copy, Clone, Debug)]
pub struct Hie {
bits: usize,
}
impl Hie {
#[inline]
pub fn bits(&self) -> usize {
return self.bits;
}
#[inline]
pub fn from_bits(x: usize) -> Self {
return Hie { bits: x };
}
#[inline]
pub unsafe fn write(&self) {
_write(self.bits);
}
/// Software Interrupt
#[inline]
pub fn vssie(&self) -> bool {
self.bits.get_bit(2)
}
#[inline]
pub fn set_vssie(&mut self, val: bool) {
self.bits.set_bit(2, val);
}
/// Timer Interrupt
#[inline]
pub fn vstie(&self) -> bool {
self.bits.get_bit(6)
}
#[inline]
pub fn set_vstie(&mut self, val: bool) {
self.bits.set_bit(6, val);
}
/// External Interrupt
#[inline]
pub fn vseie(&self) -> bool {
self.bits.get_bit(10)
}
#[inline]
pub fn set_vseie(&mut self, val: bool) {
self.bits.set_bit(10, val);
}
/// Guest External Interrupt
#[inline]
pub fn sgeie(&self) -> bool {
self.bits.get_bit(12)
}
#[inline]
pub fn set_sgeie(&mut self, val: bool) {
self.bits.set_bit(12, val);
}
}
read_csr_as!(Hie, 1540, __read_hie);
write_csr!(1540, __write_hie);
set!(1540, __set_hie);
clear!(1540, __clear_hie);
// bit ops
set_clear_csr!(
///Software Interrupt
, set_vssie, clear_vssie, 1 << 2);
set_clear_csr!(
///Timer Interrupt
, set_vstie, clear_vstie, 1 << 6);
set_clear_csr!(
///External Interrupt
, set_vseie, clear_vseie, 1 << 10);
set_clear_csr!(
///Guest External Interrupt
, set_sgeie, clear_sgeie, 1 << 12);
// enums

View File

@@ -0,0 +1,77 @@
//! Hypervisor Interrupt Pending Register.
use bit_field::BitField;
#[derive(Copy, Clone, Debug)]
pub struct Hip {
bits: usize,
}
impl Hip {
#[inline]
pub fn bits(&self) -> usize {
return self.bits;
}
#[inline]
pub fn from_bits(x: usize) -> Self {
return Hip { bits: x };
}
#[inline]
pub unsafe fn write(&self) {
_write(self.bits);
}
/// Software Interrupt
#[inline]
pub fn vssip(&self) -> bool {
self.bits.get_bit(2)
}
#[inline]
pub fn set_vssip(&mut self, val: bool) {
self.bits.set_bit(2, val);
}
/// Timer Interrupt
#[inline]
pub fn vstip(&self) -> bool {
self.bits.get_bit(6)
}
#[inline]
pub fn set_vstip(&mut self, val: bool) {
self.bits.set_bit(6, val);
}
/// External Interrupt
#[inline]
pub fn vseip(&self) -> bool {
self.bits.get_bit(10)
}
#[inline]
pub fn set_vseip(&mut self, val: bool) {
self.bits.set_bit(10, val);
}
/// Guest External Interrupt
#[inline]
pub fn sgeip(&self) -> bool {
self.bits.get_bit(12)
}
#[inline]
pub fn set_sgeip(&mut self, val: bool) {
self.bits.set_bit(12, val);
}
}
read_csr_as!(Hip, 1604, __read_hip);
write_csr!(1604, __write_hip);
set!(1604, __set_hip);
clear!(1604, __clear_hip);
// bit ops
set_clear_csr!(
///Software Interrupt
, set_vssip, clear_vssip, 1 << 2);
set_clear_csr!(
///Timer Interrupt
, set_vstip, clear_vstip, 1 << 6);
set_clear_csr!(
///External Interrupt
, set_vseip, clear_vseip, 1 << 10);
set_clear_csr!(
///Guest External Interrupt
, set_sgeip, clear_sgeip, 1 << 12);
// enums

View File

@@ -0,0 +1,160 @@
//! HStatus Register.
use bit_field::BitField;
#[derive(Copy, Clone, Debug)]
pub struct Hstatus {
bits: usize,
}
impl Hstatus {
#[inline]
pub fn bits(&self) -> usize {
return self.bits;
}
#[inline]
pub fn from_bits(x: usize) -> Self {
return Hstatus { bits: x };
}
#[inline]
pub unsafe fn write(&self) {
_write(self.bits);
}
/// Effective XLEN for VM.
#[inline]
pub fn vsxl(&self) -> VsxlValues {
VsxlValues::from(self.bits.get_bits(32..34))
}
#[inline]
pub fn set_vsxl(&mut self, val: VsxlValues) {
self.bits.set_bits(32..34, val as usize);
}
/// TSR for VM.
#[inline]
pub fn vtsr(&self) -> bool {
self.bits.get_bit(22)
}
#[inline]
pub fn set_vtsr(&mut self, val: bool) {
self.bits.set_bit(22, val);
}
/// TW for VM.
#[inline]
pub fn vtw(&self) -> bool {
self.bits.get_bit(21)
}
#[inline]
pub fn set_vtw(&mut self, val: bool) {
self.bits.set_bit(21, val);
}
/// TVM for VM.
#[inline]
pub fn vtvm(&self) -> bool {
self.bits.get_bit(20)
}
#[inline]
pub fn set_vtvm(&mut self, val: bool) {
self.bits.set_bit(20, val);
}
/// Virtual Guest External Interrupt Number.
#[inline]
pub fn vgein(&self) -> usize {
self.bits.get_bits(12..18)
}
#[inline]
pub fn set_vgein(&mut self, val: usize) {
self.bits.set_bits(12..18, val);
}
/// Hypervisor User mode.
#[inline]
pub fn hu(&self) -> bool {
self.bits.get_bit(9)
}
#[inline]
pub fn set_hu(&mut self, val: bool) {
self.bits.set_bit(9, val);
}
/// Supervisor Previous Virtual Privilege.
#[inline]
pub fn spvp(&self) -> bool {
self.bits.get_bit(8)
}
#[inline]
pub fn set_spvp(&mut self, val: bool) {
self.bits.set_bit(8, val);
}
/// Supervisor Previous Virtualization mode.
#[inline]
pub fn spv(&self) -> bool {
self.bits.get_bit(7)
}
#[inline]
pub fn set_spv(&mut self, val: bool) {
self.bits.set_bit(7, val);
}
/// Guest Virtual Address.
#[inline]
pub fn gva(&self) -> bool {
self.bits.get_bit(6)
}
#[inline]
pub fn set_gva(&mut self, val: bool) {
self.bits.set_bit(6, val);
}
/// VS access endianness.
#[inline]
pub fn vsbe(&self) -> bool {
self.bits.get_bit(5)
}
#[inline]
pub fn set_vsbe(&mut self, val: bool) {
self.bits.set_bit(5, val);
}
}
read_csr_as!(Hstatus, 1536, __read_hstatus);
write_csr!(1536, __write_hstatus);
set!(1536, __set_hstatus);
clear!(1536, __clear_hstatus);
// bit ops
set_clear_csr!(
///TSR for VM.
, set_vtsr, clear_vtsr, 1 << 22);
set_clear_csr!(
///TW for VM.
, set_vtw, clear_vtw, 1 << 21);
set_clear_csr!(
///TVM for VM.
, set_vtvm, clear_vtvm, 1 << 20);
set_clear_csr!(
///Hypervisor User mode.
, set_hu, clear_hu, 1 << 9);
set_clear_csr!(
///Supervisor Previous Virtual Privilege.
, set_spvp, clear_spvp, 1 << 8);
set_clear_csr!(
///Supervisor Previous Virtualization mode.
, set_spv, clear_spv, 1 << 7);
set_clear_csr!(
///Guest Virtual Address.
, set_gva, clear_gva, 1 << 6);
set_clear_csr!(
///VS access endianness.
, set_vsbe, clear_vsbe, 1 << 5);
// enums
#[derive(Copy, Clone, Debug)]
#[repr(usize)]
pub enum VsxlValues {
Vsxl32 = 1,
Vsxl64 = 2,
Vsxl128 = 3,
}
impl VsxlValues {
fn from(x: usize) -> Self {
match x {
1 => Self::Vsxl32,
2 => Self::Vsxl64,
3 => Self::Vsxl128,
_ => unreachable!(),
}
}
}

View File

@@ -0,0 +1,4 @@
//! Hypervisor Time Delta Register.
read_composite_csr!(super::htimedeltah::read(), read());
read_csr_as_usize!(1541, __read_htimedelta);
write_csr_as_usize!(1541, __write_htimedelta);

View File

@@ -0,0 +1,3 @@
//! Hypervisor Time Delta Register.
read_csr_as_usize!(1557, __read_htimedeltah);
write_csr_as_usize!(1557, __write_htimedeltah);

View File

@@ -0,0 +1,3 @@
//! Hypervisor Trap Instruction Register.
read_csr_as_usize!(1610, __read_htinst);
write_csr_as_usize!(1610, __write_htinst);

View File

@@ -0,0 +1,3 @@
//! Hypervisor Trap Value Register.
read_csr_as_usize!(1603, __read_htval);
write_csr_as_usize!(1603, __write_htval);

View File

@@ -0,0 +1,65 @@
//! Hypervisor Virtual Interrupt Pending Register.
use bit_field::BitField;
#[derive(Copy, Clone, Debug)]
pub struct Hvip {
bits: usize,
}
impl Hvip {
#[inline]
pub fn bits(&self) -> usize {
return self.bits;
}
#[inline]
pub fn from_bits(x: usize) -> Self {
return Hvip { bits: x };
}
#[inline]
pub unsafe fn write(&self) {
_write(self.bits);
}
/// Software Interrupt
#[inline]
pub fn vssip(&self) -> bool {
self.bits.get_bit(2)
}
#[inline]
pub fn set_vssip(&mut self, val: bool) {
self.bits.set_bit(2, val);
}
/// Timer Interrupt
#[inline]
pub fn vstip(&self) -> bool {
self.bits.get_bit(6)
}
#[inline]
pub fn set_vstip(&mut self, val: bool) {
self.bits.set_bit(6, val);
}
/// External Interrupt
#[inline]
pub fn vseip(&self) -> bool {
self.bits.get_bit(10)
}
#[inline]
pub fn set_vseip(&mut self, val: bool) {
self.bits.set_bit(10, val);
}
}
read_csr_as!(Hvip, 1605, __read_hvip);
write_csr!(1605, __write_hvip);
set!(1605, __set_hvip);
clear!(1605, __clear_hvip);
// bit ops
set_clear_csr!(
///Software Interrupt
, set_vssip, clear_vssip, 1 << 2);
set_clear_csr!(
///Timer Interrupt
, set_vstip, clear_vstip, 1 << 6);
set_clear_csr!(
///External Interrupt
, set_vseip, clear_vseip, 1 << 10);
// enums

View File

@@ -0,0 +1,23 @@
pub mod hcounteren;
pub mod hedeleg;
pub mod hgatp;
pub mod hgeie;
pub mod hgeip;
pub mod hideleg;
pub mod hie;
pub mod hip;
pub mod hstatus;
pub mod htimedelta;
pub mod htimedeltah;
pub mod htinst;
pub mod htval;
pub mod hvip;
pub mod vsatp;
pub mod vscause;
pub mod vsepc;
pub mod vsie;
pub mod vsip;
pub mod vsscratch;
pub mod vsstatus;
pub mod vstval;
pub mod vstvec;

View File

@@ -0,0 +1,73 @@
//! Virtual Supervisor Guest Address Translation and Protection Register.
use bit_field::BitField;
#[derive(Copy, Clone, Debug)]
pub struct Vsatp {
bits: usize,
}
impl Vsatp {
#[inline]
pub fn bits(&self) -> usize {
return self.bits;
}
#[inline]
pub fn from_bits(x: usize) -> Self {
return Vsatp { bits: x };
}
#[inline]
pub unsafe fn write(&self) {
_write(self.bits);
}
/// Guest address translation mode.
#[inline]
pub fn mode(&self) -> HgatpValues {
HgatpValues::from(self.bits.get_bits(60..64))
}
#[inline]
pub fn set_mode(&mut self, val: HgatpValues) {
self.bits.set_bits(60..64, val as usize);
}
/// ASID.
#[inline]
pub fn asid(&self) -> usize {
self.bits.get_bits(44..60)
}
#[inline]
pub fn set_asid(&mut self, val: usize) {
self.bits.set_bits(44..60, val);
}
/// Physical Page Number for root page table.
#[inline]
pub fn ppn(&self) -> usize {
self.bits.get_bits(0..44)
}
#[inline]
pub fn set_ppn(&mut self, val: usize) {
self.bits.set_bits(0..44, val);
}
}
read_csr_as!(Vsatp, 640, __read_vsatp);
write_csr!(640, __write_vsatp);
set!(640, __set_vsatp);
clear!(640, __clear_vsatp);
// bit ops
// enums
#[derive(Copy, Clone, Debug)]
#[repr(usize)]
pub enum HgatpValues {
Bare = 0,
Sv39x4 = 8,
Sv48x4 = 9,
}
impl HgatpValues {
fn from(x: usize) -> Self {
match x {
0 => Self::Bare,
8 => Self::Sv39x4,
9 => Self::Sv48x4,
_ => unreachable!(),
}
}
}

View File

@@ -0,0 +1,50 @@
//! Virtual Supervisor Cause Register.
use bit_field::BitField;
#[derive(Copy, Clone, Debug)]
pub struct Vscause {
bits: usize,
}
impl Vscause {
#[inline]
pub fn bits(&self) -> usize {
return self.bits;
}
#[inline]
pub fn from_bits(x: usize) -> Self {
return Vscause { bits: x };
}
#[inline]
pub unsafe fn write(&self) {
_write(self.bits);
}
/// Is cause interrupt.
#[inline]
pub fn interrupt(&self) -> bool {
self.bits.get_bit(63)
}
#[inline]
pub fn set_interrupt(&mut self, val: bool) {
self.bits.set_bit(63, val);
}
/// Exception code
#[inline]
pub fn code(&self) -> usize {
self.bits.get_bits(0..63)
}
#[inline]
pub fn set_code(&mut self, val: usize) {
self.bits.set_bits(0..63, val);
}
}
read_csr_as!(Vscause, 578, __read_vscause);
write_csr!(578, __write_vscause);
set!(578, __set_vscause);
clear!(578, __clear_vscause);
// bit ops
set_clear_csr!(
///Is cause interrupt.
, set_interrupt, clear_interrupt, 1 << 63);
// enums

Some files were not shown because too many files have changed in this diff Show More