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rmO!S<3+S~|93eoRWs9nc
z$|(6pNeIXul_ZmN3rPV@X@(XHj94;N7L+zcXiOXxY?dJ;OyC!*h+rQH&00jSXe-jR
z7!!m>MoPg%`;?~FUt_5P)4>BQB`}%uobPOUe`tB_(%W_vJvvk1{+&&qdyHRSH2m4e
z>|Z^W`_j}skMo?UrKkt0I
zH}}nDqPJ-5GjILxQ~Qtq>Am-S55Lp%RMAu*+Se;W|;H59=v^TVJY)gL|$JU9')
+ 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
diff --git a/ci-user/check/ch1.py b/ci-user/check/ch1.py
new file mode 100644
index 0000000..5fda5dc
--- /dev/null
+++ b/ci-user/check/ch1.py
@@ -0,0 +1,14 @@
+import base
+
+EXPECTED = [
+ "Hello, world!",
+]
+
+TEMP = []
+
+NOT_EXPECTED = [
+ "FAIL: T.T",
+]
+
+if __name__ == "__main__":
+ base.test(EXPECTED + TEMP, NOT_EXPECTED)
\ No newline at end of file
diff --git a/ci-user/check/ch2.py b/ci-user/check/ch2.py
new file mode 100644
index 0000000..0682b39
--- /dev/null
+++ b/ci-user/check/ch2.py
@@ -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)
diff --git a/ci-user/check/ch3.py b/ci-user/check/ch3.py
new file mode 100644
index 0000000..98ce1b3
--- /dev/null
+++ b/ci-user/check/ch3.py
@@ -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)
diff --git a/ci-user/check/ch4.py b/ci-user/check/ch4.py
new file mode 100644
index 0000000..423841d
--- /dev/null
+++ b/ci-user/check/ch4.py
@@ -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)
diff --git a/ci-user/check/ch5.py b/ci-user/check/ch5.py
new file mode 100644
index 0000000..e37fc6d
--- /dev/null
+++ b/ci-user/check/ch5.py
@@ -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)
diff --git a/ci-user/check/ch5_1.py b/ci-user/check/ch5_1.py
new file mode 100644
index 0000000..34149e8
--- /dev/null
+++ b/ci-user/check/ch5_1.py
@@ -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
\ No newline at end of file
diff --git a/ci-user/check/ch6.py b/ci-user/check/ch6.py
new file mode 100644
index 0000000..745cebc
--- /dev/null
+++ b/ci-user/check/ch6.py
@@ -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)
diff --git a/ci-user/check/ch7.py b/ci-user/check/ch7.py
new file mode 100644
index 0000000..99baed8
--- /dev/null
+++ b/ci-user/check/ch7.py
@@ -0,0 +1,4 @@
+import base
+
+if __name__ == '__main__':
+ base.test([], [])
diff --git a/ci-user/check/ch8.py b/ci-user/check/ch8.py
new file mode 100644
index 0000000..e0f41b0
--- /dev/null
+++ b/ci-user/check/ch8.py
@@ -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)
diff --git a/ci-user/overwrite.py b/ci-user/overwrite.py
new file mode 100644
index 0000000..cbb7412
--- /dev/null
+++ b/ci-user/overwrite.py
@@ -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)
diff --git a/ci-user/overwrite/Makefile-ch2 b/ci-user/overwrite/Makefile-ch2
new file mode 100644
index 0000000..7bc97b0
--- /dev/null
+++ b/ci-user/overwrite/Makefile-ch2
@@ -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
diff --git a/ci-user/overwrite/Makefile-ch3 b/ci-user/overwrite/Makefile-ch3
new file mode 100644
index 0000000..68f6427
--- /dev/null
+++ b/ci-user/overwrite/Makefile-ch3
@@ -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
diff --git a/ci-user/overwrite/Makefile-ch6 b/ci-user/overwrite/Makefile-ch6
new file mode 100644
index 0000000..49d2466
--- /dev/null
+++ b/ci-user/overwrite/Makefile-ch6
@@ -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
diff --git a/ci-user/overwrite/build-bin.rs b/ci-user/overwrite/build-bin.rs
new file mode 100644
index 0000000..6c341c6
--- /dev/null
+++ b/ci-user/overwrite/build-bin.rs
@@ -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(())
+}
diff --git a/ci-user/overwrite/build-elf.rs b/ci-user/overwrite/build-elf.rs
new file mode 100644
index 0000000..2eac708
--- /dev/null
+++ b/ci-user/overwrite/build-elf.rs
@@ -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(())
+}
diff --git a/ci-user/overwrite/easy-fs-fuse-ch7.rs b/ci-user/overwrite/easy-fs-fuse-ch7.rs
new file mode 100644
index 0000000..800ff5a
--- /dev/null
+++ b/ci-user/overwrite/easy-fs-fuse-ch7.rs
@@ -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);
+
+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 = 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(())
+}
diff --git a/ci-user/overwrite/easy-fs-fuse.rs b/ci-user/overwrite/easy-fs-fuse.rs
new file mode 100644
index 0000000..4b5abec
--- /dev/null
+++ b/ci-user/overwrite/easy-fs-fuse.rs
@@ -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);
+
+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 = 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(())
+}
diff --git a/ci-user/riscv/.gitignore b/ci-user/riscv/.gitignore
new file mode 100644
index 0000000..e38997a
--- /dev/null
+++ b/ci-user/riscv/.gitignore
@@ -0,0 +1,5 @@
+Cargo.lock
+target/
+bin/*.after
+bin/*.before
+bin/*.o
diff --git a/ci-user/riscv/.travis.yml b/ci-user/riscv/.travis.yml
new file mode 100644
index 0000000..b70d20a
--- /dev/null
+++ b/ci-user/riscv/.travis.yml
@@ -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
diff --git a/ci-user/riscv/CHANGELOG.md b/ci-user/riscv/CHANGELOG.md
new file mode 100644
index 0000000..e4d7b23
--- /dev/null
+++ b/ci-user/riscv/CHANGELOG.md
@@ -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` (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
diff --git a/ci-user/riscv/CODE_OF_CONDUCT.md b/ci-user/riscv/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000..fccadf9
--- /dev/null
+++ b/ci-user/riscv/CODE_OF_CONDUCT.md
@@ -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
diff --git a/ci-user/riscv/Cargo.toml b/ci-user/riscv/Cargo.toml
new file mode 100644
index 0000000..4e23193
--- /dev/null
+++ b/ci-user/riscv/Cargo.toml
@@ -0,0 +1,21 @@
+[package]
+name = "riscv"
+version = "0.6.0"
+repository = "https://github.com/rust-embedded/riscv"
+authors = ["The RISC-V Team "]
+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 = []
diff --git a/ci-user/riscv/README.md b/ci-user/riscv/README.md
new file mode 100644
index 0000000..98c7a42
--- /dev/null
+++ b/ci-user/riscv/README.md
@@ -0,0 +1,41 @@
+[](https://crates.io/crates/riscv)
+[](https://crates.io/crates/riscv)
+[](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
diff --git a/ci-user/riscv/asm.S b/ci-user/riscv/asm.S
new file mode 100644
index 0000000..9ae7aaa
--- /dev/null
+++ b/ci-user/riscv/asm.S
@@ -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
diff --git a/ci-user/riscv/asm.h b/ci-user/riscv/asm.h
new file mode 100644
index 0000000..2b675e7
--- /dev/null
+++ b/ci-user/riscv/asm.h
@@ -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 */
+
diff --git a/ci-user/riscv/assemble.ps1 b/ci-user/riscv/assemble.ps1
new file mode 100644
index 0000000..1bfc265
--- /dev/null
+++ b/ci-user/riscv/assemble.ps1
@@ -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
diff --git a/ci-user/riscv/assemble.sh b/ci-user/riscv/assemble.sh
new file mode 100755
index 0000000..217131d
--- /dev/null
+++ b/ci-user/riscv/assemble.sh
@@ -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
diff --git a/ci-user/riscv/build.rs b/ci-user/riscv/build.rs
new file mode 100644
index 0000000..d1c3328
--- /dev/null
+++ b/ci-user/riscv/build.rs
@@ -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");
+ }
+}
diff --git a/ci-user/riscv/check-blobs.sh b/ci-user/riscv/check-blobs.sh
new file mode 100755
index 0000000..36d885e
--- /dev/null
+++ b/ci-user/riscv/check-blobs.sh
@@ -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
diff --git a/ci-user/riscv/descriptor/generate_hypervisor_csr.sh b/ci-user/riscv/descriptor/generate_hypervisor_csr.sh
new file mode 100755
index 0000000..d6e009a
--- /dev/null
+++ b/ci-user/riscv/descriptor/generate_hypervisor_csr.sh
@@ -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
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/generator.rs b/ci-user/riscv/descriptor/generator.rs
new file mode 100644
index 0000000..f984403
--- /dev/null
+++ b/ci-user/riscv/descriptor/generator.rs
@@ -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::().unwrap();
+ let lo = parts.next().unwrap().parse::().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 {
+ 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>,
+}
+
+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::().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());
+}
diff --git a/ci-user/riscv/descriptor/hcounteren.txt b/ci-user/riscv/descriptor/hcounteren.txt
new file mode 100644
index 0000000..2df37ba
--- /dev/null
+++ b/ci-user/riscv/descriptor/hcounteren.txt
@@ -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.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/hedeleg.txt b/ci-user/riscv/descriptor/hedeleg.txt
new file mode 100644
index 0000000..988f5f9
--- /dev/null
+++ b/ci-user/riscv/descriptor/hedeleg.txt
@@ -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.
diff --git a/ci-user/riscv/descriptor/hgatp.txt b/ci-user/riscv/descriptor/hgatp.txt
new file mode 100644
index 0000000..3763903
--- /dev/null
+++ b/ci-user/riscv/descriptor/hgatp.txt
@@ -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.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/hgeie.txt b/ci-user/riscv/descriptor/hgeie.txt
new file mode 100644
index 0000000..c5af3c0
--- /dev/null
+++ b/ci-user/riscv/descriptor/hgeie.txt
@@ -0,0 +1,4 @@
+Hgeie
+1543
+end
+Hypervisor Guest External Interrupt Enable Register.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/hgeip.txt b/ci-user/riscv/descriptor/hgeip.txt
new file mode 100644
index 0000000..3b354d2
--- /dev/null
+++ b/ci-user/riscv/descriptor/hgeip.txt
@@ -0,0 +1,4 @@
+Hgeip
+3602
+end
+Hypervisor Guest External Interrupt Pending Register.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/hideleg.txt b/ci-user/riscv/descriptor/hideleg.txt
new file mode 100644
index 0000000..ea8f5ea
--- /dev/null
+++ b/ci-user/riscv/descriptor/hideleg.txt
@@ -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.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/hie.txt b/ci-user/riscv/descriptor/hie.txt
new file mode 100644
index 0000000..f67ffc6
--- /dev/null
+++ b/ci-user/riscv/descriptor/hie.txt
@@ -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.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/hip.txt b/ci-user/riscv/descriptor/hip.txt
new file mode 100644
index 0000000..e067ef1
--- /dev/null
+++ b/ci-user/riscv/descriptor/hip.txt
@@ -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.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/hstatus.txt b/ci-user/riscv/descriptor/hstatus.txt
new file mode 100644
index 0000000..11ee985
--- /dev/null
+++ b/ci-user/riscv/descriptor/hstatus.txt
@@ -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.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/htimedelta.txt b/ci-user/riscv/descriptor/htimedelta.txt
new file mode 100644
index 0000000..d850625
--- /dev/null
+++ b/ci-user/riscv/descriptor/htimedelta.txt
@@ -0,0 +1,5 @@
+Htimedelta
+1541
+end
+Hypervisor Time Delta Register.
+read_composite_csr!(super::htimedeltah::read(), read());
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/htimedeltah.txt b/ci-user/riscv/descriptor/htimedeltah.txt
new file mode 100644
index 0000000..1b6147f
--- /dev/null
+++ b/ci-user/riscv/descriptor/htimedeltah.txt
@@ -0,0 +1,4 @@
+Htimedeltah
+1557
+end
+Hypervisor Time Delta Register.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/htinst.txt b/ci-user/riscv/descriptor/htinst.txt
new file mode 100644
index 0000000..b3efc33
--- /dev/null
+++ b/ci-user/riscv/descriptor/htinst.txt
@@ -0,0 +1,4 @@
+Htinst
+1610
+end
+Hypervisor Trap Instruction Register.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/htval.txt b/ci-user/riscv/descriptor/htval.txt
new file mode 100644
index 0000000..eec176f
--- /dev/null
+++ b/ci-user/riscv/descriptor/htval.txt
@@ -0,0 +1,4 @@
+Htval
+1603
+end
+Hypervisor Trap Value Register.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/hvip.txt b/ci-user/riscv/descriptor/hvip.txt
new file mode 100644
index 0000000..5f8dfbe
--- /dev/null
+++ b/ci-user/riscv/descriptor/hvip.txt
@@ -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.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/vsatp.txt b/ci-user/riscv/descriptor/vsatp.txt
new file mode 100644
index 0000000..789ecfb
--- /dev/null
+++ b/ci-user/riscv/descriptor/vsatp.txt
@@ -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.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/vscause.txt b/ci-user/riscv/descriptor/vscause.txt
new file mode 100644
index 0000000..fabf4b4
--- /dev/null
+++ b/ci-user/riscv/descriptor/vscause.txt
@@ -0,0 +1,6 @@
+Vscause
+578
+interrupt,63,63,number,Is cause interrupt.
+code,62,0,number,Exception code
+end
+Virtual Supervisor Cause Register.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/vsepc.txt b/ci-user/riscv/descriptor/vsepc.txt
new file mode 100644
index 0000000..c1db586
--- /dev/null
+++ b/ci-user/riscv/descriptor/vsepc.txt
@@ -0,0 +1,4 @@
+Vsepc
+577
+end
+Virtual Supervisor Exception Program Counter.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/vsie.txt b/ci-user/riscv/descriptor/vsie.txt
new file mode 100644
index 0000000..b3dfaae
--- /dev/null
+++ b/ci-user/riscv/descriptor/vsie.txt
@@ -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.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/vsip.txt b/ci-user/riscv/descriptor/vsip.txt
new file mode 100644
index 0000000..14d7245
--- /dev/null
+++ b/ci-user/riscv/descriptor/vsip.txt
@@ -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.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/vsscratch.txt b/ci-user/riscv/descriptor/vsscratch.txt
new file mode 100644
index 0000000..9f1f5ae
--- /dev/null
+++ b/ci-user/riscv/descriptor/vsscratch.txt
@@ -0,0 +1,4 @@
+Vsscratch
+576
+end
+Virtual Supervisor Scratch Register.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/vsstatus.txt b/ci-user/riscv/descriptor/vsstatus.txt
new file mode 100644
index 0000000..02577f1
--- /dev/null
+++ b/ci-user/riscv/descriptor/vsstatus.txt
@@ -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.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/vstval.txt b/ci-user/riscv/descriptor/vstval.txt
new file mode 100644
index 0000000..c3a9e46
--- /dev/null
+++ b/ci-user/riscv/descriptor/vstval.txt
@@ -0,0 +1,4 @@
+Vstval
+579
+end
+Virtual Supervisor Trap Value Register.
\ No newline at end of file
diff --git a/ci-user/riscv/descriptor/vstvec.txt b/ci-user/riscv/descriptor/vstvec.txt
new file mode 100644
index 0000000..c2c4a57
--- /dev/null
+++ b/ci-user/riscv/descriptor/vstvec.txt
@@ -0,0 +1,6 @@
+Vstvec
+517
+base,63,2,number,
+mode,1,0,number,
+end
+Virtual Supervisor Trap Vector Base Address Register.
\ No newline at end of file
diff --git a/ci-user/riscv/src/addr/gpax4.rs b/ci-user/riscv/src/addr/gpax4.rs
new file mode 100644
index 0000000..c7bc734
--- /dev/null
+++ b/ci-user/riscv/src/addr/gpax4.rs
@@ -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
+ }
+}
diff --git a/ci-user/riscv/src/addr/mod.rs b/ci-user/riscv/src/addr/mod.rs
new file mode 100644
index 0000000..9b33ce8
--- /dev/null
+++ b/ci-user/riscv/src/addr/mod.rs
@@ -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;
+ pub type Frame = FrameWith;
+ };
+}
+#[macro_export]
+macro_rules! use_sv39 {
+ () => {
+ pub type VirtAddr = VirtAddrSv39;
+ pub type PhysAddr = PhysAddrSv39;
+ pub type Page = PageWith;
+ pub type Frame = FrameWith;
+ };
+}
+#[macro_export]
+macro_rules! use_sv48 {
+ () => {
+ pub type VirtAddr = VirtAddrSv48;
+ pub type PhysAddr = PhysAddrSv48;
+ pub type Page = PageWith;
+ pub type Frame = FrameWith;
+ };
+}
+#[cfg(target_arch = "riscv64")]
+use_sv48!();
+
+#[cfg(target_arch = "riscv32")]
+use_sv32!();
diff --git a/ci-user/riscv/src/addr/page.rs b/ci-user/riscv/src/addr/page.rs
new file mode 100644
index 0000000..2c36f9b
--- /dev/null
+++ b/ci-user/riscv/src/addr/page.rs
@@ -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);
+
+impl PageWithL4 for PageWith {
+ 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 PageWithL3 for PageWith {
+ 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 PageWithL2 for PageWith {
+ 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 PageWith {
+ 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);
+
+impl PageWithL4 for FrameWith {
+ 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 PageWithL3 for FrameWith {
+ 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 PageWithL2 for FrameWith {
+ 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 FrameWith {
+ 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)
+ }
+}
diff --git a/ci-user/riscv/src/addr/sv32.rs b/ci-user/riscv/src/addr/sv32.rs
new file mode 100644
index 0000000..193b7f6
--- /dev/null
+++ b/ci-user/riscv/src/addr/sv32.rs
@@ -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 {}
diff --git a/ci-user/riscv/src/addr/sv39.rs b/ci-user/riscv/src/addr/sv39.rs
new file mode 100644
index 0000000..b059192
--- /dev/null
+++ b/ci-user/riscv/src/addr/sv39.rs
@@ -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 {}
diff --git a/ci-user/riscv/src/addr/sv48.rs b/ci-user/riscv/src/addr/sv48.rs
new file mode 100644
index 0000000..880bd3e
--- /dev/null
+++ b/ci-user/riscv/src/addr/sv48.rs
@@ -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 {}
diff --git a/ci-user/riscv/src/asm.rs b/ci-user/riscv/src/asm.rs
new file mode 100644
index 0000000..fe1ad56
--- /dev/null
+++ b/ci-user/riscv/src/asm.rs
@@ -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::*;
diff --git a/ci-user/riscv/src/interrupt.rs b/ci-user/riscv/src/interrupt.rs
new file mode 100644
index 0000000..9b8598d
--- /dev/null
+++ b/ci-user/riscv/src/interrupt.rs
@@ -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: 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
+}
diff --git a/ci-user/riscv/src/lib.rs b/ci-user/riscv/src/lib.rs
new file mode 100644
index 0000000..4f2ec2e
--- /dev/null
+++ b/ci-user/riscv/src/lib.rs
@@ -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;
diff --git a/ci-user/riscv/src/paging/frame_alloc.rs b/ci-user/riscv/src/paging/frame_alloc.rs
new file mode 100644
index 0000000..89b4ada
--- /dev/null
+++ b/ci-user/riscv/src/paging/frame_alloc.rs
@@ -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 {
+ /// Allocate a frame of the appropriate size and return it if possible.
+ fn alloc(&mut self) -> Option>;
+}
+
+/// A trait for types that can deallocate a frame of memory.
+pub trait FrameDeallocatorFor {
+ /// Deallocate the given frame of memory.
+ fn dealloc(&mut self, frame: FrameWith);
+}
+
+/// Polyfill for default use cases.
+
+#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
+pub trait FrameAllocator {
+ fn alloc(&mut self) -> Option;
+}
+#[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 FrameAllocatorFor for T {
+ #[inline]
+ fn alloc(&mut self) -> Option {
+ FrameAllocator::alloc(self)
+ }
+}
+#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
+impl FrameDeallocatorFor for T {
+ #[inline]
+ fn dealloc(&mut self, frame: Frame) {
+ FrameDeallocator::dealloc(self, frame)
+ }
+}
diff --git a/ci-user/riscv/src/paging/mapper.rs b/ci-user/riscv/src/paging/mapper.rs
new file mode 100644
index 0000000..6e47730
--- /dev/null
+++ b/ci-user/riscv/src/paging/mapper.rs
@@ -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,
+ frame: FrameWith,
+ flags: PageTableFlags,
+ allocator: &mut impl FrameAllocatorFor<::P>,
+ ) -> Result;
+
+ /// 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,
+ ) -> Result<(FrameWith, Self::MapperFlush), UnmapError<::P>>;
+
+ /// Get the reference of the specified `page` entry
+ fn ref_entry(&mut self, page: PageWith) -> Result<&mut Self::Entry, FlagUpdateError>;
+
+ /// Updates the flags of an existing mapping.
+ fn update_flags(
+ &mut self,
+ page: PageWith,
+ flags: PageTableFlags,
+ ) -> Result {
+ self.ref_entry(page).map(|e| {
+ e.set(e.frame::(), flags);
+ Self::MapperFlush::new(page)
+ })
+ }
+
+ /// Return the frame that the specified page is mapped to.
+ fn translate_page(&mut self, page: PageWith) -> Option> {
+ 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,
+ flags: PageTableFlags,
+ allocator: &mut impl FrameAllocatorFor<::P>,
+ ) -> Result {
+ 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(page: PageWith) -> 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(page: PageWith) -> 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 {
+ /// 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 MapperExt for T {
+ type Page = PageWith<::V>;
+ type Frame = FrameWith<::P>;
+}
diff --git a/ci-user/riscv/src/paging/mod.rs b/ci-user/riscv/src/paging/mod.rs
new file mode 100644
index 0000000..7df9b06
--- /dev/null
+++ b/ci-user/riscv/src/paging/mod.rs
@@ -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::*;
diff --git a/ci-user/riscv/src/paging/multi_level.rs b/ci-user/riscv/src/paging/multi_level.rs
new file mode 100644
index 0000000..ae1a114
--- /dev/null
+++ b/ci-user/riscv/src/paging/multi_level.rs
@@ -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<::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::();
+ 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: ::Page,
+ frame: ::Frame,
+ flags: PageTableFlags,
+ allocator: &mut impl FrameAllocatorFor<::P>,
+ ) -> Result {
+ 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: ::Page,
+ ) -> Result<(::Frame, Self::MapperFlush), UnmapError<::P>>
+ {
+ if self.root_table[page.p2_index()].is_unused() {
+ return Err(UnmapError::PageNotMapped);
+ }
+ let p1_frame = self.root_table[page.p2_index()].frame::();
+ 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: ::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::();
+ 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<::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::();
+ 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::();
+ 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: ::Page,
+ frame: ::Frame,
+ flags: PageTableFlags,
+ allocator: &mut impl FrameAllocatorFor<::P>,
+ ) -> Result {
+ 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: ::Page,
+ ) -> Result<(::Frame, Self::MapperFlush), UnmapError<::P>>
+ {
+ if self.root_table[page.p3_index()].is_unused() {
+ return Err(UnmapError::PageNotMapped);
+ }
+ let p2_frame = self.root_table[page.p3_index()].frame::();
+ 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::();
+ 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: ::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::();
+ 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::();
+ 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<::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::();
+ 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::();
+ 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::();
+ 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: ::Page,
+ frame: ::Frame,
+ flags: PageTableFlags,
+ allocator: &mut impl FrameAllocatorFor<::P>,
+ ) -> Result {
+ 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: