From 93e6ee55ecd0dfa54553913f0319a2b9e1e600fd Mon Sep 17 00:00:00 2001 From: Yu Chen Date: Tue, 28 Jun 2022 09:27:28 +0800 Subject: [PATCH] add ci contents --- ci-user/.gitignore | 6 + ci-user/.gitlab-ci.yml | 61 +++ ci-user/Makefile | 48 ++ ci-user/README.md | 67 +++ ci-user/check/base.py | 46 ++ ci-user/check/ch1.py | 14 + ci-user/check/ch2.py | 17 + ci-user/check/ch3.py | 21 + ci-user/check/ch4.py | 18 + ci-user/check/ch5.py | 22 + ci-user/check/ch5_1.py | 15 + ci-user/check/ch6.py | 20 + ci-user/check/ch7.py | 4 + ci-user/check/ch8.py | 42 ++ ci-user/overwrite.py | 28 ++ ci-user/overwrite/Makefile-ch2 | 24 + ci-user/overwrite/Makefile-ch3 | 24 + ci-user/overwrite/Makefile-ch6 | 31 ++ ci-user/overwrite/build-bin.rs | 56 +++ ci-user/overwrite/build-elf.rs | 56 +++ ci-user/overwrite/easy-fs-fuse-ch7.rs | 82 ++++ ci-user/overwrite/easy-fs-fuse.rs | 82 ++++ ci-user/riscv/.gitignore | 5 + ci-user/riscv/.travis.yml | 51 ++ ci-user/riscv/CHANGELOG.md | 45 ++ ci-user/riscv/CODE_OF_CONDUCT.md | 37 ++ ci-user/riscv/Cargo.toml | 21 + ci-user/riscv/README.md | 41 ++ ci-user/riscv/asm.S | 454 ++++++++++++++++++ ci-user/riscv/asm.h | 48 ++ ci-user/riscv/assemble.ps1 | 20 + ci-user/riscv/assemble.sh | 22 + ci-user/riscv/build.rs | 35 ++ ci-user/riscv/check-blobs.sh | 21 + .../descriptor/generate_hypervisor_csr.sh | 8 + ci-user/riscv/descriptor/generator.rs | 312 ++++++++++++ ci-user/riscv/descriptor/hcounteren.txt | 36 ++ ci-user/riscv/descriptor/hedeleg.txt | 16 + ci-user/riscv/descriptor/hgatp.txt | 7 + ci-user/riscv/descriptor/hgeie.txt | 4 + ci-user/riscv/descriptor/hgeip.txt | 4 + ci-user/riscv/descriptor/hideleg.txt | 7 + ci-user/riscv/descriptor/hie.txt | 8 + ci-user/riscv/descriptor/hip.txt | 8 + ci-user/riscv/descriptor/hstatus.txt | 14 + ci-user/riscv/descriptor/htimedelta.txt | 5 + ci-user/riscv/descriptor/htimedeltah.txt | 4 + ci-user/riscv/descriptor/htinst.txt | 4 + ci-user/riscv/descriptor/htval.txt | 4 + ci-user/riscv/descriptor/hvip.txt | 7 + ci-user/riscv/descriptor/vsatp.txt | 7 + ci-user/riscv/descriptor/vscause.txt | 6 + ci-user/riscv/descriptor/vsepc.txt | 4 + ci-user/riscv/descriptor/vsie.txt | 7 + ci-user/riscv/descriptor/vsip.txt | 7 + ci-user/riscv/descriptor/vsscratch.txt | 4 + ci-user/riscv/descriptor/vsstatus.txt | 14 + ci-user/riscv/descriptor/vstval.txt | 4 + ci-user/riscv/descriptor/vstvec.txt | 6 + ci-user/riscv/src/addr/gpax4.rs | 211 ++++++++ ci-user/riscv/src/addr/mod.rs | 98 ++++ ci-user/riscv/src/addr/page.rs | 174 +++++++ ci-user/riscv/src/addr/sv32.rs | 91 ++++ ci-user/riscv/src/addr/sv39.rs | 115 +++++ ci-user/riscv/src/addr/sv48.rs | 125 +++++ ci-user/riscv/src/asm.rs | 152 ++++++ ci-user/riscv/src/interrupt.rs | 58 +++ ci-user/riscv/src/lib.rs | 27 ++ ci-user/riscv/src/paging/frame_alloc.rs | 40 ++ ci-user/riscv/src/paging/mapper.rs | 136 ++++++ ci-user/riscv/src/paging/mod.rs | 13 + ci-user/riscv/src/paging/multi_level.rs | 354 ++++++++++++++ ci-user/riscv/src/paging/multi_level_x4.rs | 42 ++ ci-user/riscv/src/paging/page_table.rs | 252 ++++++++++ ci-user/riscv/src/paging/page_table_x4.rs | 44 ++ ci-user/riscv/src/register/fcsr.rs | 134 ++++++ ci-user/riscv/src/register/hpmcounterx.rs | 82 ++++ .../src/register/hypervisorx64/hcounteren.rs | 413 ++++++++++++++++ .../src/register/hypervisorx64/hedeleg.rs | 173 +++++++ .../riscv/src/register/hypervisorx64/hgatp.rs | 73 +++ .../riscv/src/register/hypervisorx64/hgeie.rs | 3 + .../riscv/src/register/hypervisorx64/hgeip.rs | 3 + .../src/register/hypervisorx64/hideleg.rs | 65 +++ .../riscv/src/register/hypervisorx64/hie.rs | 77 +++ .../riscv/src/register/hypervisorx64/hip.rs | 77 +++ .../src/register/hypervisorx64/hstatus.rs | 160 ++++++ .../src/register/hypervisorx64/htimedelta.rs | 4 + .../src/register/hypervisorx64/htimedeltah.rs | 3 + .../src/register/hypervisorx64/htinst.rs | 3 + .../riscv/src/register/hypervisorx64/htval.rs | 3 + .../riscv/src/register/hypervisorx64/hvip.rs | 65 +++ .../riscv/src/register/hypervisorx64/mod.rs | 23 + .../riscv/src/register/hypervisorx64/vsatp.rs | 73 +++ .../src/register/hypervisorx64/vscause.rs | 50 ++ .../riscv/src/register/hypervisorx64/vsepc.rs | 3 + .../riscv/src/register/hypervisorx64/vsie.rs | 65 +++ .../riscv/src/register/hypervisorx64/vsip.rs | 65 +++ .../src/register/hypervisorx64/vsscratch.rs | 3 + .../src/register/hypervisorx64/vsstatus.rs | 154 ++++++ .../src/register/hypervisorx64/vstval.rs | 3 + .../src/register/hypervisorx64/vstvec.rs | 47 ++ ci-user/riscv/src/register/macros.rs | 272 +++++++++++ ci-user/riscv/src/register/marchid.rs | 27 ++ ci-user/riscv/src/register/mcause.rs | 138 ++++++ ci-user/riscv/src/register/mcycle.rs | 4 + ci-user/riscv/src/register/mcycleh.rs | 3 + ci-user/riscv/src/register/medeleg.rs | 148 ++++++ ci-user/riscv/src/register/mepc.rs | 4 + ci-user/riscv/src/register/mhartid.rs | 3 + ci-user/riscv/src/register/mhpmcounterx.rs | 84 ++++ ci-user/riscv/src/register/mhpmeventx.rs | 41 ++ ci-user/riscv/src/register/mideleg.rs | 76 +++ ci-user/riscv/src/register/mie.rs | 103 ++++ ci-user/riscv/src/register/mimpid.rs | 27 ++ ci-user/riscv/src/register/minstret.rs | 4 + ci-user/riscv/src/register/minstreth.rs | 3 + ci-user/riscv/src/register/mip.rs | 100 ++++ ci-user/riscv/src/register/misa.rs | 60 +++ ci-user/riscv/src/register/mod.rs | 104 ++++ ci-user/riscv/src/register/mscratch.rs | 4 + ci-user/riscv/src/register/mstatus.rs | 214 +++++++++ ci-user/riscv/src/register/mtval.rs | 3 + ci-user/riscv/src/register/mtvec.rs | 47 ++ ci-user/riscv/src/register/mvendorid.rs | 32 ++ ci-user/riscv/src/register/pmpaddrx.rs | 28 ++ ci-user/riscv/src/register/pmpcfgx.rs | 23 + ci-user/riscv/src/register/satp.rs | 119 +++++ ci-user/riscv/src/register/scause.rs | 133 +++++ ci-user/riscv/src/register/sepc.rs | 4 + ci-user/riscv/src/register/sie.rs | 76 +++ ci-user/riscv/src/register/sip.rs | 55 +++ ci-user/riscv/src/register/sscratch.rs | 4 + ci-user/riscv/src/register/sstatus.rs | 161 +++++++ ci-user/riscv/src/register/stval.rs | 3 + ci-user/riscv/src/register/stvec.rs | 40 ++ ci-user/riscv/src/register/time.rs | 4 + ci-user/riscv/src/register/timeh.rs | 3 + ci-user/riscv/src/register/ucause.rs | 17 + ci-user/riscv/src/register/uepc.rs | 4 + ci-user/riscv/src/register/uie.rs | 49 ++ ci-user/riscv/src/register/uip.rs | 37 ++ ci-user/riscv/src/register/uscratch.rs | 4 + ci-user/riscv/src/register/ustatus.rs | 37 ++ ci-user/riscv/src/register/utval.rs | 3 + ci-user/riscv/src/register/utvec.rs | 40 ++ ci-user/user/.cargo/config | 7 + ci-user/user/.gitignore | 4 + ci-user/user/Cargo.toml | 19 + ci-user/user/Makefile | 64 +++ ci-user/user/build.py | 23 + ci-user/user/src/bin/ch2b_bad_address.rs | 16 + ci-user/user/src/bin/ch2b_bad_instructions.rs | 15 + ci-user/user/src/bin/ch2b_bad_register.rs | 16 + ci-user/user/src/bin/ch2b_hello_world.rs | 14 + ci-user/user/src/bin/ch2b_power_3.rs | 28 ++ ci-user/user/src/bin/ch2b_power_5.rs | 28 ++ ci-user/user/src/bin/ch2b_power_7.rs | 28 ++ ci-user/user/src/bin/ch3_taskinfo.rs | 46 ++ ci-user/user/src/bin/ch3b_sleep.rs | 24 + ci-user/user/src/bin/ch3b_sleep1.rs | 22 + ci-user/user/src/bin/ch3b_yield0.rs | 30 ++ ci-user/user/src/bin/ch3b_yield1.rs | 30 ++ ci-user/user/src/bin/ch3b_yield2.rs | 30 ++ ci-user/user/src/bin/ch4_mmap0.rs | 33 ++ ci-user/user/src/bin/ch4_mmap1.rs | 25 + ci-user/user/src/bin/ch4_mmap2.rs | 26 + ci-user/user/src/bin/ch4_mmap3.rs | 25 + ci-user/user/src/bin/ch4_unmap.rs | 36 ++ ci-user/user/src/bin/ch4_unmap2.rs | 23 + ci-user/user/src/bin/ch5_exit0.rs | 17 + ci-user/user/src/bin/ch5_exit1.rs | 17 + ci-user/user/src/bin/ch5_getpid.rs | 18 + ci-user/user/src/bin/ch5_setprio.rs | 20 + ci-user/user/src/bin/ch5_spawn0.rs | 29 ++ ci-user/user/src/bin/ch5_spawn1.rs | 35 ++ ci-user/user/src/bin/ch5_stride.rs | 33 ++ ci-user/user/src/bin/ch5_stride0.rs | 43 ++ ci-user/user/src/bin/ch5_stride1.rs | 39 ++ ci-user/user/src/bin/ch5_stride2.rs | 39 ++ ci-user/user/src/bin/ch5_stride3.rs | 39 ++ ci-user/user/src/bin/ch5_stride4.rs | 39 ++ ci-user/user/src/bin/ch5_stride5.rs | 39 ++ ci-user/user/src/bin/ch5_usertest.rs | 61 +++ ci-user/user/src/bin/ch5b_exit.rs | 30 ++ ci-user/user/src/bin/ch5b_forktest.rs | 34 ++ ci-user/user/src/bin/ch5b_forktest2.rs | 34 ++ ci-user/user/src/bin/ch5b_forktest_simple.rs | 28 ++ ci-user/user/src/bin/ch5b_forktree.rs | 37 ++ ci-user/user/src/bin/ch5b_initproc.rs | 28 ++ ci-user/user/src/bin/ch5b_user_shell.rs | 66 +++ ci-user/user/src/bin/ch6_file0.rs | 31 ++ ci-user/user/src/bin/ch6_file1.rs | 26 + ci-user/user/src/bin/ch6_file2.rs | 46 ++ ci-user/user/src/bin/ch6_file3.rs | 31 ++ ci-user/user/src/bin/ch6_usertest.rs | 51 ++ ci-user/user/src/bin/ch6b_cat.rs | 33 ++ ci-user/user/src/bin/ch6b_filetest_simple.rs | 38 ++ ci-user/user/src/bin/ch6b_initproc.rs | 28 ++ ci-user/user/src/bin/ch6b_user_shell.rs | 66 +++ ci-user/user/src/bin/ch7_usertest.rs | 29 ++ ci-user/user/src/bin/ch7b_cat.rs | 34 ++ ci-user/user/src/bin/ch7b_initproc.rs | 28 ++ ci-user/user/src/bin/ch7b_pipe_large_test.rs | 71 +++ ci-user/user/src/bin/ch7b_pipetest.rs | 44 ++ ci-user/user/src/bin/ch7b_run_pipe_test.rs | 21 + ci-user/user/src/bin/ch7b_user_shell.rs | 130 +++++ ci-user/user/src/bin/ch7b_yield.rs | 17 + ci-user/user/src/bin/ch8_deadlock_mutex1.rs | 22 + ci-user/user/src/bin/ch8_deadlock_sem1.rs | 102 ++++ ci-user/user/src/bin/ch8_deadlock_sem2.rs | 76 +++ ci-user/user/src/bin/ch8_usertest.rs | 60 +++ ci-user/user/src/bin/ch8b_initproc.rs | 28 ++ ci-user/user/src/bin/ch8b_mpsc_sem.rs | 73 +++ ci-user/user/src/bin/ch8b_phil_din_mutex.rs | 109 +++++ ci-user/user/src/bin/ch8b_race_adder.rs | 43 ++ .../user/src/bin/ch8b_race_adder_atomic.rs | 52 ++ ci-user/user/src/bin/ch8b_race_adder_loop.rs | 52 ++ .../src/bin/ch8b_race_adder_mutex_spin.rs | 47 ++ .../user/src/bin/ch8b_stackful_coroutine.rs | 346 +++++++++++++ .../user/src/bin/ch8b_stackless_coroutine.rs | 129 +++++ ci-user/user/src/bin/ch8b_sync_sem.rs | 45 ++ ci-user/user/src/bin/ch8b_test_condvar.rs | 59 +++ ci-user/user/src/bin/ch8b_threads.rs | 62 +++ ci-user/user/src/bin/ch8b_threads_arg.rs | 45 ++ ci-user/user/src/bin/ch8b_user_shell.rs | 214 +++++++++ ci-user/user/src/console.rs | 75 +++ ci-user/user/src/lang_items.rs | 17 + ci-user/user/src/lib.rs | 359 ++++++++++++++ ci-user/user/src/linker.ld | 33 ++ ci-user/user/src/syscall.rs | 258 ++++++++++ 230 files changed, 12559 insertions(+) create mode 100644 ci-user/.gitignore create mode 100644 ci-user/.gitlab-ci.yml create mode 100644 ci-user/Makefile create mode 100644 ci-user/README.md create mode 100644 ci-user/check/base.py create mode 100644 ci-user/check/ch1.py create mode 100644 ci-user/check/ch2.py create mode 100644 ci-user/check/ch3.py create mode 100644 ci-user/check/ch4.py create mode 100644 ci-user/check/ch5.py create mode 100644 ci-user/check/ch5_1.py create mode 100644 ci-user/check/ch6.py create mode 100644 ci-user/check/ch7.py create mode 100644 ci-user/check/ch8.py create mode 100644 ci-user/overwrite.py create mode 100644 ci-user/overwrite/Makefile-ch2 create mode 100644 ci-user/overwrite/Makefile-ch3 create mode 100644 ci-user/overwrite/Makefile-ch6 create mode 100644 ci-user/overwrite/build-bin.rs create mode 100644 ci-user/overwrite/build-elf.rs create mode 100644 ci-user/overwrite/easy-fs-fuse-ch7.rs create mode 100644 ci-user/overwrite/easy-fs-fuse.rs create mode 100644 ci-user/riscv/.gitignore create mode 100644 ci-user/riscv/.travis.yml create mode 100644 ci-user/riscv/CHANGELOG.md create mode 100644 ci-user/riscv/CODE_OF_CONDUCT.md create mode 100644 ci-user/riscv/Cargo.toml create mode 100644 ci-user/riscv/README.md create mode 100644 ci-user/riscv/asm.S create mode 100644 ci-user/riscv/asm.h create mode 100644 ci-user/riscv/assemble.ps1 create mode 100755 ci-user/riscv/assemble.sh create mode 100644 ci-user/riscv/build.rs create mode 100755 ci-user/riscv/check-blobs.sh create mode 100755 ci-user/riscv/descriptor/generate_hypervisor_csr.sh create mode 100644 ci-user/riscv/descriptor/generator.rs create mode 100644 ci-user/riscv/descriptor/hcounteren.txt create mode 100644 ci-user/riscv/descriptor/hedeleg.txt create mode 100644 ci-user/riscv/descriptor/hgatp.txt create mode 100644 ci-user/riscv/descriptor/hgeie.txt create mode 100644 ci-user/riscv/descriptor/hgeip.txt create mode 100644 ci-user/riscv/descriptor/hideleg.txt create mode 100644 ci-user/riscv/descriptor/hie.txt create mode 100644 ci-user/riscv/descriptor/hip.txt create mode 100644 ci-user/riscv/descriptor/hstatus.txt create mode 100644 ci-user/riscv/descriptor/htimedelta.txt create mode 100644 ci-user/riscv/descriptor/htimedeltah.txt create mode 100644 ci-user/riscv/descriptor/htinst.txt create mode 100644 ci-user/riscv/descriptor/htval.txt create mode 100644 ci-user/riscv/descriptor/hvip.txt create mode 100644 ci-user/riscv/descriptor/vsatp.txt create mode 100644 ci-user/riscv/descriptor/vscause.txt create mode 100644 ci-user/riscv/descriptor/vsepc.txt create mode 100644 ci-user/riscv/descriptor/vsie.txt create mode 100644 ci-user/riscv/descriptor/vsip.txt create mode 100644 ci-user/riscv/descriptor/vsscratch.txt create mode 100644 ci-user/riscv/descriptor/vsstatus.txt create mode 100644 ci-user/riscv/descriptor/vstval.txt create mode 100644 ci-user/riscv/descriptor/vstvec.txt create mode 100644 ci-user/riscv/src/addr/gpax4.rs create mode 100644 ci-user/riscv/src/addr/mod.rs create mode 100644 ci-user/riscv/src/addr/page.rs create mode 100644 ci-user/riscv/src/addr/sv32.rs create mode 100644 ci-user/riscv/src/addr/sv39.rs create mode 100644 ci-user/riscv/src/addr/sv48.rs create mode 100644 ci-user/riscv/src/asm.rs create mode 100644 ci-user/riscv/src/interrupt.rs create mode 100644 ci-user/riscv/src/lib.rs create mode 100644 ci-user/riscv/src/paging/frame_alloc.rs create mode 100644 ci-user/riscv/src/paging/mapper.rs create mode 100644 ci-user/riscv/src/paging/mod.rs create mode 100644 ci-user/riscv/src/paging/multi_level.rs create mode 100644 ci-user/riscv/src/paging/multi_level_x4.rs create mode 100644 ci-user/riscv/src/paging/page_table.rs create mode 100644 ci-user/riscv/src/paging/page_table_x4.rs create mode 100644 ci-user/riscv/src/register/fcsr.rs create mode 100644 ci-user/riscv/src/register/hpmcounterx.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/hcounteren.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/hedeleg.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/hgatp.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/hgeie.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/hgeip.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/hideleg.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/hie.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/hip.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/hstatus.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/htimedelta.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/htimedeltah.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/htinst.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/htval.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/hvip.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/mod.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/vsatp.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/vscause.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/vsepc.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/vsie.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/vsip.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/vsscratch.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/vsstatus.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/vstval.rs create mode 100644 ci-user/riscv/src/register/hypervisorx64/vstvec.rs create mode 100644 ci-user/riscv/src/register/macros.rs create mode 100644 ci-user/riscv/src/register/marchid.rs create mode 100644 ci-user/riscv/src/register/mcause.rs create mode 100644 ci-user/riscv/src/register/mcycle.rs create mode 100644 ci-user/riscv/src/register/mcycleh.rs create mode 100644 ci-user/riscv/src/register/medeleg.rs create mode 100644 ci-user/riscv/src/register/mepc.rs create mode 100644 ci-user/riscv/src/register/mhartid.rs create mode 100644 ci-user/riscv/src/register/mhpmcounterx.rs create mode 100644 ci-user/riscv/src/register/mhpmeventx.rs create mode 100644 ci-user/riscv/src/register/mideleg.rs create mode 100644 ci-user/riscv/src/register/mie.rs create mode 100644 ci-user/riscv/src/register/mimpid.rs create mode 100644 ci-user/riscv/src/register/minstret.rs create mode 100644 ci-user/riscv/src/register/minstreth.rs create mode 100644 ci-user/riscv/src/register/mip.rs create mode 100644 ci-user/riscv/src/register/misa.rs create mode 100644 ci-user/riscv/src/register/mod.rs create mode 100644 ci-user/riscv/src/register/mscratch.rs create mode 100644 ci-user/riscv/src/register/mstatus.rs create mode 100644 ci-user/riscv/src/register/mtval.rs create mode 100644 ci-user/riscv/src/register/mtvec.rs create mode 100644 ci-user/riscv/src/register/mvendorid.rs create mode 100644 ci-user/riscv/src/register/pmpaddrx.rs create mode 100644 ci-user/riscv/src/register/pmpcfgx.rs create mode 100644 ci-user/riscv/src/register/satp.rs create mode 100644 ci-user/riscv/src/register/scause.rs create mode 100644 ci-user/riscv/src/register/sepc.rs create mode 100644 ci-user/riscv/src/register/sie.rs create mode 100644 ci-user/riscv/src/register/sip.rs create mode 100644 ci-user/riscv/src/register/sscratch.rs create mode 100644 ci-user/riscv/src/register/sstatus.rs create mode 100644 ci-user/riscv/src/register/stval.rs create mode 100644 ci-user/riscv/src/register/stvec.rs create mode 100644 ci-user/riscv/src/register/time.rs create mode 100644 ci-user/riscv/src/register/timeh.rs create mode 100644 ci-user/riscv/src/register/ucause.rs create mode 100644 ci-user/riscv/src/register/uepc.rs create mode 100644 ci-user/riscv/src/register/uie.rs create mode 100644 ci-user/riscv/src/register/uip.rs create mode 100644 ci-user/riscv/src/register/uscratch.rs create mode 100644 ci-user/riscv/src/register/ustatus.rs create mode 100644 ci-user/riscv/src/register/utval.rs create mode 100644 ci-user/riscv/src/register/utvec.rs create mode 100644 ci-user/user/.cargo/config create mode 100644 ci-user/user/.gitignore create mode 100644 ci-user/user/Cargo.toml create mode 100644 ci-user/user/Makefile create mode 100644 ci-user/user/build.py create mode 100644 ci-user/user/src/bin/ch2b_bad_address.rs create mode 100644 ci-user/user/src/bin/ch2b_bad_instructions.rs create mode 100644 ci-user/user/src/bin/ch2b_bad_register.rs create mode 100644 ci-user/user/src/bin/ch2b_hello_world.rs create mode 100644 ci-user/user/src/bin/ch2b_power_3.rs create mode 100644 ci-user/user/src/bin/ch2b_power_5.rs create mode 100644 ci-user/user/src/bin/ch2b_power_7.rs create mode 100644 ci-user/user/src/bin/ch3_taskinfo.rs create mode 100644 ci-user/user/src/bin/ch3b_sleep.rs create mode 100644 ci-user/user/src/bin/ch3b_sleep1.rs create mode 100644 ci-user/user/src/bin/ch3b_yield0.rs create mode 100644 ci-user/user/src/bin/ch3b_yield1.rs create mode 100644 ci-user/user/src/bin/ch3b_yield2.rs create mode 100644 ci-user/user/src/bin/ch4_mmap0.rs create mode 100644 ci-user/user/src/bin/ch4_mmap1.rs create mode 100644 ci-user/user/src/bin/ch4_mmap2.rs create mode 100644 ci-user/user/src/bin/ch4_mmap3.rs create mode 100644 ci-user/user/src/bin/ch4_unmap.rs create mode 100644 ci-user/user/src/bin/ch4_unmap2.rs create mode 100644 ci-user/user/src/bin/ch5_exit0.rs create mode 100644 ci-user/user/src/bin/ch5_exit1.rs create mode 100644 ci-user/user/src/bin/ch5_getpid.rs create mode 100644 ci-user/user/src/bin/ch5_setprio.rs create mode 100644 ci-user/user/src/bin/ch5_spawn0.rs create mode 100644 ci-user/user/src/bin/ch5_spawn1.rs create mode 100644 ci-user/user/src/bin/ch5_stride.rs create mode 100644 ci-user/user/src/bin/ch5_stride0.rs create mode 100644 ci-user/user/src/bin/ch5_stride1.rs create mode 100644 ci-user/user/src/bin/ch5_stride2.rs create mode 100644 ci-user/user/src/bin/ch5_stride3.rs create mode 100644 ci-user/user/src/bin/ch5_stride4.rs create mode 100644 ci-user/user/src/bin/ch5_stride5.rs create mode 100644 ci-user/user/src/bin/ch5_usertest.rs create mode 100644 ci-user/user/src/bin/ch5b_exit.rs create mode 100644 ci-user/user/src/bin/ch5b_forktest.rs create mode 100644 ci-user/user/src/bin/ch5b_forktest2.rs create mode 100644 ci-user/user/src/bin/ch5b_forktest_simple.rs create mode 100644 ci-user/user/src/bin/ch5b_forktree.rs create mode 100644 ci-user/user/src/bin/ch5b_initproc.rs create mode 100644 ci-user/user/src/bin/ch5b_user_shell.rs create mode 100644 ci-user/user/src/bin/ch6_file0.rs create mode 100644 ci-user/user/src/bin/ch6_file1.rs create mode 100644 ci-user/user/src/bin/ch6_file2.rs create mode 100644 ci-user/user/src/bin/ch6_file3.rs create mode 100644 ci-user/user/src/bin/ch6_usertest.rs create mode 100644 ci-user/user/src/bin/ch6b_cat.rs create mode 100644 ci-user/user/src/bin/ch6b_filetest_simple.rs create mode 100644 ci-user/user/src/bin/ch6b_initproc.rs create mode 100644 ci-user/user/src/bin/ch6b_user_shell.rs create mode 100644 ci-user/user/src/bin/ch7_usertest.rs create mode 100644 ci-user/user/src/bin/ch7b_cat.rs create mode 100644 ci-user/user/src/bin/ch7b_initproc.rs create mode 100644 ci-user/user/src/bin/ch7b_pipe_large_test.rs create mode 100644 ci-user/user/src/bin/ch7b_pipetest.rs create mode 100644 ci-user/user/src/bin/ch7b_run_pipe_test.rs create mode 100644 ci-user/user/src/bin/ch7b_user_shell.rs create mode 100644 ci-user/user/src/bin/ch7b_yield.rs create mode 100644 ci-user/user/src/bin/ch8_deadlock_mutex1.rs create mode 100644 ci-user/user/src/bin/ch8_deadlock_sem1.rs create mode 100644 ci-user/user/src/bin/ch8_deadlock_sem2.rs create mode 100644 ci-user/user/src/bin/ch8_usertest.rs create mode 100644 ci-user/user/src/bin/ch8b_initproc.rs create mode 100644 ci-user/user/src/bin/ch8b_mpsc_sem.rs create mode 100644 ci-user/user/src/bin/ch8b_phil_din_mutex.rs create mode 100644 ci-user/user/src/bin/ch8b_race_adder.rs create mode 100644 ci-user/user/src/bin/ch8b_race_adder_atomic.rs create mode 100644 ci-user/user/src/bin/ch8b_race_adder_loop.rs create mode 100644 ci-user/user/src/bin/ch8b_race_adder_mutex_spin.rs create mode 100644 ci-user/user/src/bin/ch8b_stackful_coroutine.rs create mode 100644 ci-user/user/src/bin/ch8b_stackless_coroutine.rs create mode 100644 ci-user/user/src/bin/ch8b_sync_sem.rs create mode 100644 ci-user/user/src/bin/ch8b_test_condvar.rs create mode 100644 ci-user/user/src/bin/ch8b_threads.rs create mode 100644 ci-user/user/src/bin/ch8b_threads_arg.rs create mode 100644 ci-user/user/src/bin/ch8b_user_shell.rs create mode 100644 ci-user/user/src/console.rs create mode 100644 ci-user/user/src/lang_items.rs create mode 100644 ci-user/user/src/lib.rs create mode 100644 ci-user/user/src/linker.ld create mode 100644 ci-user/user/src/syscall.rs diff --git a/ci-user/.gitignore b/ci-user/.gitignore new file mode 100644 index 0000000..44e530e --- /dev/null +++ b/ci-user/.gitignore @@ -0,0 +1,6 @@ +user/target +user/build +user/Cargo.lock +user/.idea +.idea +__pycache__ diff --git a/ci-user/.gitlab-ci.yml b/ci-user/.gitlab-ci.yml new file mode 100644 index 0000000..b43ce2c --- /dev/null +++ b/ci-user/.gitlab-ci.yml @@ -0,0 +1,61 @@ +default: + image: zhanghx0905/rcore-ci + +stages: + - build + +build-ch2-job: + stage: build + script: + - cd user && make all CHAPTER=2 + artifacts: + paths: + - user/build/bin/*.bin + +build-ch3_0-job: + stage: build + script: + - cd user && make all CHAPTER=3_0 + artifacts: + paths: + - user/build/bin/*.bin + +build-ch3_1-job: + stage: build + script: + - cd user && make all CHAPTER=3_1 + artifacts: + paths: + - user/build/bin/*.bin + +build-ch4-job: + stage: build + script: + - cd user && make all CHAPTER=4 + artifacts: + paths: + - user/build/elf/*.elf + +build-ch5-job: + stage: build + script: + - cd user && make all CHAPTER=5 + artifacts: + paths: + - user/build/elf/*.elf + +build-ch6-job: + stage: build + script: + - cd user && make all CHAPTER=6 + artifacts: + paths: + - user/build/elf/*.elf + +build-ch7-job: + stage: build + script: + - cd user && make all CHAPTER=7 + artifacts: + paths: + - user/build/elf/*.elf diff --git a/ci-user/Makefile b/ci-user/Makefile new file mode 100644 index 0000000..bd3777f --- /dev/null +++ b/ci-user/Makefile @@ -0,0 +1,48 @@ +RAND := $(shell awk 'BEGIN{srand();printf("%d", 65536*rand())}') +CHAPTER ?= + +ifeq ($(CHAPTER), 3) + LAB := 1 +else ifeq ($(CHAPTER), 4) + LAB := 2 +else ifeq ($(CHAPTER), 5) + INITPROC := 1 + LAB := 3 +else ifeq ($(CHAPTER), 6) + INITPROC := 1 + LAB := 4 +else ifeq ($(CHAPTER), 7) + INITPROC := 1 + LAB := 4 +else ifeq ($(CHAPTER), 8) + INITPROC := 1 + LAB := 5 +endif + +randomize: + find user/src/bin -name "*.rs" | xargs sed -i 's/OK/OK$(RAND)/g' + find user/src/bin -name "*.rs" | xargs sed -i 's/passed/passed$(RAND)/g' + find check -name "*.py" | xargs sed -i 's/OK/OK$(RAND)/g' + find check -name "*.py" | xargs sed -i 's/passed/passed$(RAND)/g' + +test: randomize + python3 overwrite.py $(CHAPTER) + make -C user build BASE=2 TEST=$(CHAPTER) CHAPTER=$(CHAPTER) +ifdef INITPROC + cp -f user/build/elf/ch$(CHAPTER)_usertest.elf user/build/elf/ch$(CHAPTER)b_initproc.elf +endif + make -C ../os run | tee stdout-ch$(CHAPTER) + python3 check/ch$(CHAPTER).py < stdout-ch$(CHAPTER) + +ifdef LAB + @for i in $(shell seq $(LAB)); do \ + if ! [ -f ../reports/lab$$i.pdf -o -f ../reports/lab$$i.md ]; then \ + echo "Report for lab$$i needed. Add your report to reports/lab$$i.pdf or reports/lab$$i.md" ; \ + exit 1 ; \ + else \ + echo "Report for lab$$i found." ; \ + fi; \ + done +endif + +.PHONY: test randomize diff --git a/ci-user/README.md b/ci-user/README.md new file mode 100644 index 0000000..64cecb4 --- /dev/null +++ b/ci-user/README.md @@ -0,0 +1,67 @@ +## rCore_tutorial_v3 TESTS + +本项目用于为 rCore 实验进行 CI 测试,在 user 目录下 `make all CHAPTER=x` 可获得第 x 章的测例。 + +- 可选项 2, 3_0, 3_2, 4, 5, 6, 7。 + +**重要**-加载地址更新: + +- chapter2 所有程序加载位置位于 0x80400000,与示例代码一致。 +- chapter3 测试程序分为 3 批,每一批的地址都为 0x80400000 + id\*0x20000,id 为程序在这一批中的序号。每一批都与参考代码一致,请分别测试。 +- chapter4-7 所有程序加载位置位于 0x0,与示例代码一致。 + +可以在 `user/build/asm` 目录下查看汇编来确认加载地址。 + +**测例更新** + +- 一部分无用测例已删除,包括 ch2_helloworld, ch3_1_yield 等。 +- sleep 测例被转移到第四章 +- ch4 之后不再测试 write1 + +rust 的把user测例分散到了各个branch里,当时想的是尽量把测试的过程屏蔽掉,现在看确实不便于管理,这学期就先这样算了. + +### 各章的测例 + +#### ch3 + +test1:write0 write1 + +test2:setprio + +test3:stride的六个测例 + +#### ch4 + +test1:sleep0 sleep1 测试 sys_time + +test2:map0123 unmap12 测试 map unmap 实现 + +#### ch5 6 7 8 + +```rust + "test_sleep\0", + "test_sleep1\0", + "test_mmap0\0", + "test_mmap1\0", + "test_mmap2\0", + "test_mmap3\0", + "test_unmap\0", + "test_unmap2\0", + "test_spawn0\0", + "test_spawn1\0", + // ch6 + "test_mail0\0", + "test_mail1\0", + "test_mail2\0", + "test_mail3\0", + // ch7 + "test_file0\0", + "test_file1\0", + "test_file2\0", + // ch8 + ... +``` + +share mem 的测例放着就行。 + +ch8 先不管。 \ No newline at end of file diff --git a/ci-user/check/base.py b/ci-user/check/base.py new file mode 100644 index 0000000..5c6b4dc --- /dev/null +++ b/ci-user/check/base.py @@ -0,0 +1,46 @@ +import sys +import re +import ch5_1 + +def test(expected, not_expected=[]): + output = sys.stdin.read(1000000) + + count = 0 + total = len(expected) + len(not_expected) + + for pattern in expected: + if re.search(pattern, output): + count += 1 + print(f'\033[92m[PASS]\033[0m found <{pattern}>') + else: + print(f'\033[91m[FAIL]\033[0m not found <{pattern}>') + + for pattern in not_expected: + if not re.search(pattern, output): + count += 1 + print(f'\033[92m[PASS]\033[0m not found <{pattern}>') + else: + print(f'\033[91m[FAIL]\033[0m found <{pattern}>') + + print('\nTest passed: %d/%d' % (count, total)) + assert count == total + + # test stride + if re.search(ch5_1.PATTERN, output): + ch5_1.stride_test(re.compile(ch5_1.PATTERN).findall(output)) + +# def test_str(expected): +# output = sys.stdin.read(1000000) + +# count = 0 +# total = len(expected) + +# for pattern in expected: +# if output.find(pattern) != -1: +# count += 1 +# print('\033[92m[PASS]\033[0m', pattern) +# else: +# print('\033[91m[FAIL]\033[0m', pattern) + +# print('\nTest passed: %d/%d' % (count, total)) +# assert count == total 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 @@ +[![crates.io](https://img.shields.io/crates/d/riscv.svg)](https://crates.io/crates/riscv) +[![crates.io](https://img.shields.io/crates/v/riscv.svg)](https://crates.io/crates/riscv) +[![Build Status](https://travis-ci.org/rust-embedded/riscv.svg?branch=master)](https://travis-ci.org/rust-embedded/riscv) + +# `riscv` + +> Low level access to RISC-V processors + +This project is developed and maintained by the [RISC-V team][team]. + +## [Documentation](https://docs.rs/crate/riscv) + +## Minimum Supported Rust Version (MSRV) + +This crate is guaranteed to compile on stable Rust 1.42.0 and up. It *might* +compile with older versions but that may change in any new patch release. + +## License + +Copyright 2019-2020 [RISC-V team][team] + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +## Code of Conduct + +Contribution to this crate is organized under the terms of the [Rust Code of +Conduct][CoC], the maintainer of this crate, the [RISC-V team][team], promises +to intervene to uphold that code of conduct. + +[CoC]: CODE_OF_CONDUCT.md +[team]: https://github.com/rust-embedded/wg#the-riscv-team 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: ::Page, + ) -> Result<(::Frame, Self::MapperFlush), UnmapError<::P>> + { + if self.root_table[page.p4_index()].is_unused() { + return Err(UnmapError::PageNotMapped); + } + let p3_frame = self.root_table[page.p4_index()].frame::(); + let p3_table: &mut PageTableX64 = unsafe { p3_frame.as_kernel_mut(self.linear_offset) }; + + if p3_table[page.p3_index()].is_unused() { + return Err(UnmapError::PageNotMapped); + } + let p2_frame = p3_table[page.p3_index()].frame::(); + 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.p4_index()].is_unused() { + return Err(FlagUpdateError::PageNotMapped); + } + let p3_frame = self.root_table[page.p4_index()].frame::(); + let p3_table: &mut PageTableX64 = unsafe { p3_frame.as_kernel_mut(self.linear_offset) }; + + if p3_table[page.p3_index()].is_unused() { + return Err(FlagUpdateError::PageNotMapped); + } + let p2_frame = p3_table[page.p3_index()].frame::(); + 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()]) + } +} + +pub type Rv32PageTable<'a> = Rv32PageTableWith<'a, VirtAddrSv32, MapperFlush>; +pub type Rv39PageTable<'a> = Rv39PageTableWith<'a, VirtAddrSv39, MapperFlush>; +pub type Rv48PageTable<'a> = Rv48PageTableWith<'a, VirtAddrSv48, MapperFlush>; diff --git a/ci-user/riscv/src/paging/multi_level_x4.rs b/ci-user/riscv/src/paging/multi_level_x4.rs new file mode 100644 index 0000000..a719e04 --- /dev/null +++ b/ci-user/riscv/src/paging/multi_level_x4.rs @@ -0,0 +1,42 @@ +use crate::addr::*; +use crate::asm::{hfence_gvma, hfence_vvma}; +use crate::paging::mapper::MapperFlushable; +use crate::paging::multi_level::Rv32PageTableWith; +use crate::paging::multi_level::{Rv39PageTableWith, Rv48PageTableWith}; + +#[must_use = "Guest Physical Address Table changes must be flushed or ignored."] +pub struct MapperFlushGPA(usize); + +impl MapperFlushable for MapperFlushGPA { + fn new(page: PageWith) -> Self { + MapperFlushGPA(page.start_address().as_usize()) + } + fn flush(self) { + unsafe { + hfence_gvma(self.0, 0); + } + } + fn ignore(self) {} +} + +#[must_use = "Guest Page Table changes must be flushed or ignored."] +pub struct MapperFlushGPT(usize); + +impl MapperFlushable for MapperFlushGPT { + fn new(page: PageWith) -> Self { + MapperFlushGPT(page.start_address().as_usize()) + } + fn flush(self) { + unsafe { + hfence_vvma(self.0, 0); + } + } + fn ignore(self) {} +} + +pub type Rv32PageTableX4<'a> = Rv32PageTableWith<'a, GPAddrSv32X4, MapperFlushGPA>; +pub type Rv39PageTableX4<'a> = Rv39PageTableWith<'a, GPAddrSv39X4, MapperFlushGPA>; +pub type Rv48PageTableX4<'a> = Rv48PageTableWith<'a, GPAddrSv48X4, MapperFlushGPA>; +pub type Rv32PageTableGuest<'a> = Rv32PageTableWith<'a, VirtAddrSv32, MapperFlushGPT>; +pub type Rv39PageTableGuest<'a> = Rv39PageTableWith<'a, VirtAddrSv39, MapperFlushGPT>; +pub type Rv48PageTableGuest<'a> = Rv48PageTableWith<'a, VirtAddrSv48, MapperFlushGPT>; diff --git a/ci-user/riscv/src/paging/page_table.rs b/ci-user/riscv/src/paging/page_table.rs new file mode 100644 index 0000000..56896fe --- /dev/null +++ b/ci-user/riscv/src/paging/page_table.rs @@ -0,0 +1,252 @@ +use addr::*; +use core::convert::TryInto; +use core::fmt::{Debug, Error, Formatter}; +use core::marker::PhantomData; +use core::ops::{Index, IndexMut}; + +pub type Entries32 = [PageTableEntryX32; RV32_ENTRY_COUNT]; +pub type Entries64 = [PageTableEntryX64; RV64_ENTRY_COUNT]; + +// To avoid const generic. +pub trait PTEIterableSlice { + fn to_pte_slice<'a>(&'a self) -> &'a [T]; + fn to_pte_slice_mut<'a>(&'a mut self) -> &'a mut [T]; + fn pte_index(&self, index: usize) -> &T; + fn pte_index_mut(&mut self, index: usize) -> &mut T; +} + +impl PTEIterableSlice for Entries32 { + fn to_pte_slice(&self) -> &[PageTableEntryX32] { + self + } + fn to_pte_slice_mut(&mut self) -> &mut [PageTableEntryX32] { + self + } + fn pte_index(&self, index: usize) -> &PageTableEntryX32 { + &self[index] + } + fn pte_index_mut(&mut self, index: usize) -> &mut PageTableEntryX32 { + &mut self[index] + } +} +impl PTEIterableSlice for Entries64 { + fn to_pte_slice(&self) -> &[PageTableEntryX64] { + self + } + fn to_pte_slice_mut(&mut self) -> &mut [PageTableEntryX64] { + self + } + fn pte_index(&self, index: usize) -> &PageTableEntryX64 { + &self[index] + } + fn pte_index_mut(&mut self, index: usize) -> &mut PageTableEntryX64 { + &mut self[index] + } +} + +#[repr(C)] +pub struct PageTableWith, E: PTE> { + entries: T, + phantom: PhantomData, +} + +impl, E: PTE> PageTableWith { + /// Clears all entries. + pub fn zero(&mut self) { + for entry in self.entries.to_pte_slice_mut().iter_mut() { + entry.set_unused(); + } + } +} + +impl, E: PTE> Index for PageTableWith { + type Output = E; + + fn index(&self, index: usize) -> &Self::Output { + self.entries.pte_index(index) + } +} + +impl, E: PTE> IndexMut for PageTableWith { + fn index_mut(&mut self, index: usize) -> &mut Self::Output { + self.entries.pte_index_mut(index) + } +} + +impl, E: PTE + Debug> Debug for PageTableWith { + fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { + f.debug_map() + .entries( + self.entries + .to_pte_slice() + .iter() + .enumerate() + .filter(|p| !p.1.is_unused()), + ) + .finish() + } +} + +pub trait PTE { + fn is_unused(&self) -> bool; + fn set_unused(&mut self); + fn flags(&self) -> PageTableFlags; + fn ppn(&self) -> usize; + fn ppn_u64(&self) -> u64; + fn addr(&self) -> T; + fn frame(&self) -> FrameWith; + fn set(&mut self, frame: FrameWith, flags: PageTableFlags); + fn flags_mut(&mut self) -> &mut PageTableFlags; +} + +#[derive(Copy, Clone)] +#[repr(C)] +pub struct PageTableEntryX32(u32); + +impl PTE for PageTableEntryX32 { + fn is_unused(&self) -> bool { + self.0 == 0 + } + fn set_unused(&mut self) { + self.0 = 0; + } + fn flags(&self) -> PageTableFlags { + PageTableFlags::from_bits_truncate(self.0 as usize) + } + fn ppn(&self) -> usize { + self.ppn_u64().try_into().unwrap() + } + fn ppn_u64(&self) -> u64 { + (self.0 >> 10) as u64 + } + fn addr(&self) -> T { + T::new_u64((self.ppn() as u64) << 12) + } + fn frame(&self) -> FrameWith { + FrameWith::of_addr(self.addr()) + } + fn set(&mut self, frame: FrameWith, mut flags: PageTableFlags) { + // U540 will raise page fault when accessing page with A=0 or D=0 + flags |= EF::ACCESSED | EF::DIRTY; + self.0 = ((frame.number() << 10) | flags.bits()) as u32; + } + fn flags_mut(&mut self) -> &mut PageTableFlags { + unsafe { &mut *(self as *mut _ as *mut PageTableFlags) } + } +} + +impl Debug for PageTableEntryX32 { + fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { + f.debug_struct("PageTableEntryX32") + .field("frame", &self.frame::()) + .field("flags", &self.flags()) + .finish() + } +} + +#[derive(Copy, Clone)] +pub struct PageTableEntryX64(u64); + +impl PTE for PageTableEntryX64 { + fn is_unused(&self) -> bool { + self.0 == 0 + } + fn set_unused(&mut self) { + self.0 = 0; + } + fn flags(&self) -> PageTableFlags { + PageTableFlags::from_bits_truncate(self.0 as usize) + } + fn ppn(&self) -> usize { + self.ppn_u64().try_into().unwrap() + } + fn ppn_u64(&self) -> u64 { + (self.0 >> 10) as u64 + } + fn addr(&self) -> T { + T::new_u64((self.ppn() as u64) << 12) + } + fn frame(&self) -> FrameWith { + FrameWith::of_addr(self.addr()) + } + fn set(&mut self, frame: FrameWith, mut flags: PageTableFlags) { + // U540 will raise page fault when accessing page with A=0 or D=0 + flags |= EF::ACCESSED | EF::DIRTY; + self.0 = ((frame.number() << 10) | flags.bits()) as u64; + } + fn flags_mut(&mut self) -> &mut PageTableFlags { + unsafe { &mut *(self as *mut _ as *mut PageTableFlags) } + } +} + +pub struct PageTableEntryX64Printer<'a, P: PhysicalAddress>( + &'a PageTableEntryX64, + PhantomData<*const P>, +); + +impl<'a, P: PhysicalAddress> Debug for PageTableEntryX64Printer<'a, P> { + fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { + f.debug_struct("PageTableEntryX64") + .field("frame", &self.0.frame::

()) + .field("flags", &self.0.flags()) + .finish() + } +} + +impl PageTableEntryX64 { + pub fn debug_sv39<'a>(&'a self) -> PageTableEntryX64Printer<'a, PhysAddrSv39> { + PageTableEntryX64Printer(self, PhantomData) + } + pub fn debug_sv48<'a>(&'a self) -> PageTableEntryX64Printer<'a, PhysAddrSv48> { + PageTableEntryX64Printer(self, PhantomData) + } +} + +impl Debug for PageTableEntryX64 { + fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { + self.debug_sv48().fmt(f) + } +} + +pub const RV64_ENTRY_COUNT: usize = 1 << 9; +pub const RV32_ENTRY_COUNT: usize = 1 << 10; +#[cfg(riscv64)] +pub const ENTRY_COUNT: usize = RV64_ENTRY_COUNT; +#[cfg(riscv32)] +pub const ENTRY_COUNT: usize = RV32_ENTRY_COUNT; +#[cfg(riscv64)] +pub type PageTableEntry = PageTableEntryX64; +#[cfg(riscv32)] +pub type PageTableEntry = PageTableEntryX32; +#[cfg(riscv64)] +pub type Entries = Entries64; +#[cfg(riscv32)] +pub type Entries = Entries32; +#[cfg(not(any(riscv32, riscv64)))] +pub const ENTRY_COUNT: usize = 1 << 0; +#[cfg(not(any(riscv32, riscv64)))] +pub type Entries = Entries64; + +pub type PageTableX32 = PageTableWith; +pub type PageTableX64 = PageTableWith; +#[cfg(riscv64)] +pub type PageTable = PageTableX64; +#[cfg(riscv32)] +pub type PageTable = PageTableX32; +bitflags! { + /// Possible flags for a page table entry. + pub struct PageTableFlags: usize { + const VALID = 1 << 0; + const READABLE = 1 << 1; + const WRITABLE = 1 << 2; + const EXECUTABLE = 1 << 3; + const USER = 1 << 4; + const GLOBAL = 1 << 5; + const ACCESSED = 1 << 6; + const DIRTY = 1 << 7; + const RESERVED1 = 1 << 8; + const RESERVED2 = 1 << 9; + } +} + +type EF = PageTableFlags; diff --git a/ci-user/riscv/src/paging/page_table_x4.rs b/ci-user/riscv/src/paging/page_table_x4.rs new file mode 100644 index 0000000..0d24193 --- /dev/null +++ b/ci-user/riscv/src/paging/page_table_x4.rs @@ -0,0 +1,44 @@ +/// This file is for Hypervisor-related x4 page tables, including Sv32x4, Sv39x4 and Sv48x4. +/// In fact, these x4 page tables are Phys-to-Phys page tables from GPAs to real PAs. +use super::page_table::{ + PTEIterableSlice, PageTableEntryX32, PageTableEntryX64, PageTableWith, RV32_ENTRY_COUNT, + RV64_ENTRY_COUNT, +}; + +// The root page table is 4 times larger. +pub const RV32_X4_ENTRY_COUNT: usize = RV32_ENTRY_COUNT << 2; +pub const RV64_X4_ENTRY_COUNT: usize = RV64_ENTRY_COUNT << 2; + +pub type Entries32X4 = [PageTableEntryX32; RV32_X4_ENTRY_COUNT]; +pub type Entries64X4 = [PageTableEntryX64; RV64_X4_ENTRY_COUNT]; + +impl PTEIterableSlice for Entries32X4 { + fn to_pte_slice(&self) -> &[PageTableEntryX32] { + self + } + fn to_pte_slice_mut(&mut self) -> &mut [PageTableEntryX32] { + self + } + fn pte_index(&self, index: usize) -> &PageTableEntryX32 { + &self[index] + } + fn pte_index_mut(&mut self, index: usize) -> &mut PageTableEntryX32 { + &mut self[index] + } +} +impl PTEIterableSlice for Entries64X4 { + fn to_pte_slice(&self) -> &[PageTableEntryX64] { + self + } + fn to_pte_slice_mut(&mut self) -> &mut [PageTableEntryX64] { + self + } + fn pte_index(&self, index: usize) -> &PageTableEntryX64 { + &self[index] + } + fn pte_index_mut(&mut self, index: usize) -> &mut PageTableEntryX64 { + &mut self[index] + } +} +pub type PageTable32X4 = PageTableWith; +pub type PageTable64X4 = PageTableWith; diff --git a/ci-user/riscv/src/register/fcsr.rs b/ci-user/riscv/src/register/fcsr.rs new file mode 100644 index 0000000..855eb5d --- /dev/null +++ b/ci-user/riscv/src/register/fcsr.rs @@ -0,0 +1,134 @@ +//! Floating-point control and status register + +use bit_field::BitField; + +/// Floating-point control and status register +#[derive(Clone, Copy, Debug)] +pub struct FCSR { + bits: u32, +} + +/// Accrued Exception Flags +#[derive(Clone, Copy, Debug)] +pub struct Flags(u32); + +/// Accrued Exception Flag +#[derive(Clone, Copy, Debug)] +pub enum Flag { + /// Inexact + NX = 0b00001, + + /// Underflow + UF = 0b00010, + + /// Overflow + OF = 0b00100, + + /// Divide by Zero + DZ = 0b01000, + + /// Invalid Operation + NV = 0b10000, +} + +impl Flags { + /// Inexact + #[inline] + pub fn nx(&self) -> bool { + self.0.get_bit(0) + } + + /// Underflow + #[inline] + pub fn uf(&self) -> bool { + self.0.get_bit(1) + } + + /// Overflow + #[inline] + pub fn of(&self) -> bool { + self.0.get_bit(2) + } + + /// Divide by Zero + #[inline] + pub fn dz(&self) -> bool { + self.0.get_bit(3) + } + + /// Invalid Operation + #[inline] + pub fn nv(&self) -> bool { + self.0.get_bit(4) + } +} + +/// Rounding Mode +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum RoundingMode { + RoundToNearestEven = 0b000, + RoundTowardsZero = 0b001, + RoundDown = 0b010, + RoundUp = 0b011, + RoundToNearestMaxMagnitude = 0b100, + Invalid = 0b111, +} + +impl FCSR { + /// Returns the contents of the register as raw bits + pub fn bits(&self) -> u32 { + self.bits + } + + /// Accrued Exception Flags + #[inline] + pub fn fflags(&self) -> Flags { + Flags(self.bits.get_bits(0..5)) + } + + /// Rounding Mode + #[inline] + pub fn frm(&self) -> RoundingMode { + match self.bits.get_bits(5..8) { + 0b000 => RoundingMode::RoundToNearestEven, + 0b001 => RoundingMode::RoundTowardsZero, + 0b010 => RoundingMode::RoundDown, + 0b011 => RoundingMode::RoundUp, + 0b100 => RoundingMode::RoundToNearestMaxMagnitude, + _ => RoundingMode::Invalid, + } + } +} + +read_csr!(0x003, __read_fcsr); +write_csr!(0x003, __write_fcsr); +clear!(0x003, __clear_fcsr); + +/// Reads the CSR +#[inline] +pub fn read() -> FCSR { + FCSR { + bits: unsafe { _read() as u32 }, + } +} + +/// Writes the CSR +#[inline] +pub unsafe fn set_rounding_mode(frm: RoundingMode) { + let old = read(); + let bits = ((frm as u32) << 5) | old.fflags().0; + _write(bits as usize); +} + +/// Resets `fflags` field bits +#[inline] +pub unsafe fn clear_flags() { + let mask = 0b11111; + _clear(mask); +} + +/// Resets `fflags` field bit +#[inline] +pub unsafe fn clear_flag(flag: Flag) { + _clear(flag as usize); +} diff --git a/ci-user/riscv/src/register/hpmcounterx.rs b/ci-user/riscv/src/register/hpmcounterx.rs new file mode 100644 index 0000000..5eb15b0 --- /dev/null +++ b/ci-user/riscv/src/register/hpmcounterx.rs @@ -0,0 +1,82 @@ +macro_rules! reg { + ( + $addr:expr, $csrl:ident, $csrh:ident, $readf:ident, $writef:ident + ) => { + /// Performance-monitoring counter + pub mod $csrl { + read_csr_as_usize!($addr, $readf); + read_composite_csr!(super::$csrh::read(), read()); + } + } +} + +macro_rules! regh { + ( + $addr:expr, $csrh:ident, $readf:ident, $writef:ident + ) => { + /// Upper 32 bits of performance-monitoring counter (RV32I only) + pub mod $csrh { + read_csr_as_usize_rv32!($addr, $readf); + } + } +} + +reg!(0xC03, hpmcounter3, hpmcounter3h, __read_hpmcounter3, __write_hpmcounter3); +reg!(0xC04, hpmcounter4, hpmcounter4h, __read_hpmcounter4, __write_hpmcounter4); +reg!(0xC05, hpmcounter5, hpmcounter5h, __read_hpmcounter5, __write_hpmcounter5); +reg!(0xC06, hpmcounter6, hpmcounter6h, __read_hpmcounter6, __write_hpmcounter6); +reg!(0xC07, hpmcounter7, hpmcounter7h, __read_hpmcounter7, __write_hpmcounter7); +reg!(0xC08, hpmcounter8, hpmcounter8h, __read_hpmcounter8, __write_hpmcounter8); +reg!(0xC09, hpmcounter9, hpmcounter9h, __read_hpmcounter9, __write_hpmcounter9); +reg!(0xC0A, hpmcounter10, hpmcounter10h, __read_hpmcounter10, __write_hpmcounter10); +reg!(0xC0B, hpmcounter11, hpmcounter11h, __read_hpmcounter11, __write_hpmcounter11); +reg!(0xC0C, hpmcounter12, hpmcounter12h, __read_hpmcounter12, __write_hpmcounter12); +reg!(0xC0D, hpmcounter13, hpmcounter13h, __read_hpmcounter13, __write_hpmcounter13); +reg!(0xC0E, hpmcounter14, hpmcounter14h, __read_hpmcounter14, __write_hpmcounter14); +reg!(0xC0F, hpmcounter15, hpmcounter15h, __read_hpmcounter15, __write_hpmcounter15); +reg!(0xC10, hpmcounter16, hpmcounter16h, __read_hpmcounter16, __write_hpmcounter16); +reg!(0xC11, hpmcounter17, hpmcounter17h, __read_hpmcounter17, __write_hpmcounter17); +reg!(0xC12, hpmcounter18, hpmcounter18h, __read_hpmcounter18, __write_hpmcounter18); +reg!(0xC13, hpmcounter19, hpmcounter19h, __read_hpmcounter19, __write_hpmcounter19); +reg!(0xC14, hpmcounter20, hpmcounter20h, __read_hpmcounter20, __write_hpmcounter20); +reg!(0xC15, hpmcounter21, hpmcounter21h, __read_hpmcounter21, __write_hpmcounter21); +reg!(0xC16, hpmcounter22, hpmcounter22h, __read_hpmcounter22, __write_hpmcounter22); +reg!(0xC17, hpmcounter23, hpmcounter23h, __read_hpmcounter23, __write_hpmcounter23); +reg!(0xC18, hpmcounter24, hpmcounter24h, __read_hpmcounter24, __write_hpmcounter24); +reg!(0xC19, hpmcounter25, hpmcounter25h, __read_hpmcounter25, __write_hpmcounter25); +reg!(0xC1A, hpmcounter26, hpmcounter26h, __read_hpmcounter26, __write_hpmcounter26); +reg!(0xC1B, hpmcounter27, hpmcounter27h, __read_hpmcounter27, __write_hpmcounter27); +reg!(0xC1C, hpmcounter28, hpmcounter28h, __read_hpmcounter28, __write_hpmcounter28); +reg!(0xC1D, hpmcounter29, hpmcounter29h, __read_hpmcounter29, __write_hpmcounter29); +reg!(0xC1E, hpmcounter30, hpmcounter30h, __read_hpmcounter30, __write_hpmcounter30); +reg!(0xC1F, hpmcounter31, hpmcounter31h, __read_hpmcounter31, __write_hpmcounter31); + +regh!(0xC83, hpmcounter3h, __read_hpmcounter3h, __write_hpmcounter3h); +regh!(0xC84, hpmcounter4h, __read_hpmcounter4h, __write_hpmcounter4h); +regh!(0xC85, hpmcounter5h, __read_hpmcounter5h, __write_hpmcounter5h); +regh!(0xC86, hpmcounter6h, __read_hpmcounter6h, __write_hpmcounter6h); +regh!(0xC87, hpmcounter7h, __read_hpmcounter7h, __write_hpmcounter7h); +regh!(0xC88, hpmcounter8h, __read_hpmcounter8h, __write_hpmcounter8h); +regh!(0xC89, hpmcounter9h, __read_hpmcounter9h, __write_hpmcounter9h); +regh!(0xC8A, hpmcounter10h, __read_hpmcounter10h, __write_hpmcounter10h); +regh!(0xC8B, hpmcounter11h, __read_hpmcounter11h, __write_hpmcounter11h); +regh!(0xC8C, hpmcounter12h, __read_hpmcounter12h, __write_hpmcounter12h); +regh!(0xC8D, hpmcounter13h, __read_hpmcounter13h, __write_hpmcounter13h); +regh!(0xC8E, hpmcounter14h, __read_hpmcounter14h, __write_hpmcounter14h); +regh!(0xC8F, hpmcounter15h, __read_hpmcounter15h, __write_hpmcounter15h); +regh!(0xC90, hpmcounter16h, __read_hpmcounter16h, __write_hpmcounter16h); +regh!(0xC91, hpmcounter17h, __read_hpmcounter17h, __write_hpmcounter17h); +regh!(0xC92, hpmcounter18h, __read_hpmcounter18h, __write_hpmcounter18h); +regh!(0xC93, hpmcounter19h, __read_hpmcounter19h, __write_hpmcounter19h); +regh!(0xC94, hpmcounter20h, __read_hpmcounter20h, __write_hpmcounter20h); +regh!(0xC95, hpmcounter21h, __read_hpmcounter21h, __write_hpmcounter21h); +regh!(0xC96, hpmcounter22h, __read_hpmcounter22h, __write_hpmcounter22h); +regh!(0xC97, hpmcounter23h, __read_hpmcounter23h, __write_hpmcounter23h); +regh!(0xC98, hpmcounter24h, __read_hpmcounter24h, __write_hpmcounter24h); +regh!(0xC99, hpmcounter25h, __read_hpmcounter25h, __write_hpmcounter25h); +regh!(0xC9A, hpmcounter26h, __read_hpmcounter26h, __write_hpmcounter26h); +regh!(0xC9B, hpmcounter27h, __read_hpmcounter27h, __write_hpmcounter27h); +regh!(0xC9C, hpmcounter28h, __read_hpmcounter28h, __write_hpmcounter28h); +regh!(0xC9D, hpmcounter29h, __read_hpmcounter29h, __write_hpmcounter29h); +regh!(0xC9E, hpmcounter30h, __read_hpmcounter30h, __write_hpmcounter30h); +regh!(0xC9F, hpmcounter31h, __read_hpmcounter31h, __write_hpmcounter31h); diff --git a/ci-user/riscv/src/register/hypervisorx64/hcounteren.rs b/ci-user/riscv/src/register/hypervisorx64/hcounteren.rs new file mode 100644 index 0000000..7f84690 --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/hcounteren.rs @@ -0,0 +1,413 @@ +//! Hypervisor Guest External Interrupt Pending Register. + +use bit_field::BitField; + +#[derive(Copy, Clone, Debug)] +pub struct Hcounteren { + bits: usize, +} +impl Hcounteren { + #[inline] + pub fn bits(&self) -> usize { + return self.bits; + } + #[inline] + pub fn from_bits(x: usize) -> Self { + return Hcounteren { bits: x }; + } + #[inline] + pub unsafe fn write(&self) { + _write(self.bits); + } + /// + #[inline] + pub fn cy(&self) -> bool { + self.bits.get_bit(0) + } + #[inline] + pub fn set_cy(&mut self, val: bool) { + self.bits.set_bit(0, val); + } + /// + #[inline] + pub fn tm(&self) -> bool { + self.bits.get_bit(1) + } + #[inline] + pub fn set_tm(&mut self, val: bool) { + self.bits.set_bit(1, val); + } + /// + #[inline] + pub fn ir(&self) -> bool { + self.bits.get_bit(2) + } + #[inline] + pub fn set_ir(&mut self, val: bool) { + self.bits.set_bit(2, val); + } + /// + #[inline] + pub fn hpm3(&self) -> bool { + self.bits.get_bit(3) + } + #[inline] + pub fn set_hpm3(&mut self, val: bool) { + self.bits.set_bit(3, val); + } + /// + #[inline] + pub fn hpm4(&self) -> bool { + self.bits.get_bit(4) + } + #[inline] + pub fn set_hpm4(&mut self, val: bool) { + self.bits.set_bit(4, val); + } + /// + #[inline] + pub fn hpm5(&self) -> bool { + self.bits.get_bit(5) + } + #[inline] + pub fn set_hpm5(&mut self, val: bool) { + self.bits.set_bit(5, val); + } + /// + #[inline] + pub fn hpm6(&self) -> bool { + self.bits.get_bit(6) + } + #[inline] + pub fn set_hpm6(&mut self, val: bool) { + self.bits.set_bit(6, val); + } + /// + #[inline] + pub fn hpm7(&self) -> bool { + self.bits.get_bit(7) + } + #[inline] + pub fn set_hpm7(&mut self, val: bool) { + self.bits.set_bit(7, val); + } + /// + #[inline] + pub fn hpm8(&self) -> bool { + self.bits.get_bit(8) + } + #[inline] + pub fn set_hpm8(&mut self, val: bool) { + self.bits.set_bit(8, val); + } + /// + #[inline] + pub fn hpm9(&self) -> bool { + self.bits.get_bit(9) + } + #[inline] + pub fn set_hpm9(&mut self, val: bool) { + self.bits.set_bit(9, val); + } + /// + #[inline] + pub fn hpm10(&self) -> bool { + self.bits.get_bit(10) + } + #[inline] + pub fn set_hpm10(&mut self, val: bool) { + self.bits.set_bit(10, val); + } + /// + #[inline] + pub fn hpm11(&self) -> bool { + self.bits.get_bit(11) + } + #[inline] + pub fn set_hpm11(&mut self, val: bool) { + self.bits.set_bit(11, val); + } + /// + #[inline] + pub fn hpm12(&self) -> bool { + self.bits.get_bit(12) + } + #[inline] + pub fn set_hpm12(&mut self, val: bool) { + self.bits.set_bit(12, val); + } + /// + #[inline] + pub fn hpm13(&self) -> bool { + self.bits.get_bit(13) + } + #[inline] + pub fn set_hpm13(&mut self, val: bool) { + self.bits.set_bit(13, val); + } + /// + #[inline] + pub fn hpm14(&self) -> bool { + self.bits.get_bit(14) + } + #[inline] + pub fn set_hpm14(&mut self, val: bool) { + self.bits.set_bit(14, val); + } + /// + #[inline] + pub fn hpm15(&self) -> bool { + self.bits.get_bit(15) + } + #[inline] + pub fn set_hpm15(&mut self, val: bool) { + self.bits.set_bit(15, val); + } + /// + #[inline] + pub fn hpm16(&self) -> bool { + self.bits.get_bit(16) + } + #[inline] + pub fn set_hpm16(&mut self, val: bool) { + self.bits.set_bit(16, val); + } + /// + #[inline] + pub fn hpm17(&self) -> bool { + self.bits.get_bit(17) + } + #[inline] + pub fn set_hpm17(&mut self, val: bool) { + self.bits.set_bit(17, val); + } + /// + #[inline] + pub fn hpm18(&self) -> bool { + self.bits.get_bit(18) + } + #[inline] + pub fn set_hpm18(&mut self, val: bool) { + self.bits.set_bit(18, val); + } + /// + #[inline] + pub fn hpm19(&self) -> bool { + self.bits.get_bit(19) + } + #[inline] + pub fn set_hpm19(&mut self, val: bool) { + self.bits.set_bit(19, val); + } + /// + #[inline] + pub fn hpm20(&self) -> bool { + self.bits.get_bit(20) + } + #[inline] + pub fn set_hpm20(&mut self, val: bool) { + self.bits.set_bit(20, val); + } + /// + #[inline] + pub fn hpm21(&self) -> bool { + self.bits.get_bit(21) + } + #[inline] + pub fn set_hpm21(&mut self, val: bool) { + self.bits.set_bit(21, val); + } + /// + #[inline] + pub fn hpm22(&self) -> bool { + self.bits.get_bit(22) + } + #[inline] + pub fn set_hpm22(&mut self, val: bool) { + self.bits.set_bit(22, val); + } + /// + #[inline] + pub fn hpm23(&self) -> bool { + self.bits.get_bit(23) + } + #[inline] + pub fn set_hpm23(&mut self, val: bool) { + self.bits.set_bit(23, val); + } + /// + #[inline] + pub fn hpm24(&self) -> bool { + self.bits.get_bit(24) + } + #[inline] + pub fn set_hpm24(&mut self, val: bool) { + self.bits.set_bit(24, val); + } + /// + #[inline] + pub fn hpm25(&self) -> bool { + self.bits.get_bit(25) + } + #[inline] + pub fn set_hpm25(&mut self, val: bool) { + self.bits.set_bit(25, val); + } + /// + #[inline] + pub fn hpm26(&self) -> bool { + self.bits.get_bit(26) + } + #[inline] + pub fn set_hpm26(&mut self, val: bool) { + self.bits.set_bit(26, val); + } + /// + #[inline] + pub fn hpm27(&self) -> bool { + self.bits.get_bit(27) + } + #[inline] + pub fn set_hpm27(&mut self, val: bool) { + self.bits.set_bit(27, val); + } + /// + #[inline] + pub fn hpm28(&self) -> bool { + self.bits.get_bit(28) + } + #[inline] + pub fn set_hpm28(&mut self, val: bool) { + self.bits.set_bit(28, val); + } + /// + #[inline] + pub fn hpm29(&self) -> bool { + self.bits.get_bit(29) + } + #[inline] + pub fn set_hpm29(&mut self, val: bool) { + self.bits.set_bit(29, val); + } + /// + #[inline] + pub fn hpm30(&self) -> bool { + self.bits.get_bit(30) + } + #[inline] + pub fn set_hpm30(&mut self, val: bool) { + self.bits.set_bit(30, val); + } + /// + #[inline] + pub fn hpm31(&self) -> bool { + self.bits.get_bit(31) + } + #[inline] + pub fn set_hpm31(&mut self, val: bool) { + self.bits.set_bit(31, val); + } +} +read_csr_as!(Hcounteren, 3602, __read_hcounteren); +write_csr!(3602, __write_hcounteren); +set!(3602, __set_hcounteren); +clear!(3602, __clear_hcounteren); +// bit ops +set_clear_csr!( + /// + , set_cy, clear_cy, 1 << 0); +set_clear_csr!( + /// + , set_tm, clear_tm, 1 << 1); +set_clear_csr!( + /// + , set_ir, clear_ir, 1 << 2); +set_clear_csr!( + /// + , set_hpm3, clear_hpm3, 1 << 3); +set_clear_csr!( + /// + , set_hpm4, clear_hpm4, 1 << 4); +set_clear_csr!( + /// + , set_hpm5, clear_hpm5, 1 << 5); +set_clear_csr!( + /// + , set_hpm6, clear_hpm6, 1 << 6); +set_clear_csr!( + /// + , set_hpm7, clear_hpm7, 1 << 7); +set_clear_csr!( + /// + , set_hpm8, clear_hpm8, 1 << 8); +set_clear_csr!( + /// + , set_hpm9, clear_hpm9, 1 << 9); +set_clear_csr!( + /// + , set_hpm10, clear_hpm10, 1 << 10); +set_clear_csr!( + /// + , set_hpm11, clear_hpm11, 1 << 11); +set_clear_csr!( + /// + , set_hpm12, clear_hpm12, 1 << 12); +set_clear_csr!( + /// + , set_hpm13, clear_hpm13, 1 << 13); +set_clear_csr!( + /// + , set_hpm14, clear_hpm14, 1 << 14); +set_clear_csr!( + /// + , set_hpm15, clear_hpm15, 1 << 15); +set_clear_csr!( + /// + , set_hpm16, clear_hpm16, 1 << 16); +set_clear_csr!( + /// + , set_hpm17, clear_hpm17, 1 << 17); +set_clear_csr!( + /// + , set_hpm18, clear_hpm18, 1 << 18); +set_clear_csr!( + /// + , set_hpm19, clear_hpm19, 1 << 19); +set_clear_csr!( + /// + , set_hpm20, clear_hpm20, 1 << 20); +set_clear_csr!( + /// + , set_hpm21, clear_hpm21, 1 << 21); +set_clear_csr!( + /// + , set_hpm22, clear_hpm22, 1 << 22); +set_clear_csr!( + /// + , set_hpm23, clear_hpm23, 1 << 23); +set_clear_csr!( + /// + , set_hpm24, clear_hpm24, 1 << 24); +set_clear_csr!( + /// + , set_hpm25, clear_hpm25, 1 << 25); +set_clear_csr!( + /// + , set_hpm26, clear_hpm26, 1 << 26); +set_clear_csr!( + /// + , set_hpm27, clear_hpm27, 1 << 27); +set_clear_csr!( + /// + , set_hpm28, clear_hpm28, 1 << 28); +set_clear_csr!( + /// + , set_hpm29, clear_hpm29, 1 << 29); +set_clear_csr!( + /// + , set_hpm30, clear_hpm30, 1 << 30); +set_clear_csr!( + /// + , set_hpm31, clear_hpm31, 1 << 31); + +// enums diff --git a/ci-user/riscv/src/register/hypervisorx64/hedeleg.rs b/ci-user/riscv/src/register/hypervisorx64/hedeleg.rs new file mode 100644 index 0000000..aac1eb9 --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/hedeleg.rs @@ -0,0 +1,173 @@ +//! Hypervisor Exception Delegation Register. + +use bit_field::BitField; + +#[derive(Copy, Clone, Debug)] +pub struct Hedeleg { + bits: usize, +} +impl Hedeleg { + #[inline] + pub fn bits(&self) -> usize { + return self.bits; + } + #[inline] + pub fn from_bits(x: usize) -> Self { + return Hedeleg { bits: x }; + } + #[inline] + pub unsafe fn write(&self) { + _write(self.bits); + } + /// Instruction address misaligned + #[inline] + pub fn ex0(&self) -> bool { + self.bits.get_bit(0) + } + #[inline] + pub fn set_ex0(&mut self, val: bool) { + self.bits.set_bit(0, val); + } + /// Instruction access fault + #[inline] + pub fn ex1(&self) -> bool { + self.bits.get_bit(1) + } + #[inline] + pub fn set_ex1(&mut self, val: bool) { + self.bits.set_bit(1, val); + } + /// Illegal instruction + #[inline] + pub fn ex2(&self) -> bool { + self.bits.get_bit(2) + } + #[inline] + pub fn set_ex2(&mut self, val: bool) { + self.bits.set_bit(2, val); + } + /// Breakpoint + #[inline] + pub fn ex3(&self) -> bool { + self.bits.get_bit(3) + } + #[inline] + pub fn set_ex3(&mut self, val: bool) { + self.bits.set_bit(3, val); + } + /// Load address misaligned + #[inline] + pub fn ex4(&self) -> bool { + self.bits.get_bit(4) + } + #[inline] + pub fn set_ex4(&mut self, val: bool) { + self.bits.set_bit(4, val); + } + /// Load access fault + #[inline] + pub fn ex5(&self) -> bool { + self.bits.get_bit(5) + } + #[inline] + pub fn set_ex5(&mut self, val: bool) { + self.bits.set_bit(5, val); + } + /// Store/AMO address misaligned + #[inline] + pub fn ex6(&self) -> bool { + self.bits.get_bit(6) + } + #[inline] + pub fn set_ex6(&mut self, val: bool) { + self.bits.set_bit(6, val); + } + /// Store/AMO access fault + #[inline] + pub fn ex7(&self) -> bool { + self.bits.get_bit(7) + } + #[inline] + pub fn set_ex7(&mut self, val: bool) { + self.bits.set_bit(7, val); + } + /// Environment call from U-mode or VU-mode + #[inline] + pub fn ex8(&self) -> bool { + self.bits.get_bit(8) + } + #[inline] + pub fn set_ex8(&mut self, val: bool) { + self.bits.set_bit(8, val); + } + /// Instruction page fault + #[inline] + pub fn ex12(&self) -> bool { + self.bits.get_bit(12) + } + #[inline] + pub fn set_ex12(&mut self, val: bool) { + self.bits.set_bit(12, val); + } + /// Load page fault + #[inline] + pub fn ex13(&self) -> bool { + self.bits.get_bit(13) + } + #[inline] + pub fn set_ex13(&mut self, val: bool) { + self.bits.set_bit(13, val); + } + /// Store/AMO page fault + #[inline] + pub fn ex15(&self) -> bool { + self.bits.get_bit(15) + } + #[inline] + pub fn set_ex15(&mut self, val: bool) { + self.bits.set_bit(15, val); + } +} +read_csr_as!(Hedeleg, 1538, __read_hedeleg); +write_csr!(1538, __write_hedeleg); +set!(1538, __set_hedeleg); +clear!(1538, __clear_hedeleg); +// bit ops +set_clear_csr!( + ///Instruction address misaligned + , set_ex0, clear_ex0, 1 << 0); +set_clear_csr!( + ///Instruction access fault + , set_ex1, clear_ex1, 1 << 1); +set_clear_csr!( + ///Illegal instruction + , set_ex2, clear_ex2, 1 << 2); +set_clear_csr!( + ///Breakpoint + , set_ex3, clear_ex3, 1 << 3); +set_clear_csr!( + ///Load address misaligned + , set_ex4, clear_ex4, 1 << 4); +set_clear_csr!( + ///Load access fault + , set_ex5, clear_ex5, 1 << 5); +set_clear_csr!( + ///Store/AMO address misaligned + , set_ex6, clear_ex6, 1 << 6); +set_clear_csr!( + ///Store/AMO access fault + , set_ex7, clear_ex7, 1 << 7); +set_clear_csr!( + ///Environment call from U-mode or VU-mode + , set_ex8, clear_ex8, 1 << 8); +set_clear_csr!( + ///Instruction page fault + , set_ex12, clear_ex12, 1 << 12); +set_clear_csr!( + ///Load page fault + , set_ex13, clear_ex13, 1 << 13); +set_clear_csr!( + ///Store/AMO page fault + , set_ex15, clear_ex15, 1 << 15); + +// enums diff --git a/ci-user/riscv/src/register/hypervisorx64/hgatp.rs b/ci-user/riscv/src/register/hypervisorx64/hgatp.rs new file mode 100644 index 0000000..798b55c --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/hgatp.rs @@ -0,0 +1,73 @@ +//! Hypervisor Guest Address Translation and Protection Register. + +use bit_field::BitField; + +#[derive(Copy, Clone, Debug)] +pub struct Hgatp { + bits: usize, +} +impl Hgatp { + #[inline] + pub fn bits(&self) -> usize { + return self.bits; + } + #[inline] + pub fn from_bits(x: usize) -> Self { + return Hgatp { bits: x }; + } + #[inline] + pub unsafe fn write(&self) { + _write(self.bits); + } + /// Guest address translation mode. + #[inline] + pub fn mode(&self) -> HgatpValues { + HgatpValues::from(self.bits.get_bits(60..64)) + } + #[inline] + pub fn set_mode(&mut self, val: HgatpValues) { + self.bits.set_bits(60..64, val as usize); + } + /// Virtual machine ID. + #[inline] + pub fn vmid(&self) -> usize { + self.bits.get_bits(44..58) + } + #[inline] + pub fn set_vmid(&mut self, val: usize) { + self.bits.set_bits(44..58, val); + } + /// Physical Page Number for root page table. + #[inline] + pub fn ppn(&self) -> usize { + self.bits.get_bits(0..44) + } + #[inline] + pub fn set_ppn(&mut self, val: usize) { + self.bits.set_bits(0..44, val); + } +} +read_csr_as!(Hgatp, 1664, __read_hgatp); +write_csr!(1664, __write_hgatp); +set!(1664, __set_hgatp); +clear!(1664, __clear_hgatp); +// bit ops + +// enums +#[derive(Copy, Clone, Debug)] +#[repr(usize)] +pub enum HgatpValues { + Bare = 0, + Sv39x4 = 8, + Sv48x4 = 9, +} +impl HgatpValues { + fn from(x: usize) -> Self { + match x { + 0 => Self::Bare, + 8 => Self::Sv39x4, + 9 => Self::Sv48x4, + _ => unreachable!(), + } + } +} diff --git a/ci-user/riscv/src/register/hypervisorx64/hgeie.rs b/ci-user/riscv/src/register/hypervisorx64/hgeie.rs new file mode 100644 index 0000000..09d9725 --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/hgeie.rs @@ -0,0 +1,3 @@ +//! Hypervisor Guest External Interrupt Enable Register. +read_csr_as_usize!(1543, __read_hgeie); +write_csr_as_usize!(1543, __write_hgeie); diff --git a/ci-user/riscv/src/register/hypervisorx64/hgeip.rs b/ci-user/riscv/src/register/hypervisorx64/hgeip.rs new file mode 100644 index 0000000..75f1cab --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/hgeip.rs @@ -0,0 +1,3 @@ +//! Hypervisor Guest External Interrupt Pending Register. +read_csr_as_usize!(3602, __read_hgeip); +write_csr_as_usize!(3602, __write_hgeip); diff --git a/ci-user/riscv/src/register/hypervisorx64/hideleg.rs b/ci-user/riscv/src/register/hypervisorx64/hideleg.rs new file mode 100644 index 0000000..f138ab0 --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/hideleg.rs @@ -0,0 +1,65 @@ +//! Hypervisor Interrupt Delegation Register. + +use bit_field::BitField; + +#[derive(Copy, Clone, Debug)] +pub struct Hideleg { + bits: usize, +} +impl Hideleg { + #[inline] + pub fn bits(&self) -> usize { + return self.bits; + } + #[inline] + pub fn from_bits(x: usize) -> Self { + return Hideleg { bits: x }; + } + #[inline] + pub unsafe fn write(&self) { + _write(self.bits); + } + /// Software Interrupt + #[inline] + pub fn sip(&self) -> bool { + self.bits.get_bit(2) + } + #[inline] + pub fn set_sip(&mut self, val: bool) { + self.bits.set_bit(2, val); + } + /// Timer Interrupt + #[inline] + pub fn tip(&self) -> bool { + self.bits.get_bit(6) + } + #[inline] + pub fn set_tip(&mut self, val: bool) { + self.bits.set_bit(6, val); + } + /// External Interrupt + #[inline] + pub fn eip(&self) -> bool { + self.bits.get_bit(10) + } + #[inline] + pub fn set_eip(&mut self, val: bool) { + self.bits.set_bit(10, val); + } +} +read_csr_as!(Hideleg, 1539, __read_hideleg); +write_csr!(1539, __write_hideleg); +set!(1539, __set_hideleg); +clear!(1539, __clear_hideleg); +// bit ops +set_clear_csr!( + ///Software Interrupt + , set_sip, clear_sip, 1 << 2); +set_clear_csr!( + ///Timer Interrupt + , set_tip, clear_tip, 1 << 6); +set_clear_csr!( + ///External Interrupt + , set_eip, clear_eip, 1 << 10); + +// enums diff --git a/ci-user/riscv/src/register/hypervisorx64/hie.rs b/ci-user/riscv/src/register/hypervisorx64/hie.rs new file mode 100644 index 0000000..64d1d0c --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/hie.rs @@ -0,0 +1,77 @@ +//! Hypervisor Interrupt Enable Register. + +use bit_field::BitField; + +#[derive(Copy, Clone, Debug)] +pub struct Hie { + bits: usize, +} +impl Hie { + #[inline] + pub fn bits(&self) -> usize { + return self.bits; + } + #[inline] + pub fn from_bits(x: usize) -> Self { + return Hie { bits: x }; + } + #[inline] + pub unsafe fn write(&self) { + _write(self.bits); + } + /// Software Interrupt + #[inline] + pub fn vssie(&self) -> bool { + self.bits.get_bit(2) + } + #[inline] + pub fn set_vssie(&mut self, val: bool) { + self.bits.set_bit(2, val); + } + /// Timer Interrupt + #[inline] + pub fn vstie(&self) -> bool { + self.bits.get_bit(6) + } + #[inline] + pub fn set_vstie(&mut self, val: bool) { + self.bits.set_bit(6, val); + } + /// External Interrupt + #[inline] + pub fn vseie(&self) -> bool { + self.bits.get_bit(10) + } + #[inline] + pub fn set_vseie(&mut self, val: bool) { + self.bits.set_bit(10, val); + } + /// Guest External Interrupt + #[inline] + pub fn sgeie(&self) -> bool { + self.bits.get_bit(12) + } + #[inline] + pub fn set_sgeie(&mut self, val: bool) { + self.bits.set_bit(12, val); + } +} +read_csr_as!(Hie, 1540, __read_hie); +write_csr!(1540, __write_hie); +set!(1540, __set_hie); +clear!(1540, __clear_hie); +// bit ops +set_clear_csr!( + ///Software Interrupt + , set_vssie, clear_vssie, 1 << 2); +set_clear_csr!( + ///Timer Interrupt + , set_vstie, clear_vstie, 1 << 6); +set_clear_csr!( + ///External Interrupt + , set_vseie, clear_vseie, 1 << 10); +set_clear_csr!( + ///Guest External Interrupt + , set_sgeie, clear_sgeie, 1 << 12); + +// enums diff --git a/ci-user/riscv/src/register/hypervisorx64/hip.rs b/ci-user/riscv/src/register/hypervisorx64/hip.rs new file mode 100644 index 0000000..dd29763 --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/hip.rs @@ -0,0 +1,77 @@ +//! Hypervisor Interrupt Pending Register. + +use bit_field::BitField; + +#[derive(Copy, Clone, Debug)] +pub struct Hip { + bits: usize, +} +impl Hip { + #[inline] + pub fn bits(&self) -> usize { + return self.bits; + } + #[inline] + pub fn from_bits(x: usize) -> Self { + return Hip { bits: x }; + } + #[inline] + pub unsafe fn write(&self) { + _write(self.bits); + } + /// Software Interrupt + #[inline] + pub fn vssip(&self) -> bool { + self.bits.get_bit(2) + } + #[inline] + pub fn set_vssip(&mut self, val: bool) { + self.bits.set_bit(2, val); + } + /// Timer Interrupt + #[inline] + pub fn vstip(&self) -> bool { + self.bits.get_bit(6) + } + #[inline] + pub fn set_vstip(&mut self, val: bool) { + self.bits.set_bit(6, val); + } + /// External Interrupt + #[inline] + pub fn vseip(&self) -> bool { + self.bits.get_bit(10) + } + #[inline] + pub fn set_vseip(&mut self, val: bool) { + self.bits.set_bit(10, val); + } + /// Guest External Interrupt + #[inline] + pub fn sgeip(&self) -> bool { + self.bits.get_bit(12) + } + #[inline] + pub fn set_sgeip(&mut self, val: bool) { + self.bits.set_bit(12, val); + } +} +read_csr_as!(Hip, 1604, __read_hip); +write_csr!(1604, __write_hip); +set!(1604, __set_hip); +clear!(1604, __clear_hip); +// bit ops +set_clear_csr!( + ///Software Interrupt + , set_vssip, clear_vssip, 1 << 2); +set_clear_csr!( + ///Timer Interrupt + , set_vstip, clear_vstip, 1 << 6); +set_clear_csr!( + ///External Interrupt + , set_vseip, clear_vseip, 1 << 10); +set_clear_csr!( + ///Guest External Interrupt + , set_sgeip, clear_sgeip, 1 << 12); + +// enums diff --git a/ci-user/riscv/src/register/hypervisorx64/hstatus.rs b/ci-user/riscv/src/register/hypervisorx64/hstatus.rs new file mode 100644 index 0000000..386c1a6 --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/hstatus.rs @@ -0,0 +1,160 @@ +//! HStatus Register. + +use bit_field::BitField; + +#[derive(Copy, Clone, Debug)] +pub struct Hstatus { + bits: usize, +} +impl Hstatus { + #[inline] + pub fn bits(&self) -> usize { + return self.bits; + } + #[inline] + pub fn from_bits(x: usize) -> Self { + return Hstatus { bits: x }; + } + #[inline] + pub unsafe fn write(&self) { + _write(self.bits); + } + /// Effective XLEN for VM. + #[inline] + pub fn vsxl(&self) -> VsxlValues { + VsxlValues::from(self.bits.get_bits(32..34)) + } + #[inline] + pub fn set_vsxl(&mut self, val: VsxlValues) { + self.bits.set_bits(32..34, val as usize); + } + /// TSR for VM. + #[inline] + pub fn vtsr(&self) -> bool { + self.bits.get_bit(22) + } + #[inline] + pub fn set_vtsr(&mut self, val: bool) { + self.bits.set_bit(22, val); + } + /// TW for VM. + #[inline] + pub fn vtw(&self) -> bool { + self.bits.get_bit(21) + } + #[inline] + pub fn set_vtw(&mut self, val: bool) { + self.bits.set_bit(21, val); + } + /// TVM for VM. + #[inline] + pub fn vtvm(&self) -> bool { + self.bits.get_bit(20) + } + #[inline] + pub fn set_vtvm(&mut self, val: bool) { + self.bits.set_bit(20, val); + } + /// Virtual Guest External Interrupt Number. + #[inline] + pub fn vgein(&self) -> usize { + self.bits.get_bits(12..18) + } + #[inline] + pub fn set_vgein(&mut self, val: usize) { + self.bits.set_bits(12..18, val); + } + /// Hypervisor User mode. + #[inline] + pub fn hu(&self) -> bool { + self.bits.get_bit(9) + } + #[inline] + pub fn set_hu(&mut self, val: bool) { + self.bits.set_bit(9, val); + } + /// Supervisor Previous Virtual Privilege. + #[inline] + pub fn spvp(&self) -> bool { + self.bits.get_bit(8) + } + #[inline] + pub fn set_spvp(&mut self, val: bool) { + self.bits.set_bit(8, val); + } + /// Supervisor Previous Virtualization mode. + #[inline] + pub fn spv(&self) -> bool { + self.bits.get_bit(7) + } + #[inline] + pub fn set_spv(&mut self, val: bool) { + self.bits.set_bit(7, val); + } + /// Guest Virtual Address. + #[inline] + pub fn gva(&self) -> bool { + self.bits.get_bit(6) + } + #[inline] + pub fn set_gva(&mut self, val: bool) { + self.bits.set_bit(6, val); + } + /// VS access endianness. + #[inline] + pub fn vsbe(&self) -> bool { + self.bits.get_bit(5) + } + #[inline] + pub fn set_vsbe(&mut self, val: bool) { + self.bits.set_bit(5, val); + } +} +read_csr_as!(Hstatus, 1536, __read_hstatus); +write_csr!(1536, __write_hstatus); +set!(1536, __set_hstatus); +clear!(1536, __clear_hstatus); +// bit ops +set_clear_csr!( + ///TSR for VM. + , set_vtsr, clear_vtsr, 1 << 22); +set_clear_csr!( + ///TW for VM. + , set_vtw, clear_vtw, 1 << 21); +set_clear_csr!( + ///TVM for VM. + , set_vtvm, clear_vtvm, 1 << 20); +set_clear_csr!( + ///Hypervisor User mode. + , set_hu, clear_hu, 1 << 9); +set_clear_csr!( + ///Supervisor Previous Virtual Privilege. + , set_spvp, clear_spvp, 1 << 8); +set_clear_csr!( + ///Supervisor Previous Virtualization mode. + , set_spv, clear_spv, 1 << 7); +set_clear_csr!( + ///Guest Virtual Address. + , set_gva, clear_gva, 1 << 6); +set_clear_csr!( + ///VS access endianness. + , set_vsbe, clear_vsbe, 1 << 5); + +// enums +#[derive(Copy, Clone, Debug)] +#[repr(usize)] +pub enum VsxlValues { + Vsxl32 = 1, + Vsxl64 = 2, + Vsxl128 = 3, +} +impl VsxlValues { + fn from(x: usize) -> Self { + match x { + 1 => Self::Vsxl32, + 2 => Self::Vsxl64, + 3 => Self::Vsxl128, + _ => unreachable!(), + } + } +} diff --git a/ci-user/riscv/src/register/hypervisorx64/htimedelta.rs b/ci-user/riscv/src/register/hypervisorx64/htimedelta.rs new file mode 100644 index 0000000..c3874b2 --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/htimedelta.rs @@ -0,0 +1,4 @@ +//! Hypervisor Time Delta Register. +read_composite_csr!(super::htimedeltah::read(), read()); +read_csr_as_usize!(1541, __read_htimedelta); +write_csr_as_usize!(1541, __write_htimedelta); diff --git a/ci-user/riscv/src/register/hypervisorx64/htimedeltah.rs b/ci-user/riscv/src/register/hypervisorx64/htimedeltah.rs new file mode 100644 index 0000000..8d7d218 --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/htimedeltah.rs @@ -0,0 +1,3 @@ +//! Hypervisor Time Delta Register. +read_csr_as_usize!(1557, __read_htimedeltah); +write_csr_as_usize!(1557, __write_htimedeltah); diff --git a/ci-user/riscv/src/register/hypervisorx64/htinst.rs b/ci-user/riscv/src/register/hypervisorx64/htinst.rs new file mode 100644 index 0000000..0619ccb --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/htinst.rs @@ -0,0 +1,3 @@ +//! Hypervisor Trap Instruction Register. +read_csr_as_usize!(1610, __read_htinst); +write_csr_as_usize!(1610, __write_htinst); diff --git a/ci-user/riscv/src/register/hypervisorx64/htval.rs b/ci-user/riscv/src/register/hypervisorx64/htval.rs new file mode 100644 index 0000000..89694e4 --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/htval.rs @@ -0,0 +1,3 @@ +//! Hypervisor Trap Value Register. +read_csr_as_usize!(1603, __read_htval); +write_csr_as_usize!(1603, __write_htval); diff --git a/ci-user/riscv/src/register/hypervisorx64/hvip.rs b/ci-user/riscv/src/register/hypervisorx64/hvip.rs new file mode 100644 index 0000000..fcfb8c3 --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/hvip.rs @@ -0,0 +1,65 @@ +//! Hypervisor Virtual Interrupt Pending Register. + +use bit_field::BitField; + +#[derive(Copy, Clone, Debug)] +pub struct Hvip { + bits: usize, +} +impl Hvip { + #[inline] + pub fn bits(&self) -> usize { + return self.bits; + } + #[inline] + pub fn from_bits(x: usize) -> Self { + return Hvip { bits: x }; + } + #[inline] + pub unsafe fn write(&self) { + _write(self.bits); + } + /// Software Interrupt + #[inline] + pub fn vssip(&self) -> bool { + self.bits.get_bit(2) + } + #[inline] + pub fn set_vssip(&mut self, val: bool) { + self.bits.set_bit(2, val); + } + /// Timer Interrupt + #[inline] + pub fn vstip(&self) -> bool { + self.bits.get_bit(6) + } + #[inline] + pub fn set_vstip(&mut self, val: bool) { + self.bits.set_bit(6, val); + } + /// External Interrupt + #[inline] + pub fn vseip(&self) -> bool { + self.bits.get_bit(10) + } + #[inline] + pub fn set_vseip(&mut self, val: bool) { + self.bits.set_bit(10, val); + } +} +read_csr_as!(Hvip, 1605, __read_hvip); +write_csr!(1605, __write_hvip); +set!(1605, __set_hvip); +clear!(1605, __clear_hvip); +// bit ops +set_clear_csr!( + ///Software Interrupt + , set_vssip, clear_vssip, 1 << 2); +set_clear_csr!( + ///Timer Interrupt + , set_vstip, clear_vstip, 1 << 6); +set_clear_csr!( + ///External Interrupt + , set_vseip, clear_vseip, 1 << 10); + +// enums diff --git a/ci-user/riscv/src/register/hypervisorx64/mod.rs b/ci-user/riscv/src/register/hypervisorx64/mod.rs new file mode 100644 index 0000000..06706b1 --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/mod.rs @@ -0,0 +1,23 @@ +pub mod hcounteren; +pub mod hedeleg; +pub mod hgatp; +pub mod hgeie; +pub mod hgeip; +pub mod hideleg; +pub mod hie; +pub mod hip; +pub mod hstatus; +pub mod htimedelta; +pub mod htimedeltah; +pub mod htinst; +pub mod htval; +pub mod hvip; +pub mod vsatp; +pub mod vscause; +pub mod vsepc; +pub mod vsie; +pub mod vsip; +pub mod vsscratch; +pub mod vsstatus; +pub mod vstval; +pub mod vstvec; diff --git a/ci-user/riscv/src/register/hypervisorx64/vsatp.rs b/ci-user/riscv/src/register/hypervisorx64/vsatp.rs new file mode 100644 index 0000000..0781acc --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/vsatp.rs @@ -0,0 +1,73 @@ +//! Virtual Supervisor Guest Address Translation and Protection Register. + +use bit_field::BitField; + +#[derive(Copy, Clone, Debug)] +pub struct Vsatp { + bits: usize, +} +impl Vsatp { + #[inline] + pub fn bits(&self) -> usize { + return self.bits; + } + #[inline] + pub fn from_bits(x: usize) -> Self { + return Vsatp { bits: x }; + } + #[inline] + pub unsafe fn write(&self) { + _write(self.bits); + } + /// Guest address translation mode. + #[inline] + pub fn mode(&self) -> HgatpValues { + HgatpValues::from(self.bits.get_bits(60..64)) + } + #[inline] + pub fn set_mode(&mut self, val: HgatpValues) { + self.bits.set_bits(60..64, val as usize); + } + /// ASID. + #[inline] + pub fn asid(&self) -> usize { + self.bits.get_bits(44..60) + } + #[inline] + pub fn set_asid(&mut self, val: usize) { + self.bits.set_bits(44..60, val); + } + /// Physical Page Number for root page table. + #[inline] + pub fn ppn(&self) -> usize { + self.bits.get_bits(0..44) + } + #[inline] + pub fn set_ppn(&mut self, val: usize) { + self.bits.set_bits(0..44, val); + } +} +read_csr_as!(Vsatp, 640, __read_vsatp); +write_csr!(640, __write_vsatp); +set!(640, __set_vsatp); +clear!(640, __clear_vsatp); +// bit ops + +// enums +#[derive(Copy, Clone, Debug)] +#[repr(usize)] +pub enum HgatpValues { + Bare = 0, + Sv39x4 = 8, + Sv48x4 = 9, +} +impl HgatpValues { + fn from(x: usize) -> Self { + match x { + 0 => Self::Bare, + 8 => Self::Sv39x4, + 9 => Self::Sv48x4, + _ => unreachable!(), + } + } +} diff --git a/ci-user/riscv/src/register/hypervisorx64/vscause.rs b/ci-user/riscv/src/register/hypervisorx64/vscause.rs new file mode 100644 index 0000000..cab545f --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/vscause.rs @@ -0,0 +1,50 @@ +//! Virtual Supervisor Cause Register. + +use bit_field::BitField; + +#[derive(Copy, Clone, Debug)] +pub struct Vscause { + bits: usize, +} +impl Vscause { + #[inline] + pub fn bits(&self) -> usize { + return self.bits; + } + #[inline] + pub fn from_bits(x: usize) -> Self { + return Vscause { bits: x }; + } + #[inline] + pub unsafe fn write(&self) { + _write(self.bits); + } + /// Is cause interrupt. + #[inline] + pub fn interrupt(&self) -> bool { + self.bits.get_bit(63) + } + #[inline] + pub fn set_interrupt(&mut self, val: bool) { + self.bits.set_bit(63, val); + } + /// Exception code + #[inline] + pub fn code(&self) -> usize { + self.bits.get_bits(0..63) + } + #[inline] + pub fn set_code(&mut self, val: usize) { + self.bits.set_bits(0..63, val); + } +} +read_csr_as!(Vscause, 578, __read_vscause); +write_csr!(578, __write_vscause); +set!(578, __set_vscause); +clear!(578, __clear_vscause); +// bit ops +set_clear_csr!( + ///Is cause interrupt. + , set_interrupt, clear_interrupt, 1 << 63); + +// enums diff --git a/ci-user/riscv/src/register/hypervisorx64/vsepc.rs b/ci-user/riscv/src/register/hypervisorx64/vsepc.rs new file mode 100644 index 0000000..c5b5670 --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/vsepc.rs @@ -0,0 +1,3 @@ +//! Virtual Supervisor Exception Program Counter. +read_csr_as_usize!(577, __read_vsepc); +write_csr_as_usize!(577, __write_vsepc); diff --git a/ci-user/riscv/src/register/hypervisorx64/vsie.rs b/ci-user/riscv/src/register/hypervisorx64/vsie.rs new file mode 100644 index 0000000..7a8891d --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/vsie.rs @@ -0,0 +1,65 @@ +//! Virtual Supevisor Interrupt Enable Register. + +use bit_field::BitField; + +#[derive(Copy, Clone, Debug)] +pub struct Vsie { + bits: usize, +} +impl Vsie { + #[inline] + pub fn bits(&self) -> usize { + return self.bits; + } + #[inline] + pub fn from_bits(x: usize) -> Self { + return Vsie { bits: x }; + } + #[inline] + pub unsafe fn write(&self) { + _write(self.bits); + } + /// Software Interrupt + #[inline] + pub fn ssie(&self) -> bool { + self.bits.get_bit(1) + } + #[inline] + pub fn set_ssie(&mut self, val: bool) { + self.bits.set_bit(1, val); + } + /// Timer Interrupt + #[inline] + pub fn stie(&self) -> bool { + self.bits.get_bit(5) + } + #[inline] + pub fn set_stie(&mut self, val: bool) { + self.bits.set_bit(5, val); + } + /// External Interrupt + #[inline] + pub fn seie(&self) -> bool { + self.bits.get_bit(9) + } + #[inline] + pub fn set_seie(&mut self, val: bool) { + self.bits.set_bit(9, val); + } +} +read_csr_as!(Vsie, 516, __read_vsie); +write_csr!(516, __write_vsie); +set!(516, __set_vsie); +clear!(516, __clear_vsie); +// bit ops +set_clear_csr!( + ///Software Interrupt + , set_ssie, clear_ssie, 1 << 1); +set_clear_csr!( + ///Timer Interrupt + , set_stie, clear_stie, 1 << 5); +set_clear_csr!( + ///External Interrupt + , set_seie, clear_seie, 1 << 9); + +// enums diff --git a/ci-user/riscv/src/register/hypervisorx64/vsip.rs b/ci-user/riscv/src/register/hypervisorx64/vsip.rs new file mode 100644 index 0000000..0989e79 --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/vsip.rs @@ -0,0 +1,65 @@ +//! Virtual Supevisor Interrupt Pending Register. + +use bit_field::BitField; + +#[derive(Copy, Clone, Debug)] +pub struct Vsip { + bits: usize, +} +impl Vsip { + #[inline] + pub fn bits(&self) -> usize { + return self.bits; + } + #[inline] + pub fn from_bits(x: usize) -> Self { + return Vsip { bits: x }; + } + #[inline] + pub unsafe fn write(&self) { + _write(self.bits); + } + /// Software Interrupt + #[inline] + pub fn ssip(&self) -> bool { + self.bits.get_bit(1) + } + #[inline] + pub fn set_ssip(&mut self, val: bool) { + self.bits.set_bit(1, val); + } + /// Timer Interrupt + #[inline] + pub fn stip(&self) -> bool { + self.bits.get_bit(5) + } + #[inline] + pub fn set_stip(&mut self, val: bool) { + self.bits.set_bit(5, val); + } + /// External Interrupt + #[inline] + pub fn seip(&self) -> bool { + self.bits.get_bit(9) + } + #[inline] + pub fn set_seip(&mut self, val: bool) { + self.bits.set_bit(9, val); + } +} +read_csr_as!(Vsip, 580, __read_vsip); +write_csr!(580, __write_vsip); +set!(580, __set_vsip); +clear!(580, __clear_vsip); +// bit ops +set_clear_csr!( + ///Software Interrupt + , set_ssip, clear_ssip, 1 << 1); +set_clear_csr!( + ///Timer Interrupt + , set_stip, clear_stip, 1 << 5); +set_clear_csr!( + ///External Interrupt + , set_seip, clear_seip, 1 << 9); + +// enums diff --git a/ci-user/riscv/src/register/hypervisorx64/vsscratch.rs b/ci-user/riscv/src/register/hypervisorx64/vsscratch.rs new file mode 100644 index 0000000..e297575 --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/vsscratch.rs @@ -0,0 +1,3 @@ +//! Virtual Supervisor Scratch Register. +read_csr_as_usize!(576, __read_vsscratch); +write_csr_as_usize!(576, __write_vsscratch); diff --git a/ci-user/riscv/src/register/hypervisorx64/vsstatus.rs b/ci-user/riscv/src/register/hypervisorx64/vsstatus.rs new file mode 100644 index 0000000..c2585b8 --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/vsstatus.rs @@ -0,0 +1,154 @@ +//! Hypervisor Guest External Interrupt Pending Register. + +use bit_field::BitField; + +#[derive(Copy, Clone, Debug)] +pub struct Vsstatus { + bits: usize, +} +impl Vsstatus { + #[inline] + pub fn bits(&self) -> usize { + return self.bits; + } + #[inline] + pub fn from_bits(x: usize) -> Self { + return Vsstatus { bits: x }; + } + #[inline] + pub unsafe fn write(&self) { + _write(self.bits); + } + /// + #[inline] + pub fn sd(&self) -> usize { + self.bits.get_bits(60..64) + } + #[inline] + pub fn set_sd(&mut self, val: usize) { + self.bits.set_bits(60..64, val); + } + /// Effective User XLEN. + #[inline] + pub fn uxl(&self) -> UxlValues { + UxlValues::from(self.bits.get_bits(32..34)) + } + #[inline] + pub fn set_uxl(&mut self, val: UxlValues) { + self.bits.set_bits(32..34, val as usize); + } + /// + #[inline] + pub fn mxr(&self) -> bool { + self.bits.get_bit(19) + } + #[inline] + pub fn set_mxr(&mut self, val: bool) { + self.bits.set_bit(19, val); + } + /// + #[inline] + pub fn sum(&self) -> bool { + self.bits.get_bit(18) + } + #[inline] + pub fn set_sum(&mut self, val: bool) { + self.bits.set_bit(18, val); + } + /// + #[inline] + pub fn xs(&self) -> usize { + self.bits.get_bits(15..17) + } + #[inline] + pub fn set_xs(&mut self, val: usize) { + self.bits.set_bits(15..17, val); + } + /// + #[inline] + pub fn fs(&self) -> usize { + self.bits.get_bits(13..15) + } + #[inline] + pub fn set_fs(&mut self, val: usize) { + self.bits.set_bits(13..15, val); + } + /// + #[inline] + pub fn spp(&self) -> bool { + self.bits.get_bit(8) + } + #[inline] + pub fn set_spp(&mut self, val: bool) { + self.bits.set_bit(8, val); + } + /// + #[inline] + pub fn ube(&self) -> bool { + self.bits.get_bit(6) + } + #[inline] + pub fn set_ube(&mut self, val: bool) { + self.bits.set_bit(6, val); + } + /// + #[inline] + pub fn spie(&self) -> bool { + self.bits.get_bit(5) + } + #[inline] + pub fn set_spie(&mut self, val: bool) { + self.bits.set_bit(5, val); + } + /// + #[inline] + pub fn sie(&self) -> bool { + self.bits.get_bit(1) + } + #[inline] + pub fn set_sie(&mut self, val: bool) { + self.bits.set_bit(1, val); + } +} +read_csr_as!(Vsstatus, 512, __read_vsstatus); +write_csr!(512, __write_vsstatus); +set!(512, __set_vsstatus); +clear!(512, __clear_vsstatus); +// bit ops +set_clear_csr!( + /// + , set_mxr, clear_mxr, 1 << 19); +set_clear_csr!( + /// + , set_sum, clear_sum, 1 << 18); +set_clear_csr!( + /// + , set_spp, clear_spp, 1 << 8); +set_clear_csr!( + /// + , set_ube, clear_ube, 1 << 6); +set_clear_csr!( + /// + , set_spie, clear_spie, 1 << 5); +set_clear_csr!( + /// + , set_sie, clear_sie, 1 << 1); + +// enums +#[derive(Copy, Clone, Debug)] +#[repr(usize)] +pub enum UxlValues { + Uxl32 = 1, + Uxl64 = 2, + Uxl128 = 3, +} +impl UxlValues { + fn from(x: usize) -> Self { + match x { + 1 => Self::Uxl32, + 2 => Self::Uxl64, + 3 => Self::Uxl128, + _ => unreachable!(), + } + } +} diff --git a/ci-user/riscv/src/register/hypervisorx64/vstval.rs b/ci-user/riscv/src/register/hypervisorx64/vstval.rs new file mode 100644 index 0000000..9586646 --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/vstval.rs @@ -0,0 +1,3 @@ +//! Virtual Supervisor Trap Value Register. +read_csr_as_usize!(579, __read_vstval); +write_csr_as_usize!(579, __write_vstval); diff --git a/ci-user/riscv/src/register/hypervisorx64/vstvec.rs b/ci-user/riscv/src/register/hypervisorx64/vstvec.rs new file mode 100644 index 0000000..adece54 --- /dev/null +++ b/ci-user/riscv/src/register/hypervisorx64/vstvec.rs @@ -0,0 +1,47 @@ +//! Virtual Supervisor Trap Vector Base Address Register. + +use bit_field::BitField; + +#[derive(Copy, Clone, Debug)] +pub struct Vstvec { + bits: usize, +} +impl Vstvec { + #[inline] + pub fn bits(&self) -> usize { + return self.bits; + } + #[inline] + pub fn from_bits(x: usize) -> Self { + return Vstvec { bits: x }; + } + #[inline] + pub unsafe fn write(&self) { + _write(self.bits); + } + /// + #[inline] + pub fn base(&self) -> usize { + self.bits.get_bits(2..64) + } + #[inline] + pub fn set_base(&mut self, val: usize) { + self.bits.set_bits(2..64, val); + } + /// + #[inline] + pub fn mode(&self) -> usize { + self.bits.get_bits(0..2) + } + #[inline] + pub fn set_mode(&mut self, val: usize) { + self.bits.set_bits(0..2, val); + } +} +read_csr_as!(Vstvec, 517, __read_vstvec); +write_csr!(517, __write_vstvec); +set!(517, __set_vstvec); +clear!(517, __clear_vstvec); +// bit ops + +// enums diff --git a/ci-user/riscv/src/register/macros.rs b/ci-user/riscv/src/register/macros.rs new file mode 100644 index 0000000..5bf04c5 --- /dev/null +++ b/ci-user/riscv/src/register/macros.rs @@ -0,0 +1,272 @@ +macro_rules! read_csr { + ($csr_number:expr, $asm_fn: ident) => { + /// Reads the CSR + #[inline] + unsafe fn _read() -> usize { + match () { + #[cfg(all(riscv, feature = "inline-asm"))] + () => { + let r: usize; + asm!("csrrs {0}, {1}, x0", out(reg) r, const $csr_number); + r + } + + #[cfg(all(riscv, not(feature = "inline-asm")))] + () => { + extern "C" { + fn $asm_fn() -> usize; + } + + $asm_fn() + } + + #[cfg(not(riscv))] + () => unimplemented!(), + } + } + }; +} + +macro_rules! read_csr_rv32 { + ($csr_number:expr, $asm_fn: ident) => { + /// Reads the CSR + #[inline] + unsafe fn _read() -> usize { + match () { + #[cfg(all(riscv32, feature = "inline-asm"))] + () => { + let r: usize; + asm!("csrrs {0}, {1}, x0", out(reg) r, const $csr_number); + r + } + + #[cfg(all(riscv32, not(feature = "inline-asm")))] + () => { + extern "C" { + fn $asm_fn() -> usize; + } + + $asm_fn() + } + + #[cfg(not(riscv32))] + () => unimplemented!(), + } + } + }; +} + +macro_rules! read_csr_as { + ($register:ident, $csr_number:expr, $asm_fn: ident) => { + read_csr!($csr_number, $asm_fn); + + /// Reads the CSR + #[inline] + pub fn read() -> $register { + $register { + bits: unsafe { _read() }, + } + } + }; +} + +macro_rules! read_csr_as_usize { + ($csr_number:expr, $asm_fn: ident) => { + read_csr!($csr_number, $asm_fn); + + /// Reads the CSR + #[inline] + pub fn read() -> usize { + unsafe { _read() } + } + }; +} + +macro_rules! read_csr_as_usize_rv32 { + ($csr_number:expr, $asm_fn: ident) => { + read_csr_rv32!($csr_number, $asm_fn); + + /// Reads the CSR + #[inline] + pub fn read() -> usize { + unsafe { _read() } + } + }; +} + +macro_rules! write_csr { + ($csr_number:expr, $asm_fn: ident) => { + /// Writes the CSR + #[inline] + #[allow(unused_variables)] + unsafe fn _write(bits: usize) { + match () { + #[cfg(all(riscv, feature = "inline-asm"))] + () => asm!("csrrw x0, {1}, {0}", in(reg) bits, const $csr_number), + + #[cfg(all(riscv, not(feature = "inline-asm")))] + () => { + extern "C" { + fn $asm_fn(bits: usize); + } + + $asm_fn(bits); + } + + #[cfg(not(riscv))] + () => unimplemented!(), + } + } + }; +} + +macro_rules! write_csr_rv32 { + ($csr_number:expr, $asm_fn: ident) => { + /// Writes the CSR + #[inline] + #[allow(unused_variables)] + unsafe fn _write(bits: usize) { + match () { + #[cfg(all(riscv32, feature = "inline-asm"))] + () => asm!("csrrw x0, {1}, {0}", in(reg) bits, const $csr_number), + + #[cfg(all(riscv32, not(feature = "inline-asm")))] + () => { + extern "C" { + fn $asm_fn(bits: usize); + } + + $asm_fn(bits); + } + + #[cfg(not(riscv32))] + () => unimplemented!(), + } + } + }; +} + +macro_rules! write_csr_as_usize { + ($csr_number:expr, $asm_fn: ident) => { + write_csr!($csr_number, $asm_fn); + + /// Writes the CSR + #[inline] + pub fn write(bits: usize) { + unsafe { _write(bits) } + } + }; +} + +macro_rules! write_csr_as_usize_rv32 { + ($csr_number:expr, $asm_fn: ident) => { + write_csr_rv32!($csr_number, $asm_fn); + + /// Writes the CSR + #[inline] + pub fn write(bits: usize) { + unsafe { _write(bits) } + } + }; +} + +macro_rules! set { + ($csr_number:expr, $asm_fn: ident) => { + /// Set the CSR + #[inline] + #[allow(unused_variables)] + unsafe fn _set(bits: usize) { + match () { + #[cfg(all(riscv, feature = "inline-asm"))] + () => asm!("csrrs x0, {1}, {0}", in(reg) bits, const $csr_number), + + #[cfg(all(riscv, not(feature = "inline-asm")))] + () => { + extern "C" { + fn $asm_fn(bits: usize); + } + + $asm_fn(bits); + } + + #[cfg(not(riscv))] + () => unimplemented!(), + } + } + }; +} + +macro_rules! clear { + ($csr_number:expr, $asm_fn: ident) => { + /// Clear the CSR + #[inline] + #[allow(unused_variables)] + unsafe fn _clear(bits: usize) { + match () { + #[cfg(all(riscv, feature = "inline-asm"))] + () => asm!("csrrc x0, {1}, {0}", in(reg) bits, const $csr_number), + + #[cfg(all(riscv, not(feature = "inline-asm")))] + () => { + extern "C" { + fn $asm_fn(bits: usize); + } + + $asm_fn(bits); + } + + #[cfg(not(riscv))] + () => unimplemented!(), + } + } + }; +} + +macro_rules! set_csr { + ($(#[$attr:meta])*, $set_field:ident, $e:expr) => { + $(#[$attr])* + #[inline] + pub unsafe fn $set_field() { + _set($e); + } + }; +} + +macro_rules! clear_csr { + ($(#[$attr:meta])*, $clear_field:ident, $e:expr) => { + $(#[$attr])* + #[inline] + pub unsafe fn $clear_field() { + _clear($e); + } + }; +} + +macro_rules! set_clear_csr { + ($(#[$attr:meta])*, $set_field:ident, $clear_field:ident, $e:expr) => { + set_csr!($(#[$attr])*, $set_field, $e); + clear_csr!($(#[$attr])*, $clear_field, $e); + } +} + +macro_rules! read_composite_csr { + ($hi:expr, $lo:expr) => { + /// Reads the CSR as a 64-bit value + #[inline] + pub fn read64() -> u64 { + match () { + #[cfg(riscv32)] + () => loop { + let hi = $hi; + let lo = $lo; + if hi == $hi { + return ((hi as u64) << 32) | lo as u64; + } + }, + + #[cfg(not(riscv32))] + () => $lo as u64, + } + } + }; +} diff --git a/ci-user/riscv/src/register/marchid.rs b/ci-user/riscv/src/register/marchid.rs new file mode 100644 index 0000000..a5e3fb9 --- /dev/null +++ b/ci-user/riscv/src/register/marchid.rs @@ -0,0 +1,27 @@ +//! marchid register + +use core::num::NonZeroUsize; + +/// marchid register +#[derive(Clone, Copy, Debug)] +pub struct Marchid { + bits: NonZeroUsize, +} + +impl Marchid { + /// Returns the contents of the register as raw bits + pub fn bits(&self) -> usize { + self.bits.get() + } +} + +read_csr!(0xF11, __read_marchid); + +/// Reads the CSR +#[inline] +pub fn read() -> Option { + let r = unsafe { _read() }; + // When marchid is hardwired to zero it means that the marchid + // csr isn't implemented. + NonZeroUsize::new(r).map(|bits| Marchid { bits }) +} diff --git a/ci-user/riscv/src/register/mcause.rs b/ci-user/riscv/src/register/mcause.rs new file mode 100644 index 0000000..068266b --- /dev/null +++ b/ci-user/riscv/src/register/mcause.rs @@ -0,0 +1,138 @@ +//! mcause register + +/// mcause register +#[derive(Clone, Copy, Debug)] +pub struct Mcause { + bits: usize, +} + +/// Trap Cause +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum Trap { + Interrupt(Interrupt), + Exception(Exception), +} + +/// Interrupt +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum Interrupt { + UserSoft, + SupervisorSoft, + MachineSoft, + UserTimer, + SupervisorTimer, + MachineTimer, + UserExternal, + SupervisorExternal, + MachineExternal, + Unknown, +} + +/// Exception +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum Exception { + InstructionMisaligned, + InstructionFault, + IllegalInstruction, + Breakpoint, + LoadMisaligned, + LoadFault, + StoreMisaligned, + StoreFault, + UserEnvCall, + SupervisorEnvCall, + MachineEnvCall, + InstructionPageFault, + LoadPageFault, + StorePageFault, + Unknown, +} + +impl Interrupt { + pub fn from(nr: usize) -> Self { + match nr { + 0 => Interrupt::UserSoft, + 1 => Interrupt::SupervisorSoft, + 3 => Interrupt::MachineSoft, + 4 => Interrupt::UserTimer, + 5 => Interrupt::SupervisorTimer, + 7 => Interrupt::MachineTimer, + 8 => Interrupt::UserExternal, + 9 => Interrupt::SupervisorExternal, + 11 => Interrupt::MachineExternal, + _ => Interrupt::Unknown, + } + } +} + +impl Exception { + pub fn from(nr: usize) -> Self { + match nr { + 0 => Exception::InstructionMisaligned, + 1 => Exception::InstructionFault, + 2 => Exception::IllegalInstruction, + 3 => Exception::Breakpoint, + 4 => Exception::LoadMisaligned, + 5 => Exception::LoadFault, + 6 => Exception::StoreMisaligned, + 7 => Exception::StoreFault, + 8 => Exception::UserEnvCall, + 9 => Exception::SupervisorEnvCall, + 11 => Exception::MachineEnvCall, + 12 => Exception::InstructionPageFault, + 13 => Exception::LoadPageFault, + 15 => Exception::StorePageFault, + _ => Exception::Unknown, + } + } +} +impl Mcause { + /// Returns the contents of the register as raw bits + #[inline] + pub fn bits(&self) -> usize { + self.bits + } + + /// Returns the code field + pub fn code(&self) -> usize { + match () { + #[cfg(target_pointer_width = "32")] + () => self.bits & !(1 << 31), + #[cfg(target_pointer_width = "64")] + () => self.bits & !(1 << 63), + #[cfg(target_pointer_width = "128")] + () => self.bits & !(1 << 127), + } + } + + /// Trap Cause + #[inline] + pub fn cause(&self) -> Trap { + if self.is_interrupt() { + Trap::Interrupt(Interrupt::from(self.code())) + } else { + Trap::Exception(Exception::from(self.code())) + } + } + + /// Is trap cause an interrupt. + #[inline] + pub fn is_interrupt(&self) -> bool { + match () { + #[cfg(target_pointer_width = "32")] + () => self.bits & (1 << 31) == 1 << 31, + #[cfg(target_pointer_width = "64")] + () => self.bits & (1 << 63) == 1 << 63, + #[cfg(target_pointer_width = "128")] + () => self.bits & (1 << 127) == 1 << 127, + } + } + + /// Is trap cause an exception. + #[inline] + pub fn is_exception(&self) -> bool { + !self.is_interrupt() + } +} + +read_csr_as!(Mcause, 0x342, __read_mcause); diff --git a/ci-user/riscv/src/register/mcycle.rs b/ci-user/riscv/src/register/mcycle.rs new file mode 100644 index 0000000..95d172b --- /dev/null +++ b/ci-user/riscv/src/register/mcycle.rs @@ -0,0 +1,4 @@ +//! mcycle register + +read_csr_as_usize!(0xB00, __read_mcycle); +read_composite_csr!(super::mcycleh::read(), read()); diff --git a/ci-user/riscv/src/register/mcycleh.rs b/ci-user/riscv/src/register/mcycleh.rs new file mode 100644 index 0000000..784dca4 --- /dev/null +++ b/ci-user/riscv/src/register/mcycleh.rs @@ -0,0 +1,3 @@ +//! mcycleh register + +read_csr_as_usize_rv32!(0xB80, __read_mcycleh); diff --git a/ci-user/riscv/src/register/medeleg.rs b/ci-user/riscv/src/register/medeleg.rs new file mode 100644 index 0000000..6b86641 --- /dev/null +++ b/ci-user/riscv/src/register/medeleg.rs @@ -0,0 +1,148 @@ +//! medeleg register + +use bit_field::BitField; + +/// medeleg register +#[derive(Clone, Copy, Debug)] +pub struct Medeleg { + bits: usize, +} + +impl Medeleg { + /// Returns the contents of the register as raw bits + #[inline] + pub fn bits(&self) -> usize { + self.bits + } + + /// Instruction Address Misaligned Delegate + #[inline] + pub fn instruction_misaligned(&self) -> bool { + self.bits.get_bit(0) + } + + /// Instruction Access Fault Delegate + #[inline] + pub fn instruction_fault(&self) -> bool { + self.bits.get_bit(1) + } + + /// Illegal Instruction Delegate + #[inline] + pub fn illegal_instruction(&self) -> bool { + self.bits.get_bit(2) + } + + /// Breakpoint Delegate + #[inline] + pub fn breakpoint(&self) -> bool { + self.bits.get_bit(3) + } + + /// Load Address Misaligned Delegate + #[inline] + pub fn load_misaligned(&self) -> bool { + self.bits.get_bit(4) + } + + /// Load Access Fault Delegate + #[inline] + pub fn load_fault(&self) -> bool { + self.bits.get_bit(5) + } + + /// Store/AMO Address Misaligned Delegate + #[inline] + pub fn store_misaligned(&self) -> bool { + self.bits.get_bit(6) + } + + /// Store/AMO Access Fault Delegate + #[inline] + pub fn store_fault(&self) -> bool { + self.bits.get_bit(7) + } + + /// Environment Call from U-mode Delegate + #[inline] + pub fn user_env_call(&self) -> bool { + self.bits.get_bit(8) + } + + /// Environment Call from S-mode Delegate + #[inline] + pub fn supervisor_env_call(&self) -> bool { + self.bits.get_bit(9) + } + + /// Environment Call from M-mode Delegate + #[inline] + pub fn machine_env_call(&self) -> bool { + self.bits.get_bit(11) + } + + /// Instruction Page Fault Delegate + #[inline] + pub fn instruction_page_fault(&self) -> bool { + self.bits.get_bit(12) + } + + /// Load Page Fault Delegate + #[inline] + pub fn load_page_fault(&self) -> bool { + self.bits.get_bit(13) + } + + /// Store/AMO Page Fault Delegate + #[inline] + pub fn store_page_fault(&self) -> bool { + self.bits.get_bit(15) + } +} + +read_csr_as!(Medeleg, 0x302, __read_medeleg); +set!(0x302, __set_medeleg); +clear!(0x302, __clear_medeleg); + +set_clear_csr!( + /// Instruction Address Misaligned Delegate + , set_instruction_misaligned, clear_instruction_misaligned, 1 << 0); +set_clear_csr!( + /// Instruction Access Fault Delegate + , set_instruction_fault, clear_instruction_fault, 1 << 1); +set_clear_csr!( + /// Illegal Instruction Delegate + , set_illegal_instruction, clear_illegal_instruction, 1 << 2); +set_clear_csr!( + /// Breakpoint Delegate + , set_breakpoint, clear_breakpoint, 1 << 3); +set_clear_csr!( + /// Load Address Misaligned Delegate + , set_load_misaligned, clear_load_misaligned, 1 << 4); +set_clear_csr!( + /// Load Access Fault Delegate + , set_load_fault, clear_load_fault, 1 << 5); +set_clear_csr!( + /// Store/AMO Address Misaligned Delegate + , set_store_misaligned, clear_store_misaligned, 1 << 6); +set_clear_csr!( + /// Store/AMO Access fault + , set_store_fault, clear_store_fault, 1 << 7); +set_clear_csr!( + /// Environment Call from U-mode Delegate + , set_user_env_call, clear_user_env_call, 1 << 8); +set_clear_csr!( + /// Environment Call from S-mode Delegate + , set_supervisor_env_call, clear_supervisor_env_call, 1 << 9); +set_clear_csr!( + /// Environment Call from M-mode Delegate + , set_machine_env_call, clear_machine_env_call, 1 << 11); +set_clear_csr!( + /// Instruction Page Fault Delegate + , set_instruction_page_fault, clear_instruction_page_fault, 1 << 12); +set_clear_csr!( + /// Load Page Fault Delegate + , set_load_page_fault, clear_load_page_fault, 1 << 13); +set_clear_csr!( + /// Store/AMO Page Fault Delegate + , set_store_page_fault, clear_store_page_fault, 1 << 15); diff --git a/ci-user/riscv/src/register/mepc.rs b/ci-user/riscv/src/register/mepc.rs new file mode 100644 index 0000000..160dff5 --- /dev/null +++ b/ci-user/riscv/src/register/mepc.rs @@ -0,0 +1,4 @@ +//! mepc register + +read_csr_as_usize!(0x341, __read_mepc); +write_csr_as_usize!(0x341, __write_mepc); diff --git a/ci-user/riscv/src/register/mhartid.rs b/ci-user/riscv/src/register/mhartid.rs new file mode 100644 index 0000000..3960388 --- /dev/null +++ b/ci-user/riscv/src/register/mhartid.rs @@ -0,0 +1,3 @@ +//! mhartid register + +read_csr_as_usize!(0xf14, __read_mhartid); diff --git a/ci-user/riscv/src/register/mhpmcounterx.rs b/ci-user/riscv/src/register/mhpmcounterx.rs new file mode 100644 index 0000000..df3b6c4 --- /dev/null +++ b/ci-user/riscv/src/register/mhpmcounterx.rs @@ -0,0 +1,84 @@ +macro_rules! reg { + ( + $addr:expr, $csrl:ident, $csrh:ident, $readf:ident, $writef:ident + ) => { + /// Machine performance-monitoring counter + pub mod $csrl { + read_csr_as_usize!($addr, $readf); + write_csr_as_usize!($addr, $writef); + read_composite_csr!(super::$csrh::read(), read()); + } + } +} + +macro_rules! regh { + ( + $addr:expr, $csrh:ident, $readf:ident, $writef:ident + ) => { + /// Upper 32 bits of machine performance-monitoring counter (RV32I only) + pub mod $csrh { + read_csr_as_usize_rv32!($addr, $readf); + write_csr_as_usize_rv32!($addr, $writef); + } + } +} + +reg!(0xB03, mhpmcounter3, mhpmcounter3h, __read_mhpmcounter3, __write_mhpmcounter3); +reg!(0xB04, mhpmcounter4, mhpmcounter4h, __read_mhpmcounter4, __write_mhpmcounter4); +reg!(0xB05, mhpmcounter5, mhpmcounter5h, __read_mhpmcounter5, __write_mhpmcounter5); +reg!(0xB06, mhpmcounter6, mhpmcounter6h, __read_mhpmcounter6, __write_mhpmcounter6); +reg!(0xB07, mhpmcounter7, mhpmcounter7h, __read_mhpmcounter7, __write_mhpmcounter7); +reg!(0xB08, mhpmcounter8, mhpmcounter8h, __read_mhpmcounter8, __write_mhpmcounter8); +reg!(0xB09, mhpmcounter9, mhpmcounter9h, __read_mhpmcounter9, __write_mhpmcounter9); +reg!(0xB0A, mhpmcounter10, mhpmcounter10h, __read_mhpmcounter10, __write_mhpmcounter10); +reg!(0xB0B, mhpmcounter11, mhpmcounter11h, __read_mhpmcounter11, __write_mhpmcounter11); +reg!(0xB0C, mhpmcounter12, mhpmcounter12h, __read_mhpmcounter12, __write_mhpmcounter12); +reg!(0xB0D, mhpmcounter13, mhpmcounter13h, __read_mhpmcounter13, __write_mhpmcounter13); +reg!(0xB0E, mhpmcounter14, mhpmcounter14h, __read_mhpmcounter14, __write_mhpmcounter14); +reg!(0xB0F, mhpmcounter15, mhpmcounter15h, __read_mhpmcounter15, __write_mhpmcounter15); +reg!(0xB10, mhpmcounter16, mhpmcounter16h, __read_mhpmcounter16, __write_mhpmcounter16); +reg!(0xB11, mhpmcounter17, mhpmcounter17h, __read_mhpmcounter17, __write_mhpmcounter17); +reg!(0xB12, mhpmcounter18, mhpmcounter18h, __read_mhpmcounter18, __write_mhpmcounter18); +reg!(0xB13, mhpmcounter19, mhpmcounter19h, __read_mhpmcounter19, __write_mhpmcounter19); +reg!(0xB14, mhpmcounter20, mhpmcounter20h, __read_mhpmcounter20, __write_mhpmcounter20); +reg!(0xB15, mhpmcounter21, mhpmcounter21h, __read_mhpmcounter21, __write_mhpmcounter21); +reg!(0xB16, mhpmcounter22, mhpmcounter22h, __read_mhpmcounter22, __write_mhpmcounter22); +reg!(0xB17, mhpmcounter23, mhpmcounter23h, __read_mhpmcounter23, __write_mhpmcounter23); +reg!(0xB18, mhpmcounter24, mhpmcounter24h, __read_mhpmcounter24, __write_mhpmcounter24); +reg!(0xB19, mhpmcounter25, mhpmcounter25h, __read_mhpmcounter25, __write_mhpmcounter25); +reg!(0xB1A, mhpmcounter26, mhpmcounter26h, __read_mhpmcounter26, __write_mhpmcounter26); +reg!(0xB1B, mhpmcounter27, mhpmcounter27h, __read_mhpmcounter27, __write_mhpmcounter27); +reg!(0xB1C, mhpmcounter28, mhpmcounter28h, __read_mhpmcounter28, __write_mhpmcounter28); +reg!(0xB1D, mhpmcounter29, mhpmcounter29h, __read_mhpmcounter29, __write_mhpmcounter29); +reg!(0xB1E, mhpmcounter30, mhpmcounter30h, __read_mhpmcounter30, __write_mhpmcounter30); +reg!(0xB1F, mhpmcounter31, mhpmcounter31h, __read_mhpmcounter31, __write_mhpmcounter31); + +regh!(0xB83, mhpmcounter3h, __read_mhpmcounter3h, __write_mhpmcounter3h); +regh!(0xB84, mhpmcounter4h, __read_mhpmcounter4h, __write_mhpmcounter4h); +regh!(0xB85, mhpmcounter5h, __read_mhpmcounter5h, __write_mhpmcounter5h); +regh!(0xB86, mhpmcounter6h, __read_mhpmcounter6h, __write_mhpmcounter6h); +regh!(0xB87, mhpmcounter7h, __read_mhpmcounter7h, __write_mhpmcounter7h); +regh!(0xB88, mhpmcounter8h, __read_mhpmcounter8h, __write_mhpmcounter8h); +regh!(0xB89, mhpmcounter9h, __read_mhpmcounter9h, __write_mhpmcounter9h); +regh!(0xB8A, mhpmcounter10h, __read_mhpmcounter10h, __write_mhpmcounter10h); +regh!(0xB8B, mhpmcounter11h, __read_mhpmcounter11h, __write_mhpmcounter11h); +regh!(0xB8C, mhpmcounter12h, __read_mhpmcounter12h, __write_mhpmcounter12h); +regh!(0xB8D, mhpmcounter13h, __read_mhpmcounter13h, __write_mhpmcounter13h); +regh!(0xB8E, mhpmcounter14h, __read_mhpmcounter14h, __write_mhpmcounter14h); +regh!(0xB8F, mhpmcounter15h, __read_mhpmcounter15h, __write_mhpmcounter15h); +regh!(0xB90, mhpmcounter16h, __read_mhpmcounter16h, __write_mhpmcounter16h); +regh!(0xB91, mhpmcounter17h, __read_mhpmcounter17h, __write_mhpmcounter17h); +regh!(0xB92, mhpmcounter18h, __read_mhpmcounter18h, __write_mhpmcounter18h); +regh!(0xB93, mhpmcounter19h, __read_mhpmcounter19h, __write_mhpmcounter19h); +regh!(0xB94, mhpmcounter20h, __read_mhpmcounter20h, __write_mhpmcounter20h); +regh!(0xB95, mhpmcounter21h, __read_mhpmcounter21h, __write_mhpmcounter21h); +regh!(0xB96, mhpmcounter22h, __read_mhpmcounter22h, __write_mhpmcounter22h); +regh!(0xB97, mhpmcounter23h, __read_mhpmcounter23h, __write_mhpmcounter23h); +regh!(0xB98, mhpmcounter24h, __read_mhpmcounter24h, __write_mhpmcounter24h); +regh!(0xB99, mhpmcounter25h, __read_mhpmcounter25h, __write_mhpmcounter25h); +regh!(0xB9A, mhpmcounter26h, __read_mhpmcounter26h, __write_mhpmcounter26h); +regh!(0xB9B, mhpmcounter27h, __read_mhpmcounter27h, __write_mhpmcounter27h); +regh!(0xB9C, mhpmcounter28h, __read_mhpmcounter28h, __write_mhpmcounter28h); +regh!(0xB9D, mhpmcounter29h, __read_mhpmcounter29h, __write_mhpmcounter29h); +regh!(0xB9E, mhpmcounter30h, __read_mhpmcounter30h, __write_mhpmcounter30h); +regh!(0xB9F, mhpmcounter31h, __read_mhpmcounter31h, __write_mhpmcounter31h); diff --git a/ci-user/riscv/src/register/mhpmeventx.rs b/ci-user/riscv/src/register/mhpmeventx.rs new file mode 100644 index 0000000..db7d4b0 --- /dev/null +++ b/ci-user/riscv/src/register/mhpmeventx.rs @@ -0,0 +1,41 @@ +macro_rules! reg { + ( + $addr:expr, $csr:ident, $readf:ident, $writef:ident + ) => { + /// Machine performance-monitoring event selector + pub mod $csr { + read_csr_as_usize!($addr, $readf); + write_csr_as_usize!($addr, $writef); + } + }; +} + +reg!(0x323, mhpmevent3, __read_mhpmevent3, __write_mhpmevent3); +reg!(0x324, mhpmevent4, __read_mhpmevent4, __write_mhpmevent4); +reg!(0x325, mhpmevent5, __read_mhpmevent5, __write_mhpmevent5); +reg!(0x326, mhpmevent6, __read_mhpmevent6, __write_mhpmevent6); +reg!(0x327, mhpmevent7, __read_mhpmevent7, __write_mhpmevent7); +reg!(0x328, mhpmevent8, __read_mhpmevent8, __write_mhpmevent8); +reg!(0x329, mhpmevent9, __read_mhpmevent9, __write_mhpmevent9); +reg!(0x32A, mhpmevent10, __read_mhpmevent10, __write_mhpmevent10); +reg!(0x32B, mhpmevent11, __read_mhpmevent11, __write_mhpmevent11); +reg!(0x32C, mhpmevent12, __read_mhpmevent12, __write_mhpmevent12); +reg!(0x32D, mhpmevent13, __read_mhpmevent13, __write_mhpmevent13); +reg!(0x32E, mhpmevent14, __read_mhpmevent14, __write_mhpmevent14); +reg!(0x32F, mhpmevent15, __read_mhpmevent15, __write_mhpmevent15); +reg!(0x330, mhpmevent16, __read_mhpmevent16, __write_mhpmevent16); +reg!(0x331, mhpmevent17, __read_mhpmevent17, __write_mhpmevent17); +reg!(0x332, mhpmevent18, __read_mhpmevent18, __write_mhpmevent18); +reg!(0x333, mhpmevent19, __read_mhpmevent19, __write_mhpmevent19); +reg!(0x334, mhpmevent20, __read_mhpmevent20, __write_mhpmevent20); +reg!(0x335, mhpmevent21, __read_mhpmevent21, __write_mhpmevent21); +reg!(0x336, mhpmevent22, __read_mhpmevent22, __write_mhpmevent22); +reg!(0x337, mhpmevent23, __read_mhpmevent23, __write_mhpmevent23); +reg!(0x338, mhpmevent24, __read_mhpmevent24, __write_mhpmevent24); +reg!(0x339, mhpmevent25, __read_mhpmevent25, __write_mhpmevent25); +reg!(0x33A, mhpmevent26, __read_mhpmevent26, __write_mhpmevent26); +reg!(0x33B, mhpmevent27, __read_mhpmevent27, __write_mhpmevent27); +reg!(0x33C, mhpmevent28, __read_mhpmevent28, __write_mhpmevent28); +reg!(0x33D, mhpmevent29, __read_mhpmevent29, __write_mhpmevent29); +reg!(0x33E, mhpmevent30, __read_mhpmevent30, __write_mhpmevent30); +reg!(0x33F, mhpmevent31, __read_mhpmevent31, __write_mhpmevent31); diff --git a/ci-user/riscv/src/register/mideleg.rs b/ci-user/riscv/src/register/mideleg.rs new file mode 100644 index 0000000..207c18e --- /dev/null +++ b/ci-user/riscv/src/register/mideleg.rs @@ -0,0 +1,76 @@ +//! mideleg register + +use bit_field::BitField; + +/// mideleg register +#[derive(Clone, Copy, Debug)] +pub struct Mideleg { + bits: usize, +} + +impl Mideleg { + /// Returns the contents of the register as raw bits + #[inline] + pub fn bits(&self) -> usize { + self.bits + } + + /// User Software Interrupt Delegate + #[inline] + pub fn usoft(&self) -> bool { + self.bits.get_bit(0) + } + + /// Supervisor Software Interrupt Delegate + #[inline] + pub fn ssoft(&self) -> bool { + self.bits.get_bit(1) + } + + /// User Timer Interrupt Delegate + #[inline] + pub fn utimer(&self) -> bool { + self.bits.get_bit(4) + } + + /// Supervisor Timer Interrupt Delegate + #[inline] + pub fn stimer(&self) -> bool { + self.bits.get_bit(5) + } + + /// User External Interrupt Delegate + #[inline] + pub fn uext(&self) -> bool { + self.bits.get_bit(8) + } + + /// Supervisor External Interrupt Delegate + #[inline] + pub fn sext(&self) -> bool { + self.bits.get_bit(9) + } +} + +read_csr_as!(Mideleg, 0x303, __read_mideleg); +set!(0x303, __set_mideleg); +clear!(0x303, __clear_mideleg); + +set_clear_csr!( + /// User Software Interrupt Delegate + , set_usoft, clear_usoft, 1 << 0); +set_clear_csr!( + /// Supervisor Software Interrupt Delegate + , set_ssoft, clear_ssoft, 1 << 1); +set_clear_csr!( + /// User Timer Interrupt Delegate + , set_utimer, clear_utimer, 1 << 4); +set_clear_csr!( + /// Supervisor Timer Interrupt Delegate + , set_stimer, clear_stimer, 1 << 5); +set_clear_csr!( + /// User External Interrupt Delegate + , set_uext, clear_uext, 1 << 8); +set_clear_csr!( + /// Supervisor External Interrupt Delegate + , set_sext, clear_sext, 1 << 9); diff --git a/ci-user/riscv/src/register/mie.rs b/ci-user/riscv/src/register/mie.rs new file mode 100644 index 0000000..121a5b5 --- /dev/null +++ b/ci-user/riscv/src/register/mie.rs @@ -0,0 +1,103 @@ +//! mie register + +use bit_field::BitField; + +/// mie register +#[derive(Clone, Copy, Debug)] +pub struct Mie { + bits: usize, +} + +impl Mie { + /// Returns the contents of the register as raw bits + #[inline] + pub fn bits(&self) -> usize { + self.bits + } + + /// User Software Interrupt Enable + #[inline] + pub fn usoft(&self) -> bool { + self.bits.get_bit(0) + } + + /// Supervisor Software Interrupt Enable + #[inline] + pub fn ssoft(&self) -> bool { + self.bits.get_bit(1) + } + + /// Machine Software Interrupt Enable + #[inline] + pub fn msoft(&self) -> bool { + self.bits.get_bit(3) + } + + /// User Timer Interrupt Enable + #[inline] + pub fn utimer(&self) -> bool { + self.bits.get_bit(4) + } + + /// Supervisor Timer Interrupt Enable + #[inline] + pub fn stimer(&self) -> bool { + self.bits.get_bit(5) + } + + /// Machine Timer Interrupt Enable + #[inline] + pub fn mtimer(&self) -> bool { + self.bits.get_bit(7) + } + + /// User External Interrupt Enable + #[inline] + pub fn uext(&self) -> bool { + self.bits.get_bit(8) + } + + /// Supervisor External Interrupt Enable + #[inline] + pub fn sext(&self) -> bool { + self.bits.get_bit(9) + } + + /// Machine External Interrupt Enable + #[inline] + pub fn mext(&self) -> bool { + self.bits.get_bit(11) + } +} + +read_csr_as!(Mie, 0x304, __read_mie); +set!(0x304, __set_mie); +clear!(0x304, __clear_mie); + +set_clear_csr!( + /// User Software Interrupt Enable + , set_usoft, clear_usoft, 1 << 0); +set_clear_csr!( + /// Supervisor Software Interrupt Enable + , set_ssoft, clear_ssoft, 1 << 1); +set_clear_csr!( + /// Machine Software Interrupt Enable + , set_msoft, clear_msoft, 1 << 3); +set_clear_csr!( + /// User Timer Interrupt Enable + , set_utimer, clear_utimer, 1 << 4); +set_clear_csr!( + /// Supervisor Timer Interrupt Enable + , set_stimer, clear_stimer, 1 << 5); +set_clear_csr!( + /// Machine Timer Interrupt Enable + , set_mtimer, clear_mtimer, 1 << 7); +set_clear_csr!( + /// User External Interrupt Enable + , set_uext, clear_uext, 1 << 8); +set_clear_csr!( + /// Supervisor External Interrupt Enable + , set_sext, clear_sext, 1 << 9); +set_clear_csr!( + /// Machine External Interrupt Enable + , set_mext, clear_mext, 1 << 11); diff --git a/ci-user/riscv/src/register/mimpid.rs b/ci-user/riscv/src/register/mimpid.rs new file mode 100644 index 0000000..39555a8 --- /dev/null +++ b/ci-user/riscv/src/register/mimpid.rs @@ -0,0 +1,27 @@ +//! mimpid register + +use core::num::NonZeroUsize; + +/// mimpid register +#[derive(Clone, Copy, Debug)] +pub struct Mimpid { + bits: NonZeroUsize, +} + +impl Mimpid { + /// Returns the contents of the register as raw bits + pub fn bits(&self) -> usize { + self.bits.get() + } +} + +read_csr!(0xF11, __read_mimpid); + +/// Reads the CSR +#[inline] +pub fn read() -> Option { + let r = unsafe { _read() }; + // When mimpid is hardwired to zero it means that the mimpid + // csr isn't implemented. + NonZeroUsize::new(r).map(|bits| Mimpid { bits }) +} diff --git a/ci-user/riscv/src/register/minstret.rs b/ci-user/riscv/src/register/minstret.rs new file mode 100644 index 0000000..d553dd8 --- /dev/null +++ b/ci-user/riscv/src/register/minstret.rs @@ -0,0 +1,4 @@ +//! minstret register + +read_csr_as_usize!(0xB02, __read_minstret); +read_composite_csr!(super::minstreth::read(), read()); diff --git a/ci-user/riscv/src/register/minstreth.rs b/ci-user/riscv/src/register/minstreth.rs new file mode 100644 index 0000000..56bc54e --- /dev/null +++ b/ci-user/riscv/src/register/minstreth.rs @@ -0,0 +1,3 @@ +//! minstreth register + +read_csr_as_usize_rv32!(0xB82, __read_minstreth); diff --git a/ci-user/riscv/src/register/mip.rs b/ci-user/riscv/src/register/mip.rs new file mode 100644 index 0000000..1a4cf82 --- /dev/null +++ b/ci-user/riscv/src/register/mip.rs @@ -0,0 +1,100 @@ +//! mip register + +use bit_field::BitField; + +/// mip register +#[derive(Clone, Copy, Debug)] +pub struct Mip { + bits: usize, +} + +impl Mip { + /// Returns the contents of the register as raw bits + #[inline] + pub fn bits(&self) -> usize { + self.bits + } + + /// User Software Interrupt Pending + #[inline] + pub fn usoft(&self) -> bool { + self.bits.get_bit(0) + } + + /// Supervisor Software Interrupt Pending + #[inline] + pub fn ssoft(&self) -> bool { + self.bits.get_bit(1) + } + + /// Machine Software Interrupt Pending + #[inline] + pub fn msoft(&self) -> bool { + self.bits.get_bit(3) + } + + /// User Timer Interrupt Pending + #[inline] + pub fn utimer(&self) -> bool { + self.bits.get_bit(4) + } + + /// Supervisor Timer Interrupt Pending + #[inline] + pub fn stimer(&self) -> bool { + self.bits.get_bit(5) + } + + /// Machine Timer Interrupt Pending + #[inline] + pub fn mtimer(&self) -> bool { + self.bits.get_bit(7) + } + + /// User External Interrupt Pending + #[inline] + pub fn uext(&self) -> bool { + self.bits.get_bit(8) + } + + /// Supervisor External Interrupt Pending + #[inline] + pub fn sext(&self) -> bool { + self.bits.get_bit(9) + } + + /// Machine External Interrupt Pending + #[inline] + pub fn mext(&self) -> bool { + self.bits.get_bit(11) + } +} + +read_csr_as!(Mip, 0x344, __read_mip); +set!(0x344, __set_mip); +clear!(0x344, __clear_mip); + +set_clear_csr!( + /// User Software Interrupt Pending + , set_usoft, clear_usoft, 1 << 0); +set_clear_csr!( + /// Supervisor Software Interrupt Pending + , set_ssoft, clear_ssoft, 1 << 1); +set_clear_csr!( + /// Machine Software Interrupt Pending + , set_msoft, clear_msoft, 1 << 3); +set_clear_csr!( + /// User Timer Interrupt Pending + , set_utimer, clear_utimer, 1 << 4); +set_clear_csr!( + /// Supervisor Timer Interrupt Pending + , set_stimer, clear_stimer, 1 << 5); +set_clear_csr!( + /// Machine Timer Interrupt Pending + , set_mtimer, clear_mtimer, 1 << 7); +set_clear_csr!( + /// User External Interrupt Pending + , set_uext, clear_uext, 1 << 8); +set_clear_csr!( + /// Supervisor External Interrupt Pending + , set_sext, clear_sext, 1 << 9); diff --git a/ci-user/riscv/src/register/misa.rs b/ci-user/riscv/src/register/misa.rs new file mode 100644 index 0000000..6c3d860 --- /dev/null +++ b/ci-user/riscv/src/register/misa.rs @@ -0,0 +1,60 @@ +//! misa register + +use core::num::NonZeroUsize; + +/// misa register +#[derive(Clone, Copy, Debug)] +pub struct Misa { + bits: NonZeroUsize, +} + +/// Machine XLEN +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum MXL { + XLEN32, + XLEN64, + XLEN128, +} + +impl Misa { + /// Returns the contents of the register as raw bits + pub fn bits(&self) -> usize { + self.bits.get() + } + + /// Returns the machine xlen. + pub fn mxl(&self) -> MXL { + let value = match () { + #[cfg(target_pointer_width = "32")] + () => (self.bits() >> 30) as u8, + #[cfg(target_pointer_width = "64")] + () => (self.bits() >> 62) as u8, + }; + match value { + 1 => MXL::XLEN32, + 2 => MXL::XLEN64, + 3 => MXL::XLEN128, + _ => unreachable!(), + } + } + + /// Returns true when the atomic extension is implemented. + pub fn has_extension(&self, extension: char) -> bool { + let bit = extension as u8 - 65; + if bit > 25 { + return false; + } + self.bits() & (1 << bit) == (1 << bit) + } +} + +read_csr!(0x301, __read_misa); + +/// Reads the CSR +#[inline] +pub fn read() -> Option { + let r = unsafe { _read() }; + // When misa is hardwired to zero it means that the misa csr + // isn't implemented. + NonZeroUsize::new(r).map(|bits| Misa { bits }) +} diff --git a/ci-user/riscv/src/register/mod.rs b/ci-user/riscv/src/register/mod.rs new file mode 100644 index 0000000..d0804c1 --- /dev/null +++ b/ci-user/riscv/src/register/mod.rs @@ -0,0 +1,104 @@ +//! RISC-V CSR's +//! +//! The following registers are not available on 64-bit implementations. +//! +//! - cycleh +//! - timeh +//! - instreth +//! - hpmcounter[3-31]h +//! - mcycleh +//! - minstreth +//! - mhpmcounter[3-31]h + +#[macro_use] +mod macros; + +// User Trap Setup +pub mod uie; +pub mod ustatus; +pub mod utvec; + +// User Trap Handling +pub mod ucause; +pub mod uepc; +pub mod uip; +pub mod uscratch; +pub mod utval; + +// User Floating-Point CSRs +// TODO: frm, fflags +pub mod fcsr; + +// User Counter/Timers +// TODO: cycle[h], instret[h] +pub mod time; +#[rustfmt::skip] // long macro use +mod hpmcounterx; +pub use self::hpmcounterx::*; +pub mod timeh; + +// Supervisor Trap Setup +// TODO: sedeleg, sideleg +pub mod sie; +pub mod sstatus; +pub mod stvec; +// TODO: scounteren + +// Supervisor Trap Handling +pub mod scause; +pub mod sepc; +pub mod sip; +pub mod sscratch; +pub mod stval; + +// Supervisor Protection and Translation +pub mod satp; + +// Machine Information Registers +pub mod marchid; +pub mod mhartid; +pub mod mimpid; +pub mod mvendorid; + +// Machine Trap Setup +pub mod medeleg; +pub mod mideleg; +pub mod mie; +pub mod misa; +pub mod mstatus; +pub mod mtvec; +// TODO: mcounteren + +// Machine Trap Handling +pub mod mcause; +pub mod mepc; +pub mod mip; +pub mod mscratch; +pub mod mtval; + +// Machine Protection and Translation +mod pmpcfgx; +pub use self::pmpcfgx::*; +mod pmpaddrx; +pub use self::pmpaddrx::*; + +// Machine Counter/Timers +pub mod mcycle; +#[rustfmt::skip] // long macro use +mod mhpmcounterx; +pub mod minstret; +pub use self::mhpmcounterx::*; +pub mod mcycleh; +pub mod minstreth; + +// Machine Counter Setup +mod mhpmeventx; +pub use self::mhpmeventx::*; + +// TODO: Debug/Trace Registers (shared with Debug Mode) + +// TODO: Debug Mode Registers + +// Hypervisor Extension Registers +mod hypervisorx64; +pub use self::hypervisorx64::*; diff --git a/ci-user/riscv/src/register/mscratch.rs b/ci-user/riscv/src/register/mscratch.rs new file mode 100644 index 0000000..c5ef9fe --- /dev/null +++ b/ci-user/riscv/src/register/mscratch.rs @@ -0,0 +1,4 @@ +//! mscratch register + +read_csr_as_usize!(0x340, __read_mscratch); +write_csr_as_usize!(0x340, __write_mscratch); diff --git a/ci-user/riscv/src/register/mstatus.rs b/ci-user/riscv/src/register/mstatus.rs new file mode 100644 index 0000000..97b7b71 --- /dev/null +++ b/ci-user/riscv/src/register/mstatus.rs @@ -0,0 +1,214 @@ +//! mstatus register +// TODO: Virtualization, Memory Privilege and Extension Context Fields + +use bit_field::BitField; +use core::mem::size_of; + +/// mstatus register +#[derive(Clone, Copy, Debug)] +pub struct Mstatus { + bits: usize, +} + +/// Additional extension state +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum XS { + /// All off + AllOff = 0, + + /// None dirty or clean, some on + NoneDirtyOrClean = 1, + + /// None dirty, some clean + NoneDirtySomeClean = 2, + + /// Some dirty + SomeDirty = 3, +} + +/// Floating-point extension state +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum FS { + Off = 0, + Initial = 1, + Clean = 2, + Dirty = 3, +} + +/// Machine Previous Privilege Mode +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum MPP { + Machine = 3, + Supervisor = 1, + User = 0, +} + +/// Supervisor Previous Privilege Mode +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum SPP { + Supervisor = 1, + User = 0, +} + +impl Mstatus { + /// User Interrupt Enable + #[inline] + pub fn uie(&self) -> bool { + self.bits.get_bit(0) + } + + /// Supervisor Interrupt Enable + #[inline] + pub fn sie(&self) -> bool { + self.bits.get_bit(1) + } + + /// Machine Interrupt Enable + #[inline] + pub fn mie(&self) -> bool { + self.bits.get_bit(3) + } + + /// User Previous Interrupt Enable + #[inline] + pub fn upie(&self) -> bool { + self.bits.get_bit(4) + } + + /// Supervisor Previous Interrupt Enable + #[inline] + pub fn spie(&self) -> bool { + self.bits.get_bit(5) + } + + /// Machine Previous Interrupt Enable + #[inline] + pub fn mpie(&self) -> bool { + self.bits.get_bit(7) + } + + /// Supervisor Previous Privilege Mode + #[inline] + pub fn spp(&self) -> SPP { + match self.bits.get_bit(8) { + true => SPP::Supervisor, + false => SPP::User, + } + } + + /// Machine Previous Privilege Mode + #[inline] + pub fn mpp(&self) -> MPP { + match self.bits.get_bits(11..13) { + 0b00 => MPP::User, + 0b01 => MPP::Supervisor, + 0b11 => MPP::Machine, + _ => unreachable!(), + } + } + + #[inline] + pub fn set_mpie(&mut self, val: bool) { + self.bits.set_bit(7, val); + } + + #[inline] + pub fn set_mie(&mut self, val: bool) { + self.bits.set_bit(3, val); + } + + #[inline] + pub fn set_mpp(&mut self, val: MPP) { + self.bits.set_bits(11..13, val as usize); + } + + /// Floating-point extension state + /// + /// Encodes the status of the floating-point unit, + /// including the CSR `fcsr` and floating-point data registers `f0–f31`. + #[inline] + pub fn fs(&self) -> FS { + match self.bits.get_bits(13..15) { + 0b00 => FS::Off, + 0b01 => FS::Initial, + 0b10 => FS::Clean, + 0b11 => FS::Dirty, + _ => unreachable!(), + } + } + + /// Additional extension state + /// + /// Encodes the status of additional user-mode extensions and associated state. + #[inline] + pub fn xs(&self) -> XS { + match self.bits.get_bits(15..17) { + 0b00 => XS::AllOff, + 0b01 => XS::NoneDirtyOrClean, + 0b10 => XS::NoneDirtySomeClean, + 0b11 => XS::SomeDirty, + _ => unreachable!(), + } + } + + /// Whether either the FS field or XS field + /// signals the presence of some dirty state + #[inline] + pub fn sd(&self) -> bool { + self.bits.get_bit(size_of::() * 8 - 1) + } +} + +read_csr_as!(Mstatus, 0x300, __read_mstatus); +write_csr!(0x300, __write_mstatus); +set!(0x300, __set_mstatus); +clear!(0x300, __clear_mstatus); + +set_clear_csr!( + /// User Interrupt Enable + , set_uie, clear_uie, 1 << 0); + +set_clear_csr!( + /// Supervisor Interrupt Enable + , set_sie, clear_sie, 1 << 1); + +set_clear_csr!( + /// Machine Interrupt Enable + , set_mie, clear_mie, 1 << 3); + +set_csr!( + /// User Previous Interrupt Enable + , set_upie, 1 << 4); + +set_csr!( + /// Supervisor Previous Interrupt Enable + , set_spie, 1 << 5); + +set_csr!( + /// Machine Previous Interrupt Enable + , set_mpie, 1 << 7); + +/// Supervisor Previous Privilege Mode +#[inline] +pub unsafe fn set_spp(spp: SPP) { + match spp { + SPP::Supervisor => _set(1 << 8), + SPP::User => _clear(1 << 8), + } +} + +/// Machine Previous Privilege Mode +#[inline] +pub unsafe fn set_mpp(mpp: MPP) { + let mut value = _read(); + value.set_bits(11..13, mpp as usize); + _write(value); +} + +/// Floating-point extension state +#[inline] +pub unsafe fn set_fs(fs: FS) { + let mut value = _read(); + value.set_bits(13..15, fs as usize); + _write(value); +} diff --git a/ci-user/riscv/src/register/mtval.rs b/ci-user/riscv/src/register/mtval.rs new file mode 100644 index 0000000..2afb7cb --- /dev/null +++ b/ci-user/riscv/src/register/mtval.rs @@ -0,0 +1,3 @@ +//! mtval register + +read_csr_as_usize!(0x343, __read_mtval); diff --git a/ci-user/riscv/src/register/mtvec.rs b/ci-user/riscv/src/register/mtvec.rs new file mode 100644 index 0000000..6a069d1 --- /dev/null +++ b/ci-user/riscv/src/register/mtvec.rs @@ -0,0 +1,47 @@ +//! mtvec register + +/// mtvec register +#[derive(Clone, Copy, Debug)] +pub struct Mtvec { + bits: usize, +} + +/// Trap mode +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum TrapMode { + Direct = 0, + Vectored = 1, +} + +impl Mtvec { + /// Returns the contents of the register as raw bits + pub fn bits(&self) -> usize { + self.bits + } + + /// Returns the trap-vector base-address + pub fn address(&self) -> usize { + self.bits - (self.bits & 0b11) + } + + /// Returns the trap-vector mode + pub fn trap_mode(&self) -> Option { + let mode = self.bits & 0b11; + match mode { + 0 => Some(TrapMode::Direct), + 1 => Some(TrapMode::Vectored), + _ => None, + } + } +} + +read_csr_as!(Mtvec, 0x305, __read_mtvec); + +write_csr!(0x305, __write_mtvec); + +/// Writes the CSR +#[inline] +pub unsafe fn write(addr: usize, mode: TrapMode) { + let bits = addr + mode as usize; + _write(bits); +} diff --git a/ci-user/riscv/src/register/mvendorid.rs b/ci-user/riscv/src/register/mvendorid.rs new file mode 100644 index 0000000..9b99d47 --- /dev/null +++ b/ci-user/riscv/src/register/mvendorid.rs @@ -0,0 +1,32 @@ +//! mvendorid register + +use core::num::NonZeroUsize; + +/// mvendorid register +#[derive(Clone, Copy, Debug)] +pub struct Mvendorid { + bits: NonZeroUsize, +} + +impl Mvendorid { + /// Returns the contents of the register as raw bits + pub fn bits(&self) -> usize { + self.bits.get() + } + + /// Returns the JEDEC manufacturer ID + pub fn jedec_manufacturer(&self) -> usize { + self.bits() >> 7 + } +} + +read_csr!(0xF11, __read_mvendorid); + +/// Reads the CSR +#[inline] +pub fn read() -> Option { + let r = unsafe { _read() }; + // When mvendorid is hardwired to zero it means that the mvendorid + // csr isn't implemented. + NonZeroUsize::new(r).map(|bits| Mvendorid { bits }) +} diff --git a/ci-user/riscv/src/register/pmpaddrx.rs b/ci-user/riscv/src/register/pmpaddrx.rs new file mode 100644 index 0000000..cfa43fc --- /dev/null +++ b/ci-user/riscv/src/register/pmpaddrx.rs @@ -0,0 +1,28 @@ +macro_rules! reg { + ( + $addr:expr, $csr:ident, $readf:ident, $writef:ident + ) => { + /// Physical memory protection address register + pub mod $csr { + read_csr_as_usize!($addr, $readf); + write_csr_as_usize!($addr, $writef); + } + }; +} + +reg!(0x3B0, pmpaddr0, __read_pmpaddr0, __write_pmpaddr0); +reg!(0x3B1, pmpaddr1, __read_pmpaddr1, __write_pmpaddr1); +reg!(0x3B2, pmpaddr2, __read_pmpaddr2, __write_pmpaddr2); +reg!(0x3B3, pmpaddr3, __read_pmpaddr3, __write_pmpaddr3); +reg!(0x3B4, pmpaddr4, __read_pmpaddr4, __write_pmpaddr4); +reg!(0x3B5, pmpaddr5, __read_pmpaddr5, __write_pmpaddr5); +reg!(0x3B6, pmpaddr6, __read_pmpaddr6, __write_pmpaddr6); +reg!(0x3B7, pmpaddr7, __read_pmpaddr7, __write_pmpaddr7); +reg!(0x3B8, pmpaddr8, __read_pmpaddr8, __write_pmpaddr8); +reg!(0x3B9, pmpaddr9, __read_pmpaddr9, __write_pmpaddr9); +reg!(0x3BA, pmpaddr10, __read_pmpaddr10, __write_pmpaddr10); +reg!(0x3BB, pmpaddr11, __read_pmpaddr11, __write_pmpaddr11); +reg!(0x3BC, pmpaddr12, __read_pmpaddr12, __write_pmpaddr12); +reg!(0x3BD, pmpaddr13, __read_pmpaddr13, __write_pmpaddr13); +reg!(0x3BE, pmpaddr14, __read_pmpaddr14, __write_pmpaddr14); +reg!(0x3BF, pmpaddr15, __read_pmpaddr15, __write_pmpaddr15); diff --git a/ci-user/riscv/src/register/pmpcfgx.rs b/ci-user/riscv/src/register/pmpcfgx.rs new file mode 100644 index 0000000..ec27251 --- /dev/null +++ b/ci-user/riscv/src/register/pmpcfgx.rs @@ -0,0 +1,23 @@ +/// Physical memory protection configuration +pub mod pmpcfg0 { + read_csr_as_usize!(0x3A0, __read_pmpcfg0); + write_csr_as_usize!(0x3A0, __write_pmpcfg0); +} + +/// Physical memory protection configuration, RV32 only +pub mod pmpcfg1 { + read_csr_as_usize_rv32!(0x3A1, __read_pmpcfg1); + write_csr_as_usize_rv32!(0x3A1, __write_pmpcfg1); +} + +/// Physical memory protection configuration +pub mod pmpcfg2 { + read_csr_as_usize!(0x3A2, __read_pmpcfg2); + write_csr_as_usize!(0x3A2, __write_pmpcfg2); +} + +/// Physical memory protection configuration, RV32 only +pub mod pmpcfg3 { + read_csr_as_usize_rv32!(0x3A3, __read_pmpcfg3); + write_csr_as_usize_rv32!(0x3A3, __write_pmpcfg3); +} diff --git a/ci-user/riscv/src/register/satp.rs b/ci-user/riscv/src/register/satp.rs new file mode 100644 index 0000000..481c8ca --- /dev/null +++ b/ci-user/riscv/src/register/satp.rs @@ -0,0 +1,119 @@ +//! satp register + +#[cfg(riscv)] +use addr::Frame; +#[cfg(riscv)] +use bit_field::BitField; + +/// satp register +#[derive(Clone, Copy, Debug)] +pub struct Satp { + bits: usize, +} + +impl Satp { + /// Returns the contents of the register as raw bits + #[inline] + pub fn bits(&self) -> usize { + self.bits + } + + /// Current address-translation scheme + #[inline] + #[cfg(riscv32)] + pub fn mode(&self) -> Mode { + match self.bits.get_bit(31) { + false => Mode::Bare, + true => Mode::Sv32, + } + } + + /// Current address-translation scheme + #[inline] + #[cfg(riscv64)] + pub fn mode(&self) -> Mode { + match self.bits.get_bits(60..64) { + 0 => Mode::Bare, + 8 => Mode::Sv39, + 9 => Mode::Sv48, + 10 => Mode::Sv57, + 11 => Mode::Sv64, + _ => unreachable!(), + } + } + + /// Address space identifier + #[inline] + #[cfg(riscv32)] + pub fn asid(&self) -> usize { + self.bits.get_bits(22..31) + } + + /// Address space identifier + #[inline] + #[cfg(riscv64)] + pub fn asid(&self) -> usize { + self.bits.get_bits(44..60) + } + + /// Physical page number + #[inline] + #[cfg(riscv32)] + pub fn ppn(&self) -> usize { + self.bits.get_bits(0..22) + } + + /// Physical page number + #[inline] + #[cfg(riscv64)] + pub fn ppn(&self) -> usize { + self.bits.get_bits(0..44) + } + + /// Physical frame + #[inline] + #[cfg(riscv)] + pub fn frame(&self) -> Frame { + Frame::of_ppn(self.ppn()) + } +} + +#[cfg(riscv32)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Mode { + Bare = 0, + Sv32 = 1, +} + +#[cfg(riscv64)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Mode { + Bare = 0, + Sv39 = 8, + Sv48 = 9, + Sv57 = 10, + Sv64 = 11, +} + +read_csr_as!(Satp, 0x180, __read_satp); +write_csr_as_usize!(0x180, __write_satp); + +#[inline] +#[cfg(riscv32)] +pub unsafe fn set(mode: Mode, asid: usize, ppn: usize) { + let mut bits = 0usize; + bits.set_bits(31..32, mode as usize); + bits.set_bits(22..31, asid); + bits.set_bits(0..22, ppn); + _write(bits); +} + +#[inline] +#[cfg(riscv64)] +pub unsafe fn set(mode: Mode, asid: usize, ppn: usize) { + let mut bits = 0usize; + bits.set_bits(60..64, mode as usize); + bits.set_bits(44..60, asid); + bits.set_bits(0..44, ppn); + _write(bits); +} diff --git a/ci-user/riscv/src/register/scause.rs b/ci-user/riscv/src/register/scause.rs new file mode 100644 index 0000000..5117c15 --- /dev/null +++ b/ci-user/riscv/src/register/scause.rs @@ -0,0 +1,133 @@ +//! scause register + +use bit_field::BitField; +use core::mem::size_of; + +/// scause register +#[derive(Clone, Copy)] +pub struct Scause { + bits: usize, +} + +/// Trap Cause +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum Trap { + Interrupt(Interrupt), + Exception(Exception), +} + +/// Interrupt +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum Interrupt { + UserSoft, + VirtualSupervisorSoft, + SupervisorSoft, + UserTimer, + VirtualSupervisorTimer, + SupervisorTimer, + UserExternal, + VirtualSupervisorExternal, + SupervisorExternal, + Unknown, +} + +/// Exception +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum Exception { + InstructionMisaligned, + InstructionFault, + IllegalInstruction, + Breakpoint, + LoadFault, + StoreMisaligned, + StoreFault, + UserEnvCall, + VirtualSupervisorEnvCall, + InstructionPageFault, + LoadPageFault, + StorePageFault, + InstructionGuestPageFault, + LoadGuestPageFault, + VirtualInstruction, + StoreGuestPageFault, + Unknown, +} + +impl Interrupt { + pub fn from(nr: usize) -> Self { + match nr { + 0 => Interrupt::UserSoft, + 1 => Interrupt::SupervisorSoft, + 2 => Interrupt::VirtualSupervisorSoft, + 4 => Interrupt::UserTimer, + 5 => Interrupt::SupervisorTimer, + 6 => Interrupt::VirtualSupervisorTimer, + 8 => Interrupt::UserExternal, + 9 => Interrupt::SupervisorExternal, + 10 => Interrupt::VirtualSupervisorExternal, + _ => Interrupt::Unknown, + } + } +} + +impl Exception { + pub fn from(nr: usize) -> Self { + match nr { + 0 => Exception::InstructionMisaligned, + 1 => Exception::InstructionFault, + 2 => Exception::IllegalInstruction, + 3 => Exception::Breakpoint, + 5 => Exception::LoadFault, + 6 => Exception::StoreMisaligned, + 7 => Exception::StoreFault, + 8 => Exception::UserEnvCall, + 10 => Exception::VirtualSupervisorEnvCall, + 12 => Exception::InstructionPageFault, + 13 => Exception::LoadPageFault, + 15 => Exception::StorePageFault, + 20 => Exception::InstructionGuestPageFault, + 21 => Exception::LoadGuestPageFault, + 22 => Exception::VirtualInstruction, + 23 => Exception::StoreGuestPageFault, + _ => Exception::Unknown, + } + } +} + +impl Scause { + /// Returns the contents of the register as raw bits + #[inline] + pub fn bits(&self) -> usize { + self.bits + } + + /// Returns the code field + pub fn code(&self) -> usize { + let bit = 1 << (size_of::() * 8 - 1); + self.bits & !bit + } + + /// Trap Cause + #[inline] + pub fn cause(&self) -> Trap { + if self.is_interrupt() { + Trap::Interrupt(Interrupt::from(self.code())) + } else { + Trap::Exception(Exception::from(self.code())) + } + } + + /// Is trap cause an interrupt. + #[inline] + pub fn is_interrupt(&self) -> bool { + self.bits.get_bit(size_of::() * 8 - 1) + } + + /// Is trap cause an exception. + #[inline] + pub fn is_exception(&self) -> bool { + !self.is_interrupt() + } +} + +read_csr_as!(Scause, 0x142, __read_scause); diff --git a/ci-user/riscv/src/register/sepc.rs b/ci-user/riscv/src/register/sepc.rs new file mode 100644 index 0000000..aba69df --- /dev/null +++ b/ci-user/riscv/src/register/sepc.rs @@ -0,0 +1,4 @@ +//! sepc register + +read_csr_as_usize!(0x141, __read_sepc); +write_csr_as_usize!(0x141, __write_sepc); diff --git a/ci-user/riscv/src/register/sie.rs b/ci-user/riscv/src/register/sie.rs new file mode 100644 index 0000000..b652110 --- /dev/null +++ b/ci-user/riscv/src/register/sie.rs @@ -0,0 +1,76 @@ +//! sie register + +use bit_field::BitField; + +/// sie register +#[derive(Clone, Copy, Debug)] +pub struct Sie { + bits: usize, +} + +impl Sie { + /// Returns the contents of the register as raw bits + #[inline] + pub fn bits(&self) -> usize { + self.bits + } + + /// User Software Interrupt Enable + #[inline] + pub fn usoft(&self) -> bool { + self.bits.get_bit(0) + } + + /// Supervisor Software Interrupt Enable + #[inline] + pub fn ssoft(&self) -> bool { + self.bits.get_bit(1) + } + + /// User Timer Interrupt Enable + #[inline] + pub fn utimer(&self) -> bool { + self.bits.get_bit(4) + } + + /// Supervisor Timer Interrupt Enable + #[inline] + pub fn stimer(&self) -> bool { + self.bits.get_bit(5) + } + + /// User External Interrupt Enable + #[inline] + pub fn uext(&self) -> bool { + self.bits.get_bit(8) + } + + /// Supervisor External Interrupt Enable + #[inline] + pub fn sext(&self) -> bool { + self.bits.get_bit(9) + } +} + +read_csr_as!(Sie, 0x104, __read_sie); +set!(0x104, __set_sie); +clear!(0x104, __clear_sie); + +set_clear_csr!( + /// User Software Interrupt Enable + , set_usoft, clear_usoft, 1 << 0); +set_clear_csr!( + /// Supervisor Software Interrupt Enable + , set_ssoft, clear_ssoft, 1 << 1); +set_clear_csr!( + /// User Timer Interrupt Enable + , set_utimer, clear_utimer, 1 << 4); +set_clear_csr!( + /// Supervisor Timer Interrupt Enable + , set_stimer, clear_stimer, 1 << 5); +set_clear_csr!( + /// User External Interrupt Enable + , set_uext, clear_uext, 1 << 8); +set_clear_csr!( + /// Supervisor External Interrupt Enable + , set_sext, clear_sext, 1 << 9); diff --git a/ci-user/riscv/src/register/sip.rs b/ci-user/riscv/src/register/sip.rs new file mode 100644 index 0000000..f625661 --- /dev/null +++ b/ci-user/riscv/src/register/sip.rs @@ -0,0 +1,55 @@ +//! sip register + +use bit_field::BitField; + +/// sip register +#[derive(Clone, Copy, Debug)] +pub struct Sip { + bits: usize, +} + +impl Sip { + /// Returns the contents of the register as raw bits + #[inline] + pub fn bits(&self) -> usize { + self.bits + } + + /// User Software Interrupt Pending + #[inline] + pub fn usoft(&self) -> bool { + self.bits.get_bit(0) + } + + /// Supervisor Software Interrupt Pending + #[inline] + pub fn ssoft(&self) -> bool { + self.bits.get_bit(1) + } + + /// User Timer Interrupt Pending + #[inline] + pub fn utimer(&self) -> bool { + self.bits.get_bit(4) + } + + /// Supervisor Timer Interrupt Pending + #[inline] + pub fn stimer(&self) -> bool { + self.bits.get_bit(5) + } + + /// User External Interrupt Pending + #[inline] + pub fn uext(&self) -> bool { + self.bits.get_bit(8) + } + + /// Supervisor External Interrupt Pending + #[inline] + pub fn sext(&self) -> bool { + self.bits.get_bit(9) + } +} + +read_csr_as!(Sip, 0x144, __read_sip); diff --git a/ci-user/riscv/src/register/sscratch.rs b/ci-user/riscv/src/register/sscratch.rs new file mode 100644 index 0000000..349812c --- /dev/null +++ b/ci-user/riscv/src/register/sscratch.rs @@ -0,0 +1,4 @@ +//! sscratch register + +read_csr_as_usize!(0x140, __read_sscratch); +write_csr_as_usize!(0x140, __write_sscratch); diff --git a/ci-user/riscv/src/register/sstatus.rs b/ci-user/riscv/src/register/sstatus.rs new file mode 100644 index 0000000..37a1753 --- /dev/null +++ b/ci-user/riscv/src/register/sstatus.rs @@ -0,0 +1,161 @@ +//! sstatus register + +pub use super::mstatus::FS; +use bit_field::BitField; +use core::mem::size_of; + +/// Supervisor Status Register +#[derive(Clone, Copy, Debug)] +pub struct Sstatus { + bits: usize, +} + +/// Supervisor Previous Privilege Mode +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum SPP { + Supervisor = 1, + User = 0, +} + +impl Sstatus { + /// Returns the contents of the register as raw bits + #[inline] + pub fn bits(&self) -> usize { + self.bits + } + + /// User Interrupt Enable + #[inline] + pub fn uie(&self) -> bool { + self.bits.get_bit(0) + } + + /// Supervisor Interrupt Enable + #[inline] + pub fn sie(&self) -> bool { + self.bits.get_bit(1) + } + + /// User Previous Interrupt Enable + #[inline] + pub fn upie(&self) -> bool { + self.bits.get_bit(4) + } + + /// Supervisor Previous Interrupt Enable + #[inline] + pub fn spie(&self) -> bool { + self.bits.get_bit(5) + } + + /// Supervisor Previous Privilege Mode + #[inline] + pub fn spp(&self) -> SPP { + match self.bits.get_bit(8) { + true => SPP::Supervisor, + false => SPP::User, + } + } + + /// The status of the floating-point unit + #[inline] + pub fn fs(&self) -> FS { + match self.bits.get_bits(13..15) { + 0 => FS::Off, + 1 => FS::Initial, + 2 => FS::Clean, + 3 => FS::Dirty, + _ => unreachable!(), + } + } + + /// The status of additional user-mode extensions + /// and associated state + #[inline] + pub fn xs(&self) -> FS { + match self.bits.get_bits(15..17) { + 0 => FS::Off, + 1 => FS::Initial, + 2 => FS::Clean, + 3 => FS::Dirty, + _ => unreachable!(), + } + } + + /// Permit Supervisor User Memory access + #[inline] + pub fn sum(&self) -> bool { + self.bits.get_bit(18) + } + + /// Make eXecutable Readable + #[inline] + pub fn mxr(&self) -> bool { + self.bits.get_bit(19) + } + + /// Whether either the FS field or XS field + /// signals the presence of some dirty state + #[inline] + pub fn sd(&self) -> bool { + self.bits.get_bit(size_of::() * 8 - 1) + } + + #[inline] + pub fn set_spie(&mut self, val: bool) { + self.bits.set_bit(5, val); + } + + #[inline] + pub fn set_sie(&mut self, val: bool) { + self.bits.set_bit(1, val); + } + + #[inline] + pub fn set_spp(&mut self, val: SPP) { + self.bits.set_bit(8, val == SPP::Supervisor); + } +} + +read_csr_as!(Sstatus, 0x100, __read_sstatus); +write_csr!(0x100, __write_sstatus); +set!(0x100, __set_sstatus); +clear!(0x100, __clear_sstatus); + +set_clear_csr!( + /// User Interrupt Enable + , set_uie, clear_uie, 1 << 0); +set_clear_csr!( + /// Supervisor Interrupt Enable + , set_sie, clear_sie, 1 << 1); +set_csr!( + /// User Previous Interrupt Enable + , set_upie, 1 << 4); +set_csr!( + /// Supervisor Previous Interrupt Enable + , set_spie, 1 << 5); +set_clear_csr!( + /// Make eXecutable Readable + , set_mxr, clear_mxr, 1 << 19); +set_clear_csr!( + /// Permit Supervisor User Memory access + , set_sum, clear_sum, 1 << 18); + +/// Supervisor Previous Privilege Mode +#[inline] +#[cfg(riscv)] +pub unsafe fn set_spp(spp: SPP) { + match spp { + SPP::Supervisor => _set(1 << 8), + SPP::User => _clear(1 << 8), + } +} + +/// The status of the floating-point unit +#[inline] +#[cfg(riscv)] +pub unsafe fn set_fs(fs: FS) { + let mut value = _read(); + value.set_bits(13..15, fs as usize); + _write(value); +} diff --git a/ci-user/riscv/src/register/stval.rs b/ci-user/riscv/src/register/stval.rs new file mode 100644 index 0000000..722cc19 --- /dev/null +++ b/ci-user/riscv/src/register/stval.rs @@ -0,0 +1,3 @@ +//! stval register + +read_csr_as_usize!(0x143, __read_stval); diff --git a/ci-user/riscv/src/register/stvec.rs b/ci-user/riscv/src/register/stvec.rs new file mode 100644 index 0000000..7df0027 --- /dev/null +++ b/ci-user/riscv/src/register/stvec.rs @@ -0,0 +1,40 @@ +//! stvec register + +pub use crate::register::mtvec::TrapMode; + +/// stvec register +#[derive(Clone, Copy, Debug)] +pub struct Stvec { + bits: usize, +} + +impl Stvec { + /// Returns the contents of the register as raw bits + pub fn bits(&self) -> usize { + self.bits + } + + /// Returns the trap-vector base-address + pub fn address(&self) -> usize { + self.bits - (self.bits & 0b11) + } + + /// Returns the trap-vector mode + pub fn trap_mode(&self) -> Option { + let mode = self.bits & 0b11; + match mode { + 0 => Some(TrapMode::Direct), + 1 => Some(TrapMode::Vectored), + _ => None, + } + } +} + +read_csr_as!(Stvec, 0x105, __read_stvec); +write_csr!(0x105, __write_stvec); + +/// Writes the CSR +#[inline] +pub unsafe fn write(addr: usize, mode: TrapMode) { + _write(addr + mode as usize); +} diff --git a/ci-user/riscv/src/register/time.rs b/ci-user/riscv/src/register/time.rs new file mode 100644 index 0000000..665b507 --- /dev/null +++ b/ci-user/riscv/src/register/time.rs @@ -0,0 +1,4 @@ +//! time register + +read_csr_as_usize!(0xC01, __read_time); +read_composite_csr!(super::timeh::read(), read()); diff --git a/ci-user/riscv/src/register/timeh.rs b/ci-user/riscv/src/register/timeh.rs new file mode 100644 index 0000000..ff725db --- /dev/null +++ b/ci-user/riscv/src/register/timeh.rs @@ -0,0 +1,3 @@ +//! timeh register + +read_csr_as_usize_rv32!(0xC81, __read_timeh); diff --git a/ci-user/riscv/src/register/ucause.rs b/ci-user/riscv/src/register/ucause.rs new file mode 100644 index 0000000..06dd8a3 --- /dev/null +++ b/ci-user/riscv/src/register/ucause.rs @@ -0,0 +1,17 @@ +//! ucause register + +/// ucause register +#[derive(Clone, Copy, Debug)] +pub struct Ucause { + bits: usize, +} + +impl Ucause { + /// Returns the contents of the register as raw bits + #[inline] + pub fn bits(&self) -> usize { + self.bits + } +} + +read_csr_as!(Ucause, 0x042, __read_ucause); diff --git a/ci-user/riscv/src/register/uepc.rs b/ci-user/riscv/src/register/uepc.rs new file mode 100644 index 0000000..1c9fa0e --- /dev/null +++ b/ci-user/riscv/src/register/uepc.rs @@ -0,0 +1,4 @@ +//! uepc register + +read_csr_as_usize!(0x041, __read_uepc); +write_csr_as_usize!(0x041, __write_uepc); diff --git a/ci-user/riscv/src/register/uie.rs b/ci-user/riscv/src/register/uie.rs new file mode 100644 index 0000000..4a5e9e0 --- /dev/null +++ b/ci-user/riscv/src/register/uie.rs @@ -0,0 +1,49 @@ +//! uie register + +use bit_field::BitField; + +/// uie register +#[derive(Clone, Copy, Debug)] +pub struct Uie { + bits: usize, +} + +impl Uie { + /// Returns the contents of the register as raw bits + #[inline] + pub fn bits(&self) -> usize { + self.bits + } + + /// User Software Interrupt Enable + #[inline] + pub fn usoft(&self) -> bool { + self.bits.get_bit(0) + } + + /// User Timer Interrupt Enable + #[inline] + pub fn utimer(&self) -> bool { + self.bits.get_bit(4) + } + + /// User External Interrupt Enable + #[inline] + pub fn uext(&self) -> bool { + self.bits.get_bit(8) + } +} + +read_csr_as!(Uie, 0x004, __read_uie); +set!(0x004, __set_uie); +clear!(0x004, __clear_uie); + +set_clear_csr!( + /// User Software Interrupt Enable + , set_usoft, clear_usoft, 1 << 0); +set_clear_csr!( + /// User Timer Interrupt Enable + , set_utimer, clear_utimer, 1 << 4); +set_clear_csr!( + /// User External Interrupt Enable + , set_uext, clear_uext, 1 << 8); diff --git a/ci-user/riscv/src/register/uip.rs b/ci-user/riscv/src/register/uip.rs new file mode 100644 index 0000000..ec92ad8 --- /dev/null +++ b/ci-user/riscv/src/register/uip.rs @@ -0,0 +1,37 @@ +//! uip register + +use bit_field::BitField; + +/// uip register +#[derive(Clone, Copy, Debug)] +pub struct Uip { + bits: usize, +} + +impl Uip { + /// Returns the contents of the register as raw bits + #[inline] + pub fn bits(&self) -> usize { + self.bits + } + + /// User Software Interrupt Pending + #[inline] + pub fn usoft(&self) -> bool { + self.bits.get_bit(0) + } + + /// User Timer Interrupt Pending + #[inline] + pub fn utimer(&self) -> bool { + self.bits.get_bit(4) + } + + /// User External Interrupt Pending + #[inline] + pub fn uext(&self) -> bool { + self.bits.get_bit(8) + } +} + +read_csr_as!(Uip, 0x044, __read_uip); diff --git a/ci-user/riscv/src/register/uscratch.rs b/ci-user/riscv/src/register/uscratch.rs new file mode 100644 index 0000000..2bc2253 --- /dev/null +++ b/ci-user/riscv/src/register/uscratch.rs @@ -0,0 +1,4 @@ +//! uscratch register + +read_csr_as_usize!(0x040, __read_uscratch); +write_csr_as_usize!(0x040, __write_uscratch); diff --git a/ci-user/riscv/src/register/ustatus.rs b/ci-user/riscv/src/register/ustatus.rs new file mode 100644 index 0000000..81890ba --- /dev/null +++ b/ci-user/riscv/src/register/ustatus.rs @@ -0,0 +1,37 @@ +//! ustatus register +// TODO: Virtualization, Memory Privilege and Extension Context Fields + +use bit_field::BitField; + +/// ustatus register +#[derive(Clone, Copy, Debug)] +pub struct Ustatus { + bits: usize, +} + +impl Ustatus { + /// User Interrupt Enable + #[inline] + pub fn uie(&self) -> bool { + self.bits.get_bit(0) + } + + /// User Previous Interrupt Enable + #[inline] + pub fn upie(&self) -> bool { + self.bits.get_bit(4) + } +} + +read_csr_as!(Ustatus, 0x000, __read_ustatus); +write_csr!(0x000, __write_ustatus); +set!(0x000, __set_ustatus); +clear!(0x000, __clear_ustatus); + +set_clear_csr!( + /// User Interrupt Enable + , set_uie, clear_uie, 1 << 0); + +set_csr!( + /// User Previous Interrupt Enable + , set_upie, 1 << 4); diff --git a/ci-user/riscv/src/register/utval.rs b/ci-user/riscv/src/register/utval.rs new file mode 100644 index 0000000..b87dca6 --- /dev/null +++ b/ci-user/riscv/src/register/utval.rs @@ -0,0 +1,3 @@ +//! utval register + +read_csr_as_usize!(0x043, __read_utval); diff --git a/ci-user/riscv/src/register/utvec.rs b/ci-user/riscv/src/register/utvec.rs new file mode 100644 index 0000000..7111078 --- /dev/null +++ b/ci-user/riscv/src/register/utvec.rs @@ -0,0 +1,40 @@ +//! stvec register + +pub use crate::register::mtvec::TrapMode; + +/// stvec register +#[derive(Clone, Copy, Debug)] +pub struct Utvec { + bits: usize, +} + +impl Utvec { + /// Returns the contents of the register as raw bits + pub fn bits(&self) -> usize { + self.bits + } + + /// Returns the trap-vector base-address + pub fn address(&self) -> usize { + self.bits - (self.bits & 0b11) + } + + /// Returns the trap-vector mode + pub fn trap_mode(&self) -> Option { + let mode = self.bits & 0b11; + match mode { + 0 => Some(TrapMode::Direct), + 1 => Some(TrapMode::Vectored), + _ => None, + } + } +} + +read_csr_as!(Utvec, 0x005, __read_utvec); +write_csr!(0x005, __write_utvec); + +/// Writes the CSR +#[inline] +pub unsafe fn write(addr: usize, mode: TrapMode) { + _write(addr + mode as usize); +} diff --git a/ci-user/user/.cargo/config b/ci-user/user/.cargo/config new file mode 100644 index 0000000..e5ded8a --- /dev/null +++ b/ci-user/user/.cargo/config @@ -0,0 +1,7 @@ +[build] +target = "riscv64gc-unknown-none-elf" + +[target.riscv64gc-unknown-none-elf] +rustflags = [ + "-Clink-args=-Tsrc/linker.ld", +] diff --git a/ci-user/user/.gitignore b/ci-user/user/.gitignore new file mode 100644 index 0000000..b5004eb --- /dev/null +++ b/ci-user/user/.gitignore @@ -0,0 +1,4 @@ +target/* +.vscode/ +build/ +.idea/ \ No newline at end of file diff --git a/ci-user/user/Cargo.toml b/ci-user/user/Cargo.toml new file mode 100644 index 0000000..bdd5019 --- /dev/null +++ b/ci-user/user/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "user_lib" +version = "0.1.0" +authors = ["Yifan Wu "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +buddy_system_allocator = "0.6" +bitflags = "1.2.1" +spin = "0.9" +lock_api = "=0.4.6" +lazy_static = { version = "1.4.0", features = ["spin_no_std"] } + +[profile.release] +opt-level = "z" # Optimize for size. +strip = true # Automatically strip symbols from the binary. +lto = true diff --git a/ci-user/user/Makefile b/ci-user/user/Makefile new file mode 100644 index 0000000..1c87fe9 --- /dev/null +++ b/ci-user/user/Makefile @@ -0,0 +1,64 @@ +TARGET := riscv64gc-unknown-none-elf +MODE := release +APP_DIR := src/bin +TARGET_DIR := target/$(TARGET)/$(MODE) +BUILD_DIR := build +OBJDUMP := rust-objdump --arch-name=riscv64 +OBJCOPY := rust-objcopy --binary-architecture=riscv64 +PY := python3 + +BASE ?= 0 +CHAPTER ?= 0 +TEST ?= $(CHAPTER) + +ifeq ($(TEST), 0) # No test, deprecated, previously used in v3 + APPS := $(filter-out $(wildcard $(APP_DIR)/ch*.rs), $(wildcard $(APP_DIR)/*.rs)) +else ifeq ($(TEST), 1) # All test + APPS := $(wildcard $(APP_DIR)/ch*.rs) +else + TESTS := $(shell seq $(BASE) $(TEST)) + ifeq ($(BASE), 0) # Normal tests only + APPS := $(foreach T, $(TESTS), $(wildcard $(APP_DIR)/ch$(T)_*.rs)) + else ifeq ($(BASE), 1) # Basic tests only + APPS := $(foreach T, $(TESTS), $(wildcard $(APP_DIR)/ch$(T)b_*.rs)) + else # Basic and normal + APPS := $(foreach T, $(TESTS), $(wildcard $(APP_DIR)/ch$(T)*.rs)) + endif +endif + +ELFS := $(patsubst $(APP_DIR)/%.rs, $(TARGET_DIR)/%, $(APPS)) + +binary: + @echo $(ELFS) + @if [ ${CHAPTER} -gt 3 ]; then \ + cargo build --release ;\ + else \ + CHAPTER=$(CHAPTER) python3 build.py ;\ + fi + @$(foreach elf, $(ELFS), \ + $(OBJCOPY) $(elf) --strip-all -O binary $(patsubst $(TARGET_DIR)/%, $(TARGET_DIR)/%.bin, $(elf)); \ + cp $(elf) $(patsubst $(TARGET_DIR)/%, $(TARGET_DIR)/%.elf, $(elf));) + +disasm: + @$(foreach elf, $(ELFS), \ + $(OBJDUMP) $(elf) -S > $(patsubst $(TARGET_DIR)/%, $(TARGET_DIR)/%.asm, $(elf));) + @$(foreach t, $(ELFS), cp $(t).asm $(BUILD_DIR)/asm/;) + +pre: + @mkdir -p $(BUILD_DIR)/bin/ + @mkdir -p $(BUILD_DIR)/elf/ + @mkdir -p $(BUILD_DIR)/app/ + @mkdir -p $(BUILD_DIR)/asm/ + @$(foreach t, $(APPS), cp $(t) $(BUILD_DIR)/app/;) + +build: clean pre binary + @$(foreach t, $(ELFS), cp $(t).bin $(BUILD_DIR)/bin/;) + @$(foreach t, $(ELFS), cp $(t).elf $(BUILD_DIR)/elf/;) + +clean: + @cargo clean + @rm -rf $(BUILD_DIR) + +all: build + +.PHONY: elf binary build clean all \ No newline at end of file diff --git a/ci-user/user/build.py b/ci-user/user/build.py new file mode 100644 index 0000000..de0cb66 --- /dev/null +++ b/ci-user/user/build.py @@ -0,0 +1,23 @@ +import os + +base_address = 0x80400000 +step = 0x20000 +linker = "src/linker.ld" + +app_id = 0 +apps = os.listdir("build/app") +apps.sort() +chapter = os.getenv("CHAPTER") + +for app in apps: + app = app[: app.find(".")] + os.system( + "cargo rustc --bin %s --release -- -Clink-args=-Ttext=%x" + % (app, base_address + step * app_id) + ) + print( + "[build.py] application %s start with address %s" + % (app, hex(base_address + step * app_id)) + ) + if chapter == '3': + app_id = app_id + 1 diff --git a/ci-user/user/src/bin/ch2b_bad_address.rs b/ci-user/user/src/bin/ch2b_bad_address.rs new file mode 100644 index 0000000..bb6dfeb --- /dev/null +++ b/ci-user/user/src/bin/ch2b_bad_address.rs @@ -0,0 +1,16 @@ +#![no_std] +#![no_main] + +extern crate user_lib; + +/// 由于 rustsbi 的问题,该程序无法正确退出 +/// > rustsbi 0.2.0-alpha.1 已经修复,可以正常退出 + +#[no_mangle] +pub fn main() -> isize { + unsafe { + #[allow(clippy::zero_ptr)] + (0x0 as *mut u8).write_volatile(0); + } + panic!("FAIL: T.T\n"); +} \ No newline at end of file diff --git a/ci-user/user/src/bin/ch2b_bad_instructions.rs b/ci-user/user/src/bin/ch2b_bad_instructions.rs new file mode 100644 index 0000000..f60791e --- /dev/null +++ b/ci-user/user/src/bin/ch2b_bad_instructions.rs @@ -0,0 +1,15 @@ +#![no_std] +#![no_main] + +extern crate user_lib; + +/// 由于 rustsbi 的问题,该程序无法正确退出 +/// > rustsbi 0.2.0-alpha.1 已经修复,可以正常退出 + +#[no_mangle] +pub fn main() -> ! { + unsafe { + core::arch::asm!("sret"); + } + panic!("FAIL: T.T\n"); +} \ No newline at end of file diff --git a/ci-user/user/src/bin/ch2b_bad_register.rs b/ci-user/user/src/bin/ch2b_bad_register.rs new file mode 100644 index 0000000..0bed325 --- /dev/null +++ b/ci-user/user/src/bin/ch2b_bad_register.rs @@ -0,0 +1,16 @@ +#![no_std] +#![no_main] + +extern crate user_lib; + +/// 由于 rustsbi 的问题,该程序无法正确退出 +/// > rustsbi 0.2.0-alpha.1 已经修复,可以正常退出 + +#[no_mangle] +pub fn main() -> ! { + let mut sstatus: usize; + unsafe { + core::arch::asm!("csrr {}, sstatus", out(reg) sstatus); + } + panic!("(-_-) I get sstatus:{:x}\nFAIL: T.T\n", sstatus); +} diff --git a/ci-user/user/src/bin/ch2b_hello_world.rs b/ci-user/user/src/bin/ch2b_hello_world.rs new file mode 100644 index 0000000..327dec7 --- /dev/null +++ b/ci-user/user/src/bin/ch2b_hello_world.rs @@ -0,0 +1,14 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +/// 正确输出: +/// Hello world from user mode program! + +#[no_mangle] +fn main() -> i32 { + println!("Hello, world from user mode program!"); + 0 +} \ No newline at end of file diff --git a/ci-user/user/src/bin/ch2b_power_3.rs b/ci-user/user/src/bin/ch2b_power_3.rs new file mode 100644 index 0000000..e0ec5f3 --- /dev/null +++ b/ci-user/user/src/bin/ch2b_power_3.rs @@ -0,0 +1,28 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +const LEN: usize = 100; + +#[no_mangle] +fn main() -> i32 { + let p = 3u64; + let m = 998244353u64; + let iter: usize = 200000; + let mut s = [0u64; LEN]; + let mut cur = 0usize; + s[cur] = 1; + for i in 1..=iter { + let next = if cur + 1 == LEN { 0 } else { cur + 1 }; + s[next] = s[cur] * p % m; + cur = next; + if i % 10000 == 0 { + println!("power_3 [{}/{}]", i, iter); + } + } + println!("{}^{} = {}(MOD {})", p, iter, s[cur], m); + println!("Test power_3 OK!"); + 0 +} \ No newline at end of file diff --git a/ci-user/user/src/bin/ch2b_power_5.rs b/ci-user/user/src/bin/ch2b_power_5.rs new file mode 100644 index 0000000..e47761b --- /dev/null +++ b/ci-user/user/src/bin/ch2b_power_5.rs @@ -0,0 +1,28 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +const LEN: usize = 100; + +#[no_mangle] +fn main() -> i32 { + let p = 5u64; + let m = 998244353u64; + let iter: usize = 140000; + let mut s = [0u64; LEN]; + let mut cur = 0usize; + s[cur] = 1; + for i in 1..=iter { + let next = if cur + 1 == LEN { 0 } else { cur + 1 }; + s[next] = s[cur] * p % m; + cur = next; + if i % 10000 == 0 { + println!("power_5 [{}/{}]", i, iter); + } + } + println!("{}^{} = {}(MOD {})", p, iter, s[cur], m); + println!("Test power_5 OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch2b_power_7.rs b/ci-user/user/src/bin/ch2b_power_7.rs new file mode 100644 index 0000000..a97d2f5 --- /dev/null +++ b/ci-user/user/src/bin/ch2b_power_7.rs @@ -0,0 +1,28 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +const LEN: usize = 100; + +#[no_mangle] +fn main() -> i32 { + let p = 7u64; + let m = 998244353u64; + let iter: usize = 160000; + let mut s = [0u64; LEN]; + let mut cur = 0usize; + s[cur] = 1; + for i in 1..=iter { + let next = if cur + 1 == LEN { 0 } else { cur + 1 }; + s[next] = s[cur] * p % m; + cur = next; + if i % 10000 == 0 { + println!("power_7 [{}/{}]", i, iter); + } + } + println!("{}^{} = {}(MOD {})", p, iter, s[cur], m); + println!("Test power_7 OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch3_taskinfo.rs b/ci-user/user/src/bin/ch3_taskinfo.rs new file mode 100644 index 0000000..7f55f15 --- /dev/null +++ b/ci-user/user/src/bin/ch3_taskinfo.rs @@ -0,0 +1,46 @@ +#![no_std] +#![no_main] + +extern crate user_lib; + +use user_lib::{ + get_time, println, sleep, task_info, TaskInfo, TaskStatus, SYSCALL_EXIT, SYSCALL_GETTIMEOFDAY, + SYSCALL_TASK_INFO, SYSCALL_WRITE, SYSCALL_YIELD, +}; + +#[no_mangle] +pub fn main() -> usize { + let t1 = get_time() as usize; + let info = TaskInfo::new(); + get_time(); + sleep(500); + let t2 = get_time() as usize; + // 注意本次 task info 调用也计入 + assert_eq!(0, task_info(&info)); + let t3 = get_time() as usize; + assert!(3 <= info.syscall_times[SYSCALL_GETTIMEOFDAY]); + assert_eq!(1, info.syscall_times[SYSCALL_TASK_INFO]); + assert_eq!(0, info.syscall_times[SYSCALL_WRITE]); + assert!(0 < info.syscall_times[SYSCALL_YIELD]); + assert_eq!(0, info.syscall_times[SYSCALL_EXIT]); + assert!(t2 - t1 <= info.time + 1); + assert!(info.time < t3 - t1 + 100); + assert!(info.status == TaskStatus::Running); + + // 想想为什么 write 调用是两次 + println!("string from task info test\n"); + let t4 = get_time() as usize; + assert_eq!(0, task_info(&info)); + let t5 = get_time() as usize; + assert!(5 <= info.syscall_times[SYSCALL_GETTIMEOFDAY]); + assert_eq!(2, info.syscall_times[SYSCALL_TASK_INFO]); + assert_eq!(2, info.syscall_times[SYSCALL_WRITE]); + assert!(0 < info.syscall_times[SYSCALL_YIELD]); + assert_eq!(0, info.syscall_times[SYSCALL_EXIT]); + assert!(t4 - t1 <= info.time + 1); + assert!(info.time < t5 - t1 + 100); + assert!(info.status == TaskStatus::Running); + + println!("Test task info OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch3b_sleep.rs b/ci-user/user/src/bin/ch3b_sleep.rs new file mode 100644 index 0000000..1312f6c --- /dev/null +++ b/ci-user/user/src/bin/ch3b_sleep.rs @@ -0,0 +1,24 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::{get_time, yield_}; + +/// 正确输出:(无报错信息) +/// get_time OK! {...} +/// Test sleep OK! + +#[no_mangle] +fn main() -> i32 { + let current_time = get_time(); + assert!(current_time > 0); + println!("get_time OK! {}", current_time); + let wait_for = current_time + 3000; + while get_time() < wait_for { + yield_(); + } + println!("Test sleep OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch3b_sleep1.rs b/ci-user/user/src/bin/ch3b_sleep1.rs new file mode 100644 index 0000000..da0cae3 --- /dev/null +++ b/ci-user/user/src/bin/ch3b_sleep1.rs @@ -0,0 +1,22 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::{get_time, sleep}; + +#[no_mangle] +pub fn main() -> i32 { + let start = get_time(); + println!("current time_msec = {}", start); + sleep(100); + let end = get_time(); + println!( + "time_msec = {} after sleeping 100 ticks, delta = {}ms!", + end, + end - start + ); + println!("Test sleep1 passed!"); + 0 +} diff --git a/ci-user/user/src/bin/ch3b_yield0.rs b/ci-user/user/src/bin/ch3b_yield0.rs new file mode 100644 index 0000000..1e09edd --- /dev/null +++ b/ci-user/user/src/bin/ch3b_yield0.rs @@ -0,0 +1,30 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::yield_; + +const WIDTH: usize = 10; +const HEIGHT: usize = 5; + +/* +理想结果:三个程序交替输出 ABC +*/ + +#[no_mangle] +fn main() -> i32 { + for i in 0..HEIGHT { + let buf = ['A' as u8; WIDTH]; + println!( + "{} [{}/{}]", + core::str::from_utf8(&buf).unwrap(), + i + 1, + HEIGHT + ); + yield_(); + } + println!("Test write A OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch3b_yield1.rs b/ci-user/user/src/bin/ch3b_yield1.rs new file mode 100644 index 0000000..ebfc13f --- /dev/null +++ b/ci-user/user/src/bin/ch3b_yield1.rs @@ -0,0 +1,30 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::yield_; + +const WIDTH: usize = 10; +const HEIGHT: usize = 5; + +/* +理想结果:三个程序交替输出 ABC +*/ + +#[no_mangle] +fn main() -> i32 { + for i in 0..HEIGHT { + let buf = ['B' as u8; WIDTH]; + println!( + "{} [{}/{}]", + core::str::from_utf8(&buf).unwrap(), + i + 1, + HEIGHT + ); + yield_(); + } + println!("Test write B OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch3b_yield2.rs b/ci-user/user/src/bin/ch3b_yield2.rs new file mode 100644 index 0000000..acbaac3 --- /dev/null +++ b/ci-user/user/src/bin/ch3b_yield2.rs @@ -0,0 +1,30 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::yield_; + +/* +理想结果:三个程序交替输出 ABC +*/ + +const WIDTH: usize = 10; +const HEIGHT: usize = 5; + +#[no_mangle] +fn main() -> i32 { + for i in 0..HEIGHT { + let buf = ['C' as u8; WIDTH]; + println!( + "{} [{}/{}]", + core::str::from_utf8(&buf).unwrap(), + i + 1, + HEIGHT + ); + yield_(); + } + println!("Test write C OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch4_mmap0.rs b/ci-user/user/src/bin/ch4_mmap0.rs new file mode 100644 index 0000000..5247eec --- /dev/null +++ b/ci-user/user/src/bin/ch4_mmap0.rs @@ -0,0 +1,33 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::mmap; + +/* +理想结果:输出 Test 04_1 OK! +*/ + +#[no_mangle] +fn main() -> i32 { + let start: usize = 0x10000000; + let len: usize = 4096; + let prot: usize = 3; + assert_eq!(0, mmap(start, len, prot)); + for i in start..(start + len) { + let addr: *mut u8 = i as *mut u8; + unsafe { + *addr = i as u8; + } + } + for i in start..(start + len) { + let addr: *mut u8 = i as *mut u8; + unsafe { + assert_eq!(*addr, i as u8); + } + } + println!("Test 04_1 OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch4_mmap1.rs b/ci-user/user/src/bin/ch4_mmap1.rs new file mode 100644 index 0000000..63d6411 --- /dev/null +++ b/ci-user/user/src/bin/ch4_mmap1.rs @@ -0,0 +1,25 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::mmap; + +/* +理想结果:程序触发访存异常,被杀死。不输出 error 就算过。 +*/ + +#[no_mangle] +fn main() -> i32 { + let start: usize = 0x10000000; + let len: usize = 4096; + let prot: usize = 1; + assert_eq!(0, mmap(start, len, prot)); + let addr: *mut u8 = start as *mut u8; + unsafe { + *addr = start as u8; + } + println!("Should cause error, Test 04_2 fail!"); + 0 +} diff --git a/ci-user/user/src/bin/ch4_mmap2.rs b/ci-user/user/src/bin/ch4_mmap2.rs new file mode 100644 index 0000000..2489fa6 --- /dev/null +++ b/ci-user/user/src/bin/ch4_mmap2.rs @@ -0,0 +1,26 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::mmap; + +/* +理想结果:程序触发访存异常,被杀死。不输出 error 就算过。 +*/ + +#[no_mangle] +fn main() -> i32 { + let start: usize = 0x10000000; + let len: usize = 4096; + let prot: usize = 2; + assert_eq!(0, mmap(start, len, prot)); + let addr: *mut u8 = start as *mut u8; + unsafe { + // *addr = start as u8; // can't write, R == 0 && W == 1 is illegal in riscv + assert!(*addr != 0); + } + println!("Should cause error, Test 04_2 fail!"); + 0 +} diff --git a/ci-user/user/src/bin/ch4_mmap3.rs b/ci-user/user/src/bin/ch4_mmap3.rs new file mode 100644 index 0000000..d9d04b6 --- /dev/null +++ b/ci-user/user/src/bin/ch4_mmap3.rs @@ -0,0 +1,25 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::mmap; + +/* +理想结果:对于错误的 mmap 返回 -1,最终输出 Test 04_4 test OK! +*/ + +#[no_mangle] +fn main() -> i32 { + let start: usize = 0x10000000; + let len: usize = 4096; + let prot: usize = 3; + assert_eq!(0, mmap(start, len, prot)); + assert_eq!(mmap(start - len, len + 1, prot), -1); + assert_eq!(mmap(start + len + 1, len, prot), -1); + assert_eq!(mmap(start + len, len, 0), -1); + assert_eq!(mmap(start + len, len, prot | 8), -1); + println!("Test 04_4 test OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch4_unmap.rs b/ci-user/user/src/bin/ch4_unmap.rs new file mode 100644 index 0000000..b64f862 --- /dev/null +++ b/ci-user/user/src/bin/ch4_unmap.rs @@ -0,0 +1,36 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::{mmap, munmap}; + +/* +理想结果:输出 Test 04_5 ummap OK! +*/ + +#[no_mangle] +fn main() -> i32 { + let start: usize = 0x10000000; + let len: usize = 4096; + let prot: usize = 3; + assert_eq!(0, mmap(start, len, prot)); + assert_eq!(mmap(start + len, len * 2, prot), 0); + assert_eq!(munmap(start, len), 0); + assert_eq!(mmap(start - len, len + 1, prot), 0); + for i in (start - len)..(start + len * 3) { + let addr: *mut u8 = i as *mut u8; + unsafe { + *addr = i as u8; + } + } + for i in (start - len)..(start + len * 3) { + let addr: *mut u8 = i as *mut u8; + unsafe { + assert_eq!(*addr, i as u8); + } + } + println!("Test 04_5 ummap OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch4_unmap2.rs b/ci-user/user/src/bin/ch4_unmap2.rs new file mode 100644 index 0000000..85ddb75 --- /dev/null +++ b/ci-user/user/src/bin/ch4_unmap2.rs @@ -0,0 +1,23 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::{mmap, munmap}; + +/* +理想结果:输出 Test 04_6 ummap2 OK! +*/ + +#[no_mangle] +fn main() -> i32 { + let start: usize = 0x10000000; + let len: usize = 4096; + let prot: usize = 3; + assert_eq!(0, mmap(start, len, prot)); + assert_eq!(munmap(start, len + 1), -1); + assert_eq!(munmap(start + 1, len - 1), -1); + println!("Test 04_6 ummap2 OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch5_exit0.rs b/ci-user/user/src/bin/ch5_exit0.rs new file mode 100644 index 0000000..3bae851 --- /dev/null +++ b/ci-user/user/src/bin/ch5_exit0.rs @@ -0,0 +1,17 @@ +#![no_std] +#![no_main] + +extern crate user_lib; +use user_lib::exit; + +/* +辅助测例,正常退出,不输出 FAIL 即可。 +*/ + +#[allow(unreachable_code)] +#[no_mangle] +pub fn main() -> i32 { + exit(66778); + panic!("FAIL: T.T\n"); + 0 +} diff --git a/ci-user/user/src/bin/ch5_exit1.rs b/ci-user/user/src/bin/ch5_exit1.rs new file mode 100644 index 0000000..47c09cb --- /dev/null +++ b/ci-user/user/src/bin/ch5_exit1.rs @@ -0,0 +1,17 @@ +#![no_std] +#![no_main] + +extern crate user_lib; +use user_lib::exit; + +/* +辅助测例,正常退出,不输出 FAIL 即可。 +*/ + +#[allow(unreachable_code)] +#[no_mangle] +pub fn main() -> i32 { + exit(-233); + panic!("FAIL: T.T\n"); + 0 +} diff --git a/ci-user/user/src/bin/ch5_getpid.rs b/ci-user/user/src/bin/ch5_getpid.rs new file mode 100644 index 0000000..66ee732 --- /dev/null +++ b/ci-user/user/src/bin/ch5_getpid.rs @@ -0,0 +1,18 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::getpid; + +/* +辅助测例 打印子进程 pid +*/ + +#[no_mangle] +pub fn main() -> i32 { + let pid = getpid(); + println!("Test getpid OK! pid = {}", pid); + 0 +} diff --git a/ci-user/user/src/bin/ch5_setprio.rs b/ci-user/user/src/bin/ch5_setprio.rs new file mode 100644 index 0000000..6aa1064 --- /dev/null +++ b/ci-user/user/src/bin/ch5_setprio.rs @@ -0,0 +1,20 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +use user_lib::set_priority; + +/// 正确输出:(无报错信息) +/// Test set_priority OK! + +#[no_mangle] +pub fn main() -> i32 { + assert_eq!(set_priority(10), 10); + assert_eq!(set_priority(isize::MAX), isize::MAX); + assert_eq!(set_priority(0), -1); + assert_eq!(set_priority(1), -1); + assert_eq!(set_priority(-10), -1); + println!("Test set_priority OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch5_spawn0.rs b/ci-user/user/src/bin/ch5_spawn0.rs new file mode 100644 index 0000000..aff47ac --- /dev/null +++ b/ci-user/user/src/bin/ch5_spawn0.rs @@ -0,0 +1,29 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::{spawn, wait}; +const MAX_CHILD: usize = 40; + +/* +理想结果:生成 MAX_CHILD 个 getpid 的子进程,全部结束后,输出 Test spawn0 OK! +*/ + +#[no_mangle] +pub fn main() -> i32 { + for _ in 0..MAX_CHILD { + let cpid = spawn("ch5_getpid\0"); + assert!(cpid >= 0, "child pid invalid"); + println!("new child {}", cpid); + } + let mut exit_code: i32 = 0; + for _ in 0..MAX_CHILD { + assert!(wait(&mut exit_code) > 0, "wait stopped early"); + assert_eq!(exit_code, 0, "error exit ocde {}", exit_code); + } + assert!(wait(&mut exit_code) <= 0, "wait got too many"); + println!("Test spawn0 OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch5_spawn1.rs b/ci-user/user/src/bin/ch5_spawn1.rs new file mode 100644 index 0000000..b6dbc38 --- /dev/null +++ b/ci-user/user/src/bin/ch5_spawn1.rs @@ -0,0 +1,35 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::{spawn, wait, waitpid}; + +/// 程序行为:先后产生 3 个有特定返回值的程序,检查 waitpid 能够获取正确返回值。 + +/// 理想输出: +/// new child i +/// Test wait OK! +/// Test waitpid OK! + +#[no_mangle] +pub fn main() -> i32 { + let cpid = spawn("ch5_exit0\0"); + assert!(cpid >= 0, "child pid invalid"); + println!("new child {}", cpid); + let mut exit_code: i32 = 0; + let exit_pid = wait(&mut exit_code); + assert_eq!(exit_pid, cpid, "error exit pid"); + assert_eq!(exit_code, 66778, "error exit code"); + println!("Test wait OK!"); + let (cpid0, cpid1) = (spawn("ch5_exit0\0"), spawn("ch5_exit1\0")); + let exit_pid = waitpid(cpid1 as usize, &mut exit_code); + assert_eq!(exit_pid, cpid1, "error exit pid"); + assert_eq!(exit_code, -233, "error exit code"); + let exit_pid = wait(&mut exit_code); + assert_eq!(exit_pid, cpid0, "error exit pid"); + assert_eq!(exit_code, 66778, "error exit code"); + println!("Test waitpid OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch5_stride.rs b/ci-user/user/src/bin/ch5_stride.rs new file mode 100644 index 0000000..ca44875 --- /dev/null +++ b/ci-user/user/src/bin/ch5_stride.rs @@ -0,0 +1,33 @@ +#![no_std] +#![no_main] + +extern crate user_lib; + +static TESTS: &[&str] = &[ + "ch5_stride0\0", + "ch5_stride1\0", + "ch5_stride2\0", + "ch5_stride3\0", + "ch5_stride4\0", + "ch5_stride5\0", +]; + + +use user_lib::{spawn, waitpid, set_priority}; + +#[no_mangle] +pub fn main() -> i32 { + let mut pid = [0; 6]; + let mut i = 0; + for test in TESTS { + pid[i] = spawn(*test); + i += 1; + } + set_priority(4); + for i in 0..6{ + let mut xstate: i32 = Default::default(); + let wait_pid = waitpid(pid[i] as usize, &mut xstate); + assert_eq!(pid[i], wait_pid); + } + 0 +} diff --git a/ci-user/user/src/bin/ch5_stride0.rs b/ci-user/user/src/bin/ch5_stride0.rs new file mode 100644 index 0000000..718e28a --- /dev/null +++ b/ci-user/user/src/bin/ch5_stride0.rs @@ -0,0 +1,43 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +use user_lib::{get_time, set_priority}; + +/* +理想结果:6个进程退出时,输出 count 基本正比于 priority +*/ + +fn spin_delay() { + let mut j = true; + for _ in 0..10 { + j = !j; + } +} + +// to get enough accuracy, MAX_TIME (the running time of each process) should > 1000 mseconds. +const MAX_TIME: isize = 4000; +pub fn count_during(prio: isize) -> isize { + let start_time = get_time(); + let mut acc = 0; + set_priority(prio); + loop { + spin_delay(); + acc += 1; + if acc % 400 == 0 { + let time = get_time() - start_time; + if time > MAX_TIME { + return acc; + } + } + } +} + +#[no_mangle] +pub fn main() -> usize { + let prio = 5; + let count = count_during(prio); + println!("priority = {}, exitcode = {}, ratio = {}", prio, count, count/prio); + 0 +} diff --git a/ci-user/user/src/bin/ch5_stride1.rs b/ci-user/user/src/bin/ch5_stride1.rs new file mode 100644 index 0000000..9c00caf --- /dev/null +++ b/ci-user/user/src/bin/ch5_stride1.rs @@ -0,0 +1,39 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +use user_lib::{get_time, set_priority}; + +fn spin_delay() { + let mut j = true; + for _ in 0..10 { + j = !j; + } +} + +// to get enough accuracy, MAX_TIME (the running time of each process) should > 1000 mseconds. +const MAX_TIME: isize = 4000; +fn count_during(prio: isize) -> isize { + let start_time = get_time(); + let mut acc = 0; + set_priority(prio); + loop { + spin_delay(); + acc += 1; + if acc % 400 == 0 { + let time = get_time() - start_time; + if time > MAX_TIME { + return acc; + } + } + } +} + +#[no_mangle] +pub fn main() -> usize { + let prio = 6; + let count = count_during(prio); + println!("priority = {}, exitcode = {}, ratio = {}", prio, count, count/prio); + 0 +} \ No newline at end of file diff --git a/ci-user/user/src/bin/ch5_stride2.rs b/ci-user/user/src/bin/ch5_stride2.rs new file mode 100644 index 0000000..ac35682 --- /dev/null +++ b/ci-user/user/src/bin/ch5_stride2.rs @@ -0,0 +1,39 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +use user_lib::{get_time, set_priority}; + +fn spin_delay() { + let mut j = true; + for _ in 0..10 { + j = !j; + } +} + +// to get enough accuracy, MAX_TIME (the running time of each process) should > 1000 mseconds. +const MAX_TIME: isize = 4000; +fn count_during(prio: isize) -> isize { + let start_time = get_time(); + let mut acc = 0; + set_priority(prio); + loop { + spin_delay(); + acc += 1; + if acc % 400 == 0 { + let time = get_time() - start_time; + if time > MAX_TIME { + return acc; + } + } + } +} + +#[no_mangle] +pub fn main() -> usize { + let prio = 7; + let count = count_during(prio); + println!("priority = {}, exitcode = {}, ratio = {}", prio, count, count/prio); + 0 +} \ No newline at end of file diff --git a/ci-user/user/src/bin/ch5_stride3.rs b/ci-user/user/src/bin/ch5_stride3.rs new file mode 100644 index 0000000..87b9851 --- /dev/null +++ b/ci-user/user/src/bin/ch5_stride3.rs @@ -0,0 +1,39 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +use user_lib::{get_time, set_priority}; + +fn spin_delay() { + let mut j = true; + for _ in 0..10 { + j = !j; + } +} + +// to get enough accuracy, MAX_TIME (the running time of each process) should > 1000 mseconds. +const MAX_TIME: isize = 4000; +fn count_during(prio: isize) -> isize { + let start_time = get_time(); + let mut acc = 0; + set_priority(prio); + loop { + spin_delay(); + acc += 1; + if acc % 400 == 0 { + let time = get_time() - start_time; + if time > MAX_TIME { + return acc; + } + } + } +} + +#[no_mangle] +pub fn main() -> usize { + let prio = 8; + let count = count_during(prio); + println!("priority = {}, exitcode = {}, ratio = {}", prio, count, count/prio); + 0 +} diff --git a/ci-user/user/src/bin/ch5_stride4.rs b/ci-user/user/src/bin/ch5_stride4.rs new file mode 100644 index 0000000..cf01c03 --- /dev/null +++ b/ci-user/user/src/bin/ch5_stride4.rs @@ -0,0 +1,39 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +use user_lib::{get_time, set_priority}; + +fn spin_delay() { + let mut j = true; + for _ in 0..10 { + j = !j; + } +} + +// to get enough accuracy, MAX_TIME (the running time of each process) should > 1000 mseconds. +const MAX_TIME: isize = 4000; +fn count_during(prio: isize) -> isize { + let start_time = get_time(); + let mut acc = 0; + set_priority(prio); + loop { + spin_delay(); + acc += 1; + if acc % 400 == 0 { + let time = get_time() - start_time; + if time > MAX_TIME { + return acc; + } + } + } +} + +#[no_mangle] +pub fn main() -> usize { + let prio = 9; + let count = count_during(prio); + println!("priority = {}, exitcode = {}, ratio = {}", prio, count, count/prio); + 0 +} \ No newline at end of file diff --git a/ci-user/user/src/bin/ch5_stride5.rs b/ci-user/user/src/bin/ch5_stride5.rs new file mode 100644 index 0000000..aba1363 --- /dev/null +++ b/ci-user/user/src/bin/ch5_stride5.rs @@ -0,0 +1,39 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +use user_lib::{get_time, set_priority}; + +fn spin_delay() { + let mut j = true; + for _ in 0..10 { + j = !j; + } +} + +// to get enough accuracy, MAX_TIME (the running time of each process) should > 1000 mseconds. +const MAX_TIME: isize = 4000; +fn count_during(prio: isize) -> isize { + let start_time = get_time(); + let mut acc = 0; + set_priority(prio); + loop { + spin_delay(); + acc += 1; + if acc % 400 == 0 { + let time = get_time() - start_time; + if time > MAX_TIME { + return acc; + } + } + } +} + +#[no_mangle] +pub fn main() -> usize { + let prio = 10; + let count = count_during(prio); + println!("priority = {}, exitcode = {}, ratio = {}", prio, count, count/prio); + 0 +} \ No newline at end of file diff --git a/ci-user/user/src/bin/ch5_usertest.rs b/ci-user/user/src/bin/ch5_usertest.rs new file mode 100644 index 0000000..1ee95be --- /dev/null +++ b/ci-user/user/src/bin/ch5_usertest.rs @@ -0,0 +1,61 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +static TESTS: &[&str] = &[ + "ch2b_hello_world\0", + "ch2b_power_3\0", + "ch2b_power_5\0", + "ch2b_power_7\0", + "ch3b_yield0\0", + "ch3b_yield1\0", + "ch3b_yield2\0", + "ch3b_sleep\0", + "ch3b_sleep1\0", + "ch4_mmap0\0", + "ch4_mmap1\0", + "ch4_mmap2\0", + "ch4_mmap3\0", + "ch4_unmap\0", + "ch4_unmap2\0", + "ch5_spawn0\0", + "ch5_spawn1\0", + "ch5_setprio\0", + // "ch5_stride\0", +]; +static STEST: &str = "ch5_stride\0"; + +use user_lib::{spawn, waitpid}; + +/// 辅助测例,运行所有其他测例。 + +#[no_mangle] +pub fn main() -> i32 { + let mut pid = [0; 20]; + for (i, &test) in TESTS.iter().enumerate() { + println!("Usertests: Running {}", test); + pid[i] = spawn(test); + } + let mut xstate: i32 = Default::default(); + for (i, &test) in TESTS.iter().enumerate() { + let wait_pid = waitpid(pid[i] as usize, &mut xstate); + assert_eq!(pid[i], wait_pid); + println!( + "\x1b[32mUsertests: Test {} in Process {} exited with code {}\x1b[0m", + test, pid[i], xstate + ); + } + println!("Usertests: Running {}", STEST); + let spid = spawn(STEST); + xstate = Default::default(); + let wait_pid = waitpid(spid as usize, &mut xstate); + assert_eq!(spid, wait_pid); + println!( + "\x1b[32mUsertests: Test {} in Process {} exited with code {}\x1b[0m", + STEST, spid, xstate + ); + println!("ch5 Usertests passed!"); + 0 +} diff --git a/ci-user/user/src/bin/ch5b_exit.rs b/ci-user/user/src/bin/ch5b_exit.rs new file mode 100644 index 0000000..60510c9 --- /dev/null +++ b/ci-user/user/src/bin/ch5b_exit.rs @@ -0,0 +1,30 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +use user_lib::{exit, fork, wait, waitpid, yield_}; + +const MAGIC: i32 = -0x10384; + +#[no_mangle] +pub fn main() -> i32 { + println!("I am the parent. Forking the child..."); + let pid = fork(); + if pid == 0 { + println!("I am the child."); + for _ in 0..7 { + yield_(); + } + exit(MAGIC); + } else { + println!("I am parent, fork a child pid {}", pid); + } + println!("I am the parent, waiting now.."); + let mut xstate: i32 = 0; + assert!(waitpid(pid as usize, &mut xstate) == pid && xstate == MAGIC); + assert!(waitpid(pid as usize, &mut xstate) < 0 && wait(&mut xstate) <= 0); + println!("waitpid {} ok.", pid); + println!("exit pass."); + 0 +} diff --git a/ci-user/user/src/bin/ch5b_forktest.rs b/ci-user/user/src/bin/ch5b_forktest.rs new file mode 100644 index 0000000..22b53a9 --- /dev/null +++ b/ci-user/user/src/bin/ch5b_forktest.rs @@ -0,0 +1,34 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::{exit, fork, wait}; + +const MAX_CHILD: usize = 40; + +#[no_mangle] +pub fn main() -> i32 { + for i in 0..MAX_CHILD { + let pid = fork(); + if pid == 0 { + println!("I am child {}", i); + exit(0); + } else { + println!("forked child pid = {}", pid); + } + assert!(pid > 0); + } + let mut exit_code: i32 = 0; + for _ in 0..MAX_CHILD { + if wait(&mut exit_code) <= 0 { + panic!("wait stopped early"); + } + } + if wait(&mut exit_code) > 0 { + panic!("wait got too many"); + } + println!("forktest pass."); + 0 +} diff --git a/ci-user/user/src/bin/ch5b_forktest2.rs b/ci-user/user/src/bin/ch5b_forktest2.rs new file mode 100644 index 0000000..c91ce15 --- /dev/null +++ b/ci-user/user/src/bin/ch5b_forktest2.rs @@ -0,0 +1,34 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::{exit, fork, get_time, getpid, sleep, wait}; + +static NUM: usize = 30; + +#[no_mangle] +pub fn main() -> i32 { + for _ in 0..NUM { + let pid = fork(); + if pid == 0 { + let current_time = get_time(); + let sleep_length = + (current_time as i32 as isize) * (current_time as i32 as isize) % 1000 + 1000; + println!("pid {} sleep for {} ms", getpid(), sleep_length); + sleep(sleep_length as usize); + println!("pid {} OK!", getpid()); + exit(0); + } + } + + let mut exit_code: i32 = 0; + for _ in 0..NUM { + assert!(wait(&mut exit_code) > 0); + assert_eq!(exit_code, 0); + } + assert!(wait(&mut exit_code) < 0); + println!("forktest2 test passed!"); + 0 +} diff --git a/ci-user/user/src/bin/ch5b_forktest_simple.rs b/ci-user/user/src/bin/ch5b_forktest_simple.rs new file mode 100644 index 0000000..29a624b --- /dev/null +++ b/ci-user/user/src/bin/ch5b_forktest_simple.rs @@ -0,0 +1,28 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::{fork, getpid, wait}; + +#[no_mangle] +pub fn main() -> i32 { + assert_eq!(wait(&mut 0i32), -1); + println!("sys_wait without child process test passed!"); + println!("parent start, pid = {}!", getpid()); + let pid = fork(); + if pid == 0 { + // child process + println!("hello child process!"); + 100 + } else { + // parent process + let mut exit_code: i32 = 0; + println!("ready waiting on parent process!"); + assert_eq!(pid, wait(&mut exit_code)); + assert_eq!(exit_code, 100); + println!("child process pid = {}, exit code = {}", pid, exit_code); + 0 + } +} diff --git a/ci-user/user/src/bin/ch5b_forktree.rs b/ci-user/user/src/bin/ch5b_forktree.rs new file mode 100644 index 0000000..bfcfc4c --- /dev/null +++ b/ci-user/user/src/bin/ch5b_forktree.rs @@ -0,0 +1,37 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::{exit, fork, getpid, sleep, yield_}; + +const DEPTH: usize = 4; + +fn fork_child(cur: &str, branch: char) { + let mut next = [0u8; DEPTH + 1]; + let l = cur.len(); + if l >= DEPTH { + return; + } + next[..l].copy_from_slice(cur.as_bytes()); + next[l] = branch as u8; + if fork() == 0 { + fork_tree(core::str::from_utf8(&next[..l + 1]).unwrap()); + yield_(); + exit(0); + } +} + +fn fork_tree(cur: &str) { + println!("pid{}: {}", getpid(), cur); + fork_child(cur, '0'); + fork_child(cur, '1'); +} + +#[no_mangle] +pub fn main() -> i32 { + fork_tree(""); + sleep(3000); + 0 +} diff --git a/ci-user/user/src/bin/ch5b_initproc.rs b/ci-user/user/src/bin/ch5b_initproc.rs new file mode 100644 index 0000000..7fe93d8 --- /dev/null +++ b/ci-user/user/src/bin/ch5b_initproc.rs @@ -0,0 +1,28 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::{exec, fork, wait, yield_}; + +#[no_mangle] +fn main() -> i32 { + if fork() == 0 { + exec("ch5b_user_shell\0", &[0 as *const u8]); + } else { + loop { + let mut exit_code: i32 = 0; + let pid = wait(&mut exit_code); + if pid == -1 { + yield_(); + continue; + } + println!( + "[initproc] Released a zombie process, pid={}, exit_code={}", + pid, exit_code, + ); + } + } + 0 +} diff --git a/ci-user/user/src/bin/ch5b_user_shell.rs b/ci-user/user/src/bin/ch5b_user_shell.rs new file mode 100644 index 0000000..ea7ae52 --- /dev/null +++ b/ci-user/user/src/bin/ch5b_user_shell.rs @@ -0,0 +1,66 @@ +#![no_std] +#![no_main] + +extern crate alloc; + +#[macro_use] +extern crate user_lib; + +const LF: u8 = 0x0au8; +const CR: u8 = 0x0du8; +const DL: u8 = 0x7fu8; +const BS: u8 = 0x08u8; + +use alloc::string::String; +use user_lib::console::getchar; +use user_lib::{exec, flush, fork, waitpid}; + +#[no_mangle] +pub fn main() -> i32 { + println!("Rust user shell"); + let mut line: String = String::new(); + print!(">> "); + flush(); + loop { + let c = getchar(); + match c { + LF | CR => { + print!("\n"); + if !line.is_empty() { + line.push('\0'); + let pid = fork(); + if pid == 0 { + // child process + if exec(line.as_str(), &[0 as *const u8]) == -1 { + println!("Error when executing!"); + return -4; + } + unreachable!(); + } else { + let mut exit_code: i32 = 0; + let exit_pid = waitpid(pid as usize, &mut exit_code); + assert_eq!(pid, exit_pid); + println!("Shell: Process {} exited with code {}", pid, exit_code); + } + line.clear(); + } + print!(">> "); + flush(); + } + BS | DL => { + if !line.is_empty() { + print!("{}", BS as char); + print!(" "); + print!("{}", BS as char); + flush(); + line.pop(); + } + } + _ => { + print!("{}", c as char); + flush(); + line.push(c as char); + } + } + } +} diff --git a/ci-user/user/src/bin/ch6_file0.rs b/ci-user/user/src/bin/ch6_file0.rs new file mode 100644 index 0000000..0b61fc9 --- /dev/null +++ b/ci-user/user/src/bin/ch6_file0.rs @@ -0,0 +1,31 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::{close, open, read, write, OpenFlags}; + +/// 测试文件基本读写,输出 Test file0 OK! 就算正确。 + +#[no_mangle] +pub fn main() -> i32 { + let test_str = "Hello, world!"; + let fname = "fname\0"; + let fd = open(fname, OpenFlags::CREATE | OpenFlags::WRONLY); + assert!(fd > 0); + let fd = fd as usize; + write(fd, test_str.as_bytes()); + close(fd); + + let fd = open(fname, OpenFlags::RDONLY); + assert!(fd > 0); + let fd = fd as usize; + let mut buffer = [0u8; 100]; + let read_len = read(fd, &mut buffer) as usize; + close(fd); + + assert_eq!(test_str, core::str::from_utf8(&buffer[..read_len]).unwrap(),); + println!("Test file0 OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch6_file1.rs b/ci-user/user/src/bin/ch6_file1.rs new file mode 100644 index 0000000..6565121 --- /dev/null +++ b/ci-user/user/src/bin/ch6_file1.rs @@ -0,0 +1,26 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +use user_lib::{close, fstat, open, OpenFlags, Stat, StatMode}; + +/// 测试 fstat,输出 Test fstat OK! 就算正确。 + +#[no_mangle] +pub fn main() -> i32 { + let fname = "fname1\0"; + let fd = open(fname, OpenFlags::CREATE | OpenFlags::WRONLY); + assert!(fd > 0); + let fd = fd as usize; + let stat: Stat = Stat::new(); + let ret = fstat(fd, &stat); + assert_eq!(ret, 0); + assert_eq!(stat.mode, StatMode::FILE); + assert_eq!(stat.nlink, 1); + close(fd); + // unlink(fname); + // It's recommended to rebuild the disk image. This program will not clean the file "fname1". + println!("Test fstat OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch6_file2.rs b/ci-user/user/src/bin/ch6_file2.rs new file mode 100644 index 0000000..c646314 --- /dev/null +++ b/ci-user/user/src/bin/ch6_file2.rs @@ -0,0 +1,46 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +use user_lib::{close, fstat, link, open, read, unlink, write, OpenFlags, Stat}; + +/// 测试 link/unlink,输出 Test link OK! 就算正确。 + +#[no_mangle] +pub fn main() -> i32 { + let test_str = "Hello, world!"; + let fname = "fname2\0"; + let (lname0, lname1, lname2) = ("linkname0\0", "linkname1\0", "linkname2\0"); + let fd = open(fname, OpenFlags::CREATE | OpenFlags::WRONLY) as usize; + link(fname, lname0); + let stat = Stat::new(); + fstat(fd, &stat); + assert_eq!(stat.nlink, 2); + link(fname, lname1); + link(fname, lname2); + fstat(fd, &stat); + assert_eq!(stat.nlink, 4); + write(fd, test_str.as_bytes()); + close(fd); + + unlink(fname); + let fd = open(lname0, OpenFlags::RDONLY) as usize; + let stat2 = Stat::new(); + let mut buf = [0u8; 100]; + let read_len = read(fd, &mut buf) as usize; + assert_eq!(test_str, core::str::from_utf8(&buf[..read_len]).unwrap(),); + fstat(fd, &stat2); + assert_eq!(stat2.dev, stat.dev); + assert_eq!(stat2.ino, stat.ino); + assert_eq!(stat2.nlink, 3); + unlink(lname1); + unlink(lname2); + fstat(fd, &stat2); + assert_eq!(stat2.nlink, 1); + close(fd); + unlink(lname0); + // It's Ok if you don't delete the inode and data blocks. + println!("Test link OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch6_file3.rs b/ci-user/user/src/bin/ch6_file3.rs new file mode 100644 index 0000000..2c21a4a --- /dev/null +++ b/ci-user/user/src/bin/ch6_file3.rs @@ -0,0 +1,31 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +use user_lib::{close, open, unlink, write, OpenFlags}; + +/// 测试大量 open/unlink,输出 Test mass open/unlink OK! 就算正确。 + +#[no_mangle] +pub fn main() -> i32 { + let test_str = "some random long long long long long long long long string".repeat(50); + let fname = "fname3\0"; + for i in 0..10 { + let fd = open(fname, OpenFlags::CREATE | OpenFlags::WRONLY); + if fd == -1 { + panic!("failed to crate file"); + } + let fd = fd as usize; + for _ in 0..50 { + write(fd, test_str.as_bytes()); + } + close(fd); + assert_eq!(unlink(fname), 0); + let fd = open(fname, OpenFlags::RDONLY); + assert!(fd < 0); + println!("test iteration {}", i) + } + println!("Test mass open/unlink OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch6_usertest.rs b/ci-user/user/src/bin/ch6_usertest.rs new file mode 100644 index 0000000..e9bcb51 --- /dev/null +++ b/ci-user/user/src/bin/ch6_usertest.rs @@ -0,0 +1,51 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +static TESTS: &[&str] = &[ + "ch2b_hello_world\0", + "ch2b_power_3\0", + "ch2b_power_5\0", + "ch2b_power_7\0", + "ch3b_yield0\0", + "ch3b_yield1\0", + "ch3b_yield2\0", + "ch3b_sleep\0", + "ch3b_sleep1\0", + "ch4_mmap0\0", + "ch4_mmap1\0", + "ch4_mmap2\0", + "ch4_mmap3\0", + "ch4_unmap\0", + "ch4_unmap2\0", + "ch5b_forktest2\0", + "ch5_spawn0\0", + "ch5_spawn1\0", + "ch6_file0\0", + "ch6_file1\0", + "ch6_file2\0", + "ch6_file3\0", +]; + +use user_lib::{spawn, waitpid}; + +/// 辅助测例,运行所有其他测例。 + +#[no_mangle] +pub fn main() -> i32 { + for test in TESTS { + println!("Usertests: Running {}", test); + let pid = spawn(*test); + let mut xstate: i32 = Default::default(); + let wait_pid = waitpid(pid as usize, &mut xstate); + assert_eq!(pid, wait_pid); + println!( + "\x1b[32mUsertests: Test {} in Process {} exited with code {}\x1b[0m", + test, pid, xstate + ); + } + println!("ch6 Usertests passed!"); + 0 +} diff --git a/ci-user/user/src/bin/ch6b_cat.rs b/ci-user/user/src/bin/ch6b_cat.rs new file mode 100644 index 0000000..f9b43e2 --- /dev/null +++ b/ci-user/user/src/bin/ch6b_cat.rs @@ -0,0 +1,33 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +extern crate alloc; + +use user_lib::{ + open, + OpenFlags, + close, + read, +}; +use alloc::string::String; + +#[no_mangle] +pub fn main() -> i32 { + let fd = open("filea\0", OpenFlags::RDONLY); + if fd == -1 { + panic!("Error occured when opening file"); + } + let fd = fd as usize; + let mut buf = [0u8; 16]; + let mut s = String::new(); + loop { + let size = read(fd, &mut buf) as usize; + if size == 0 { break; } + s.push_str(core::str::from_utf8(&buf[..size]).unwrap()); + } + println!("{}", s); + close(fd); + 0 +} diff --git a/ci-user/user/src/bin/ch6b_filetest_simple.rs b/ci-user/user/src/bin/ch6b_filetest_simple.rs new file mode 100644 index 0000000..60fda6a --- /dev/null +++ b/ci-user/user/src/bin/ch6b_filetest_simple.rs @@ -0,0 +1,38 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::{ + open, + close, + read, + write, + OpenFlags, +}; + +#[no_mangle] +pub fn main() -> i32 { + let test_str = "Hello, world!"; + let filea = "filea\0"; + let fd = open(filea, OpenFlags::CREATE | OpenFlags::WRONLY); + assert!(fd > 0); + let fd = fd as usize; + write(fd, test_str.as_bytes()); + close(fd); + + let fd = open(filea, OpenFlags::RDONLY); + assert!(fd > 0); + let fd = fd as usize; + let mut buffer = [0u8; 100]; + let read_len = read(fd, &mut buffer) as usize; + close(fd); + + assert_eq!( + test_str, + core::str::from_utf8(&buffer[..read_len]).unwrap(), + ); + println!("file_test passed!"); + 0 +} \ No newline at end of file diff --git a/ci-user/user/src/bin/ch6b_initproc.rs b/ci-user/user/src/bin/ch6b_initproc.rs new file mode 100644 index 0000000..008cd79 --- /dev/null +++ b/ci-user/user/src/bin/ch6b_initproc.rs @@ -0,0 +1,28 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::{exec, fork, wait, yield_}; + +#[no_mangle] +fn main() -> i32 { + if fork() == 0 { + exec("ch6b_user_shell\0", &[0 as *const u8]); + } else { + loop { + let mut exit_code: i32 = 0; + let pid = wait(&mut exit_code); + if pid == -1 { + yield_(); + continue; + } + println!( + "[initproc] Released a zombie process, pid={}, exit_code={}", + pid, exit_code, + ); + } + } + 0 +} diff --git a/ci-user/user/src/bin/ch6b_user_shell.rs b/ci-user/user/src/bin/ch6b_user_shell.rs new file mode 100644 index 0000000..ea7ae52 --- /dev/null +++ b/ci-user/user/src/bin/ch6b_user_shell.rs @@ -0,0 +1,66 @@ +#![no_std] +#![no_main] + +extern crate alloc; + +#[macro_use] +extern crate user_lib; + +const LF: u8 = 0x0au8; +const CR: u8 = 0x0du8; +const DL: u8 = 0x7fu8; +const BS: u8 = 0x08u8; + +use alloc::string::String; +use user_lib::console::getchar; +use user_lib::{exec, flush, fork, waitpid}; + +#[no_mangle] +pub fn main() -> i32 { + println!("Rust user shell"); + let mut line: String = String::new(); + print!(">> "); + flush(); + loop { + let c = getchar(); + match c { + LF | CR => { + print!("\n"); + if !line.is_empty() { + line.push('\0'); + let pid = fork(); + if pid == 0 { + // child process + if exec(line.as_str(), &[0 as *const u8]) == -1 { + println!("Error when executing!"); + return -4; + } + unreachable!(); + } else { + let mut exit_code: i32 = 0; + let exit_pid = waitpid(pid as usize, &mut exit_code); + assert_eq!(pid, exit_pid); + println!("Shell: Process {} exited with code {}", pid, exit_code); + } + line.clear(); + } + print!(">> "); + flush(); + } + BS | DL => { + if !line.is_empty() { + print!("{}", BS as char); + print!(" "); + print!("{}", BS as char); + flush(); + line.pop(); + } + } + _ => { + print!("{}", c as char); + flush(); + line.push(c as char); + } + } + } +} diff --git a/ci-user/user/src/bin/ch7_usertest.rs b/ci-user/user/src/bin/ch7_usertest.rs new file mode 100644 index 0000000..dae1b98 --- /dev/null +++ b/ci-user/user/src/bin/ch7_usertest.rs @@ -0,0 +1,29 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +static TESTS: &[&str] = &[ +]; + +use user_lib::{spawn, waitpid}; + +/// 辅助测例,运行所有其他测例。 + +#[no_mangle] +pub fn main() -> i32 { + for test in TESTS { + println!("Usertests: Running {}", test); + let pid = spawn(*test); + let mut xstate: i32 = Default::default(); + let wait_pid = waitpid(pid as usize, &mut xstate); + assert_eq!(pid, wait_pid); + println!( + "\x1b[32mUsertests: Test {} in Process {} exited with code {}\x1b[0m", + test, pid, xstate + ); + } + println!("ch7 Usertests passed!"); + 0 +} diff --git a/ci-user/user/src/bin/ch7b_cat.rs b/ci-user/user/src/bin/ch7b_cat.rs new file mode 100644 index 0000000..84fb8a6 --- /dev/null +++ b/ci-user/user/src/bin/ch7b_cat.rs @@ -0,0 +1,34 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +extern crate alloc; + +use user_lib::{ + open, + OpenFlags, + close, + read, +}; +use alloc::string::String; + +#[no_mangle] +pub fn main(argc: usize, argv: &[&str]) -> i32 { + assert!(argc == 2); + let fd = open(argv[1], OpenFlags::RDONLY); + if fd == -1 { + panic!("Error occured when opening file"); + } + let fd = fd as usize; + let mut buf = [0u8; 16]; + let mut s = String::new(); + loop { + let size = read(fd, &mut buf) as usize; + if size == 0 { break; } + s.push_str(core::str::from_utf8(&buf[..size]).unwrap()); + } + println!("{}", s); + close(fd); + 0 +} diff --git a/ci-user/user/src/bin/ch7b_initproc.rs b/ci-user/user/src/bin/ch7b_initproc.rs new file mode 100644 index 0000000..f9a887d --- /dev/null +++ b/ci-user/user/src/bin/ch7b_initproc.rs @@ -0,0 +1,28 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::{exec, fork, wait, yield_}; + +#[no_mangle] +fn main() -> i32 { + if fork() == 0 { + exec("ch7b_user_shell\0", &[0 as *const u8]); + } else { + loop { + let mut exit_code: i32 = 0; + let pid = wait(&mut exit_code); + if pid == -1 { + yield_(); + continue; + } + println!( + "[initproc] Released a zombie process, pid={}, exit_code={}", + pid, exit_code, + ); + } + } + 0 +} diff --git a/ci-user/user/src/bin/ch7b_pipe_large_test.rs b/ci-user/user/src/bin/ch7b_pipe_large_test.rs new file mode 100644 index 0000000..eeac104 --- /dev/null +++ b/ci-user/user/src/bin/ch7b_pipe_large_test.rs @@ -0,0 +1,71 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +extern crate alloc; + +use alloc::format; +use user_lib::{close, fork, get_time, pipe, read, wait, write}; + +const LENGTH: usize = 3000; +#[no_mangle] +pub fn main() -> i32 { + // create pipes + // parent write to child + let mut down_pipe_fd = [0usize; 2]; + // child write to parent + let mut up_pipe_fd = [0usize; 2]; + pipe(&mut down_pipe_fd); + pipe(&mut up_pipe_fd); + let mut random_str = [0u8; LENGTH]; + if fork() == 0 { + // close write end of down pipe + close(down_pipe_fd[1]); + // close read end of up pipe + close(up_pipe_fd[0]); + assert_eq!(read(down_pipe_fd[0], &mut random_str) as usize, LENGTH); + close(down_pipe_fd[0]); + let sum: usize = random_str.iter().map(|v| *v as usize).sum::(); + println!("sum = {}(child)", sum); + let sum_str = format!("{}", sum); + write(up_pipe_fd[1], sum_str.as_bytes()); + close(up_pipe_fd[1]); + println!("Child process exited!"); + 0 + } else { + // close read end of down pipe + close(down_pipe_fd[0]); + // close write end of up pipe + close(up_pipe_fd[1]); + // generate a long random string + for ch in random_str.iter_mut().take(LENGTH) { + *ch = get_time() as u8; + } + // send it + assert_eq!( + write(down_pipe_fd[1], &random_str) as usize, + random_str.len() + ); + // close write end of down pipe + close(down_pipe_fd[1]); + // calculate sum(parent) + let sum: usize = random_str.iter().map(|v| *v as usize).sum::(); + println!("sum = {}(parent)", sum); + // recv sum(child) + let mut child_result = [0u8; 32]; + let result_len = read(up_pipe_fd[0], &mut child_result) as usize; + close(up_pipe_fd[0]); + // check + assert_eq!( + sum, + str::parse::(core::str::from_utf8(&child_result[..result_len]).unwrap()) + .unwrap() + ); + let mut _unused: i32 = 0; + wait(&mut _unused); + println!("pipe_large_test passed!"); + 0 + } +} diff --git a/ci-user/user/src/bin/ch7b_pipetest.rs b/ci-user/user/src/bin/ch7b_pipetest.rs new file mode 100644 index 0000000..5436c63 --- /dev/null +++ b/ci-user/user/src/bin/ch7b_pipetest.rs @@ -0,0 +1,44 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::{close, fork, pipe, read, wait, write}; + +static STR: &str = "Hello, world!"; + +#[no_mangle] +pub fn main() -> i32 { + // create pipe + let mut pipe_fd = [0usize; 2]; + pipe(&mut pipe_fd); + // read end + assert_eq!(pipe_fd[0], 3); + // write end + assert_eq!(pipe_fd[1], 4); + if fork() == 0 { + // child process, read from parent + // close write_end + close(pipe_fd[1]); + let mut buffer = [0u8; 32]; + let len_read = read(pipe_fd[0], &mut buffer) as usize; + // close read_end + close(pipe_fd[0]); + assert_eq!(core::str::from_utf8(&buffer[..len_read]).unwrap(), STR); + println!("Read OK, child process exited!"); + 0 + } else { + // parent process, write to child + // close read end + close(pipe_fd[0]); + assert_eq!(write(pipe_fd[1], STR.as_bytes()), STR.len() as isize); + // close write end + close(pipe_fd[1]); + let mut child_exit_code: i32 = 0; + wait(&mut child_exit_code); + assert_eq!(child_exit_code, 0); + println!("pipetest passed!"); + 0 + } +} diff --git a/ci-user/user/src/bin/ch7b_run_pipe_test.rs b/ci-user/user/src/bin/ch7b_run_pipe_test.rs new file mode 100644 index 0000000..08dfbc1 --- /dev/null +++ b/ci-user/user/src/bin/ch7b_run_pipe_test.rs @@ -0,0 +1,21 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::{exec, fork, wait}; + +#[no_mangle] +pub fn main() -> i32 { + for i in 0..1000 { + if fork() == 0 { + exec("ch7b_pipe_large_test\0", &[0 as *const u8]); + } else { + let mut _unused: i32 = 0; + wait(&mut _unused); + println!("Iter {} OK.", i); + } + } + 0 +} diff --git a/ci-user/user/src/bin/ch7b_user_shell.rs b/ci-user/user/src/bin/ch7b_user_shell.rs new file mode 100644 index 0000000..23dbb1e --- /dev/null +++ b/ci-user/user/src/bin/ch7b_user_shell.rs @@ -0,0 +1,130 @@ +#![no_std] +#![no_main] + +extern crate alloc; + +#[macro_use] +extern crate user_lib; + +const LF: u8 = 0x0au8; +const CR: u8 = 0x0du8; +const DL: u8 = 0x7fu8; +const BS: u8 = 0x08u8; + +use alloc::string::String; +use alloc::vec::Vec; +use user_lib::console::getchar; +use user_lib::{close, dup, exec, flush, fork, open, waitpid, OpenFlags}; + +#[no_mangle] +pub fn main() -> i32 { + println!("Rust user shell"); + let mut line: String = String::new(); + print!(">> "); + flush(); + loop { + let c = getchar(); + match c { + LF | CR => { + println!(""); + if !line.is_empty() { + let args: Vec<_> = line.as_str().split(' ').collect(); + let mut args_copy: Vec = args + .iter() + .map(|&arg| { + let mut string = String::new(); + string.push_str(arg); + string + }) + .collect(); + + args_copy.iter_mut().for_each(|string| { + string.push('\0'); + }); + + // redirect input + let mut input = String::new(); + if let Some((idx, _)) = args_copy + .iter() + .enumerate() + .find(|(_, arg)| arg.as_str() == "<\0") + { + input = args_copy[idx + 1].clone(); + args_copy.drain(idx..=idx + 1); + } + + // redirect output + let mut output = String::new(); + if let Some((idx, _)) = args_copy + .iter() + .enumerate() + .find(|(_, arg)| arg.as_str() == ">\0") + { + output = args_copy[idx + 1].clone(); + args_copy.drain(idx..=idx + 1); + } + + let mut args_addr: Vec<*const u8> = + args_copy.iter().map(|arg| arg.as_ptr()).collect(); + args_addr.push(0 as *const u8); + let pid = fork(); + if pid == 0 { + // input redirection + if !input.is_empty() { + let input_fd = open(input.as_str(), OpenFlags::RDONLY); + if input_fd == -1 { + println!("Error when opening file {}", input); + return -4; + } + let input_fd = input_fd as usize; + close(0); + assert_eq!(dup(input_fd), 0); + close(input_fd); + } + // output redirection + if !output.is_empty() { + let output_fd = + open(output.as_str(), OpenFlags::CREATE | OpenFlags::WRONLY); + if output_fd == -1 { + println!("Error when opening file {}", output); + return -4; + } + let output_fd = output_fd as usize; + close(1); + assert_eq!(dup(output_fd), 1); + close(output_fd); + } + // child process + if exec(args_copy[0].as_str(), args_addr.as_slice()) == -1 { + println!("Error when executing!"); + return -4; + } + unreachable!(); + } else { + let mut exit_code: i32 = 0; + let exit_pid = waitpid(pid as usize, &mut exit_code); + assert_eq!(pid, exit_pid); + println!("Shell: Process {} exited with code {}", pid, exit_code); + } + line.clear(); + } + print!(">> "); + flush(); + } + BS | DL => { + if !line.is_empty() { + print!("{}", BS as char); + print!(" "); + print!("{}", BS as char); + flush(); + line.pop(); + } + } + _ => { + print!("{}", c as char); + flush(); + line.push(c as char); + } + } + } +} diff --git a/ci-user/user/src/bin/ch7b_yield.rs b/ci-user/user/src/bin/ch7b_yield.rs new file mode 100644 index 0000000..55032e4 --- /dev/null +++ b/ci-user/user/src/bin/ch7b_yield.rs @@ -0,0 +1,17 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +use user_lib::{getpid, yield_}; + +#[no_mangle] +pub fn main() -> i32 { + println!("Hello, I am process {}.", getpid()); + for i in 0..5 { + yield_(); + println!("Back in process {}, iteration {}.", getpid(), i); + } + println!("yield pass."); + 0 +} \ No newline at end of file diff --git a/ci-user/user/src/bin/ch8_deadlock_mutex1.rs b/ci-user/user/src/bin/ch8_deadlock_mutex1.rs new file mode 100644 index 0000000..15a0f2d --- /dev/null +++ b/ci-user/user/src/bin/ch8_deadlock_mutex1.rs @@ -0,0 +1,22 @@ +#![no_std] +#![no_main] +#![allow(clippy::println_empty_string)] + +#[macro_use] +extern crate user_lib; +extern crate alloc; + +use user_lib::{enable_deadlock_detect, mutex_blocking_create, mutex_lock, mutex_unlock}; + +// 理想结果:检测到死锁 + +#[no_mangle] +pub fn main() -> i32 { + enable_deadlock_detect(true); + let mid = mutex_blocking_create() as usize; + assert_eq!(mutex_lock(mid), 0); + assert_eq!(mutex_lock(mid), -0xdead); + mutex_unlock(mid); + println!("deadlock test mutex 1 OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch8_deadlock_sem1.rs b/ci-user/user/src/bin/ch8_deadlock_sem1.rs new file mode 100644 index 0000000..21b1f95 --- /dev/null +++ b/ci-user/user/src/bin/ch8_deadlock_sem1.rs @@ -0,0 +1,102 @@ +#![no_std] +#![no_main] +#![allow(clippy::println_empty_string)] + +#[macro_use] +extern crate user_lib; +extern crate alloc; + +use user_lib::{ + enable_deadlock_detect, exit, semaphore_create, semaphore_down, semaphore_up, sleep, +}; +use user_lib::{gettid, thread_create, waittid}; + +// sem 0: used to sync child thread with main +// sem 1-3: representing some kind of resource + +// 理想结果:检测到死锁,至少有一个子线程返回值不为 0 + +const SEM_BARRIER: usize = 0; +const THREAD_N: usize = 3; +const RES_TYPE: usize = 3; +const RES_NUM: [usize; RES_TYPE] = [1, 2, 1]; +const REQUEST: [Option; THREAD_N] = [Some(1), Some(3), Some(2)]; + +fn try_sem_down(sem_id: usize) { + if semaphore_down(sem_id) == -0xdead { + sem_dealloc(gettid() as usize); + println!("Deadlock detected. Test 08_sem1 failed!"); + exit(-1); + } +} + +fn sem_alloc(tid: usize) { + match tid { + 1 => assert_eq!(semaphore_down(2), 0), + 2 => { + assert_eq!(semaphore_down(1), 0); + assert_eq!(semaphore_down(2), 0); + } + 3 => assert_eq!(semaphore_down(3), 0), + _ => exit(1), + } + semaphore_down(SEM_BARRIER); +} + +fn sem_dealloc(tid: usize) { + semaphore_up(SEM_BARRIER); + match tid { + 1 => semaphore_up(2), + 2 => { + semaphore_up(1); + semaphore_up(2); + } + 3 => semaphore_up(3), + _ => exit(1), + } +} + +fn deadlock_test() { + let tid = gettid() as usize; + println!("thread {} running", tid); + sem_alloc(tid); + if let Some(sem_id) = REQUEST[tid - 1] { + try_sem_down(sem_id); + semaphore_up(sem_id); + } + sem_dealloc(tid); + println!("thread {} exited", tid); + exit(0); +} + +#[no_mangle] +pub fn main() -> i32 { + enable_deadlock_detect(true); + assert_eq!(semaphore_create(THREAD_N) as usize, SEM_BARRIER); + for _ in 0..THREAD_N { + semaphore_down(SEM_BARRIER); + } + + for n in RES_NUM { + semaphore_create(n); + } + let mut tids = [0; THREAD_N]; + + for i in 0..THREAD_N { + tids[i] = thread_create(deadlock_test as usize, 0) as usize; + } + + sleep(500); + for _ in 0..THREAD_N { + semaphore_up(SEM_BARRIER); + } + let mut failed = 0; + for tid in tids { + if waittid(tid) != 0 { + failed += 1; + } + } + assert!(failed > 0); + println!("deadlock test semaphore 1 OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch8_deadlock_sem2.rs b/ci-user/user/src/bin/ch8_deadlock_sem2.rs new file mode 100644 index 0000000..ff653ea --- /dev/null +++ b/ci-user/user/src/bin/ch8_deadlock_sem2.rs @@ -0,0 +1,76 @@ +#![no_std] +#![no_main] +#![allow(clippy::println_empty_string)] + +#[macro_use] +extern crate user_lib; +extern crate alloc; + +use user_lib::{ + enable_deadlock_detect, exit, semaphore_create, semaphore_down, semaphore_up, sleep, +}; +use user_lib::{gettid, thread_create, waittid}; + +// sem 0: used to sync child thread with main +// sem 1-3: representing some kind of resource + +// 理想结果:未检测到死锁,子线程返回值均为 0 + +const THREAD_N: usize = 4; +const RES_TYPE: usize = 2; +const RES_NUM: [usize; RES_TYPE] = [2, 2]; +const ALLOC: [usize; THREAD_N] = [2, 1, 1, 2]; +const REQUEST: [Option; THREAD_N] = [Some(1), None, Some(2), None]; + +fn try_sem_down(sem_id: usize) { + if semaphore_down(sem_id) == -0xdead { + semaphore_up(ALLOC[(gettid() - 1) as usize]); + exit(-1); + } +} + +fn deadlock_test() { + let id = (gettid() - 1) as usize; + assert_eq!(semaphore_down(ALLOC[id]), 0); + semaphore_down(0); + if let Some(sem_id) = REQUEST[id] { + try_sem_down(sem_id); + semaphore_up(sem_id); + } + semaphore_up(ALLOC[id]); + exit(0); +} + +#[no_mangle] +pub fn main() -> i32 { + enable_deadlock_detect(true); + semaphore_create(THREAD_N); + for _ in 0..THREAD_N { + semaphore_down(0); + } + + for n in RES_NUM { + semaphore_create(n); + } + let mut tids = [0; THREAD_N]; + + for i in 0..THREAD_N { + tids[i] = thread_create(deadlock_test as usize, 0) as usize; + } + + sleep(1000); + for _ in 0..THREAD_N { + semaphore_up(0); + } + + let mut failed = 0; + for tid in tids { + if waittid(tid) != 0 { + failed += 1; + } + } + + assert_eq!(failed, 0); + println!("deadlock test semaphore 2 OK!"); + 0 +} diff --git a/ci-user/user/src/bin/ch8_usertest.rs b/ci-user/user/src/bin/ch8_usertest.rs new file mode 100644 index 0000000..79ec4af --- /dev/null +++ b/ci-user/user/src/bin/ch8_usertest.rs @@ -0,0 +1,60 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +const TESTS: &[&str] = &[ + "ch2b_hello_world\0", + "ch2b_power_3\0", + "ch2b_power_5\0", + "ch2b_power_7\0", + "ch3b_sleep\0", + "ch3b_sleep1\0", + "ch3b_yield0\0", + "ch3b_yield1\0", + "ch3b_yield2\0", + "ch5b_forktest2\0", + "ch6b_filetest_simple\0", + "ch7b_pipetest\0", + "ch8_deadlock_mutex1\0", + "ch8_deadlock_sem1\0", + "ch8_deadlock_sem2\0", + "ch8b_mpsc_sem\0", + "ch8b_phil_din_mutex\0", + "ch8b_race_adder_mutex_spin\0", + "ch8b_sync_sem\0", + "ch8b_test_condvar\0", + "ch8b_threads\0", + "ch8b_threads_arg\0", +]; + +const TEST_NUM: usize = TESTS.len(); + +use user_lib::{exec, fork, waitpid}; + +#[no_mangle] +pub fn main() -> i32 { + let mut pids = [0; TEST_NUM]; + for (i, &test) in TESTS.iter().enumerate() { + println!("Usertests: Running {}", test); + let pid = fork(); + if pid == 0 { + exec(&*test, &[core::ptr::null::()]); + panic!("unreachable!"); + } else { + pids[i] = pid; + } + } + let mut xstate: i32 = Default::default(); + for (i, &test) in TESTS.iter().enumerate() { + let wait_pid = waitpid(pids[i] as usize, &mut xstate); + assert_eq!(pids[i], wait_pid); + println!( + "\x1b[32mUsertests: Test {} in Process {} exited with code {}\x1b[0m", + test, pids[i], xstate + ); + } + println!("ch8 Usertests passed!"); + 0 +} diff --git a/ci-user/user/src/bin/ch8b_initproc.rs b/ci-user/user/src/bin/ch8b_initproc.rs new file mode 100644 index 0000000..1e4011d --- /dev/null +++ b/ci-user/user/src/bin/ch8b_initproc.rs @@ -0,0 +1,28 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +use user_lib::{exec, fork, wait, yield_}; + +#[no_mangle] +fn main() -> i32 { + if fork() == 0 { + exec("ch7b_user_shell\0", &[core::ptr::null::()]); + } else { + loop { + let mut exit_code: i32 = 0; + let pid = wait(&mut exit_code); + if pid == -1 { + yield_(); + continue; + } + println!( + "[initproc] Released a zombie process, pid={}, exit_code={}", + pid, exit_code, + ); + } + } + 0 +} diff --git a/ci-user/user/src/bin/ch8b_mpsc_sem.rs b/ci-user/user/src/bin/ch8b_mpsc_sem.rs new file mode 100644 index 0000000..7b92b9b --- /dev/null +++ b/ci-user/user/src/bin/ch8b_mpsc_sem.rs @@ -0,0 +1,73 @@ +#![no_std] +#![no_main] +#![allow(clippy::println_empty_string)] + +#[macro_use] +extern crate user_lib; + +extern crate alloc; + +use alloc::vec::Vec; +use user_lib::exit; +use user_lib::{semaphore_create, semaphore_down, semaphore_up}; +use user_lib::{thread_create, waittid}; + +const SEM_MUTEX: usize = 0; +const SEM_EMPTY: usize = 1; +const SEM_EXISTED: usize = 2; +const BUFFER_SIZE: usize = 8; +static mut BUFFER: [usize; BUFFER_SIZE] = [0; BUFFER_SIZE]; +static mut FRONT: usize = 0; +static mut TAIL: usize = 0; +const PRODUCER_COUNT: usize = 4; +const NUMBER_PER_PRODUCER: usize = 100; + +unsafe fn producer(id: *const usize) -> ! { + let id = *id; + for _ in 0..NUMBER_PER_PRODUCER { + semaphore_down(SEM_EMPTY); + semaphore_down(SEM_MUTEX); + BUFFER[FRONT] = id; + FRONT = (FRONT + 1) % BUFFER_SIZE; + semaphore_up(SEM_MUTEX); + semaphore_up(SEM_EXISTED); + } + exit(0) +} + +unsafe fn consumer() -> ! { + for _ in 0..PRODUCER_COUNT * NUMBER_PER_PRODUCER { + semaphore_down(SEM_EXISTED); + semaphore_down(SEM_MUTEX); + print!("{} ", BUFFER[TAIL]); + TAIL = (TAIL + 1) % BUFFER_SIZE; + semaphore_up(SEM_MUTEX); + semaphore_up(SEM_EMPTY); + } + println!(""); + exit(0) +} + +#[no_mangle] +pub fn main() -> i32 { + // create semaphores + assert_eq!(semaphore_create(1) as usize, SEM_MUTEX); + assert_eq!(semaphore_create(BUFFER_SIZE) as usize, SEM_EMPTY); + assert_eq!(semaphore_create(0) as usize, SEM_EXISTED); + // create threads + let ids: Vec<_> = (0..PRODUCER_COUNT).collect(); + let mut threads = Vec::new(); + for i in 0..PRODUCER_COUNT { + threads.push(thread_create( + producer as usize, + &ids.as_slice()[i] as *const _ as usize, + )); + } + threads.push(thread_create(consumer as usize, 0)); + // wait for all threads to complete + for thread in threads.iter() { + waittid(*thread as usize); + } + println!("mpsc_sem passed!"); + 0 +} diff --git a/ci-user/user/src/bin/ch8b_phil_din_mutex.rs b/ci-user/user/src/bin/ch8b_phil_din_mutex.rs new file mode 100644 index 0000000..7c0765b --- /dev/null +++ b/ci-user/user/src/bin/ch8b_phil_din_mutex.rs @@ -0,0 +1,109 @@ +#![no_std] +#![no_main] +#![allow(clippy::println_empty_string)] + +#[macro_use] +extern crate user_lib; +extern crate alloc; + +use alloc::vec::Vec; +use user_lib::{exit, get_time, sleep_blocking}; +use user_lib::{mutex_blocking_create, mutex_lock, mutex_unlock}; +use user_lib::{thread_create, waittid}; + +const N: usize = 5; +const ROUND: usize = 4; +// A round: think -> wait for forks -> eat +const GRAPH_SCALE: usize = 10; + +fn get_time_u() -> usize { + get_time() as usize +} + +// Time unit: ms +const ARR: [[usize; ROUND * 2]; N] = [ + [70, 80, 100, 40, 50, 60, 20, 40], + [30, 60, 20, 70, 100, 10, 30, 60], + [50, 20, 90, 20, 40, 60, 120, 40], + [50, 100, 60, 50, 80, 60, 20, 90], + [60, 10, 60, 60, 20, 50, 60, 20], +]; +static mut THINK: [[usize; ROUND * 2]; N] = [[0; ROUND * 2]; N]; +static mut EAT: [[usize; ROUND * 2]; N] = [[0; ROUND * 2]; N]; + +fn philosopher_dining_problem(id: *const usize) { + let id = unsafe { *id }; + let left = id; + let right = if id == N - 1 { 0 } else { id + 1 }; + let min = if left < right { left } else { right }; + let max = left + right - min; + for round in 0..ROUND { + // thinking + unsafe { + THINK[id][2 * round] = get_time_u(); + } + sleep_blocking(ARR[id][2 * round]); + unsafe { + THINK[id][2 * round + 1] = get_time_u(); + } + // wait for forks + mutex_lock(min); + mutex_lock(max); + // eating + unsafe { + EAT[id][2 * round] = get_time_u(); + } + sleep_blocking(ARR[id][2 * round + 1]); + unsafe { + EAT[id][2 * round + 1] = get_time_u(); + } + mutex_unlock(max); + mutex_unlock(min); + } + exit(0) +} + +#[no_mangle] +pub fn main() -> i32 { + println!("Here comes {} philosophers!", N); + let mut v = Vec::new(); + let ids: Vec<_> = (0..N).collect(); + let start = get_time_u(); + for i in 0..N { + assert_eq!(mutex_blocking_create(), i as isize); + v.push(thread_create( + philosopher_dining_problem as usize, + &ids.as_slice()[i] as *const _ as usize, + )); + } + for tid in v.iter() { + waittid(*tid as usize); + } + let time_cost = get_time_u() - start; + println!("time cost = {}", time_cost); + println!("'-' -> THINKING; 'x' -> EATING; ' ' -> WAITING "); + for id in (0..N).into_iter().chain(0..=0) { + print!("#{}:", id); + for j in 0..time_cost / GRAPH_SCALE { + let current_time = j * GRAPH_SCALE + start; + if (0..ROUND).any(|round| unsafe { + let start_thinking = THINK[id][2 * round]; + let end_thinking = THINK[id][2 * round + 1]; + start_thinking <= current_time && current_time <= end_thinking + }) { + print!("-"); + } else if (0..ROUND).any(|round| unsafe { + let start_eating = EAT[id][2 * round]; + let end_eating = EAT[id][2 * round + 1]; + start_eating <= current_time && current_time <= end_eating + }) { + print!("x"); + } else { + print!(" "); + }; + } + println!(""); + } + println!("philosopher dining problem with mutex test passed!"); + 0 +} diff --git a/ci-user/user/src/bin/ch8b_race_adder.rs b/ci-user/user/src/bin/ch8b_race_adder.rs new file mode 100644 index 0000000..139e137 --- /dev/null +++ b/ci-user/user/src/bin/ch8b_race_adder.rs @@ -0,0 +1,43 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +extern crate alloc; + +use alloc::vec::Vec; +use user_lib::{exit, get_time, thread_create, waittid}; + +static mut A: usize = 0; +const PER_THREAD: usize = 1000; +const THREAD_COUNT: usize = 16; + +unsafe fn f() -> ! { + let mut t = 2usize; + for _ in 0..PER_THREAD { + let a = &mut A as *mut usize; + let cur = a.read_volatile(); + for _ in 0..500 { + t = t * t % 10007; + } + a.write_volatile(cur + 1); + } + exit(t as i32) +} + +#[no_mangle] +pub fn main() -> i32 { + let start = get_time(); + let mut v = Vec::new(); + for _ in 0..THREAD_COUNT { + v.push(thread_create(f as usize, 0) as usize); + } + let mut time_cost = Vec::new(); + for tid in v.iter() { + time_cost.push(waittid(*tid)); + } + println!("time cost is {}ms", get_time() - start); + assert_eq!(unsafe { A }, PER_THREAD * THREAD_COUNT); + println!("race adder test passed!"); + 0 +} diff --git a/ci-user/user/src/bin/ch8b_race_adder_atomic.rs b/ci-user/user/src/bin/ch8b_race_adder_atomic.rs new file mode 100644 index 0000000..c00fe6a --- /dev/null +++ b/ci-user/user/src/bin/ch8b_race_adder_atomic.rs @@ -0,0 +1,52 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +extern crate alloc; + +use alloc::vec::Vec; +use core::sync::atomic::{AtomicBool, Ordering}; +use user_lib::{exit, get_time, thread_create, waittid, yield_}; + +static mut A: usize = 0; +static OCCUPIED: AtomicBool = AtomicBool::new(false); +const PER_THREAD: usize = 1000; +const THREAD_COUNT: usize = 16; + +unsafe fn f() -> ! { + let mut t = 2usize; + for _ in 0..PER_THREAD { + while OCCUPIED + .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed) + .is_err() + { + yield_(); + } + let a = &mut A as *mut usize; + let cur = a.read_volatile(); + for _ in 0..500 { + t = t * t % 10007; + } + a.write_volatile(cur + 1); + OCCUPIED.store(false, Ordering::Relaxed); + } + exit(t as i32) +} + +#[no_mangle] +pub fn main() -> i32 { + let start = get_time(); + let mut v = Vec::new(); + for _ in 0..THREAD_COUNT { + v.push(thread_create(f as usize, 0) as usize); + } + let mut time_cost = Vec::new(); + for tid in v.iter() { + time_cost.push(waittid(*tid)); + } + println!("time cost is {}ms", get_time() - start); + assert_eq!(unsafe { A }, PER_THREAD * THREAD_COUNT); + println!("race adder using atomic test passed!"); + 0 +} diff --git a/ci-user/user/src/bin/ch8b_race_adder_loop.rs b/ci-user/user/src/bin/ch8b_race_adder_loop.rs new file mode 100644 index 0000000..11a0324 --- /dev/null +++ b/ci-user/user/src/bin/ch8b_race_adder_loop.rs @@ -0,0 +1,52 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +extern crate alloc; + +use alloc::vec::Vec; +use user_lib::{exit, get_time, thread_create, waittid, yield_}; + +static mut A: usize = 0; +static mut OCCUPIED: bool = false; +const PER_THREAD: usize = 1000; +const THREAD_COUNT: usize = 16; + +unsafe fn f() -> ! { + let mut t = 2usize; + for _ in 0..PER_THREAD { + while OCCUPIED { + yield_(); + } + OCCUPIED = true; + // enter critical section + let a = &mut A as *mut usize; + let cur = a.read_volatile(); + for _ in 0..500 { + t = t * t % 10007; + } + a.write_volatile(cur + 1); + // exit critical section + OCCUPIED = false; + } + + exit(t as i32) +} + +#[no_mangle] +pub fn main() -> i32 { + let start = get_time(); + let mut v = Vec::new(); + for _ in 0..THREAD_COUNT { + v.push(thread_create(f as usize, 0) as usize); + } + let mut time_cost = Vec::new(); + for tid in v.iter() { + time_cost.push(waittid(*tid)); + } + println!("time cost is {}ms", get_time() - start); + assert_eq!(unsafe { A }, PER_THREAD * THREAD_COUNT); + println!("race adder using loop test passed!"); + 0 +} diff --git a/ci-user/user/src/bin/ch8b_race_adder_mutex_spin.rs b/ci-user/user/src/bin/ch8b_race_adder_mutex_spin.rs new file mode 100644 index 0000000..d2df338 --- /dev/null +++ b/ci-user/user/src/bin/ch8b_race_adder_mutex_spin.rs @@ -0,0 +1,47 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +extern crate alloc; + +use alloc::vec::Vec; +use user_lib::{exit, get_time, thread_create, waittid}; +use user_lib::{mutex_create, mutex_lock, mutex_unlock}; + +static mut A: usize = 0; +const PER_THREAD: usize = 1000; +const THREAD_COUNT: usize = 16; + +unsafe fn f() -> ! { + let mut t = 2usize; + for _ in 0..PER_THREAD { + mutex_lock(0); + let a = &mut A as *mut usize; + let cur = a.read_volatile(); + for _ in 0..500 { + t = t * t % 10007; + } + a.write_volatile(cur + 1); + mutex_unlock(0); + } + exit(t as i32) +} + +#[no_mangle] +pub fn main() -> i32 { + let start = get_time(); + assert_eq!(mutex_create(), 0); + let mut v = Vec::new(); + for _ in 0..THREAD_COUNT { + v.push(thread_create(f as usize, 0) as usize); + } + let mut time_cost = Vec::new(); + for tid in v.iter() { + time_cost.push(waittid(*tid)); + } + println!("time cost is {}ms", get_time() - start); + assert_eq!(unsafe { A }, PER_THREAD * THREAD_COUNT); + println!("race adder using spin mutex test passed!"); + 0 +} diff --git a/ci-user/user/src/bin/ch8b_stackful_coroutine.rs b/ci-user/user/src/bin/ch8b_stackful_coroutine.rs new file mode 100644 index 0000000..2341547 --- /dev/null +++ b/ci-user/user/src/bin/ch8b_stackful_coroutine.rs @@ -0,0 +1,346 @@ +// we porting below codes to Rcore Tutorial v3 +// https://cfsamson.gitbook.io/green-threads-explained-in-200-lines-of-rust/ +// https://github.com/cfsamson/example-greenthreads +#![no_std] +#![no_main] +#![feature(naked_functions)] + +extern crate alloc; +#[macro_use] +extern crate user_lib; + +use alloc::vec; +use alloc::vec::Vec; +use core::arch::asm; + +use user_lib::exit; + +// In our simple example we set most constraints here. +const DEFAULT_STACK_SIZE: usize = 4096; //128 got SEGFAULT, 256(1024, 4096) got right results. +const MAX_TASKS: usize = 5; +static mut RUNTIME: usize = 0; + +pub struct Runtime { + tasks: Vec, + current: usize, +} + +#[derive(PartialEq, Eq, Debug)] +enum State { + Available, + Running, + Ready, +} + +struct Task { + id: usize, + stack: Vec, + ctx: TaskContext, + state: State, +} + +#[derive(Debug, Default)] +#[repr(C)] // not strictly needed but Rust ABI is not guaranteed to be stable +pub struct TaskContext { + // 15 u64 + x1: u64, //ra: return addres + x2: u64, //sp + x8: u64, //s0,fp + x9: u64, //s1 + x18: u64, //x18-27: s2-11 + x19: u64, + x20: u64, + x21: u64, + x22: u64, + x23: u64, + x24: u64, + x25: u64, + x26: u64, + x27: u64, + nx1: u64, //new return addres +} + +impl Task { + fn new(id: usize) -> Self { + // We initialize each task here and allocate the stack. This is not neccesary, + // we can allocate memory for it later, but it keeps complexity down and lets us focus on more interesting parts + // to do it here. The important part is that once allocated it MUST NOT move in memory. + Task { + id, + stack: vec![0_u8; DEFAULT_STACK_SIZE], + ctx: TaskContext::default(), + state: State::Available, + } + } +} + +impl Runtime { + pub fn new() -> Self { + // This will be our base task, which will be initialized in the `running` state + let base_task = Task { + id: 0, + stack: vec![0_u8; DEFAULT_STACK_SIZE], + ctx: TaskContext::default(), + state: State::Running, + }; + + // We initialize the rest of our tasks. + let mut tasks = vec![base_task]; + let mut available_tasks: Vec = (1..MAX_TASKS).map(|i| Task::new(i)).collect(); + tasks.append(&mut available_tasks); + + Runtime { tasks, current: 0 } + } + + /// This is cheating a bit, but we need a pointer to our Runtime stored so we can call yield on it even if + /// we don't have a reference to it. + pub fn init(&self) { + unsafe { + let r_ptr: *const Runtime = self; + RUNTIME = r_ptr as usize; + } + } + + /// This is where we start running our runtime. If it is our base task, we call yield until + /// it returns false (which means that there are no tasks scheduled) and we are done. + pub fn run(&mut self) { + while self.t_yield() {} + println!("All tasks finished!"); + } + + /// This is our return function. The only place we use this is in our `guard` function. + /// If the current task is not our base task we set its state to Available. It means + /// we're finished with it. Then we yield which will schedule a new task to be run. + fn t_return(&mut self) { + if self.current != 0 { + self.tasks[self.current].state = State::Available; + self.t_yield(); + } + } + + /// This is the heart of our runtime. Here we go through all tasks and see if anyone is in the `Ready` state. + /// If no task is `Ready` we're all done. This is an extremely simple scheduler using only a round-robin algorithm. + /// + /// If we find a task that's ready to be run we change the state of the current task from `Running` to `Ready`. + /// Then we call switch which will save the current context (the old context) and load the new context + /// into the CPU which then resumes based on the context it was just passed. + /// + /// NOITCE: if we comment below `#[inline(never)]`, we can not get the corrent running result + #[inline(never)] + fn t_yield(&mut self) -> bool { + let mut pos = self.current; + while self.tasks[pos].state != State::Ready { + pos += 1; + if pos == self.tasks.len() { + pos = 0; + } + if pos == self.current { + return false; + } + } + + if self.tasks[self.current].state != State::Available { + self.tasks[self.current].state = State::Ready; + } + + self.tasks[pos].state = State::Running; + let old_pos = self.current; + self.current = pos; + + unsafe { + switch(&mut self.tasks[old_pos].ctx, &self.tasks[pos].ctx); + } + + // NOTE: this might look strange and it is. Normally we would just mark this as `unreachable!()` but our compiler + // is too smart for it's own good so it optimized our code away on release builds. Curiously this happens on windows + // and not on linux. This is a common problem in tests so Rust has a `black_box` function in the `test` crate that + // will "pretend" to use a value we give it to prevent the compiler from eliminating code. I'll just do this instead, + // this code will never be run anyways and if it did it would always be `true`. + self.tasks.len() > 0 + } + + /// While `yield` is the logically interesting function I think this the technically most interesting. + /// + /// When we spawn a new task we first check if there are any available tasks (tasks in `Parked` state). + /// If we run out of tasks we panic in this scenario but there are several (better) ways to handle that. + /// We keep things simple for now. + /// + /// When we find an available task we get the stack length and a pointer to our u8 bytearray. + /// + /// The next part we have to use some unsafe functions. First we write an address to our `guard` function + /// that will be called if the function we provide returns. Then we set the address to the function we + /// pass inn. + /// + /// Third, we set the value of `sp` which is the stack pointer to the address of our provided function so we start + /// executing that first when we are scheuled to run. + /// + /// Lastly we set the state as `Ready` which means we have work to do and is ready to do it. + pub fn spawn(&mut self, f: fn()) { + let available = self + .tasks + .iter_mut() + .find(|t| t.state == State::Available) + .expect("no available task."); + + let size = available.stack.len(); + unsafe { + let s_ptr = available.stack.as_mut_ptr().offset(size as isize); + + // make sure our stack itself is 8 byte aligned - it will always + // offset to a lower memory address. Since we know we're at the "high" + // memory address of our allocated space, we know that offsetting to + // a lower one will be a valid address (given that we actually allocated) + // enough space to actually get an aligned pointer in the first place). + let s_ptr = (s_ptr as usize & !7) as *mut u8; + + available.ctx.x1 = guard as u64; //ctx.x1 is old return address + available.ctx.nx1 = f as u64; //ctx.nx2 is new return address + available.ctx.x2 = s_ptr.offset(-32) as u64; //cxt.x2 is sp + } + available.state = State::Ready; + } +} + +/// This is our guard function that we place on top of the stack. All this function does is set the +/// state of our current task and then `yield` which will then schedule a new task to be run. +fn guard() { + unsafe { + let rt_ptr = RUNTIME as *mut Runtime; + (*rt_ptr).t_return(); + }; +} + +/// We know that Runtime is alive the length of the program and that we only access from one core +/// (so no datarace). We yield execution of the current task by dereferencing a pointer to our +/// Runtime and then calling `t_yield` +pub fn yield_task() { + unsafe { + let rt_ptr = RUNTIME as *mut Runtime; + (*rt_ptr).t_yield(); + }; +} + +/// So here is our inline Assembly. As you remember from our first example this is just a bit more elaborate where we first +/// read out the values of all the registers we need and then sets all the register values to the register values we +/// saved when we suspended exceution on the "new" task. +/// +/// This is essentially all we need to do to save and resume execution. +/// +/// Some details about inline assembly. +/// +/// The assembly commands in the string literal is called the assemblt template. It is preceeded by +/// zero or up to four segments indicated by ":": +/// +/// - First ":" we have our output parameters, this parameters that this function will return. +/// - Second ":" we have the input parameters which is our contexts. We only read from the "new" context +/// but we modify the "old" context saving our registers there (see volatile option below) +/// - Third ":" This our clobber list, this is information to the compiler that these registers can't be used freely +/// - Fourth ":" This is options we can pass inn, Rust has 3: "alignstack", "volatile" and "intel" +/// +/// For this to work on windows we need to use "alignstack" where the compiler adds the neccesary padding to +/// make sure our stack is aligned. Since we modify one of our inputs, our assembly has "side effects" +/// therefore we should use the `volatile` option. I **think** this is actually set for us by default +/// when there are no output parameters given (my own assumption after going through the source code) +/// for the `asm` macro, but we should make it explicit anyway. +/// +/// One last important part (it will not work without this) is the #[naked] attribute. Basically this lets us have full +/// control over the stack layout since normal functions has a prologue-and epilogue added by the +/// compiler that will cause trouble for us. We avoid this by marking the funtion as "Naked". +/// For this to work on `release` builds we also need to use the `#[inline(never)] attribute or else +/// the compiler decides to inline this function (curiously this currently only happens on Windows). +/// If the function is inlined we get a curious runtime error where it fails when switching back +/// to as saved context and in general our assembly will not work as expected. +/// +/// see: https://github.com/rust-lang/rfcs/blob/master/text/1201-naked-fns.md +/// see: https://doc.rust-lang.org/nightly/reference/inline-assembly.html +/// see: https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html +#[naked] +#[no_mangle] +unsafe fn switch(old: *mut TaskContext, new: *const TaskContext) { + // a0: _old, a1: _new + asm!( + " + sd x1, 0x00(a0) + sd x2, 0x08(a0) + sd x8, 0x10(a0) + sd x9, 0x18(a0) + sd x18, 0x20(a0) + sd x19, 0x28(a0) + sd x20, 0x30(a0) + sd x21, 0x38(a0) + sd x22, 0x40(a0) + sd x23, 0x48(a0) + sd x24, 0x50(a0) + sd x25, 0x58(a0) + sd x26, 0x60(a0) + sd x27, 0x68(a0) + sd x1, 0x70(a0) + + ld x1, 0x00(a1) + ld x2, 0x08(a1) + ld x8, 0x10(a1) + ld x9, 0x18(a1) + ld x18, 0x20(a1) + ld x19, 0x28(a1) + ld x20, 0x30(a1) + ld x21, 0x38(a1) + ld x22, 0x40(a1) + ld x23, 0x48(a1) + ld x24, 0x50(a1) + ld x25, 0x58(a1) + ld x26, 0x60(a1) + ld x27, 0x68(a1) + ld t0, 0x70(a1) + + jr t0 + ", + options(noreturn) + ); +} + +#[no_mangle] +pub fn main() { + println!("stackful_coroutine begin..."); + println!("TASK 0(Runtime) STARTING"); + let mut runtime = Runtime::new(); + runtime.init(); + runtime.spawn(|| { + println!("TASK 1 STARTING"); + let id = 1; + for i in 0..4 { + println!("task: {} counter: {}", id, i); + yield_task(); + } + println!("TASK 1 FINISHED"); + }); + runtime.spawn(|| { + println!("TASK 2 STARTING"); + let id = 2; + for i in 0..8 { + println!("task: {} counter: {}", id, i); + yield_task(); + } + println!("TASK 2 FINISHED"); + }); + runtime.spawn(|| { + println!("TASK 3 STARTING"); + let id = 3; + for i in 0..12 { + println!("task: {} counter: {}", id, i); + yield_task(); + } + println!("TASK 3 FINISHED"); + }); + runtime.spawn(|| { + println!("TASK 4 STARTING"); + let id = 4; + for i in 0..16 { + println!("task: {} counter: {}", id, i); + yield_task(); + } + println!("TASK 4 FINISHED"); + }); + runtime.run(); + println!("stackful_coroutine PASSED"); + exit(0); +} diff --git a/ci-user/user/src/bin/ch8b_stackless_coroutine.rs b/ci-user/user/src/bin/ch8b_stackless_coroutine.rs new file mode 100644 index 0000000..43aeb2d --- /dev/null +++ b/ci-user/user/src/bin/ch8b_stackless_coroutine.rs @@ -0,0 +1,129 @@ +// https://blog.aloni.org/posts/a-stack-less-rust-coroutine-100-loc/ +// https://github.com/chyyuu/example-coroutine-and-thread/tree/stackless-coroutine-x86 +#![no_std] +#![no_main] + +use core::future::Future; +use core::pin::Pin; +use core::task::{Context, Poll}; +use core::task::{RawWaker, RawWakerVTable, Waker}; + +extern crate alloc; +use alloc::collections::VecDeque; + +use alloc::boxed::Box; + +#[macro_use] +extern crate user_lib; + +enum State { + Halted, + Running, +} + +struct Task { + state: State, +} + +impl Task { + fn waiter<'a>(&'a mut self) -> Waiter<'a> { + Waiter { task: self } + } +} + +struct Waiter<'a> { + task: &'a mut Task, +} + +impl<'a> Future for Waiter<'a> { + type Output = (); + + fn poll(mut self: Pin<&mut Self>, _cx: &mut Context) -> Poll { + match self.task.state { + State::Halted => { + self.task.state = State::Running; + Poll::Ready(()) + } + State::Running => { + self.task.state = State::Halted; + Poll::Pending + } + } + } +} + +struct Executor { + tasks: VecDeque>>>, +} + +impl Executor { + fn new() -> Self { + Executor { + tasks: VecDeque::new(), + } + } + + fn push(&mut self, closure: C) + where + F: Future + 'static, + C: FnOnce(Task) -> F, + { + let task = Task { + state: State::Running, + }; + self.tasks.push_back(Box::pin(closure(task))); + } + + fn run(&mut self) { + let waker = create_waker(); + let mut context = Context::from_waker(&waker); + + while let Some(mut task) = self.tasks.pop_front() { + match task.as_mut().poll(&mut context) { + Poll::Pending => { + self.tasks.push_back(task); + } + Poll::Ready(()) => {} + } + } + } +} + +pub fn create_waker() -> Waker { + // Safety: The waker points to a vtable with functions that do nothing. Doing + // nothing is memory-safe. + unsafe { Waker::from_raw(RAW_WAKER) } +} + +const RAW_WAKER: RawWaker = RawWaker::new(core::ptr::null(), &VTABLE); +const VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake_by_ref, drop); + +unsafe fn clone(_: *const ()) -> RawWaker { + RAW_WAKER +} +unsafe fn wake(_: *const ()) {} +unsafe fn wake_by_ref(_: *const ()) {} +unsafe fn drop(_: *const ()) {} + +#[no_mangle] +pub fn main() -> i32 { + println!("stackless coroutine Begin.."); + let mut exec = Executor::new(); + println!(" Create futures"); + for instance in 1..=3 { + exec.push(move |mut task| async move { + println!(" Task {}: begin state", instance); + task.waiter().await; + println!(" Task {}: next state", instance); + task.waiter().await; + println!(" Task {}: end state", instance); + }); + } + + println!(" Running"); + exec.run(); + println!(" Done"); + println!("stackless coroutine PASSED"); + + 0 +} diff --git a/ci-user/user/src/bin/ch8b_sync_sem.rs b/ci-user/user/src/bin/ch8b_sync_sem.rs new file mode 100644 index 0000000..3c6c575 --- /dev/null +++ b/ci-user/user/src/bin/ch8b_sync_sem.rs @@ -0,0 +1,45 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +extern crate alloc; + +use alloc::vec; +use user_lib::exit; +use user_lib::{semaphore_create, semaphore_down, semaphore_up}; +use user_lib::{sleep_blocking, thread_create, waittid}; + +const SEM_SYNC: usize = 0; + +unsafe fn first() -> ! { + sleep_blocking(10); + println!("First work and wakeup Second"); + semaphore_up(SEM_SYNC); + exit(0) +} + +unsafe fn second() -> ! { + println!("Second want to continue,but need to wait first"); + semaphore_down(SEM_SYNC); + println!("Second can work now"); + exit(0) +} + +#[no_mangle] +pub fn main() -> i32 { + // create semaphores + assert_eq!(semaphore_create(0) as usize, SEM_SYNC); + // create threads + let threads = vec![ + thread_create(first as usize, 0), + thread_create(second as usize, 0), + ]; + // wait for all threads to complete + for thread in threads.iter() { + waittid(*thread as usize); + } + println!("sync_sem passed!"); + 0 +} diff --git a/ci-user/user/src/bin/ch8b_test_condvar.rs b/ci-user/user/src/bin/ch8b_test_condvar.rs new file mode 100644 index 0000000..26029eb --- /dev/null +++ b/ci-user/user/src/bin/ch8b_test_condvar.rs @@ -0,0 +1,59 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; + +extern crate alloc; + +use alloc::vec; +use user_lib::exit; +use user_lib::{ + condvar_create, condvar_signal, condvar_wait, mutex_blocking_create, mutex_lock, mutex_unlock, +}; +use user_lib::{sleep_blocking, thread_create, waittid}; + +static mut A: usize = 0; + +const CONDVAR_ID: usize = 0; +const MUTEX_ID: usize = 0; + +unsafe fn first() -> ! { + sleep_blocking(10); + println!("First work, Change A --> 1 and wakeup Second"); + mutex_lock(MUTEX_ID); + A = 1; + condvar_signal(CONDVAR_ID); + mutex_unlock(MUTEX_ID); + exit(0) +} + +unsafe fn second() -> ! { + println!("Second want to continue,but need to wait A=1"); + mutex_lock(MUTEX_ID); + while A == 0 { + println!("Second: A is {}", A); + condvar_wait(CONDVAR_ID, MUTEX_ID); + } + mutex_unlock(MUTEX_ID); + println!("A is {}, Second can work now", A); + exit(0) +} + +#[no_mangle] +pub fn main() -> i32 { + // create condvar & mutex + assert_eq!(condvar_create() as usize, CONDVAR_ID); + assert_eq!(mutex_blocking_create() as usize, MUTEX_ID); + // create threads + let threads = vec![ + thread_create(first as usize, 0), + thread_create(second as usize, 0), + ]; + // wait for all threads to complete + for thread in threads.iter() { + waittid(*thread as usize); + } + println!("test_condvar passed!"); + 0 +} diff --git a/ci-user/user/src/bin/ch8b_threads.rs b/ci-user/user/src/bin/ch8b_threads.rs new file mode 100644 index 0000000..0db8292 --- /dev/null +++ b/ci-user/user/src/bin/ch8b_threads.rs @@ -0,0 +1,62 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +extern crate alloc; + +use alloc::vec; +use user_lib::{exit, thread_create, waittid}; + +pub fn thread_a() -> ! { + let mut t = 2i32; + for _ in 0..1000 { + print!("a"); + for __ in 0..5000 { + t = t * t % 10007; + } + } + println!("{}", t); + exit(1) +} + +pub fn thread_b() -> ! { + let mut t = 2i32; + for _ in 0..1000 { + print!("b"); + for __ in 0..5000 { + t = t * t % 10007; + } + } + println!("{}", t); + exit(2) +} + +pub fn thread_c() -> ! { + let mut t = 2i32; + for _ in 0..1000 { + print!("c"); + for __ in 0..5000 { + t = t * t % 10007; + } + } + println!("{}", t); + exit(3) +} + +#[no_mangle] +pub fn main() -> i32 { + let v = vec![ + thread_create(thread_a as usize, 0), + thread_create(thread_b as usize, 0), + thread_create(thread_c as usize, 0), + ]; + for tid in v.iter() { + let exit_code = waittid(*tid as usize); + println!("thread#{} exited with code {}", tid, exit_code); + assert_eq!(*tid, exit_code); + } + println!("main thread exited."); + println!("threads test passed!"); + 0 +} diff --git a/ci-user/user/src/bin/ch8b_threads_arg.rs b/ci-user/user/src/bin/ch8b_threads_arg.rs new file mode 100644 index 0000000..2c0de19 --- /dev/null +++ b/ci-user/user/src/bin/ch8b_threads_arg.rs @@ -0,0 +1,45 @@ +#![no_std] +#![no_main] + +#[macro_use] +extern crate user_lib; +extern crate alloc; + +use alloc::vec::Vec; +use user_lib::{exit, thread_create, waittid}; + +struct Argument { + pub ch: char, + pub rc: i32, +} + +fn thread_print(arg: *const Argument) -> ! { + let arg = unsafe { &*arg }; + for _ in 0..1000 { + print!("{}", arg.ch); + } + exit(arg.rc) +} + +#[no_mangle] +pub fn main() -> i32 { + let mut v = Vec::new(); + let args = [ + Argument { ch: 'a', rc: 1 }, + Argument { ch: 'b', rc: 2 }, + Argument { ch: 'c', rc: 3 }, + ]; + for arg in args.iter() { + v.push(thread_create( + thread_print as usize, + arg as *const _ as usize, + )); + } + for tid in v.iter() { + let exit_code = waittid(*tid as usize); + println!("thread#{} exited with code {}", tid, exit_code); + } + println!("main thread exited."); + println!("threads with arg test passed!"); + 0 +} diff --git a/ci-user/user/src/bin/ch8b_user_shell.rs b/ci-user/user/src/bin/ch8b_user_shell.rs new file mode 100644 index 0000000..4288248 --- /dev/null +++ b/ci-user/user/src/bin/ch8b_user_shell.rs @@ -0,0 +1,214 @@ +#![no_std] +#![no_main] +#![allow(clippy::println_empty_string)] + +extern crate alloc; + +#[macro_use] +extern crate user_lib; + +const LF: u8 = 0x0au8; +const CR: u8 = 0x0du8; +const DL: u8 = 0x7fu8; +const BS: u8 = 0x08u8; +const LINE_START: &str = ">> "; + +use alloc::string::String; +use alloc::vec::Vec; +use user_lib::console::getchar; +use user_lib::{close, dup, exec, fork, open, pipe, waitpid, OpenFlags}; + +#[derive(Debug)] +struct ProcessArguments { + input: String, + output: String, + args_copy: Vec, + args_addr: Vec<*const u8>, +} + +impl ProcessArguments { + pub fn new(command: &str) -> Self { + let args: Vec<_> = command.split(' ').collect(); + let mut args_copy: Vec = args + .iter() + .filter(|&arg| !arg.is_empty()) + .map(|&arg| { + let mut string = String::new(); + string.push_str(arg); + string.push('\0'); + string + }) + .collect(); + + // redirect input + let mut input = String::new(); + if let Some((idx, _)) = args_copy + .iter() + .enumerate() + .find(|(_, arg)| arg.as_str() == "<\0") + { + input = args_copy[idx + 1].clone(); + args_copy.drain(idx..=idx + 1); + } + + // redirect output + let mut output = String::new(); + if let Some((idx, _)) = args_copy + .iter() + .enumerate() + .find(|(_, arg)| arg.as_str() == ">\0") + { + output = args_copy[idx + 1].clone(); + args_copy.drain(idx..=idx + 1); + } + + let mut args_addr: Vec<*const u8> = args_copy.iter().map(|arg| arg.as_ptr()).collect(); + args_addr.push(core::ptr::null::()); + + Self { + input, + output, + args_copy, + args_addr, + } + } +} + +#[no_mangle] +pub fn main() -> i32 { + println!("Rust user shell"); + let mut line: String = String::new(); + print!("{}", LINE_START); + loop { + let c = getchar(); + match c { + LF | CR => { + println!(""); + if !line.is_empty() { + let splited: Vec<_> = line.as_str().split('|').collect(); + let process_arguments_list: Vec<_> = splited + .iter() + .map(|&cmd| ProcessArguments::new(cmd)) + .collect(); + let mut valid = true; + for (i, process_args) in process_arguments_list.iter().enumerate() { + if i == 0 { + if !process_args.output.is_empty() { + valid = false; + } + } else if i == process_arguments_list.len() - 1 { + if !process_args.input.is_empty() { + valid = false; + } + } else if !process_args.output.is_empty() || !process_args.input.is_empty() + { + valid = false; + } + } + if process_arguments_list.len() == 1 { + valid = true; + } + if !valid { + println!("Invalid command: Inputs/Outputs cannot be correctly binded!"); + } else { + // create pipes + let mut pipes_fd: Vec<[usize; 2]> = Vec::new(); + if !process_arguments_list.is_empty() { + for _ in 0..process_arguments_list.len() - 1 { + let mut pipe_fd = [0usize; 2]; + pipe(&mut pipe_fd); + pipes_fd.push(pipe_fd); + } + } + let mut children: Vec<_> = Vec::new(); + for (i, process_argument) in process_arguments_list.iter().enumerate() { + let pid = fork(); + if pid == 0 { + let input = &process_argument.input; + let output = &process_argument.output; + let args_copy = &process_argument.args_copy; + let args_addr = &process_argument.args_addr; + // redirect input + if !input.is_empty() { + let input_fd = open(input.as_str(), OpenFlags::RDONLY); + if input_fd == -1 { + println!("Error when opening file {}", input); + return -4; + } + let input_fd = input_fd as usize; + close(0); + assert_eq!(dup(input_fd), 0); + close(input_fd); + } + // redirect output + if !output.is_empty() { + let output_fd = open( + output.as_str(), + OpenFlags::CREATE | OpenFlags::WRONLY, + ); + if output_fd == -1 { + println!("Error when opening file {}", output); + return -4; + } + let output_fd = output_fd as usize; + close(1); + assert_eq!(dup(output_fd), 1); + close(output_fd); + } + // receive input from the previous process + if i > 0 { + close(0); + let read_end = pipes_fd.get(i - 1).unwrap()[0]; + assert_eq!(dup(read_end), 0); + } + // send output to the next process + if i < process_arguments_list.len() - 1 { + close(1); + let write_end = pipes_fd.get(i).unwrap()[1]; + assert_eq!(dup(write_end), 1); + } + // close all pipe ends inherited from the parent process + for pipe_fd in pipes_fd.iter() { + close(pipe_fd[0]); + close(pipe_fd[1]); + } + // execute new application + if exec(args_copy[0].as_str(), args_addr.as_slice()) == -1 { + println!("Error when executing!"); + return -4; + } + unreachable!(); + } else { + children.push(pid); + } + } + for pipe_fd in pipes_fd.iter() { + close(pipe_fd[0]); + close(pipe_fd[1]); + } + let mut exit_code: i32 = 0; + for pid in children.into_iter() { + let exit_pid = waitpid(pid as usize, &mut exit_code); + assert_eq!(pid, exit_pid); + //println!("Shell: Process {} exited with code {}", pid, exit_code); + } + } + line.clear(); + } + print!("{}", LINE_START); + } + BS | DL => { + if !line.is_empty() { + print!("{}", BS as char); + print!(" "); + print!("{}", BS as char); + line.pop(); + } + } + _ => { + print!("{}", c as char); + line.push(c as char); + } + } + } +} diff --git a/ci-user/user/src/console.rs b/ci-user/user/src/console.rs new file mode 100644 index 0000000..6d6d1f3 --- /dev/null +++ b/ci-user/user/src/console.rs @@ -0,0 +1,75 @@ +use alloc::collections::vec_deque::VecDeque; +use alloc::sync::Arc; +use core::fmt::{self, Write}; +use spin::mutex::Mutex; + +pub const STDIN: usize = 0; +pub const STDOUT: usize = 1; + +const CONSOLE_BUFFER_SIZE: usize = 256 * 10; + +use super::{read, write}; +use lazy_static::*; + +struct ConsoleBuffer(VecDeque); + +lazy_static! { + static ref CONSOLE_BUFFER: Arc> = { + let buffer = VecDeque::::with_capacity(CONSOLE_BUFFER_SIZE); + Arc::new(Mutex::new(ConsoleBuffer(buffer))) + }; +} + +impl ConsoleBuffer { + fn flush(&mut self) -> isize { + let s: &[u8] = self.0.make_contiguous(); + let ret = write(STDOUT, s); + self.0.clear(); + ret + } +} + +impl Write for ConsoleBuffer { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.as_bytes().iter() { + self.0.push_back(*c); + if (*c == b'\n' || self.0.len() == CONSOLE_BUFFER_SIZE) && -1 == self.flush() { + return Err(fmt::Error); + } + } + Ok(()) + } +} + +#[allow(unused)] +pub fn print(args: fmt::Arguments) { + let mut buf = CONSOLE_BUFFER.lock(); + // buf.write_fmt(args).unwrap(); + // BUG FIX: 关闭 stdout 后,本函数不能触发 panic,否则会造成死锁 + buf.write_fmt(args); +} + +#[macro_export] +macro_rules! print { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!($fmt $(, $($arg)+)?)); + } +} + +#[macro_export] +macro_rules! println { + ($fmt: literal $(, $($arg: tt)+)?) => { + $crate::console::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?)); + } +} + +pub fn getchar() -> u8 { + let mut c = [0u8; 1]; + read(STDIN, &mut c); + c[0] +} + +pub fn flush() { + let mut buf = CONSOLE_BUFFER.lock(); + buf.flush(); +} diff --git a/ci-user/user/src/lang_items.rs b/ci-user/user/src/lang_items.rs new file mode 100644 index 0000000..2d81a1d --- /dev/null +++ b/ci-user/user/src/lang_items.rs @@ -0,0 +1,17 @@ +use crate::exit; + +#[panic_handler] +fn panic_handler(panic_info: &core::panic::PanicInfo) -> ! { + let err = panic_info.message().unwrap(); + if let Some(location) = panic_info.location() { + println!( + "Panicked at {}:{}, {}", + location.file(), + location.line(), + err + ); + } else { + println!("Panicked: {}", err); + } + exit(-1); +} diff --git a/ci-user/user/src/lib.rs b/ci-user/user/src/lib.rs new file mode 100644 index 0000000..cee97ee --- /dev/null +++ b/ci-user/user/src/lib.rs @@ -0,0 +1,359 @@ +#![no_std] +#![feature(linkage)] +#![feature(panic_info_message)] +#![feature(alloc_error_handler)] + +#[macro_use] +pub mod console; +mod lang_items; +mod syscall; + +extern crate alloc; +extern crate core; +#[macro_use] +extern crate bitflags; + +use alloc::vec::Vec; +use buddy_system_allocator::LockedHeap; +pub use console::{flush, STDIN, STDOUT}; +pub use syscall::*; + +const USER_HEAP_SIZE: usize = 16384; + +static mut HEAP_SPACE: [u8; USER_HEAP_SIZE] = [0; USER_HEAP_SIZE]; + +#[global_allocator] +static HEAP: LockedHeap = LockedHeap::empty(); + +#[alloc_error_handler] +pub fn handle_alloc_error(layout: core::alloc::Layout) -> ! { + panic!("Heap allocation error, layout = {:?}", layout); +} + +fn clear_bss() { + extern "C" { + fn start_bss(); + fn end_bss(); + } + unsafe { + core::slice::from_raw_parts_mut( + start_bss as usize as *mut u8, + end_bss as usize - start_bss as usize, + ) + .fill(0); + } +} + +#[no_mangle] +#[link_section = ".text.entry"] +pub extern "C" fn _start(argc: usize, argv: usize) -> ! { + clear_bss(); + unsafe { + HEAP.lock() + .init(HEAP_SPACE.as_ptr() as usize, USER_HEAP_SIZE); + } + let mut v: Vec<&'static str> = Vec::new(); + for i in 0..argc { + let str_start = + unsafe { ((argv + i * core::mem::size_of::()) as *const usize).read_volatile() }; + let len = (0usize..) + .find(|i| unsafe { ((str_start + *i) as *const u8).read_volatile() == 0 }) + .unwrap(); + v.push( + core::str::from_utf8(unsafe { + core::slice::from_raw_parts(str_start as *const u8, len) + }) + .unwrap(), + ); + } + exit(main(argc, v.as_slice())); +} + +#[linkage = "weak"] +#[no_mangle] +fn main(_argc: usize, _argv: &[&str]) -> i32 { + panic!("Cannot find main!"); +} + +bitflags! { + pub struct OpenFlags: u32 { + const RDONLY = 0; + const WRONLY = 1 << 0; + const RDWR = 1 << 1; + const CREATE = 1 << 9; + const TRUNC = 1 << 10; + } +} + +#[repr(C)] +#[derive(Debug, Default)] +pub struct TimeVal { + pub sec: usize, + pub usec: usize, +} + +impl TimeVal { + pub fn new() -> Self { + Self::default() + } +} + +#[derive(Copy, Clone, PartialEq, Debug)] +pub enum TaskStatus { + UnInit, + Ready, + Running, + Exited, +} + +#[derive(Copy, Clone, Debug)] +pub struct SyscallInfo { + pub id: usize, + pub times: usize, +} + +const MAX_SYSCALL_NUM: usize = 500; + +#[derive(Debug)] +pub struct TaskInfo { + pub status: TaskStatus, + pub syscall_times: [u32; MAX_SYSCALL_NUM], + pub time: usize, +} + +impl TaskInfo { + pub fn new() -> Self { + TaskInfo { + status: TaskStatus::UnInit, + syscall_times: [0; MAX_SYSCALL_NUM], + time: 0, + } + } +} + +#[repr(C)] +#[derive(Debug)] +pub struct Stat { + /// ID of device containing file + pub dev: u64, + /// inode number + pub ino: u64, + /// file type and mode + pub mode: StatMode, + /// number of hard links + pub nlink: u32, + /// unused pad + pad: [u64; 7], +} + +impl Stat { + pub fn new() -> Self { + Stat { + dev: 0, + ino: 0, + mode: StatMode::NULL, + nlink: 0, + pad: [0; 7], + } + } +} + +impl Default for Stat { + fn default() -> Self { + Self::new() + } +} + +bitflags! { + pub struct StatMode: u32 { + const NULL = 0; + /// directory + const DIR = 0o040000; + /// ordinary regular file + const FILE = 0o100000; + } +} + +const AT_FDCWD: isize = -100; + +pub fn open(path: &str, flags: OpenFlags) -> isize { + sys_openat(AT_FDCWD as usize, path, flags.bits, OpenFlags::RDWR.bits) +} + +pub fn close(fd: usize) -> isize { + if fd == STDOUT { + console::flush(); + } + sys_close(fd) +} + +pub fn read(fd: usize, buf: &mut [u8]) -> isize { + sys_read(fd, buf) +} + +pub fn write(fd: usize, buf: &[u8]) -> isize { + sys_write(fd, buf) +} + +pub fn link(old_path: &str, new_path: &str) -> isize { + sys_linkat(AT_FDCWD as usize, old_path, AT_FDCWD as usize, new_path, 0) +} + +pub fn unlink(path: &str) -> isize { + sys_unlinkat(AT_FDCWD as usize, path, 0) +} + +pub fn fstat(fd: usize, st: &Stat) -> isize { + sys_fstat(fd, st) +} + +pub fn mail_read(buf: &mut [u8]) -> isize { + sys_mail_read(buf) +} + +pub fn mail_write(pid: usize, buf: &[u8]) -> isize { + sys_mail_write(pid, buf) +} + +pub fn exit(exit_code: i32) -> ! { + console::flush(); + sys_exit(exit_code); +} + +pub fn yield_() -> isize { + sys_yield() +} + +pub fn get_time() -> isize { + let time = TimeVal::new(); + match sys_get_time(&time, 0) { + 0 => ((time.sec & 0xffff) * 1000 + time.usec / 1000) as isize, + _ => -1, + } +} + +pub fn getpid() -> isize { + sys_getpid() +} + +pub fn fork() -> isize { + sys_fork() +} + +pub fn exec(path: &str, args: &[*const u8]) -> isize { + sys_exec(path, args) +} + +pub fn set_priority(prio: isize) -> isize { + sys_set_priority(prio) +} + +pub fn wait(exit_code: &mut i32) -> isize { + loop { + match sys_waitpid(-1, exit_code as *mut _) { + -2 => { + sys_yield(); + } + n => { + return n; + } + } + } +} + +pub fn waitpid(pid: usize, exit_code: &mut i32) -> isize { + loop { + match sys_waitpid(pid as isize, exit_code as *mut _) { + -2 => { + sys_yield(); + } + n => { + return n; + } + } + } +} + +pub fn sleep_blocking(sleep_ms: usize) { + sys_sleep(sleep_ms); +} + +pub fn sleep(period_ms: usize) { + let start = get_time(); + while get_time() < start + period_ms as isize { + sys_yield(); + } +} +pub fn mmap(start: usize, len: usize, prot: usize) -> isize { + sys_mmap(start, len, prot) +} + +pub fn munmap(start: usize, len: usize) -> isize { + sys_munmap(start, len) +} + +pub fn spawn(path: &str) -> isize { + sys_spawn(path) +} + +pub fn dup(fd: usize) -> isize { + sys_dup(fd) +} +pub fn pipe(pipe_fd: &mut [usize]) -> isize { + sys_pipe(pipe_fd) +} + +pub fn task_info(info: &TaskInfo) -> isize { + sys_task_info(info) +} + +pub fn thread_create(entry: usize, arg: usize) -> isize { + sys_thread_create(entry, arg) +} +pub fn gettid() -> isize { + sys_gettid() +} +pub fn waittid(tid: usize) -> isize { + loop { + match sys_waittid(tid) { + -2 => { + yield_(); + } + exit_code => return exit_code, + } + } +} + +pub fn mutex_create() -> isize { + sys_mutex_create(false) +} +pub fn mutex_blocking_create() -> isize { + sys_mutex_create(true) +} +pub fn mutex_lock(mutex_id: usize) -> isize { + sys_mutex_lock(mutex_id) +} +pub fn mutex_unlock(mutex_id: usize) { + sys_mutex_unlock(mutex_id); +} +pub fn semaphore_create(res_count: usize) -> isize { + sys_semaphore_create(res_count) +} +pub fn semaphore_up(sem_id: usize) { + sys_semaphore_up(sem_id); +} +pub fn enable_deadlock_detect(enabled: bool) -> isize { + sys_enable_deadlock_detect(enabled as usize) +} +pub fn semaphore_down(sem_id: usize) -> isize { + sys_semaphore_down(sem_id) +} +pub fn condvar_create() -> isize { + sys_condvar_create(0) +} +pub fn condvar_signal(condvar_id: usize) { + sys_condvar_signal(condvar_id); +} +pub fn condvar_wait(condvar_id: usize, mutex_id: usize) { + sys_condvar_wait(condvar_id, mutex_id); +} diff --git a/ci-user/user/src/linker.ld b/ci-user/user/src/linker.ld new file mode 100644 index 0000000..f3f996e --- /dev/null +++ b/ci-user/user/src/linker.ld @@ -0,0 +1,33 @@ +OUTPUT_ARCH(riscv) +ENTRY(_start) + +BASE_ADDRESS = 0x0; + +SECTIONS +{ + . = BASE_ADDRESS; + .text : { + *(.text.entry) + *(.text .text.*) + } + . = ALIGN(4K); + .rodata : { + *(.rodata .rodata.*) + *(.srodata .srodata.*) + } + . = ALIGN(4K); + .data : { + *(.data .data.*) + *(.sdata .sdata.*) + } + .bss : { + start_bss = .; + *(.bss .bss.*) + *(.sbss .sbss.*) + end_bss = .; + } + /DISCARD/ : { + *(.eh_frame) + *(.debug*) + } +} \ No newline at end of file diff --git a/ci-user/user/src/syscall.rs b/ci-user/user/src/syscall.rs new file mode 100644 index 0000000..f671438 --- /dev/null +++ b/ci-user/user/src/syscall.rs @@ -0,0 +1,258 @@ +use crate::TaskInfo; + +use super::{Stat, TimeVal}; + +pub const SYSCALL_OPENAT: usize = 56; +pub const SYSCALL_CLOSE: usize = 57; +pub const SYSCALL_READ: usize = 63; +pub const SYSCALL_WRITE: usize = 64; +pub const SYSCALL_UNLINKAT: usize = 35; +pub const SYSCALL_LINKAT: usize = 37; +pub const SYSCALL_FSTAT: usize = 80; +pub const SYSCALL_EXIT: usize = 93; +pub const SYSCALL_SLEEP: usize = 101; +pub const SYSCALL_YIELD: usize = 124; +pub const SYSCALL_GETTIMEOFDAY: usize = 169; +pub const SYSCALL_GETPID: usize = 172; +pub const SYSCALL_GETTID: usize = 178; +pub const SYSCALL_FORK: usize = 220; +pub const SYSCALL_EXEC: usize = 221; +pub const SYSCALL_WAITPID: usize = 260; +pub const SYSCALL_SET_PRIORITY: usize = 140; +pub const SYSCALL_MUNMAP: usize = 215; +pub const SYSCALL_MMAP: usize = 222; +pub const SYSCALL_SPAWN: usize = 400; +pub const SYSCALL_MAIL_READ: usize = 401; +pub const SYSCALL_MAIL_WRITE: usize = 402; +pub const SYSCALL_DUP: usize = 24; +pub const SYSCALL_PIPE: usize = 59; +pub const SYSCALL_TASK_INFO: usize = 410; +pub const SYSCALL_THREAD_CREATE: usize = 460; +pub const SYSCALL_WAITTID: usize = 462; +pub const SYSCALL_MUTEX_CREATE: usize = 463; +pub const SYSCALL_MUTEX_LOCK: usize = 464; +pub const SYSCALL_MUTEX_UNLOCK: usize = 466; +pub const SYSCALL_SEMAPHORE_CREATE: usize = 467; +pub const SYSCALL_SEMAPHORE_UP: usize = 468; +pub const SYSCALL_ENABLE_DEADLOCK_DETECT: usize = 469; +pub const SYSCALL_SEMAPHORE_DOWN: usize = 470; +pub const SYSCALL_CONDVAR_CREATE: usize = 471; +pub const SYSCALL_CONDVAR_SIGNAL: usize = 472; +pub const SYSCALL_CONDVAR_WAIT: usize = 473; + +pub fn syscall(id: usize, args: [usize; 3]) -> isize { + let mut ret: isize; + unsafe { + core::arch::asm!( + "ecall", + inlateout("x10") args[0] => ret, + in("x11") args[1], + in("x12") args[2], + in("x17") id + ); + } + ret +} + +pub fn syscall6(id: usize, args: [usize; 6]) -> isize { + let mut ret: isize; + unsafe { + core::arch::asm!("ecall", + inlateout("x10") args[0] => ret, + in("x11") args[1], + in("x12") args[2], + in("x13") args[3], + in("x14") args[4], + in("x15") args[5], + in("x17") id + ); + } + ret +} + +pub fn sys_openat(dirfd: usize, path: &str, flags: u32, mode: u32) -> isize { + syscall6( + SYSCALL_OPENAT, + [ + dirfd, + path.as_ptr() as usize, + flags as usize, + mode as usize, + 0, + 0, + ], + ) +} + +pub fn sys_close(fd: usize) -> isize { + syscall(SYSCALL_CLOSE, [fd, 0, 0]) +} + +pub fn sys_read(fd: usize, buffer: &mut [u8]) -> isize { + syscall( + SYSCALL_READ, + [fd, buffer.as_mut_ptr() as usize, buffer.len()], + ) +} + +pub fn sys_write(fd: usize, buffer: &[u8]) -> isize { + syscall(SYSCALL_WRITE, [fd, buffer.as_ptr() as usize, buffer.len()]) +} + +pub fn sys_linkat( + old_dirfd: usize, + old_path: &str, + new_dirfd: usize, + new_path: &str, + flags: usize, +) -> isize { + syscall6( + SYSCALL_LINKAT, + [ + old_dirfd, + old_path.as_ptr() as usize, + new_dirfd, + new_path.as_ptr() as usize, + flags, + 0, + ], + ) +} + +pub fn sys_unlinkat(dirfd: usize, path: &str, flags: usize) -> isize { + syscall(SYSCALL_UNLINKAT, [dirfd, path.as_ptr() as usize, flags]) +} + +pub fn sys_fstat(fd: usize, st: &Stat) -> isize { + syscall(SYSCALL_FSTAT, [fd, st as *const _ as usize, 0]) +} + +pub fn sys_mail_read(buffer: &mut [u8]) -> isize { + syscall( + SYSCALL_MAIL_READ, + [buffer.as_ptr() as usize, buffer.len(), 0], + ) +} + +pub fn sys_mail_write(pid: usize, buffer: &[u8]) -> isize { + syscall( + SYSCALL_MAIL_WRITE, + [pid, buffer.as_ptr() as usize, buffer.len()], + ) +} + +pub fn sys_exit(exit_code: i32) -> ! { + syscall(SYSCALL_EXIT, [exit_code as usize, 0, 0]); + panic!("sys_exit never returns!"); +} + +pub fn sys_sleep(sleep_ms: usize) -> isize { + syscall(SYSCALL_SLEEP, [sleep_ms, 0, 0]) +} + +pub fn sys_yield() -> isize { + syscall(SYSCALL_YIELD, [0, 0, 0]) +} + +pub fn sys_get_time(time: &TimeVal, tz: usize) -> isize { + syscall(SYSCALL_GETTIMEOFDAY, [time as *const _ as usize, tz, 0]) +} + +pub fn sys_getpid() -> isize { + syscall(SYSCALL_GETPID, [0, 0, 0]) +} + +pub fn sys_fork() -> isize { + syscall(SYSCALL_FORK, [0, 0, 0]) +} + +pub fn sys_exec(path: &str, args: &[*const u8]) -> isize { + syscall( + SYSCALL_EXEC, + [path.as_ptr() as usize, args.as_ptr() as usize, 0], + ) +} + +pub fn sys_waitpid(pid: isize, xstatus: *mut i32) -> isize { + syscall(SYSCALL_WAITPID, [pid as usize, xstatus as usize, 0]) +} + +pub fn sys_set_priority(prio: isize) -> isize { + syscall(SYSCALL_SET_PRIORITY, [prio as usize, 0, 0]) +} + +pub fn sys_mmap(start: usize, len: usize, prot: usize) -> isize { + syscall(SYSCALL_MMAP, [start, len, prot]) +} + +pub fn sys_munmap(start: usize, len: usize) -> isize { + syscall(SYSCALL_MUNMAP, [start, len, 0]) +} + +pub fn sys_spawn(path: &str) -> isize { + syscall(SYSCALL_SPAWN, [path.as_ptr() as usize, 0, 0]) +} + +pub fn sys_dup(fd: usize) -> isize { + syscall(SYSCALL_DUP, [fd, 0, 0]) +} + +pub fn sys_pipe(pipe: &mut [usize]) -> isize { + syscall(SYSCALL_PIPE, [pipe.as_mut_ptr() as usize, 0, 0]) +} + +pub fn sys_task_info(info: &TaskInfo) -> isize { + syscall(SYSCALL_TASK_INFO, [info as *const _ as usize, 0, 0]) +} + +pub fn sys_thread_create(entry: usize, arg: usize) -> isize { + syscall(SYSCALL_THREAD_CREATE, [entry, arg, 0]) +} + +pub fn sys_gettid() -> isize { + syscall(SYSCALL_GETTID, [0; 3]) +} + +pub fn sys_waittid(tid: usize) -> isize { + syscall(SYSCALL_WAITTID, [tid, 0, 0]) +} + +pub fn sys_mutex_create(blocking: bool) -> isize { + syscall(SYSCALL_MUTEX_CREATE, [blocking as usize, 0, 0]) +} + +pub fn sys_mutex_lock(id: usize) -> isize { + syscall(SYSCALL_MUTEX_LOCK, [id, 0, 0]) +} + +pub fn sys_mutex_unlock(id: usize) -> isize { + syscall(SYSCALL_MUTEX_UNLOCK, [id, 0, 0]) +} + +pub fn sys_semaphore_create(res_count: usize) -> isize { + syscall(SYSCALL_SEMAPHORE_CREATE, [res_count, 0, 0]) +} + +pub fn sys_semaphore_up(sem_id: usize) -> isize { + syscall(SYSCALL_SEMAPHORE_UP, [sem_id, 0, 0]) +} + +pub fn sys_enable_deadlock_detect(enabled: usize) -> isize { + syscall(SYSCALL_ENABLE_DEADLOCK_DETECT, [enabled, 0, 0]) +} + +pub fn sys_semaphore_down(sem_id: usize) -> isize { + syscall(SYSCALL_SEMAPHORE_DOWN, [sem_id, 0, 0]) +} + +pub fn sys_condvar_create(_arg: usize) -> isize { + syscall(SYSCALL_CONDVAR_CREATE, [_arg, 0, 0]) +} + +pub fn sys_condvar_signal(condvar_id: usize) -> isize { + syscall(SYSCALL_CONDVAR_SIGNAL, [condvar_id, 0, 0]) +} + +pub fn sys_condvar_wait(condvar_id: usize, mutex_id: usize) -> isize { + syscall(SYSCALL_CONDVAR_WAIT, [condvar_id, mutex_id, 0]) +}