Compare commits

..

2 commits

Author SHA1 Message Date
7c982b238b
nemu: update devShell deps
Some checks failed
Build abstract machine with nix / build-abstract-machine (push) Failing after 1m10s
Run CTests within npc / npc-test (push) Failing after 1m37s
2024-07-09 20:43:47 +08:00
3acab0a751
npc: wip, cannot build 2024-07-09 20:42:01 +08:00
21 changed files with 424 additions and 134 deletions

View file

@ -128,11 +128,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1710242657, "lastModified": 1714032877,
"narHash": "sha256-tgaILHKZH6vC8P8N8NBMNQ/XIpTY72zMojlGLPLPLZk=", "narHash": "sha256-6KKe4xdHPQbGtM5icLHKxgcYyFKF47a98csTQG7vkvU=",
"ref": "refs/heads/master", "ref": "refs/heads/master",
"rev": "6a499c8371c6a14d11a8c2fcc9f233e7b8e688a0", "rev": "f6acae14927a6df78ce2304007369095e140da9c",
"revCount": 148, "revCount": 149,
"type": "git", "type": "git",
"url": "https://git.xinyang.life/xin/nur.git" "url": "https://git.xinyang.life/xin/nur.git"
}, },

View file

@ -22,6 +22,7 @@
overlays = [ overlays = [
(self: super: { (self: super: {
nvboard = nur-xin.legacyPackages.${system}.nvboard; nvboard = nur-xin.legacyPackages.${system}.nvboard;
mini-gdbstub = nur-xin.legacyPackages.${system}.mini-gdbstub;
}) })
]; ];
}; };
@ -65,23 +66,36 @@
nativeBuildInputs = [ nativeBuildInputs = [
pkgs.cmake pkgs.cmake
pkgs.gcc # Generate expr tests
]; ];
cmakeFlags = [ cmakeFlags = [
(pkgs.lib.cmakeFeature "ISA" "riscv") (pkgs.lib.cmakeFeature "ARCH" "riscv-nemu")
(pkgs.lib.cmakeFeature "PLATFORM" "nemu")
]; ];
buildInputs = [ buildInputs = [
# SDL2 # SDL2
self.packages.${system}.abstract-machine self.packages.${system}.abstract-machine
]; ];
cmakeBuildType = "RelWithDebInfo";
dontStrip = true;
}; };
devShells.nemu = pkgs.mkShell { devShells.nemu = pkgs.mkShell {
packages = with pkgs; [ packages = with pkgs; [
clang-tools clang-tools
gdb gdb
SDL2
gnumake
pkg-config
flex
bison
dtc
readline
libllvm
mini-gdbstub
]; ];
inputsFrom = [ inputsFrom = [
self.packages.${system}.nemu self.packages.${system}.nemu

View file

@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 3.26) cmake_minimum_required(VERSION 3.26)
project(flow) project(flow)
set (CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD 17)
cmake_policy(SET CMP0144 NEW) cmake_policy(SET CMP0144 NEW)
include(CMakeDependentOption) include(CMakeDependentOption)
@ -12,17 +12,24 @@ list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake)
# -- Build options # -- Build options
option(BUILD_USE_BLOOP "Whether to use bloop to speed up elaborate" OFF) option(BUILD_USE_BLOOP "Whether to use bloop to speed up elaborate" OFF)
option(BUILD_SIM_TARGET "Whether to build verilator simulation binary" ON) option(BUILD_SIM_TARGET "Whether to build verilator simulation binary" ON)
cmake_dependent_option(BUILD_SIM_NVBOARD_TARGET "Whether to build nvboard target" OFF "BUILD_SIM_TARGET" OFF) cmake_dependent_option(
BUILD_SIM_NVBOARD_TARGET "Whether to build nvboard target" OFF
"BUILD_SIM_TARGET" OFF)
option(ENABLE_YSYX_GIT_TRACKER "Ysyx tracker support" ON) option(ENABLE_YSYX_GIT_TRACKER "Ysyx tracker support" ON)
set(TOPMODULE "Flow" CACHE STRING "Topmodule name in chisel") set(TOPMODULE
set(DIFFTEST_LIB "" CACHE STRING "Dynamic library file used as difftest reference") "Flow"
CACHE STRING "Topmodule name in chisel")
set(DIFFTEST_LIB
""
CACHE FILEPATH "Dynamic library file used as difftest reference")
set(DIFFTEST_RESOURCE_DIR
""
CACHE PATH "Dynamic library file used as difftest reference")
# -- Ysyx tracker, configure # -- Ysyx tracker, configure
if(ENABLE_YSYX_GIT_TRACKER) if(ENABLE_YSYX_GIT_TRACKER)
execute_process( execute_process(COMMAND ${CMAKE_SOURCE_DIR}/../git_commit.sh "configure(npc)"
COMMAND ${CMAKE_SOURCE_DIR}/../git_commit.sh "configure(npc)" WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/..)
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/..
)
endif() endif()
# -- Check dependencies # -- Check dependencies
@ -51,13 +58,15 @@ set(CHISEL_OUTPUT_VERILATOR_CONF ${CHISEL_OUTPUT_DIR}/conf.vlt)
set(CHISEL_OUTPUT_TOPMODULE ${CHISEL_OUTPUT_DIR}/${TOPMODULE}.sv) set(CHISEL_OUTPUT_TOPMODULE ${CHISEL_OUTPUT_DIR}/${TOPMODULE}.sv)
set(CHISEL_EMIT_ARGS "--target-dir ${CHISEL_OUTPUT_DIR}") set(CHISEL_EMIT_ARGS "--target-dir ${CHISEL_OUTPUT_DIR}")
# -- Find difftest binaries
file(GLOB_RECURSE DIFFTEST_BINARY_FILES "${DIFFTEST_RESOURCE_DIR}/*.bin")
# -- Build NVBoard executable # -- Build NVBoard executable
if(BUILD_SIM_NVBOARD_TARGET) if(BUILD_SIM_NVBOARD_TARGET)
add_subdirectory(csrc_nvboard) add_subdirectory(csrc_nvboard)
endif() endif()
# -- Build Verilator executable and add to test # -- Build Verilator executable and add to test
include_directories(include)
add_subdirectory(utils) add_subdirectory(utils)
add_subdirectory(csrc) add_subdirectory(csrc)
@ -66,7 +75,7 @@ add_subdirectory(csrc)
if(ENABLE_YSYX_GIT_TRACKER) if(ENABLE_YSYX_GIT_TRACKER)
add_custom_target( add_custom_target(
ysyx_git_tracer ALL ysyx_git_tracer ALL
COMMAND ${CMAKE_SOURCE_DIR}/../git_commit.sh "build_${CMAKE_PROJECT_NAME}_V${TOPMODULE}" COMMAND ${CMAKE_SOURCE_DIR}/../git_commit.sh
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/.. "build_${CMAKE_PROJECT_NAME}_V${TOPMODULE}"
) WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/..)
endif() endif()

View file

@ -14,7 +14,7 @@ module RamDpi (
input reg [31:0] pc, input reg [31:0] pc,
output reg [31:0] inst output reg [31:0] inst
); );
always @(*) begin always @(posedge clock) begin
if (valid) begin // 有读写请求时 if (valid) begin // 有读写请求时
readData = pmem_read(readAddr); readData = pmem_read(readAddr);
if (writeEnable) begin // 有写请求时 if (writeEnable) begin // 有写请求时
@ -22,8 +22,8 @@ module RamDpi (
end end
end end
else begin else begin
readData = 0; readData = 32'h80000000;
end end
inst = pmem_read(pc);
end end
endmodule assign inst = pmem_read(pc);
endmodule

View file

@ -242,12 +242,12 @@ class Control(width: Int) extends RawModule {
(xori , (r(true.B) :: r(rAluOut) :: (xori , (r(true.B) :: r(rAluOut) ::
r(false.B) :: r(pStaticNpc) :: r(false.B) :: r(pStaticNpc) ::
r(aOpOr) :: r(aSrcARs1) :: r(aSrcBImmI) :: l(Bool()) :: r(aOpXor) :: r(aSrcARs1) :: r(aSrcBImmI) :: l(Bool()) ::
r(false.B) :: l(UInt(4.W)):: r(false.B) :: HNil)), r(false.B) :: l(UInt(4.W)):: r(false.B) :: HNil)),
(ori , (r(true.B) :: r(rAluOut) :: (ori , (r(true.B) :: r(rAluOut) ::
r(false.B) :: r(pStaticNpc) :: r(false.B) :: r(pStaticNpc) ::
r(aOpXor) :: r(aSrcARs1) :: r(aSrcBImmI) :: l(Bool()) :: r(aOpOr) :: r(aSrcARs1) :: r(aSrcBImmI) :: l(Bool()) ::
r(false.B) :: l(UInt(4.W)):: r(false.B) :: HNil)), r(false.B) :: l(UInt(4.W)):: r(false.B) :: HNil)),
(andi , (r(true.B) :: r(rAluOut) :: (andi , (r(true.B) :: r(rAluOut) ::

View file

@ -1 +1,2 @@
add_subdirectory(${TOPMODULE}) add_subdirectory(devices)
add_subdirectory(${TOPMODULE})

View file

@ -1,19 +1,29 @@
include(ChiselBuild) include(ChiselBuild)
add_executable(V${TOPMODULE} config.cpp main.cpp) add_executable(V${TOPMODULE} config.cpp main.cpp)
target_link_libraries(V${TOPMODULE} PRIVATE sdb) target_link_libraries(V${TOPMODULE} PRIVATE sdb devices)
target_include_directories(V${TOPMODULE} PRIVATE ${CMAKE_SOURCE_DIR}/include)
verilate(V${TOPMODULE} TRACE THREADS verilate(
TOP_MODULE ${TOPMODULE} V${TOPMODULE}
PREFIX V${TOPMODULE} TRACE
SOURCES ${CHISEL_OUTPUT_TOPMODULE} ${CHISEL_OUTPUT_VERILATOR_CONF} THREADS
INCLUDE_DIRS ${CHISEL_OUTPUT_DIR} TOP_MODULE
${TOPMODULE}
PREFIX
V${TOPMODULE}
SOURCES
${CHISEL_OUTPUT_TOPMODULE}
${CHISEL_OUTPUT_VERILATOR_CONF}
INCLUDE_DIRS
${CHISEL_OUTPUT_DIR}
VERILATOR_ARGS VERILATOR_ARGS
"--vpi" # Enable VPI "--vpi" # Enable VPI
"-Wno-UNOPTFLAT" "-Wno-UNOPTFLAT")
)
add_test( foreach(DIFFTEST_BINARY_FILE IN LISTS DIFFTEST_BINARY_FILES)
NAME V${TOPMODULE} get_filename_component(FILENAME ${DIFFTEST_BINARY_FILE} NAME_WE)
COMMAND V${TOPMODULE} add_test(NAME V${TOPMODULE}.${FILENAME}
--no-bin -m ${PROJECT_SOURCE_DIR}/resource/addi.txt COMMAND V${TOPMODULE} -m ${DIFFTEST_BINARY_FILE} --diff-lib
--diff-lib ${DIFFTEST_LIB}) ${DIFFTEST_LIB})
unset(FILENAME)
endforeach()

View file

@ -8,7 +8,7 @@ void Config::cli_parse(int argc, char **argv) {
app.add_flag("!--no-bin", memory_file_binary, app.add_flag("!--no-bin", memory_file_binary,
"Memory file is in text format"); "Memory file is in text format");
app.add_option("--wav", wavefile, "output .vcd file path"); app.add_option("--wav", wavefile, "output .vcd file path");
app.add_option("-t", max_sim_time, "Max simulation timestep"); app.add_flag("-i", interactive, "Launch sdb for interactive session");
app.add_option("--diff-lib", lib_ref, app.add_option("--diff-lib", lib_ref,
"Dynamic library file of difftest reference") "Dynamic library file of difftest reference")
->check(CLI::ExistingFile); ->check(CLI::ExistingFile);

View file

@ -1,11 +1,15 @@
#include "VFlow___024root.h" #include "VFlow___024root.h"
#include "components.hpp"
#include <VFlow.h> #include <VFlow.h>
#include <array>
#include <config.hpp> #include <config.hpp>
#include <cstdint> #include <cstdint>
#include <cstdlib> #include <cstdlib>
#include <devices.hpp>
#include <disasm.hpp> #include <disasm.hpp>
#include <filesystem> #include <filesystem>
#include <fstream> #include <fstream>
#include <memory>
#include <sdb.hpp> #include <sdb.hpp>
#include <trm_difftest.hpp> #include <trm_difftest.hpp>
#include <trm_interface.hpp> #include <trm_interface.hpp>
@ -25,27 +29,38 @@ VlModule *top;
Registers *regs; Registers *regs;
vpiHandle pc = nullptr; vpiHandle pc = nullptr;
const size_t PMEM_START = 0x80000000;
const size_t PMEM_END = 0x87ffffff;
extern "C" { extern "C" {
using MMap = MemoryMap<Memory<128 * 1024>, Devices::DeviceMap>;
void *pmem_get() { void *pmem_get() {
static auto pmem = static Devices::DeviceMap devices{
new Memory<int, 128 * 1024>(config.memory_file, config.memory_file_binary, new Devices::Serial(0x10000000, 0x1000),
std::move(config.mtrace_ranges)); new Devices::RTC(0x10001000, 0x1000),
};
static auto pmem = new MemoryMap<Memory<128 * 1024>, Devices::DeviceMap>(
std::make_unique<Memory<128 * 1024>>(
config.memory_file, config.memory_file_binary, PMEM_START, PMEM_END),
std::make_unique<Devices::DeviceMap>(devices), config.mtrace_ranges);
return pmem; return pmem;
} }
int pmem_read(int raddr) { int pmem_read(int raddr) {
void *pmem = pmem_get(); void *pmem = pmem_get();
auto mem = static_cast<Memory<int, 128 * 1024> *>(pmem); auto mem = static_cast<MMap *>(pmem);
// TODO: Do memory difftest at memory read and write to diagnose at a finer // TODO: Do memory difftest at memory read and write to diagnose at a finer
// granularity // granularity
if (config.do_mtrace) if (config.do_mtrace)
mem->trace(raddr, true, regs->get_pc()); mem->trace(raddr, true, regs->get_pc());
if (g_skip_memcheck)
return mem->read(PMEM_START);
return mem->read(raddr); return mem->read(raddr);
} }
void pmem_write(int waddr, int wdata, char wmask) { void pmem_write(int waddr, int wdata, char wmask) {
void *pmem = pmem_get(); void *pmem = pmem_get();
auto mem = static_cast<Memory<int, 128 * 1024> *>(pmem); auto mem = static_cast<MMap *>(pmem);
if (config.do_mtrace) if (config.do_mtrace)
mem->trace((std::size_t)waddr, false, regs->get_pc(), wdata); mem->trace((std::size_t)waddr, false, regs->get_pc(), wdata);
return mem->write((std::size_t)waddr, wdata, wmask); return mem->write((std::size_t)waddr, wdata, wmask);
@ -55,10 +70,7 @@ void pmem_write(int waddr, int wdata, char wmask) {
namespace NPC { namespace NPC {
void npc_memcpy(paddr_t addr, void *buf, size_t sz, bool direction) { void npc_memcpy(paddr_t addr, void *buf, size_t sz, bool direction) {
if (direction == TRM_FROM_MACHINE) { if (direction == TRM_FROM_MACHINE) {
memcpy( static_cast<MMap *>(pmem_get())->copy_to(addr, (uint8_t *)buf, sz);
buf,
static_cast<Memory<int, 128 * 1024> *>(pmem_get())->guest_to_host(addr),
sz);
} }
}; };
@ -110,7 +122,10 @@ public:
this->memcpy(addr, &buf, sizeof(word_t), TRM_FROM_MACHINE); this->memcpy(addr, &buf, sizeof(word_t), TRM_FROM_MACHINE);
return buf; return buf;
} }
void print(std::ostream &os) const override {} void print(std::ostream &os) const override {
this->regcpy(cpu_state, TRM_FROM_MACHINE);
os << *(CPUState *)cpu_state << std::endl;
}
}; };
DutTrmInterface npc_interface = DutTrmInterface npc_interface =
@ -126,18 +141,50 @@ word_t reg_str2val(const char *name, bool *success) {
int main(int argc, char **argv, char **env) { int main(int argc, char **argv, char **env) {
config.cli_parse(argc, argv); config.cli_parse(argc, argv);
if (config.max_sim_time > 1) { if (config.lib_ref.empty()) {
NPC::npc_interface.exec(config.max_sim_time / 2); if (config.interactive) {
} else { SDB::SDB sdb_npc{NPC::npc_interface};
/* -- Difftest -- */ sdb_npc.main_loop();
std::filesystem::path ref{config.lib_ref}; return 0;
RefTrmInterface ref_interface{ref}; } else {
DifftestTrmInterface diff_interface{NPC::npc_interface, ref_interface, NPC::npc_interface.init(0);
pmem_get(), 128 * 1024}; while (true) {
SDB::SDB sdb_diff{diff_interface}; word_t inst = NPC::npc_interface.at(regs->get_pc());
if (inst == 1048691) {
return 0;
}
NPC::npc_interface.exec(1);
}
}
}
int t = 8; /* -- Difftest -- */
std::filesystem::path ref{config.lib_ref};
RefTrmInterface ref_interface{ref};
DifftestTrmInterface diff_interface{
NPC::npc_interface, ref_interface,
static_cast<MMap *>(pmem_get())->get_pmem(), 128 * 1024};
if (config.interactive) {
SDB::SDB sdb_diff{diff_interface};
sdb_diff.main_loop(); sdb_diff.main_loop();
return 0;
}
try {
diff_interface.init(0);
diff_interface.exec(-1);
} catch (TrmRuntimeException &e) {
switch (e.error_code()) {
case TrmRuntimeException::EBREAK:
return 0;
case TrmRuntimeException::DIFFTEST_FAILED:
std::cout << "Difftest Failed" << std::endl;
diff_interface.print(std::cout);
return 1;
default:
std::cerr << "Unknown error happened" << std::endl;
return 1;
}
} }
return 0; return 0;

View file

@ -0,0 +1,3 @@
add_library(devices serial.cpp rtc.cpp)
target_include_directories(devices PUBLIC include)

View file

@ -0,0 +1,85 @@
#include <array>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <initializer_list>
#include <iostream>
#include <iterator>
#include <map>
#include <memory>
#include <unordered_map>
#include <utility>
namespace Devices {
class Device {
public:
uint8_t *p_buf;
uint64_t addr;
size_t len;
Device(uint64_t addr, size_t len, uint8_t buf[])
: addr(addr), len(len), p_buf(buf) {}
virtual ~Device(){};
virtual void io_handler(uint32_t offset, size_t len, bool is_write) = 0;
void transfer(uint8_t *src, size_t len, bool is_write) {
if (is_write) {
memmove(p_buf, src, len);
} else {
memmove(src, p_buf, len);
}
};
};
class Serial : public Device {
uint8_t buf[1];
public:
Serial(uint64_t addr, size_t len);
~Serial() override{};
void io_handler(uint32_t offset, size_t len, bool is_write) override;
// void transfer(uint8_t *src, size_t len, bool is_write) override;
};
class RTC : public Device {
uint8_t buf[8];
uint64_t boot_time;
uint64_t get_time_internal();
uint64_t get_time();
public:
RTC(uint64_t addr, size_t len);
~RTC() override{};
void io_handler(uint32_t offset, size_t len, bool is_write) override;
// void transfer(uint8_t *src, size_t len, bool is_write) override;
};
class DeviceMap {
std::map<uint64_t, Device *> addr_to_device;
public:
DeviceMap(std::initializer_list<Device *> devices) {
for (auto device : devices) {
addr_to_device.insert(std::make_pair(device->addr, device));
}
}
bool handle(uint64_t addr, uint8_t *data, size_t len, bool is_write) {
auto it = addr_to_device.upper_bound(addr);
if (it == addr_to_device.begin() ||
(--it)->second->addr + it->second->len <= addr) {
std::cerr << "Use of a unintialized device at memory addr: 0x" << std::hex
<< addr << std::dec << std::endl;
return false;
}
auto &device = it->second;
uint32_t offset = addr - device->addr;
if (is_write) {
device->transfer(data, len, is_write);
device->io_handler(offset, len, is_write);
} else {
device->io_handler(offset, len, is_write);
device->transfer(data, len, is_write);
}
return true;
}
};
} // namespace Devices

49
npc/csrc/devices/rtc.cpp Normal file
View file

@ -0,0 +1,49 @@
#include <cstdint>
#include <devices.hpp>
namespace Devices {
uint64_t RTC::get_time_internal() {
#if defined(CONFIG_TARGET_AM)
uint64_t us = io_read(AM_TIMER_UPTIME).us;
#elif defined(CONFIG_TIMER_GETTIMEOFDAY)
struct timeval now;
gettimeofday(&now, NULL);
uint64_t us = now.tv_sec * 1000000 + now.tv_usec;
#else
struct timespec now;
clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
uint64_t us = now.tv_sec * 1000000 + now.tv_nsec / 1000;
#endif
return us;
}
uint64_t RTC::get_time() {
if (boot_time == 0)
boot_time = get_time_internal();
uint64_t now = get_time_internal();
return now - boot_time;
}
RTC::RTC(uint64_t addr, size_t len) : Device(addr, len, buf) {
*(uint64_t *)buf = 0;
};
void RTC::io_handler(uint32_t offset, size_t len, bool is_write) {
assert(offset == 0 || offset == 4);
if (!is_write && offset == 4) {
uint64_t us = get_time();
buf[0] = (uint32_t)us;
buf[1] = us >> 32;
}
}
// void RTC::transfer(uint8_t *src, size_t len, bool is_write) {
// if (is_write) {
// for (size_t i = 0; i < len; i++)
// buf[i] = src[i];
// } else {
// for (size_t i = 0; i < len; i++)
// src[i] = buf[i];
// }
// }
} // namespace Devices

View file

@ -0,0 +1,22 @@
#include <devices.hpp>
#include <iostream>
namespace Devices {
Serial::Serial(uint64_t addr, size_t len) : Device(addr, len, buf) {
buf[0] = 0;
};
void Serial::io_handler(uint32_t offset, size_t len, bool is_write) {
if (is_write) {
std::cout << (char)buf[0];
}
}
// void Serial::transfer(uint8_t *src, size_t len, bool is_write) {
// if (is_write) {
// for (size_t i = 0; i < len; i++)
// buf[i] = src[i];
// } else {
// for (size_t i = 0; i < len; i++)
// src[i] = buf[i];
// }
// }
} // namespace Devices

View file

@ -2,22 +2,30 @@ include(ChiselBuild)
add_custom_command( add_custom_command(
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${TOPMODULE}/auto_bind.cpp OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${TOPMODULE}/auto_bind.cpp
COMMAND auto_pin_bind ${CMAKE_SOURCE_DIR}/constr/${TOPMODULE}.nxdc ${CMAKE_CURRENT_BINARY_DIR}/${TOPMODULE}/auto_bind.cpp COMMAND auto_pin_bind ${CMAKE_SOURCE_DIR}/constr/${TOPMODULE}.nxdc
DEPENDS ${CMAKE_SOURCE_DIR}/constr/${TOPMODULE}.nxdc ${CMAKE_CURRENT_BINARY_DIR}/${TOPMODULE}/auto_bind.cpp
) DEPENDS ${CMAKE_SOURCE_DIR}/constr/${TOPMODULE}.nxdc)
add_executable(V${TOPMODULE}_nvboard add_executable(V${TOPMODULE}_nvboard
${CMAKE_CURRENT_BINARY_DIR}/${TOPMODULE}/auto_bind.cpp ${CMAKE_CURRENT_BINARY_DIR}/${TOPMODULE}/auto_bind.cpp main.cpp)
main.cpp
)
verilate(V${TOPMODULE}_nvboard TRACE THREADS verilate(
TOP_MODULE ${TOPMODULE} V${TOPMODULE}_nvboard
PREFIX V${TOPMODULE} TRACE
SOURCES ${CHISEL_OUTPUT_TOPMODULE} THREADS
INCLUDE_DIRS ${CHISEL_OUTPUT_DIR}) TOP_MODULE
${TOPMODULE}
PREFIX
V${TOPMODULE}
SOURCES
${CHISEL_OUTPUT_TOPMODULE}
INCLUDE_DIRS
${CHISEL_OUTPUT_DIR})
target_include_directories(V${TOPMODULE}_nvboard PRIVATE ${NVBOARD_INCLUDE_DIR} ${SDL2_INCLUDE_DIRS}) target_include_directories(V${TOPMODULE}_nvboard PRIVATE ${NVBOARD_INCLUDE_DIR}
target_link_libraries(V${TOPMODULE}_nvboard PRIVATE ${NVBOARD_LIBRARY} SDL2::SDL2 SDL2_image::SDL2_image) ${SDL2_INCLUDE_DIRS})
target_link_libraries(
V${TOPMODULE}_nvboard PRIVATE ${NVBOARD_LIBRARY} SDL2::SDL2
SDL2_image::SDL2_image)
install(TARGETS V${TOPMODULE}_nvboard) install(TARGETS V${TOPMODULE}_nvboard)

View file

@ -11,6 +11,7 @@
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <map> #include <map>
#include <memory>
#include <sstream> #include <sstream>
#include <stdexcept> #include <stdexcept>
#include <string> #include <string>
@ -32,21 +33,21 @@ public:
} }
}; };
template <typename T, std::size_t n> class Memory { // class MemoryFile {
uint32_t expand_bits(uint8_t bits) { // std::filesystem::path filepath;
uint32_t x = bits; // public:
x = (x | (x << 7) | (x << 14) | (x << 21)) & 0x01010101;
x = x * 0xFF; // };
// printf("expand: %hhx->%x\n", bits, x);
return x; template <std::size_t n> class Memory {
} paddr_t pmem_start, pmem_end;
public: public:
std::array<T, n> mem; std::array<uint8_t, n> mem;
std::vector<std::array<uint64_t, 2>> trace_ranges; // TODO: Read memory file before init and use memcpy to initialize memory.
Memory(std::filesystem::path filepath, bool is_binary, Memory(std::filesystem::path filepath, bool is_binary, paddr_t pmem_start,
std::vector<std::array<uint64_t, 2>> &&trace_ranges) paddr_t pmem_end)
: trace_ranges(std::move(trace_ranges)) { : pmem_start(pmem_start), pmem_end(pmem_end) {
if (!std::filesystem::exists(filepath)) if (!std::filesystem::exists(filepath))
throw std::runtime_error("Memory file not found"); throw std::runtime_error("Memory file not found");
if (is_binary) { if (is_binary) {
@ -62,54 +63,79 @@ public:
} }
} }
} }
const T &operator[](std::size_t addr) { return this->read(addr); } const word_t &operator[](std::size_t addr) { return this->read(addr); }
/** void transfer(paddr_t addr, uint8_t data[], size_t len, bool is_write) {
* Always reads and returns 4 bytes from the address raddr & ~0x3u. if (is_write) {
*/ // memcpy(guest_to_host(addr), data, len);
T read(paddr_t raddr) { size_t offset = (addr - pmem_start);
// printf("raddr: 0x%x\n", raddr); std::copy(data, data + len, &mem[offset]);
return *(word_t *)guest_to_host(raddr); } else {
// memcpy(data, guest_to_host(addr), len);
size_t offset = (addr - pmem_start);
std::copy(&mem[offset], &mem[offset + len], data);
}
} }
/** bool in_pmem(paddr_t addr) const {
* Always writes to the 4 bytes at the address `waddr` & ~0x3u. return addr >= pmem_start && addr <= pmem_end;
* Each bit in `wmask` represents a mask for one byte in wdata. }
* For example, wmask = 0x3 means only the lowest 2 bytes are written, };
* and the other bytes in memory remain unchanged.
*/ template <typename Mem, typename DevMap> class MemoryMap {
void write(paddr_t waddr, T wdata, char wmask) { std::unique_ptr<Mem> ram;
std::unique_ptr<DevMap> devices;
const std::vector<std::array<uint64_t, 2>> &trace_ranges;
public:
MemoryMap(std::unique_ptr<Mem> &&ram, std::unique_ptr<DevMap> &&devices,
const std::vector<std::array<uint64_t, 2>> &trace_ranges)
: ram(std::move(ram)), devices(std::move(devices)),
trace_ranges(trace_ranges) {}
void write(paddr_t waddr, word_t wdata, char wmask) {
// printf("waddr: 0x%x\n", waddr); // printf("waddr: 0x%x\n", waddr);
uint8_t *p_data = (uint8_t *)&wdata; size_t len = (wmask & 1) + ((wmask & 2) >> 1) + ((wmask & 4) >> 2) +
while (wmask & 0x1) { ((wmask & 8) >> 3);
memcpy(guest_to_host(waddr), p_data, 1); if (ram->in_pmem(waddr)) {
waddr++; ram->transfer(waddr, (uint8_t *)&wdata, len, true);
p_data++; } else if (devices->handle(waddr, (uint8_t *)&wdata, len, true)) {
wmask >>= 1;
} }
} }
void *guest_to_host(std::size_t addr) { word_t read(paddr_t raddr) const {
extern bool g_skip_memcheck; word_t res = 0;
if (g_skip_memcheck) { // printf("raddr: 0x%x, in_pmem: %d\n", raddr, ram->in_pmem(raddr));
return mem.data(); if (ram->in_pmem(raddr)) {
ram->transfer(raddr, (uint8_t *)&res, 4, false);
} else if (devices->handle(raddr, (uint8_t *)&res, 4, false)) {
} }
if (addr < 0x80000000 || addr > 0x87ffffff) { return res;
std::cerr << std::hex << "ACCESS " << addr << std::dec << std::endl;
throw std::runtime_error("Invalid memory access");
}
// Linear mapping
return (uint8_t *)(mem.data() + (addr >> 2) - 0x20000000) + (addr & 0x3);
} }
void copy_to(paddr_t addr, uint8_t *buf, size_t len) const {
if (ram->in_pmem(addr)) {
ram->transfer(addr, buf, len, false);
} else {
std::cerr << "Not in pmem" << std::endl;
}
}
void copy_from(paddr_t addr, const uint8_t *buf, size_t len) {
if (ram->in_pmem(addr)) {
ram->transfer(addr, buf, len, true);
} else {
std::cerr << "Not in pmem" << std::endl;
}
}
void *get_pmem() { return ram->mem.data(); }
void trace(paddr_t addr, bool is_read, word_t pc = 0, word_t value = 0) { void trace(paddr_t addr, bool is_read, word_t pc = 0, word_t value = 0) {
for (auto &r : trace_ranges) { for (auto &r : trace_ranges) {
if (r[0] <= addr && r[1] >= addr) { if (r[0] <= addr && r[1] >= addr) {
std::stringstream os; std::stringstream os;
os << std::hex;
if (pc != 0) if (pc != 0)
os << "0x" << pc << " "; os << "0x" << std::hex << pc << " ";
if (is_read) if (is_read)
os << "[R] "; os << "[R] "
<< "0x" << addr << ": 0x" << this->read(addr);
else else
os << "[W] " << value << " -> "; os << "[W] " << value << " -> "
os << "0x" << addr << std::dec << std::endl; << "0x" << addr;
os << std::dec << std::endl;
std::cout << os.rdbuf(); std::cout << os.rdbuf();
break; break;
} }

View file

@ -9,7 +9,7 @@
struct Config { struct Config {
std::filesystem::path memory_file; std::filesystem::path memory_file;
uint64_t max_sim_time = 0; bool interactive{false};
bool memory_file_binary = {true}; bool memory_file_binary = {true};
bool do_mtrace{false}; bool do_mtrace{false};
std::vector<std::array<std::size_t, 2>> mtrace_ranges{ std::vector<std::array<std::size_t, 2>> mtrace_ranges{
@ -21,4 +21,4 @@ struct Config {
extern Config config; extern Config config;
#endif #endif

View file

@ -37,6 +37,7 @@ template <typename R, size_t nr_reg> struct CPUStateBase {
/* This does not update the register!!! */ /* This does not update the register!!! */
R at(std::string name) { R at(std::string name) {
// FIXME: Using this to get pc seems broken
return name == "pc" ? pc : reg[regs_by_name.at(name)]; return name == "pc" ? pc : reg[regs_by_name.at(name)];
} }
@ -154,4 +155,4 @@ struct RefTrmInterface : TrmInterface {
void print(std::ostream &os) const override { os << *(CPUState *)cpu_state; } void print(std::ostream &os) const override { os << *(CPUState *)cpu_state; }
}; };
#endif #endif

View file

@ -1,3 +1,3 @@
if (ENABLE_SDB) if(ENABLE_SDB)
add_subdirectory(sdb) add_subdirectory(sdb)
endif() endif()

View file

@ -5,14 +5,30 @@ find_package(LLVM CONFIG REQUIRED)
set(PARSER_DIR "${CMAKE_CURRENT_BINARY_DIR}") set(PARSER_DIR "${CMAKE_CURRENT_BINARY_DIR}")
set(LEXER_OUT "${PARSER_DIR}/lexer.c") set(LEXER_OUT "${PARSER_DIR}/lexer.c")
set(PARSER_OUT "${PARSER_DIR}/parser.c") set(PARSER_OUT "${PARSER_DIR}/parser.c")
flex_target(LEXER addrexp.l "${LEXER_OUT}" DEFINES_FILE "${PARSER_DIR}/addrexp_lex.h") flex_target(LEXER addrexp.l "${LEXER_OUT}"
bison_target(PARSER addrexp.y "${PARSER_OUT}" DEFINES_FILE "${PARSER_DIR}/addrexp.h") DEFINES_FILE "${PARSER_DIR}/addrexp_lex.h")
bison_target(PARSER addrexp.y "${PARSER_OUT}"
DEFINES_FILE "${PARSER_DIR}/addrexp.h")
add_flex_bison_dependency(LEXER PARSER) add_flex_bison_dependency(LEXER PARSER)
add_library(sdb OBJECT sdb.cpp console.cpp disasm.cpp "${LEXER_OUT}" "${PARSER_OUT}") add_library(sdb OBJECT sdb.cpp console.cpp disasm.cpp "${LEXER_OUT}"
llvm_map_components_to_libnames(LLVM_LIBS core target asmparser riscvasmparser riscvdesc riscvdisassembler riscvinfo riscvtargetmca) "${PARSER_OUT}")
llvm_map_components_to_libnames(
LLVM_LIBS
core
target
asmparser
riscvasmparser
riscvdesc
riscvdisassembler
riscvinfo
riscvtargetmca)
target_link_libraries(sdb PUBLIC ${LLVM_LIBS}) target_link_libraries(sdb PUBLIC ${LLVM_LIBS})
target_link_libraries(sdb PRIVATE ${Readline_LIBRARY}) target_link_libraries(sdb PRIVATE ${Readline_LIBRARY})
target_include_directories(sdb PRIVATE ${PARSER_DIR})
target_include_directories(sdb PRIVATE ${Readline_INCLUDE_DIR}) target_include_directories(
sdb
PRIVATE ${PARSER_DIR} ${Readline_INCLUDE_DIR}
PUBLIC ${CMAKE_SOURCE_DIR}/include)
target_include_directories(sdb PUBLIC include) target_include_directories(sdb PUBLIC include)

View file

@ -96,4 +96,4 @@ public:
}; };
} // namespace SDB } // namespace SDB
#endif #endif

View file

@ -3,7 +3,6 @@
#include <cstdint> #include <cstdint>
#include <disasm.hpp> #include <disasm.hpp>
#include <sdb.hpp> #include <sdb.hpp>
#include <stdexcept>
#include <trm_interface.hpp> #include <trm_interface.hpp>
#include <types.h> #include <types.h>
extern "C" { extern "C" {