/*******************************************************************************
 * Copyright (C) 2017 - 2023 MINRES Technologies GmbH
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * Contributors:
 *       eyck@minres.com - initial implementation
 ******************************************************************************/

#ifndef _RISCV_HART_MSU_VP_H
#define _RISCV_HART_MSU_VP_H

#include "iss/vm_if.h"
#include "iss/vm_types.h"
#include "riscv_hart_common.h"
#include "util/logging.h"
#include <algorithm>
#include <cstdint>
#include <elfio/elf_types.hpp>
#include <limits>
#ifndef FMT_HEADER_ONLY
#define FMT_HEADER_ONLY
#endif
#include <array>
#include <elfio/elfio.hpp>
#include <fmt/format.h>
#include <type_traits>
#include <unordered_map>
#include <util/bit_field.h>

namespace iss {
namespace arch {

template <typename BASE> class riscv_hart_msu_vp : public riscv_hart_common<BASE> {
public:
    using core = BASE;
    using base = riscv_hart_common<BASE>;
    using this_class = riscv_hart_msu_vp<BASE>;
    using phys_addr_t = typename core::phys_addr_t;
    using reg_t = typename core::reg_t;
    using addr_t = typename core::addr_t;

    static constexpr reg_t get_misa() {
        return (sizeof(reg_t) == 4 ? (1UL << 30) : (2ULL << 62)) | ISA_I | ISA_M | ISA_A | ISA_U | ISA_S | ISA_M;
    }

    static constexpr reg_t get_mstatus_mask(unsigned priv_lvl) {
        if(sizeof(reg_t) == 4) {
#if __cplusplus < 201402L
            return priv_lvl == PRIV_U ? 0x80000011UL : priv_lvl == PRIV_S ? 0x800de133UL : 0x807ff9ddUL;
#else
            switch(priv_lvl) {
            case PRIV_U:
                return 0x80000011UL; // 0b1000 0000 0000 0000 0000 0000 0001 0001
            case PRIV_S:
                return 0x800de133UL; // 0b1000 0000 0000 1101 1110 0001 0011 0011
            default:
                return 0x807ff9ddUL; // 0b1000 0000 0111 1111 1111 1001 1011 1011
            }
#endif
        } else if(sizeof(reg_t) == 8) {
            switch(priv_lvl) {
            case PRIV_U:
                return 0x8000000f00000011ULL; // 0b1...0 1111 0000 0000 0111 1111 1111 1001 1011 1011
            case PRIV_S:
                return 0x8000000f000de133ULL; // 0b1...0 0011 0000 0000 0000 1101 1110 0001 0011 0011
            default:
                return 0x8000000f007ff9ddULL; // 0b1...0 1111 0000 0000 0111 1111 1111 1001 1011 1011
            }
        } else
            assert(false && "Unsupported XLEN value");
    }

    template <typename T_ = reg_t, std::enable_if_t<std::is_same<T_, uint32_t>::value>* = nullptr>
    void write_mstatus(T_ val, unsigned priv_lvl) {
        reg_t old_val = mstatus;
        auto mask = get_mstatus_mask(priv_lvl);
        auto new_val = (old_val & ~mask) | (val & mask);
        this->state.mstatus = new_val;
    }

    template <typename T_ = reg_t, std::enable_if_t<std::is_same<T_, uint64_t>::value>* = nullptr>
    void write_mstatus(T_ val, unsigned priv_lvl) {
        reg_t old_val = mstatus;
        auto mask = get_mstatus_mask(priv_lvl);
        auto new_val = (old_val & ~mask) | (val & mask);
        if((new_val & this->state.mstatus.SXL.Mask) == 0) {
            new_val |= old_val & this->state.mstatus.SXL.Mask;
        }
        if((new_val & this->state.mstatus.UXL.Mask) == 0) {
            new_val |= old_val & this->state.mstatus.UXL.Mask;
        }
        this->state.mstatus = new_val;
    }
    reg_t satp;

    static inline vm_info decode_vm_info(uint32_t state, uint32_t sptbr) {
        if(state == PRIV_M)
            return {0, 0, 0, 0};
        if(state <= PRIV_S)
            switch(bit_sub<31, 1>(sptbr)) {
            case 0:
                return {0, 0, 0, 0}; // off
            case 1:
                return {2, 10, 4, bit_sub<0, 22>(sptbr) << PGSHIFT}; // SV32
            default:
                abort();
            }
        abort();
        return {0, 0, 0, 0}; // dummy
    }

    static inline vm_info decode_vm_info(uint32_t state, uint64_t sptbr) {
        if(state == PRIV_M)
            return {0, 0, 0, 0};
        if(state <= PRIV_S)
            switch(bit_sub<60, 4>(sptbr)) {
            case 0:
                return {0, 0, 0, 0}; // off
            case 8:
                return {3, 9, 8, bit_sub<0, 44>(sptbr) << PGSHIFT}; // SV39
            case 9:
                return {4, 9, 8, bit_sub<0, 44>(sptbr) << PGSHIFT}; // SV48
            case 10:
                return {5, 9, 8, bit_sub<0, 44>(sptbr) << PGSHIFT}; // SV57
            case 11:
                return {6, 9, 8, bit_sub<0, 44>(sptbr) << PGSHIFT}; // SV64
            default:
                abort();
            }
        abort();
        return {0, 0, 0, 0}; // dummy
    }

    const typename core::reg_t PGSIZE = 1 << PGSHIFT;
    const typename core::reg_t PGMASK = PGSIZE - 1;

    constexpr reg_t get_irq_mask(size_t mode) {
        std::array<const reg_t, 4> m = {{
            0b000100010001, // U mode
            0b001100110011, // S mode
            0,
            0b101110111011 // M mode
        }};
        return m[mode];
    }

    riscv_hart_msu_vp();

    virtual ~riscv_hart_msu_vp() = default;

    void reset(uint64_t address) override;

    phys_addr_t virt2phys(const iss::addr_t& addr) override;

    iss::status read(const address_type type, const access_type access, const uint32_t space, const uint64_t addr, const unsigned length,
                     uint8_t* const data);
    iss::status write(const address_type type, const access_type access, const uint32_t space, const uint64_t addr, const unsigned length,
                      const uint8_t* const data);

    uint64_t enter_trap(uint64_t flags) override { return riscv_hart_msu_vp::enter_trap(flags, this->fault_data, this->fault_data); }
    uint64_t enter_trap(uint64_t flags, uint64_t addr, uint64_t instr) override;
    uint64_t leave_trap(uint64_t flags) override;
    void wait_until(uint64_t flags) override;

    void set_csr(unsigned addr, reg_t val) { this->csr[addr & this->csr.page_addr_mask] = val; }

    void set_irq_num(unsigned i) { this->mcause_max_irq = 1 << util::ilog2(i); }

protected:
    virtual iss::status read_mem(phys_addr_t addr, unsigned length, uint8_t* const data);
    virtual iss::status write_mem(phys_addr_t addr, unsigned length, const uint8_t* const data);

    hart_state<reg_t> state;

    using mem_type = util::sparse_array<uint8_t, 1ULL << 32>;
    mem_type mem;
    void update_vm_info();
    std::unordered_map<reg_t, uint64_t> ptw;
    std::unordered_map<uint64_t, uint8_t> atomic_reservation;

    std::vector<uint8_t> tcm;

    iss::status read_status(unsigned addr, reg_t& val);
    iss::status write_status(unsigned addr, reg_t val);
    iss::status write_cause(unsigned addr, reg_t val);
    iss::status read_ie(unsigned addr, reg_t& val);
    iss::status write_ie(unsigned addr, reg_t val);
    iss::status read_ip(unsigned addr, reg_t& val);
    iss::status write_ideleg(unsigned addr, reg_t val);
    iss::status write_edeleg(unsigned addr, reg_t val);
    iss::status read_satp(unsigned addr, reg_t& val);
    iss::status write_satp(unsigned addr, reg_t val);

    virtual iss::status read_custom_csr_reg(unsigned addr, reg_t& val) { return iss::status::Err; };
    virtual iss::status write_custom_csr_reg(unsigned addr, reg_t val) { return iss::status::Err; };

    void register_custom_csr_rd(unsigned addr) { this->csr_rd_cb[addr] = MK_CSR_RD_CB(read_custom_csr_reg); }
    void register_custom_csr_wr(unsigned addr) { this->csr_wr_cb[addr] = MK_CSR_WR_CB(write_custom_csr_reg); }

    reg_t mhartid_reg{0x0};

    void check_interrupt();
};

template <typename BASE>
riscv_hart_msu_vp<BASE>::riscv_hart_msu_vp()
: state() {
    this->mmu = true;
    this->rd_func = util::delegate<arch_if::rd_func_sig>::from<this_class, &this_class::read>(this);
    this->rd_func = util::delegate<arch_if::wr_func_sig>::from<this_class, &this_class::write>(this);
    // common regs
    const std::array<unsigned, 17> rwaddrs{{mepc, mtvec, mscratch, mtval, mscratch, sepc, stvec, sscratch, scause, stval, sscratch, uepc,
                                            utvec, uscratch, ucause, utval, uscratch}};
    for(auto addr : rwaddrs) {
        this->csr_rd_cb[addr] = MK_CSR_RD_CB(read_plain);
        this->csr_wr_cb[addr] = MK_CSR_WR_CB(write_plain);
    }
    // special handling & overrides
    this->csr_rd_cb[mstatus] = MK_CSR_RD_CB(read_status);
    this->csr_wr_cb[mstatus] = MK_CSR_WR_CB(write_status);
    this->csr_wr_cb[mcause] = MK_CSR_WR_CB(write_cause);
    this->csr_rd_cb[sstatus] = MK_CSR_RD_CB(read_status);
    this->csr_wr_cb[sstatus] = MK_CSR_WR_CB(write_status);
    this->csr_wr_cb[scause] = MK_CSR_WR_CB(write_cause);
    this->csr_rd_cb[ustatus] = MK_CSR_RD_CB(read_status);
    this->csr_wr_cb[ustatus] = MK_CSR_WR_CB(write_status);
    this->csr_wr_cb[ucause] = MK_CSR_WR_CB(write_cause);
    this->csr_rd_cb[mtvec] = MK_CSR_RD_CB(read_tvec);
    this->csr_rd_cb[stvec] = MK_CSR_RD_CB(read_tvec);
    this->csr_rd_cb[utvec] = MK_CSR_RD_CB(read_tvec);
    this->csr_rd_cb[mip] = MK_CSR_RD_CB(read_ip);
    this->csr_wr_cb[mip] = MK_CSR_WR_CB(write_null);
    this->csr_rd_cb[sip] = MK_CSR_RD_CB(read_ip);
    this->csr_wr_cb[sip] = MK_CSR_WR_CB(write_null);
    this->csr_rd_cb[uip] = MK_CSR_RD_CB(read_ip);
    this->csr_wr_cb[uip] = MK_CSR_WR_CB(write_null);
    this->csr_rd_cb[mie] = MK_CSR_RD_CB(read_ie);
    this->csr_wr_cb[mie] = MK_CSR_WR_CB(write_ie);
    this->csr_rd_cb[sie] = MK_CSR_RD_CB(read_ie);
    this->csr_wr_cb[sie] = MK_CSR_WR_CB(write_ie);
    this->csr_rd_cb[uie] = MK_CSR_RD_CB(read_ie);
    this->csr_wr_cb[uie] = MK_CSR_WR_CB(write_ie);
    this->csr_rd_cb[mcounteren] = MK_CSR_RD_CB(read_null);
    this->csr_wr_cb[mcounteren] = MK_CSR_WR_CB(write_null);
    this->csr_wr_cb[misa] = MK_CSR_WR_CB(write_null);
    this->csr_wr_cb[mvendorid] = MK_CSR_WR_CB(write_null);
    this->csr_wr_cb[marchid] = MK_CSR_WR_CB(write_null);
    this->csr_wr_cb[mimpid] = MK_CSR_WR_CB(write_null);
    this->csr_rd_cb[satp] = MK_CSR_RD_CB(read_satp);
    this->csr_wr_cb[satp] = MK_CSR_WR_CB(write_satp);
}

template <typename BASE>
iss::status riscv_hart_msu_vp<BASE>::read(const address_type type, const access_type access, const uint32_t space, const uint64_t addr,
                                          const unsigned length, uint8_t* const data) {
#ifndef NDEBUG
    if(access && iss::access_type::DEBUG) {
        CPPLOG(TRACEALL) << "debug read of " << length << " bytes @addr 0x" << std::hex << addr;
    } else if(access && iss::access_type::FETCH) {
        CPPLOG(TRACEALL) << "fetch of " << length << " bytes  @addr 0x" << std::hex << addr;
    } else {
        CPPLOG(TRACE) << "read of " << length << " bytes  @addr 0x" << std::hex << addr;
    }
#endif
    try {
        switch(space) {
        case traits<BASE>::MEM: {
            auto alignment = is_fetch(access) ? (this->has_compressed() ? 2 : 4) : std::min<unsigned>(length, sizeof(reg_t));
            if(unlikely(is_fetch(access) && (addr & (alignment - 1)))) {
                this->fault_data = addr;
                if(access && iss::access_type::DEBUG)
                    throw trap_access(0, addr);
                this->reg.trap_state = (1 << 31); // issue trap 0
                return iss::Err;
            }
            try {
                if(!is_debug(access) && (addr & (alignment - 1))) {
                    this->reg.trap_state = 1 << 31 | 4 << 16;
                    this->fault_data = addr;
                    return iss::Err;
                }
                if(unlikely((addr & ~PGMASK) != ((addr + length - 1) & ~PGMASK))) { // we may cross a page boundary
                    vm_info vm = decode_vm_info(this->reg.PRIV, satp);
                    if(vm.levels != 0) { // VM is active
                        auto split_addr = (addr + length) & ~PGMASK;
                        auto len1 = split_addr - addr;
                        auto res = read(type, access, space, addr, len1, data);
                        if(res == iss::Ok)
                            res = read(type, access, space, split_addr, length - len1, data + len1);
                        return res;
                    }
                }
                auto res = read_mem(virt2phys(iss::addr_t{access, type, space, addr}), length, data);
                if(unlikely(res != iss::Ok && (access & access_type::DEBUG) == 0)) {
                    this->reg.trap_state = (1 << 31) | (5 << 16); // issue trap 5 (load access fault
                    this->fault_data = addr;
                }
                return res;
            } catch(trap_access& ta) {
                if((access & access_type::DEBUG) == 0) {
                    this->reg.trap_state = (1UL << 31) | ta.id;
                    this->fault_data = ta.addr;
                }
                return iss::Err;
            }
        } break;
        case traits<BASE>::CSR: {
            if(length != sizeof(reg_t))
                return iss::Err;
            return this->read_csr(addr, *reinterpret_cast<reg_t* const>(data));
        } break;
        case traits<BASE>::FENCE: {
            if((addr + length) > mem.size())
                return iss::Err;
            switch(addr) {
            case 2:   // SFENCE:VMA lower
            case 3: { // SFENCE:VMA upper
                auto tvm = state.mstatus.TVM;
                if(this->reg.PRIV == PRIV_S & tvm != 0) {
                    this->reg.trap_state = (1 << 31) | (2 << 16);
                    this->fault_data = this->reg.PC;
                    return iss::Err;
                }
                return iss::Ok;
            }
            }
        } break;
        case traits<BASE>::RES: {
            auto it = atomic_reservation.find(addr);
            if(it != atomic_reservation.end() && it->second != 0) {
                memset(data, 0xff, length);
                atomic_reservation.erase(addr);
            } else
                memset(data, 0, length);
        } break;
        default:
            return iss::Err; // assert("Not supported");
        }
        return iss::Ok;
    } catch(trap_access& ta) {
        if((access & access_type::DEBUG) == 0) {
            this->reg.trap_state = (1UL << 31) | ta.id;
            this->fault_data = ta.addr;
        }
        return iss::Err;
    }
}

template <typename BASE>
iss::status riscv_hart_msu_vp<BASE>::write(const address_type type, const access_type access, const uint32_t space, const uint64_t addr,
                                           const unsigned length, const uint8_t* const data) {
#ifndef NDEBUG
    const char* prefix = (access && iss::access_type::DEBUG) ? "debug " : "";
    switch(length) {
    case 8:
        CPPLOG(TRACE) << prefix << "write of " << length << " bytes (0x" << std::hex << *(uint64_t*)&data[0] << std::dec << ") @addr 0x"
                      << std::hex << addr;
        break;
    case 4:
        CPPLOG(TRACE) << prefix << "write of " << length << " bytes (0x" << std::hex << *(uint32_t*)&data[0] << std::dec << ") @addr 0x"
                      << std::hex << addr;
        break;
    case 2:
        CPPLOG(TRACE) << prefix << "write of " << length << " bytes (0x" << std::hex << *(uint16_t*)&data[0] << std::dec << ") @addr 0x"
                      << std::hex << addr;
        break;
    case 1:
        CPPLOG(TRACE) << prefix << "write of " << length << " bytes (0x" << std::hex << (uint16_t)data[0] << std::dec << ") @addr 0x"
                      << std::hex << addr;
        break;
    default:
        CPPLOG(TRACE) << prefix << "write of " << length << " bytes @addr " << addr;
    }
#endif
    try {
        switch(space) {
        case traits<BASE>::MEM: {
            if(unlikely((access && iss::access_type::FETCH) && (addr & 0x1) == 1)) {
                this->fault_data = addr;
                if(access && iss::access_type::DEBUG)
                    throw trap_access(0, addr);
                this->reg.trap_state = (1 << 31); // issue trap 0
                return iss::Err;
            }
            phys_addr_t paddr = virt2phys(iss::addr_t{access, type, space, addr});
            try {
                // TODO: There is no check for alignment
                if(unlikely((addr & ~PGMASK) != ((addr + length - 1) & ~PGMASK))) { // we may cross a page boundary
                    vm_info vm = decode_vm_info(this->reg.PRIV, satp);
                    if(vm.levels != 0) { // VM is active
                        auto split_addr = (addr + length) & ~PGMASK;
                        auto len1 = split_addr - addr;
                        auto res = write(type, access, space, addr, len1, data);
                        if(res == iss::Ok)
                            res = write(type, access, space, split_addr, length - len1, data + len1);
                        return res;
                    }
                }
                auto res = write_mem(paddr, length, data);
                if(unlikely(res != iss::Ok && (access & access_type::DEBUG) == 0)) {
                    this->reg.trap_state = (1UL << 31) | (7UL << 16); // issue trap 7 (Store/AMO access fault)
                    this->fault_data = addr;
                }
                return res;
            } catch(trap_access& ta) {
                this->reg.trap_state = (1UL << 31) | ta.id;
                this->fault_data = ta.addr;
                return iss::Err;
            }
        } break;
        case traits<BASE>::CSR: {
            if(length != sizeof(reg_t))
                return iss::Err;
            return this->write_csr(addr, *reinterpret_cast<const reg_t*>(data));
        } break;
        case traits<BASE>::FENCE: {
            if((addr + length) > mem.size())
                return iss::Err;
            switch(addr) {
            case 2:
            case 3: {
                ptw.clear();
                auto tvm = state.mstatus.TVM;
                if(this->reg.PRIV == PRIV_S & tvm != 0) {
                    this->reg.trap_state = (1 << 31) | (2 << 16);
                    this->fault_data = this->reg.PC;
                    return iss::Err;
                }
                return iss::Ok;
            }
            }
        } break;
        case traits<BASE>::RES: {
            atomic_reservation[addr] = data[0];
        } break;
        default:
            return iss::Err;
        }
        return iss::Ok;
    } catch(trap_access& ta) {
        if((access & access_type::DEBUG) == 0) {
            this->reg.trap_state = (1UL << 31) | ta.id;
            this->fault_data = ta.addr;
        }
        return iss::Err;
    }
}

template <typename BASE> iss::status riscv_hart_msu_vp<BASE>::read_status(unsigned addr, reg_t& val) {
    auto req_priv_lvl = (addr >> 8) & 0x3;
    val = state.mstatus & get_mstatus_mask(req_priv_lvl);
    return iss::Ok;
}

template <typename BASE> iss::status riscv_hart_msu_vp<BASE>::write_status(unsigned addr, reg_t val) {
    auto req_priv_lvl = (addr >> 8) & 0x3;
    write_mstatus(val, req_priv_lvl);
    check_interrupt();
    update_vm_info();
    return iss::Ok;
}

template <typename BASE> iss::status riscv_hart_msu_vp<BASE>::write_cause(unsigned addr, reg_t val) {
    this->csr[addr] = val & ((1UL << (traits<BASE>::XLEN - 1)) | 0xf); // TODO: make exception code size configurable
    return iss::Ok;
}

template <typename BASE> iss::status riscv_hart_msu_vp<BASE>::read_ie(unsigned addr, reg_t& val) {
    val = this->csr[mie];
    if(addr < mie)
        val &= this->csr[mideleg];
    if(addr < sie)
        val &= this->csr[sideleg];
    return iss::Ok;
}

template <typename BASE> iss::status riscv_hart_msu_vp<BASE>::write_ie(unsigned addr, reg_t val) {
    auto req_priv_lvl = (addr >> 8) & 0x3;
    auto mask = get_irq_mask(req_priv_lvl);
    this->csr[mie] = (this->csr[mie] & ~mask) | (val & mask);
    check_interrupt();
    return iss::Ok;
}

template <typename BASE> iss::status riscv_hart_msu_vp<BASE>::read_ip(unsigned addr, reg_t& val) {
    val = this->csr[mip];
    if(addr < mip)
        val &= this->csr[mideleg];
    if(addr < sip)
        val &= this->csr[sideleg];
    return iss::Ok;
}

template <typename BASE> iss::status riscv_hart_msu_vp<BASE>::read_satp(unsigned addr, reg_t& val) {
    reg_t tvm = state.mstatus.TVM;
    if(this->reg.PRIV == PRIV_S & tvm != 0) {
        this->reg.trap_state = (1 << 31) | (2 << 16);
        this->fault_data = this->reg.PC;
        return iss::Err;
    }
    val = satp;
    return iss::Ok;
}

template <typename BASE> iss::status riscv_hart_msu_vp<BASE>::write_satp(unsigned addr, reg_t val) {
    reg_t tvm = state.mstatus.TVM;
    if(this->reg.PRIV == PRIV_S & tvm != 0) {
        this->reg.trap_state = (1 << 31) | (2 << 16);
        this->fault_data = this->reg.PC;
        return iss::Err;
    }
    satp = val;
    update_vm_info();
    return iss::Ok;
}
template <typename BASE> iss::status riscv_hart_msu_vp<BASE>::read_mem(phys_addr_t paddr, unsigned length, uint8_t* const data) {
    switch(paddr.val) {
    default: {
        for(auto offs = 0U; offs < length; ++offs) {
            *(data + offs) = mem[(paddr.val + offs) % mem.size()];
        }
    }
    }
    return iss::Ok;
}

template <typename BASE> iss::status riscv_hart_msu_vp<BASE>::write_mem(phys_addr_t paddr, unsigned length, const uint8_t* const data) {
    mem_type::page_type& p = mem(paddr.val / mem.page_size);
    std::copy(data, data + length, p.data() + (paddr.val & mem.page_addr_mask));
    // tohost handling in case of riscv-test
    // according to https://github.com/riscv-software-src/riscv-isa-sim/issues/364#issuecomment-607657754:
    if(paddr.access && iss::access_type::FUNC) {
        if(paddr.val == this->tohost) {
            reg_t cur_data = *reinterpret_cast<const reg_t*>(data);
            // Extract Device (bits 63:56)
            uint8_t device = traits<BASE>::XLEN == 32
                                 ? *reinterpret_cast<uint32_t*>(p.data() + ((this->tohost + 4) & mem.page_addr_mask)) >> 24
                                 : (cur_data >> 56) & 0xFF;
            // Extract Command (bits 55:48)
            uint8_t command = traits<BASE>::XLEN == 32
                                  ? *reinterpret_cast<uint32_t*>(p.data() + ((this->tohost + 4) & mem.page_addr_mask)) >> 16
                                  : (cur_data >> 48) & 0xFF;
            // Extract payload (bits 47:0)
            uint64_t payload_addr = cur_data & 0xFFFFFFFFFFFFULL;
            if(payload_addr & 1) {
                CPPLOG(FATAL) << "tohost value is 0x" << std::hex << payload_addr << std::dec << " (" << payload_addr
                              << "), stopping simulation";
                this->reg.trap_state = std::numeric_limits<uint32_t>::max();
                this->interrupt_sim = payload_addr;
                return iss::Ok;
            } else if(device == 0 && command == 0) {
                std::array<uint64_t, 8> loaded_payload;
                if(read(address_type::PHYSICAL, access_type::DEBUG_READ, traits<BASE>::MEM, payload_addr, 8 * sizeof(uint64_t),
                        reinterpret_cast<uint8_t*>(loaded_payload.data())) == iss::Err)
                    CPPLOG(ERR) << "Syscall read went wrong";
                uint64_t syscall_num = loaded_payload.at(0);
                if(syscall_num == 64) { // SYS_WRITE
                    return this->execute_sys_write(this, loaded_payload, traits<BASE>::MEM);
                } else {
                    CPPLOG(ERR) << "tohost syscall with number 0x" << std::hex << syscall_num << std::dec << " (" << syscall_num
                                << ") not implemented";
                    this->reg.trap_state = std::numeric_limits<uint32_t>::max();
                    this->interrupt_sim = payload_addr;
                    return iss::Ok;
                }
            } else {
                CPPLOG(ERR) << "tohost functionality not implemented for device " << device << " and command " << command;
                this->reg.trap_state = std::numeric_limits<uint32_t>::max();
                this->interrupt_sim = payload_addr;
                return iss::Ok;
            }
        }
        if((traits<BASE>::XLEN == 32 && paddr.val == this->fromhost + 4) || (traits<BASE>::XLEN == 64 && paddr.val == this->fromhost)) {
            uint64_t fhostvar = *reinterpret_cast<uint64_t*>(p.data() + (this->fromhost & mem.page_addr_mask));
            *reinterpret_cast<uint64_t*>(p.data() + (this->tohost & mem.page_addr_mask)) = fhostvar;
        }
    }
    return iss::Ok;
}

template <typename BASE> inline void riscv_hart_msu_vp<BASE>::reset(uint64_t address) {
    BASE::reset(address);
    state.mstatus = hart_state<reg_t>::mstatus_reset_val;
    update_vm_info();
}

template <typename BASE> inline void riscv_hart_msu_vp<BASE>::update_vm_info() {
    this->vm[1] = decode_vm_info(this->reg.PRIV, satp);
    BASE::addr_mode[3] = BASE::addr_mode[2] = this->vm[1].is_active() ? iss::address_type::VIRTUAL : iss::address_type::PHYSICAL;
    if(state.mstatus.MPRV)
        this->vm[0] = decode_vm_info(state.mstatus.MPP, satp);
    else
        this->vm[0] = this->vm[1];
    BASE::addr_mode[1] = BASE::addr_mode[0] = this->vm[0].is_active() ? iss::address_type::VIRTUAL : iss::address_type::PHYSICAL;
    ptw.clear();
}

template <typename BASE> void riscv_hart_msu_vp<BASE>::check_interrupt() {
    auto status = state.mstatus;
    auto ip = this->csr[mip];
    auto ie = this->csr[mie];
    auto ideleg = this->csr[mideleg];
    // Multiple simultaneous interrupts and traps at the same privilege level are
    // handled in the following decreasing priority order:
    // external interrupts, software interrupts, timer interrupts, then finally
    // any synchronous traps.
    auto ena_irq = ip & ie;

    bool mie = state.mstatus.MIE;
    auto m_enabled = this->reg.PRIV < PRIV_M || (this->reg.PRIV == PRIV_M && mie);
    auto enabled_interrupts = m_enabled ? ena_irq & ~ideleg : 0;

    if(enabled_interrupts == 0) {
        auto sie = state.mstatus.SIE;
        auto s_enabled = this->reg.PRIV < PRIV_S || (this->reg.PRIV == PRIV_S && sie);
        enabled_interrupts = s_enabled ? ena_irq & ideleg : 0;
    }
    if(enabled_interrupts != 0) {
        int res = 0;
        while((enabled_interrupts & 1) == 0)
            enabled_interrupts >>= 1, res++;
        this->reg.pending_trap = res << 16 | 1; // 0x80 << 24 | (cause << 16) | trap_id
    }
}

template <typename BASE> typename riscv_hart_msu_vp<BASE>::phys_addr_t riscv_hart_msu_vp<BASE>::virt2phys(const iss::addr_t& addr) {
    const auto type = addr.access & iss::access_type::FUNC;
    auto it = ptw.find(addr.val >> PGSHIFT);
    if(it != ptw.end()) {
        const reg_t pte = it->second;
        const reg_t ad = PTE_A | (type == iss::access_type::WRITE) * PTE_D;
#ifdef RISCV_ENABLE_DIRTY
        // set accessed and possibly dirty bits.
        *(uint32_t*)ppte |= ad;
        return {addr.getAccessType(), addr.space, (pte & (~PGMASK)) | (addr.val & PGMASK)};
#else
        // take exception if access or possibly dirty bit is not set.
        if((pte & ad) == ad)
            return {addr.access, addr.space, (pte & (~PGMASK)) | (addr.val & PGMASK)};
        else
            ptw.erase(it); // throw an exception
#endif
    } else {
        uint32_t mode = type != iss::access_type::FETCH && state.mstatus.MPRV ? // MPRV
                            state.mstatus.MPP
                                                                              : this->reg.PRIV;

        const vm_info& vm = this->vm[static_cast<uint16_t>(type) / 2];

        const bool s_mode = mode == PRIV_S;
        const bool sum = state.mstatus.SUM;
        const bool mxr = state.mstatus.MXR;

        // verify bits xlen-1:va_bits-1 are all equal
        const int va_bits = PGSHIFT + vm.levels * vm.idxbits;
        const reg_t mask = (reg_t(1) << (traits<BASE>::XLEN > -(va_bits - 1))) - 1;
        const reg_t masked_msbs = (addr.val >> (va_bits - 1)) & mask;
        const int levels = (masked_msbs != 0 && masked_msbs != mask) ? 0 : vm.levels;

        reg_t base = vm.ptbase;
        for(int i = levels - 1; i >= 0; i--) {
            const int ptshift = i * vm.idxbits;
            const reg_t idx = (addr.val >> (PGSHIFT + ptshift)) & ((1 << vm.idxbits) - 1);

            // check that physical address of PTE is legal
            reg_t pte = 0;
            const uint8_t res = this->read(iss::address_type::PHYSICAL, addr.access, traits<BASE>::MEM, base + idx * vm.ptesize, vm.ptesize,
                                           (uint8_t*)&pte);
            if(res != 0)
                throw trap_load_access_fault(addr.val);
            const reg_t ppn = pte >> PTE_PPN_SHIFT;

            if(PTE_TABLE(pte)) { // next level of page table
                base = ppn << PGSHIFT;
            } else if((pte & PTE_U) ? s_mode && (type == iss::access_type::FETCH || !sum) : !s_mode) {
                break;
            } else if(!(pte & PTE_V) || (!(pte & PTE_R) && (pte & PTE_W))) {
                break;
            } else if(type == (type == iss::access_type::FETCH  ? !(pte & PTE_X)
                               : type == iss::access_type::READ ? !(pte & PTE_R) && !(mxr && (pte & PTE_X))
                                                                : !((pte & PTE_R) && (pte & PTE_W)))) {
                break;
            } else if((ppn & ((reg_t(1) << ptshift) - 1)) != 0) {
                break;
            } else {
                const reg_t ad = PTE_A | ((type == iss::access_type::WRITE) * PTE_D);
#ifdef RISCV_ENABLE_DIRTY
                // set accessed and possibly dirty bits.
                *(uint32_t*)ppte |= ad;
#else
                // take exception if access or possibly dirty bit is not set.
                if((pte & ad) != ad)
                    break;
#endif
                // for superpage mappings, make a fake leaf PTE for the TLB's benefit.
                const reg_t vpn = addr.val >> PGSHIFT;
                const reg_t value = (ppn | (vpn & ((reg_t(1) << ptshift) - 1))) << PGSHIFT;
                const reg_t offset = addr.val & PGMASK;
                ptw[vpn] = value | (pte & 0xff);
                return {addr.access, addr.space, value | offset};
            }
        }
    }
    switch(type) {
    case access_type::FETCH:
        this->fault_data = addr.val;
        throw trap_instruction_page_fault(addr.val);
    case access_type::READ:
        this->fault_data = addr.val;
        throw trap_load_page_fault(addr.val);
    case access_type::WRITE:
        this->fault_data = addr.val;
        throw trap_store_page_fault(addr.val);
    default:
        abort();
    }
}

template <typename BASE> uint64_t riscv_hart_msu_vp<BASE>::enter_trap(uint64_t flags, uint64_t addr, uint64_t instr) {
    auto cur_priv = this->reg.PRIV;
    // flags are ACTIVE[31:31], CAUSE[30:16], TRAPID[15:0]
    // calculate and write mcause val
    if(flags == std::numeric_limits<uint64_t>::max())
        flags = this->reg.trap_state;
    auto trap_id = bit_sub<0, 16>(flags);
    auto cause = bit_sub<16, 15>(flags);
    if(trap_id == 0 && cause == 11)
        cause = 0x8 + cur_priv; // adjust environment call cause
    // calculate effective privilege level
    auto new_priv = PRIV_M;
    if(trap_id == 0) { // exception
        if(cur_priv != PRIV_M && ((this->csr[medeleg] >> cause) & 0x1) != 0)
            new_priv = (this->csr[sedeleg] >> cause) & 0x1 ? PRIV_U : PRIV_S;
        // store ret addr in xepc register
        this->csr[uepc | (new_priv << 8)] = static_cast<reg_t>(addr); // store actual address instruction of exception
        /*
         * write mtval if new_priv=M_MODE, spec says:
         * When a hardware breakpoint is triggered, or an instruction-fetch, load,
         * or store address-misaligned,
         * access, or page-fault exception occurs, mtval is written with the
         * faulting effective address.
         */
        switch(cause) {
        case 0:
            this->csr[utval | (new_priv << 8)] = static_cast<reg_t>(addr);
            break;
        case 2:
            this->csr[utval | (new_priv << 8)] = (instr & 0x3) == 3 ? instr : instr & 0xffff;
            break;
        case 3:
            // TODO: implement debug mode behavior
            // csr[dpc] = addr;
            // csr[dcsr] = (csr[dcsr] & ~0x1c3) | (1<<6) | PRIV_M; //FIXME: cause should not be 4 (stepi)
            this->csr[utval | (new_priv << 8)] = addr;
            if(this->semihosting_cb) {
                // Check for semihosting call
                phys_addr_t p_addr(access_type::DEBUG_READ, traits<BASE>::MEM, addr - 4);
                std::array<uint8_t, 8> data;
                // check for SLLI_X0_X0_0X1F and SRAI_X0_X0_0X07
                this->read_mem(p_addr, 4, data.data());
                p_addr.val += 8;
                this->read_mem(p_addr, 4, data.data() + 4);

                const std::array<uint8_t, 8> ref_data = {0x13, 0x10, 0xf0, 0x01, 0x13, 0x50, 0x70, 0x40};
                if(data == ref_data) {
                    this->reg.NEXT_PC = addr + 8;

                    std::array<char, 32> buffer;
#if defined(_MSC_VER)
                    sprintf(buffer.data(), "0x%016llx", addr);
#else
                    sprintf(buffer.data(), "0x%016lx", addr);
#endif
                    CLOG(INFO, disass) << "Semihosting call at address " << buffer.data() << " occurred ";

                    this->semihosting_cb(this, &(this->reg.X10) /*a0*/, &(this->reg.X11) /*a1*/);
                    return this->reg.NEXT_PC;
                }
            }
            break;
        case 4:
        case 6:
        case 7:
            this->csr[utval | (new_priv << 8)] = this->fault_data;
            break;
        default:
            this->csr[utval | (new_priv << 8)] = 0;
        }
        this->fault_data = 0;
    } else {
        if(cur_priv != PRIV_M && ((this->csr[mideleg] >> cause) & 0x1) != 0)
            new_priv = (this->csr[sideleg] >> cause) & 0x1 ? PRIV_U : PRIV_S;
        this->csr[uepc | (new_priv << 8)] = this->reg.NEXT_PC; // store next address if interrupt
        this->reg.pending_trap = 0;
    }
    size_t adr = ucause | (new_priv << 8);
    this->csr[adr] = (trap_id << (traits<BASE>::XLEN - 1)) + cause;
    // update mstatus
    // xPP field of mstatus is written with the active privilege mode at the time
    // of the trap; the x PIE field of mstatus
    // is written with the value of the active interrupt-enable bit at the time of
    // the trap; and the x IE field of mstatus
    // is cleared
    // store the actual privilege level in yPP and store interrupt enable flags
    switch(new_priv) {
    case PRIV_M:
        state.mstatus.MPP = cur_priv;
        state.mstatus.MPIE = state.mstatus.MIE;
        state.mstatus.MIE = false;
        break;
    case PRIV_S:
        state.mstatus.SPP = cur_priv;
        state.mstatus.SPIE = state.mstatus.SIE;
        state.mstatus.SIE = false;
        break;
    case PRIV_U:
        state.mstatus.UPIE = state.mstatus.UIE;
        state.mstatus.UIE = false;
        break;
    default:
        break;
    }

    // get trap vector
    auto ivec = this->csr[utvec | (new_priv << 8)];
    // calculate addr// set NEXT_PC to trap addressess to jump to based on MODE
    // bits in mtvec
    this->reg.NEXT_PC = ivec & ~0x3UL;
    if((ivec & 0x1) == 1 && trap_id != 0)
        this->reg.NEXT_PC += 4 * cause;
    std::array<char, 32> buffer;
    sprintf(buffer.data(), "0x%016lx", addr);
    if((flags & 0xffffffff) != 0xffffffff)
        CLOG(INFO, disass) << (trap_id ? "Interrupt" : "Trap") << " with cause '"
                           << (trap_id ? this->irq_str[cause] : this->trap_str[cause]) << "' (" << cause << ")"
                           << " at address " << buffer.data() << " occurred, changing privilege level from " << this->lvl[cur_priv]
                           << " to " << this->lvl[new_priv];
    // reset trap state
    this->reg.PRIV = new_priv;
    this->reg.trap_state = 0;
    update_vm_info();
    return this->reg.NEXT_PC;
}

template <typename BASE> uint64_t riscv_hart_msu_vp<BASE>::leave_trap(uint64_t flags) {
    auto cur_priv = this->reg.PRIV;
    auto inst_priv = flags & 0x3;
    auto status = state.mstatus;

    auto tsr = state.mstatus.TSR;
    if(cur_priv == PRIV_S && inst_priv == PRIV_S && tsr != 0) {
        this->reg.trap_state = (1 << 31) | (2 << 16);
        this->fault_data = this->reg.PC;
        return this->reg.PC;
    }

    // pop the relevant lower-privilege interrupt enable and privilege mode stack
    // clear respective yIE
    switch(inst_priv) {
    case PRIV_M:
        this->reg.PRIV = state.mstatus.MPP;
        state.mstatus.MPP = 0; // clear mpp to U mode
        state.mstatus.MIE = state.mstatus.MPIE;
        state.mstatus.MPIE = 1;
        break;
    case PRIV_S:
        this->reg.PRIV = state.mstatus.SPP;
        state.mstatus.SPP = 0; // clear spp to U mode
        state.mstatus.SIE = state.mstatus.SPIE;
        state.mstatus.SPIE = 1;
        break;
    case PRIV_U:
        this->reg.PRIV = 0;
        state.mstatus.UIE = state.mstatus.UPIE;
        state.mstatus.UPIE = 1;
        break;
    }
    // sets the pc to the value stored in the x epc register.
    this->reg.NEXT_PC = this->csr[uepc | inst_priv << 8];
    CLOG(INFO, disass) << "Executing xRET , changing privilege level from " << this->lvl[cur_priv] << " to " << this->lvl[this->reg.PRIV];
    update_vm_info();
    check_interrupt();
    return this->reg.NEXT_PC;
}

template <typename BASE> void riscv_hart_msu_vp<BASE>::wait_until(uint64_t flags) {
    auto status = state.mstatus;
    auto tw = status.TW;
    if(this->reg.PRIV == PRIV_S && tw != 0) {
        this->reg.trap_state = (1 << 31) | (2 << 16);
        this->fault_data = this->reg.PC;
    }
}
} // namespace arch
} // namespace iss

#endif /* _RISCV_HART_MSU_VP_H */
