text
stringlengths 41
20k
|
---|
#include<systemc.h>
#include<vector>
#include "interfaces.hpp"
#include<nana/gui/widgets/listbox.hpp>
using std::vector;
class instruction_queue: public sc_module
{
public:
sc_port<read_if> in;
sc_port<write_if_f> out;
SC_HAS_PROCESS(instruction_queue);
instruction_queue(sc_module_name name, vector<string> inst_q, nana::listbox &instr);
void main();
private:
unsigned int pc;
vector<string> instruct_queue;
nana::listbox &instructions;
};
|
/*
* MIPS.hpp
*
* Created on: Jun 14, 2014
* Author: Pimenta
*/
#ifndef MIPS_HPP_
#define MIPS_HPP_
// lib
#include <systemc.h>
// local
#include "Context.hpp"
#include "Thread.hpp"
#include "readwrite_if.hpp"
struct Bitmap {
uint16_t unused0;
uint16_t magic_number;
uint32_t file_size;
uint32_t reserved;
uint32_t header_size;
uint32_t data_distance;
uint32_t width;
uint32_t height;
uint16_t planes;
uint16_t bpp;
uint32_t compression;
uint32_t data_size;
uint32_t horizontal_resolution;
uint32_t vertical_resolution;
uint32_t palette_size;
uint32_t important_colors;
void* buf;
};
SC_MODULE(MIPS) {
sc_in<bool> clk;
sc_port<readwrite_if> ioController;
uint32_t breg[32];
Bitmap bg;
SC_CTOR(MIPS) {
SC_METHOD(exec);
sensitive << clk.pos();
const char fn[] = "mandrill2.bmp";
const char mode[] = "rb";
breg[4] = (uint32_t)fn; breg[5] = (uint32_t)mode;
fileOpen();
breg[4] = breg[2];
breg[5] = (uint32_t)&bg.magic_number; breg[6] = 54;
fileRead();
bg.buf = malloc(bg.width*bg.height*bg.bpp/8);
breg[5] = (uint32_t)bg.buf; breg[6] = bg.width*bg.height*bg.bpp/8;
fileRead();
fileClose();
}
~MIPS() {
free(bg.buf);
}
void exec() {
uint32_t ioWord;
static bool inited = false;
if (!inited) {
inited = true;
ioController->read(0xFF400104, 4, &ioWord);
int w = ioWord >> 16, h = ioWord & 0xFFFF;
for (int y = 0; y < h && y < int(bg.height); y++) {
for (int x = 0; x < w && x < int(bg.width); x++) {
uint32_t rgbpixel;
if (bg.bpp == 8) {
uint8_t rawpixel = ((uint8_t*)bg.buf)[(bg.height - 1 - y)*bg.width + x];
rgbpixel = rawpixel | (rawpixel << 8) | (rawpixel << 16);
}
else
rgbpixel = ((uint32_t*)bg.buf)[(bg.height - 1 - y)*bg.width + x];
ioController->write(0xFF000000 + ((y*w + x) << 2), 4, &rgbpixel);
}
}
}
ioController->read(0xFF400000 + 'w', 4, &ioWord);
if (ioWord == 1) {
printf("Insert a string: ");
fflush(stdout);
std::string tmp;
ioController->read(0xFF400114, 4, &ioWord);
while (ioWord != '\r') {
tmp += char(ioWord);
printf("%c", char(ioWord));
fflush(stdout);
ioController->read(0xFF400114, 4, &ioWord);
}
printf("\nString inserted: %s\n", tmp.c_str());
fflush(stdout);
}
ioController->read(0xFF400102, 4, &ioWord);
if (ioWord)
exit();
breg[4] = 33;
sleep();
}
// ===========================================================================
// syscalls (code in v0)
// ===========================================================================
// v0: 2
// a0: 4
// a1: 5
// a2: 6
void exit() { // v0 = 10
sc_stop();
}
void fileOpen() { // v0 = 13
breg[2] = (uint32_t)fopen((const char*)breg[4], (const char*)breg[5]);
}
void fileRead() { // v0 = 14
breg[2] = (uint32_t)fread((void*)breg[5], breg[6], 1, (FILE*)breg[4]);
}
void fileWrite() { // v0 = 15
breg[2] = (uint32_t)fwrite((const void*)breg[5], breg[6], 1, (FILE*)breg[4]);
}
void fileClose() { // v0 = 16
fclose((FILE*)breg[4]);
}
void sleep() { // v0 = 32
Thread::sleep(breg[4]);
}
};
#endif /* MIPS_HPP_ */
|
/***************************************************************************\
*
*
* ___ ___ ___ ___
* / /\ / /\ / /\ / /\
* / /:/ / /::\ / /::\ / /::\
* / /:/ / /:/\:\ / /:/\:\ / /:/\:\
* / /:/ / /:/~/:/ / /:/~/::\ / /:/~/:/
* / /::\ /__/:/ /:/___ /__/:/ /:/\:\ /__/:/ /:/
* /__/:/\:\ \ \:\/:::::/ \ \:\/:/__\/ \ \:\/:/
* \__\/ \:\ \ \::/~~~~ \ \::/ \ \::/
* \ \:\ \ \:\ \ \:\ \ \:\
* \ \ \ \ \:\ \ \:\ \ \:\
* \__\/ \__\/ \__\/ \__\/
*
*
*
*
* This file is part of TRAP.
*
* TRAP is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* or see <http://www.gnu.org/licenses/>.
*
*
*
* (c) Luca Fossati, fossati@elet.polimi.it, fossati.l@gmail.com
*
\***************************************************************************/
#ifndef MEMORYLT_HPP
#define MEMORYLT_HPP
#include <systemc.h>
#include <tlm.h>
#include <tlm_utils/simple_target_socket.h>
#include <boost/lexical_cast.hpp>
#include <string>
#include <map>
#include <trap_utils.hpp>
namespace trap{
template<unsigned int N_INITIATORS, unsigned int sockSize> class SparseMemoryLT: public sc_module{
public:
tlm_utils::simple_target_socket<SparseMemoryLT, sockSize> * socket[N_INITIATORS];
SparseMemoryLT(sc_module_name name, unsigned int size, sc_time latency = SC_ZERO_TIME) :
sc_module(name), latency(latency){
for(int i = 0; i < N_INITIATORS; i++){
this->socket[i] = new tlm_utils::simple_target_socket<SparseMemoryLT, sockSize>(("mem_socket_" + boost::lexical_cast<std::string>(i)).c_str());
this->socket[i]->register_b_transport(this, &SparseMemoryLT::b_transport);
this->socket[i]->register_get_direct_mem_ptr(this, &SparseMemoryLT::get_direct_mem_ptr);
this->socket[i]->register_transport_dbg(this, &SparseMemoryLT::transport_dbg);
}
end_module();
}
~SparseMemoryLT(){
for(int i = 0; i < N_INITIATORS; i++){
delete this->socket[i];
}
}
void b_transport(tlm::tlm_generic_payload& trans, sc_time& delay){
tlm::tlm_command cmd = trans.get_command();
sc_dt::uint64 adr = trans.get_address();
unsigned char* ptr = trans.get_data_ptr();
unsigned int len = trans.get_data_length();
unsigned char* byt = trans.get_byte_enable_ptr();
unsigned int wid = trans.get_streaming_width();
if(byt != 0){
trans.set_response_status(tlm::TLM_BYTE_ENABLE_ERROR_RESPONSE);
return;
}
if(cmd == tlm::TLM_READ_COMMAND){
for(int i = 0; i < len; i++, ptr++)
*ptr = this->mem[adr + i];
}
else if(cmd == tlm::TLM_WRITE_COMMAND){
for(int i = 0; i < len; i++, ptr++)
this->mem[adr + i] = *ptr;
}
// Use temporal decoupling: add memory latency to delay argument
delay += this->latency;
trans.set_dmi_allowed(false);
trans.set_response_status(tlm::TLM_OK_RESPONSE);
}
// TLM-2 DMI method
bool get_direct_mem_ptr(tlm::tlm_generic_payload& trans, tlm::tlm_dmi& dmi_data){
// Deny read and write access
dmi_data.allow_read_write();
dmi_data.set_start_address(0);
dmi_data.set_end_address((sc_dt::uint64)-1);
return false;
}
// TLM-2 debug transaction method
unsigned int transport_dbg(tlm::tlm_generic_payload& trans){
tlm::tlm_command cmd = trans.get_command();
sc_dt::uint64 adr = trans.get_address();
unsigned char* ptr = trans.get_data_ptr();
unsigned int len = trans.get_data_length();
if(cmd == tlm::TLM_READ_COMMAND){
for(int i = 0; i < len; i++, ptr++)
*ptr = this->mem[adr + i];
}
else if(cmd == tlm::TLM_WRITE_COMMAND){
for(int i = 0; i < len; i++, ptr++)
this->mem[adr + i] = *ptr;
}
return len;
}
//Method used to directly write a word into memory; it is mainly used to load the
//application program into memory
inline void write_byte_dbg(const unsigned int & address, const unsigned char & datum) throw(){
this->mem[address] = datum;
}
private:
const sc_time latency;
std::map<unsigned int, unsigned char> mem;
};
};
#endif
|
/*
* Created on: 21. jun. 2019
* Author: Jonathan Horsted Schougaard
*/
#pragma once
#define SC_INCLUDE_FX
#include <systemc.h>
#include "DMA_data_types.h"
#include "score_lib.h"
#include <list>
#include <algorithm>
#include <math.h>
class monitor_logger
{
static std::vector<sc_time> &getInEList()
{
static std::vector<sc_time> _ingressEvent;
return _ingressEvent;
}
static std::vector<sc_time> &getEgEList()
{
static std::vector<sc_time> _egressEvent;
return _egressEvent;
}
public:
static void ingressEvent()
{
getInEList().push_back(sc_time_stamp());
}
static void egressEvent()
{
getEgEList().push_back(sc_time_stamp());
}
static void measure_log()
{
std::vector<sc_time> delta;
std::vector<sc_time> delta_in;
std::vector<sc_time> delta_eg;
sc_time min = SC_ZERO_TIME;
sc_time max = SC_ZERO_TIME;
sc_time min_in = SC_ZERO_TIME;
sc_time max_in = SC_ZERO_TIME;
sc_time min_eg = SC_ZERO_TIME;
sc_time max_eg = SC_ZERO_TIME;
for(int i=0;i < getEgEList().size();i++)
{
sc_time tmp;
if(i!=0)
{
tmp = getInEList()[i]-getInEList()[i-1];
delta_in.push_back(tmp);
if(min_in == SC_ZERO_TIME || tmp < min_in)
min_in = tmp;
if(max_in == SC_ZERO_TIME || tmp > max_in)
max_in = tmp;
tmp = getEgEList()[i]-getEgEList()[i-1];
delta_eg.push_back(tmp);
if(min_eg == SC_ZERO_TIME || tmp < min_eg)
min_eg = tmp;
if(max_eg == SC_ZERO_TIME || tmp > max_eg)
max_eg = tmp;
}
tmp = getEgEList()[i]-getInEList()[i];
delta.push_back(tmp);
if(min == SC_ZERO_TIME || tmp < min)
min = tmp;
if(max == SC_ZERO_TIME || tmp > max)
max = tmp;
}
sc_time avg = SC_ZERO_TIME;
sc_time avg_in = SC_ZERO_TIME;
sc_time avg_eg = SC_ZERO_TIME;
for(int i = 0; i < delta_in.size();i++)
{
avg_in += delta_in[i];
avg_eg += delta_eg[i];
}
avg_in = avg_in / delta_in.size();
avg_eg = avg_eg / delta_eg.size();
for(int i = 0; i < delta.size();i++)
{
avg += delta[i];
}
avg = avg / delta.size();
std::cout << "measure log:" << std::endl;
std::cout << "latency: [min , avg , max]: [" << (min) << " , " << (avg) << " , " << (max) <<"]" << std::endl;
std::cout << "interval ingress: [min , avg , max]: [" << (min_in) << " , " << (avg_in) << " , " << (max_in) <<"]" << std::endl;
std::cout << "interval egress: [min , avg , max]: [" << (min_eg) << " , " << (avg_eg) << " , " << (max_eg) <<"]" << std::endl;
}
};
SC_MODULE(waveform)
{
sc_in<bool> clk;
sc_out<bool> reset;
sc_fifo_out<DATA1024_t > source;
SC_CTOR(waveform)
{
SC_CTHREAD(waveform_thread,clk.pos());
}
void waveform_thread()
{
DATA1024_t tmp;
tmp.data = 0;
tmp.tlast = 0;
reset.write(true);
float numberGen = 0;
while(true)
{
wait();
reset.write(false);
for(int i=0;i<10;i++)
{
wait();
if(i==10-1)
{
tmp.tlast = 1;
cout << "sending TLAST signal" << endl;
}
else
{
tmp.tlast = 0;
}
if(i==0)
monitor_logger::ingressEvent();
source.write(tmp);
//while(source.num_free() != 0) {wait();}
for(int i=0;i<64;i++)
{
sc_fixed<16,8> fx = sin(numberGen)*120.1f;
//sc_signed us_tmp(fx.wl());
//us_tmp = (fx << (fx.wl()-fx.iwl()));
//tmp.data((16-1) + (16*i),16*i) = (sc_bv<16>)us_tmp;
tmp.data((16-1) + (16*i),16*i) = fixed2bv<16,8>(fx);
sc_bv<16> tmpCheckRaw = (sc_bv<16>)tmp.data((16-1) + (16*i),16*i);
sc_fixed<16,8> tmpCheck = bv2fixed<16,8>(tmpCheckRaw);
if(fx != tmpCheck)
{
sc_stop();
std::cout << "(casting error) got: " << fx << " != " << tmpCheck << std::endl ;//<< " (RAW: " << us_tmp << ")" << std::endl;
}
else
{
//std::cout << "(casting OK) got: " << fx << " != " << tmpCheck << std::endl;
}
numberGen += 0.1;
}
}
}
}
};
SC_MODULE(monitor)
{
sc_in<bool> clk;
sc_in<bool> reset;
sc_fifo_in<DATA32_t > sink;
std::ofstream ofs;
SC_CTOR(monitor)
:ofs("test.txt", std::ofstream::out)
{
SC_CTHREAD(monitor_thread,clk.pos());
reset_signal_is(reset,true);
}
~monitor()
{
ofs.close();
}
void monitor_thread()
{
DATA32_t tmp;
unsigned countdown = 30;
while(true)
{
sink.read(tmp);
monitor_logger::egressEvent();
//std::string tmp_string = "PKGnr is: " + std::to_string((unsigned)count.read().to_uint()) + "TDATA: " + std::to_string((unsigned long)tmp.data.to_uint());// + " @ " + sc_time_stamp();
//ofs << "@" << sc_time_stamp() << "last: " << tmp.tlast;
//SC_REPORT_WARNING(::SC_ID_ASSERTION_FAILED_, tmp_string.c_str());
//sc_report(true);
sc_signed ss_tmp(32);
ss_tmp = tmp.data;
sc_fixed<32,16> tmpCheck = ((sc_fixed<32*2,16*2>)ss_tmp)>>16;
cout << "TDATA: " << tmpCheck << " @ " << sc_time_stamp() << endl;
if(tmp.tlast==1)
{
//clog << "test2" << sc_time_stamp() << endl;
//cerr << "test" << sc_time_stamp() << endl;
cout << "got TLAST signal @ " << sc_time_stamp() << endl;
}
countdown--;
if(countdown==0)
{
cout << "sc_stop signal" << endl;
sc_stop();
monitor_logger::measure_log();
}
}
}
};
|
#ifndef IPS_SEQ_ITEM_VGA_HPP
#define IPS_SEQ_ITEM_VGA_HPP
#define int64 systemc_int64
#define uint64 systemc_uint64
#include <systemc.h>
#include <systemc-ams.h>
#undef int64
#undef uint64
#define int64 opencv_int64
#define uint64 opencv_uint64
#include <opencv2/opencv.hpp>
#undef int64
#undef uint64
#include "vunit.hpp"
// Image path
#define IPS_IMG_PATH_TB "../../tools/datagen/src/imgs/car_rgb_noisy_image.jpg"
/**
* @brief This class is used to generate the data for the AMS test
*
* @tparam BITS - the number of output bits of the digital pixel
* @tparam H_ACTIVE - output horizontal active video pixels
* @tparam H_FP - wait after the display period before the sync
* horizontal pulse
* @tparam H_SYNC_PULSE - assert HSYNC
* @tparam H_BP - wait after the sync horizontal pulse before starting
* the next display period
* @tparam V_ACTIVE - output vertical active video pixels
* @tparam V_FP - wait after the display period before the sync
* vertical pulse
* @tparam V_SYNC_PULSE - assert VSYNC
* @tparam V_BP - wait after the sync vertical pulse before starting
* the next display period
*/
template <
unsigned int BITS = 8,
unsigned int H_ACTIVE = 640,
unsigned int H_FP = 16,
unsigned int H_SYNC_PULSE = 96,
unsigned int H_BP = 48,
unsigned int V_ACTIVE = 480,
unsigned int V_FP = 10,
unsigned int V_SYNC_PULSE = 2,
unsigned int V_BP = 33,
int VMIN = 0,
int VMAX = 5,
VUnit VU = VUnit::v>
SCA_TDF_MODULE(seq_item_vga)
{
protected:
cv::Mat tx_img;
// Min voltage value based on the voltage units
const double V_MIN = static_cast<double>(VMIN) / static_cast<double>(VU);
// Max voltage value based on the voltage units
const double V_MAX = static_cast<double>(VMAX) / static_cast<double>(VU);
// Max digital output code
const double MAX_DIG = static_cast<double>((1 << BITS) - 1);
public:
// Counters
sca_tdf::sca_de::sca_in<unsigned int> hcount;
sca_tdf::sca_de::sca_in<unsigned int> vcount;
// Output pixel
sca_tdf::sca_out<double> o_red;
sca_tdf::sca_out<double> o_green;
sca_tdf::sca_out<double> o_blue;
SC_CTOR(seq_item_vga)
{
// Read image
const std::string img_path = IPS_IMG_PATH_TB;
cv::Mat read_img = cv::imread(img_path, cv::IMREAD_COLOR);
// CV_8UC3 Type: 8-bit unsigned, 3 channels (e.g., for a color image)
read_img.convertTo(this->tx_img, CV_8UC3);
// Check if the image is loaded successfully
if (this->tx_img.empty())
{
std::cerr << "Error: Could not open or find the image!" << std::endl;
exit(EXIT_FAILURE);
}
}
void set_attributes()
{
// Propagation time from input to output
set_timestep(sca_core::sca_time(1, sc_core::SC_NS));
this->o_red.set_delay(17);
this->o_green.set_delay(17);
this->o_blue.set_delay(17);
}
void processing()
{
const int IMG_ROW = static_cast<int>(this->vcount.read()) - (V_SYNC_PULSE + V_BP);
const int IMG_COL = static_cast<int>(this->hcount.read()) - (H_SYNC_PULSE + H_BP);
if ((IMG_ROW < 0) || (IMG_COL < 0) || (IMG_ROW >= static_cast<int>(V_ACTIVE)) || (IMG_COL >= static_cast<int>(H_ACTIVE)))
{
this->o_red.write(0.0);
this->o_green.write(0.0);
this->o_blue.write(0.0);
}
else
{
if ((IMG_ROW >= this->tx_img.rows) || (IMG_COL >= this->tx_img.cols))
{
this->o_red.write(0.0);
this->o_green.write(0.0);
this->o_blue.write(0.0);
}
else
{
cv::Vec3b pixel = tx_img.at<cv::Vec3b>(IMG_ROW, IMG_COL, 0);
this->o_red.write(sc_uint2double(static_cast<sc_uint<BITS>>(pixel[0])));
this->o_green.write(sc_uint2double(static_cast<sc_uint<BITS>>(pixel[1])));
this->o_blue.write(sc_uint2double(static_cast<sc_uint<BITS>>(pixel[2])));
}
}
}
/**
* @brief Convert the digital signal into analog signal
* The N-bit digital code is converted into an analog signal in a voltage
* range from Vmin to Vmax
*/
double sc_uint2double(sc_uint<BITS> in)
{
double dig_in = static_cast<double>(in);
return V_MIN + (dig_in / MAX_DIG) * (V_MAX - V_MIN);
}
};
#endif // IPS_SEQ_ITEM_VGA_HPP
|
#ifndef SOBEL_EDGE_DETECTOR_HPP
#define SOBEL_EDGE_DETECTOR_HPP
#define USING_TLM_TB_EN
#include <systemc.h>
SC_MODULE(Edge_Detector)
{
#ifndef USING_TLM_TB_EN
sc_inout<sc_uint<64>> data;
sc_in<sc_uint<24>> address;
#else
sc_uint<64> data;
sc_uint<24> address;
#endif // USING_TLM_TB_EN
const double delay_full_adder_1_bit = 0.361;
const double delay_full_adder = delay_full_adder_1_bit * 16;
const double delay_multiplier = 9.82;
const sc_int<16> sobelGradientX[3][3] = {{-1, 0, 1},
{-2, 0, 2},
{-1, 0, 1}};
const sc_int<16> sobelGradientY[3][3] = {{-1, -2, -1},
{ 0, 0, 0},
{ 1, 2, 1}};
sc_int<16> localWindow[3][3];
sc_int<16> resultSobelGradientX;
sc_int<16> resultSobelGradientY;
sc_int<16> localMultX[3][3];
sc_int<16> localMultY[3][3];
sc_event gotLocalWindow;
sc_event rd_t, wr_t;
sc_event mult_x, mult_y, sum_x, sum_y;
SC_CTOR(Edge_Detector)
{
SC_THREAD(wr);
SC_THREAD(rd);
SC_THREAD(compute_sobel_gradient_x);
SC_THREAD(compute_sobel_gradient_y);
SC_THREAD(perform_mult_gradient_x);
SC_THREAD(perform_mult_gradient_y);
SC_THREAD(perform_sum_gradient_x);
SC_THREAD(perform_sum_gradient_y);
}
virtual void write();
virtual void read();
void wr();
void rd();
void compute_sobel_gradient_x();
void compute_sobel_gradient_y();
void perform_mult_gradient_x();
void perform_mult_gradient_y();
void perform_sum_gradient_x();
void perform_sum_gradient_y();
};
#endif // SOBEL_EDGE_DETECTOR_HPP
|
#ifndef __ROM_3840_32_H__
#define __ROM_3840_32_H__
#include <fstream>
#include <systemc.h>
class rom_3840x32_t : public sc_module
{
public:
sc_in<uint32_t> addr1;
sc_in<uint32_t> addr2;
sc_out<uint32_t> data1;
sc_out<uint32_t> data2;
uint32_t data[3840];
void port1() {
while(true) {
uint32_t addrw32 = addr1.read();
uint32_t addrw11 = addrw32 % 4096;
data1.write(data[addrw11]);
wait();
}
}
void port2() {
while(true) {
uint32_t addrw32 = addr2.read();
uint32_t addrw11 = addrw32 % 4096;
data2.write(data[addrw11]);
wait();
}
}
void clear_memory() {
for (int i=0; i<3840; ++i) data[i] = 0;
update.write(!update.read());
}
bool load_binary(const std::string& path)
{
clear_memory();
ifstream f(path, std::ios::binary);
if (f.is_open()) {
f.seekg(0, f.end);
int size = f.tellg();
f.seekg(0, f.beg);
auto buf = new char[size];
f.read(buf, size);
// std::vector<unsigned char> buf
// (std::istreambuf_iterator<char>(f), {});
if (size == 0) return false;
if (size % 4 != 0) return false;
auto words = (uint32_t*) buf;
for (int i=0; i<size/4; ++i) {
data[i] = words[i];
}
f.close();
delete[] buf;
update.write(!update.read());
return true;
}
else {
return false;
}
}
SC_CTOR(rom_3840x32_t)
: update("update")
{
update.write(false);
SC_THREAD(port1);
sensitive << addr1;
sensitive << update;
SC_THREAD(port2);
sensitive << addr2;
sensitive << update;
}
private:
sc_signal<bool> update;
};
#endif
|
#ifndef SYSTEMC_EXAMPLES_COUNTER_HPP
#define SYSTEMC_EXAMPLES_COUNTER_HPP
#include <systemc.h>
using namespace sc_core;
/**
* @brief Construct a new Counter module object.
*
* Count is only during positive edges of the clock.
* Reset is only during 1'b0. After reset asserts, it goes out of reset.
* Enable must be asserted to start the count, otherwise the output will hold
* latest value.
*
* @tparam N - number of counter bits.
*/
template <int N>
SC_MODULE(Counter)
{
//------------------------------Module Inputs------------------------------
// Input clock
sc_in_clk clk;
// Reset bar (reset when 1'b0)
sc_in<bool> rstb;
// Starts the counter
sc_in<bool> enable;
// N-bit output of the counter
sc_out<sc_uint<N > > count_out;
//-----------------------------Local Variables-----------------------------
sc_uint<4> count_int;
public:
/**
* @brief Default constructor for Counter.
*/
SC_CTOR(Counter)
{
SC_METHOD(count);
// Sensitive to the clk posedge to carry out the count
sensitive << clk.pos();
// Sensitive to any state change to go in or out of reset
sensitive << rstb;
}
//---------------------------------Methods---------------------------------
/**
* @brief Methods that counts in every posedge of the clock, unless rstb is
* equal to 0, then the output will be always 0. Enable needs to be
* asserted, otherwise it will show latest value of the counter.
*/
void count();
};
template <int N>
void Counter<N>::count()
{
// When in reset state, set counter to 0.
if (this->rstb.read() == 0)
{
this->count_int = 0;
this->count_out.write(count_int);
}
// Count when module is enable
else if (this->enable.read() == 1)
{
this->count_int += 1;
this->count_out.write(count_int);
}
}
#endif // SYSTEMC_EXAMPLES_COUNTER_HPP
|
#pragma once
#include<string>
#include<systemc.h>
using std::string;
class write_if_f: virtual public sc_interface
{
public:
virtual void write(string) = 0;
virtual void nb_write(string) = 0;
};
class read_if_f: virtual public sc_interface
{
public:
virtual void read(string &) = 0;
virtual void nb_read(string &) = 0;
virtual void notify() = 0;
};
class write_if: virtual public sc_interface
{
public:
virtual void write(string) = 0;
};
class read_if: virtual public sc_interface
{
public:
virtual void read(string &) = 0;
};
|
/*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
****************************************************************************/
/**
* @file main.cpp
* @brief This function instantiates a parameter OWNER, CONFIGURATOR and an
* OBSERVER class
* @author P V S Phaneendra, CircuitSutra Technologies Pvt. Ltd.
* @date 12th September, 2011 (Monday)
*/
#include <cci_configuration>
#include <systemc.h>
#include <string>
#include "ex16_parameter_owner.h"
#include "ex16_parameter_configurer.h"
#include "ex16_observer.h"
/**
* @fn int sc_main(int sc_argc, char* sc_argv[])
* @brief The main testbench function, instantiates an obserers, own, and configurer
* @param sc_argc The number of input arguments
* @param sc_argv The list of the input arhuments
* @return An interger representing the exit status of the function.
*/
int sc_main(int sc_argc, char* sc_argv[]) {
cci::cci_register_broker(new cci_utils::broker("DEFAULT_BROKER"));
// Creating an originator to access the global broker
const std::string myOrgStr = "sc_main_originator";
cci::cci_originator myOriginator(myOrgStr);
// Get handle of the broker using the originator
cci::cci_broker_handle globalBroker =
cci::cci_get_global_broker(myOriginator);
// Set preset value to the 'int_param' of 'parameter_owner' class before
// their constructor begins
SC_REPORT_INFO("sc_main", "[MAIN] : Setting preset value"
" 's_address:256,d_address:512,index:0' to UDT");
// Demonstrating use of 'set_preset_cci_value' API to assign
// preset value before the construction of the model hierarchy begins.
std::string init_str("{\"s_address\":256,\"d_address\":512,\"index\":0}");
globalBroker.set_preset_cci_value("param_owner.User_data_type_param", cci::cci_value::from_json(init_str));
// Instantiation of sc_modules
ex16_parameter_owner param_owner("param_owner");
ex16_parameter_configurer param_cfgr("param_cfgr");
// Instantiate the observer class
ex16_observer observer_obj;
SC_REPORT_INFO("sc_main", "Begin Simulation.");
sc_core::sc_start(12.0, sc_core::SC_NS);
SC_REPORT_INFO("sc_main", "End Simulation.");
return EXIT_SUCCESS;
}
// sc_main
|
#include <systemc.h>
//
#include "hwcore/hf/helperlib.h"
#include <random>
#define sc_fifo hwcore::hf::sc_fifo_with_trace
//
#include "hwcore/cnn/cnn.h"
#include "hwcore/pipes/data_types.h"
#include <cmath>
SC_MODULE(tb_cnn_2d) {
#if __RTL_SIMULATION__
// DMA_performance_tester_rtl_wrapper u1;
#else
// DMA_performance_tester u1;
#endif
typedef sc_fixed<P_data_W, P_data_P> sc_data;
sc_data func(int a, int b, int c, int d) {
int tmp = ((d & 0xFF) << 24) | ((c & 0xFF) << 16) | ((b & 0xFF) << 8) | ((a & 0xFF) << 0);
return (sc_data)tmp;
}
void func_inv(sc_data in, int &a, int &b, int &c, int &d) {
a = (in.to_int() >> 0) & 0xFF;
b = (in.to_int() >> 8) & 0xFF;
c = (in.to_int() >> 16) & 0xFF;
d = (in.to_int() >> 24) & 0xFF;
}
struct dma_pkg : public hwcore::pipes::sc_fifo_base_dummy<dma_pkg> {
typedef sc_bv<P_input_width> sc_data_raw;
sc_data_raw *data_array;
uint64 size;
};
sc_clock clk;
sc_in<bool> iclk;
sc_signal<bool> reset;
sc_fifo<hwcore::pipes::sc_data_stream_t<P_input_width> > dma_source;
sc_fifo<hwcore::pipes::sc_data_stream_t<P_input_width> > dma_buf_source;
sc_fifo<hwcore::pipes::sc_data_stream_t<P_input_width> > dma_w_source;
sc_fifo<hwcore::pipes::sc_data_stream_t<64> > dma_ctrl_source;
sc_fifo<hwcore::pipes::sc_data_stream_t<P_output_width> > dma_sink;
enum {
weight_ctrl = 0,
ctrl_row_N = 1,
ctrl_row_size_pkg = 2,
ctrl_window_size = 3,
ctrl_depth = 4,
ctrl_stride = 5,
ctrl_replay = 6,
ctrl_image_size = 7,
ctrl_acf = 8,
ctrl_zeropad = 9,
ctrl_output_channel = 10,
ctrl_stitch_depth = 11,
ctrl_stitch_buf_depth = 12,
ctrl_db_output = 13,
ctrl_image_data = 14,
ctrl_pool_depth = 15,
ctrl_pool_type = 16,
ctrl_pool_N = 17,
ctrl_pool_size = 18
};
sc_signal<int> status_add, status_val;
// sc_fifo<hwcore::pipes::sc_data_stream_t<16> > wave_2_u1;
::cnn cnn_u1;
// hwcore::cnn::top_cnn<16,8,1,1,16,16> cnn_u1;
sc_trace_file *tracePtr;
ofstream of;
void log_time(std::string msg) { of << msg << ":" << sc_time_stamp().to_string() << std::endl; }
void log(std::string msg) { of << msg << std::endl; }
void fifo_debug() {
sc_time time_interval(1000, SC_NS);
while (true) {
wait(time_interval);
auto list = hwcore::hf::sc_trace_fifo::getList();
for (auto fifo_wrap : list) {
int total = fifo_wrap->num_available() + fifo_wrap->num_free();
int used = fifo_wrap->num_available();
sc_port_base *writer = fifo_wrap->getWriter();
const char *w_name = (writer ? writer->name() : fifo_wrap->name());
sc_port_base *reader = fifo_wrap->getReader();
const char *r_name = (reader ? reader->name() : fifo_wrap->name());
std::cout << "[fifo debug][ " << sc_time_stamp() << " ][Used/Total] name [writer --> reader]: [" << used
<< " / " << total << "] " << fifo_wrap->name() << " [" << w_name << " --> " << r_name << "]"
<< std::endl;
}
}
}
void status_reg_dump() {
sc_time time_interval(1000, SC_NS);
while (true) {
status_add.write(-1);
for (int i = 0; i < 10; i++)
wait();
int N_reg = status_val.read();
for (int reg_n = 0; reg_n < N_reg; reg_n++) {
status_add.write(reg_n);
for (int i = 0; i < 10; i++)
wait();
int reg_value = status_val.read();
std::cout << "[status reg dump][ " << sc_time_stamp() << " ]reg[" << reg_n << "] = " << reg_value
<< std::endl;
}
wait(time_interval);
}
}
SC_CTOR_DEFAULT(tb_cnn_2d) : SC_INST(cnn_u1), clk("clk", sc_time(5.625, SC_NS)) {
of.open("result.txt");
srand(0xbeef);
SC_MODULE_LINK(cnn_u1);
iclk(clk);
cnn_u1.status_add(status_add);
cnn_u1.status_val(status_val);
cnn_u1.data_sink(dma_source);
cnn_u1.data_buf_sink(dma_buf_source);
cnn_u1.w_sink(dma_w_source);
cnn_u1.data_source(dma_sink);
cnn_u1.ctrl_sink(dma_ctrl_source);
SC_CTHREAD(cpu_thread_vgg19_test, iclk.pos());
SC_CTHREAD(dma_sink_thread, iclk.pos());
SC_CTHREAD(dma_source_thread, iclk.pos());
SC_CTHREAD(dma_source_buf_thread, iclk.pos());
SC_CTHREAD(dma_source_w_thread, iclk.pos());
SC_CTHREAD(dma_source_ctrl_thread, iclk.pos());
SC_CTHREAD(fifo_debug, iclk.pos());
SC_CTHREAD(status_reg_dump, iclk.pos());
HLS_DEBUG_EXEC(set_stack_size(128 * 10 * 1024 * 1024));
tracePtr = sc_create_vcd_trace_file("tb_CNN");
trace(tracePtr);
}
inline void trace(sc_trace_file * trace) {
SC_TRACE_ADD(clk);
SC_TRACE_ADD(reset);
// SC_TRACE_ADD_MODULE(wave_2_u1);
// SC_TRACE_ADD_MODULE(data_ctrl);
SC_TRACE_ADD_MODULE(weight_ctrl);
SC_TRACE_ADD_MODULE(ctrl_row_N);
SC_TRACE_ADD_MODULE(ctrl_channel);
SC_TRACE_ADD_MODULE(cnn_u1);
// SC_TRACE_ADD_MODULE(u1_2_mon);
}
void do_cmd(sc_uint<8> regnr, sc_uint<56> value) {
sc_uint<64> pkg = (regnr, value);
dma_source_ctrl_ctrl.write(pkg);
}
const int dma_bw = P_input_BW_N;
const int pe_bw = P_pe_bw_n;
const int pe_n = P_pe_n;
const int db_out_n = P_data_out_n;
// typedef sc_fixed<P_data_W, P_data_P> sc_data;
void cpu_thread_vgg19_test() {
std::cout << "dma_bw:" << dma_bw << ", pe_bw: " << pe_bw << ", pe_n: " << pe_n << ", db_out_n: " << P_data_out_n
<< std::endl;
reset.write(1);
for (int i = 0; i < 10; i++)
wait();
reset.write(0);
wait();
pooling_test_512();
conv_test(16, 1, 64, 64);
const int image_size = 32;
const int N_images = 1;
const int depth = 3;
int N_W = 64;
#if 0
sc_data *X = new sc_data[image_size * image_size * depth * N_images];
{
fstream input;
input.open("/home/jonathan/vgg19/dog.txt", ios::in);
char test[512];
char *end;
const int total_size = image_size * image_size * depth * N_images;
std::cout << total_size << std::endl;
int idx = 0;
for (int i = 0; i < N_images; i++) {
for (int x = 0; x < image_size; x++) {
for (int y = 0; y < image_size; y++) {
for (int z = 0; z < depth; z++) {
input.getline(test, 512);
double tmp = std::strtod(test, &end);
std::cout << "W[" << i << "," << x << "," << y << "," << z << "] = " << tmp << std::endl;
X[idx] = tmp;
idx++;
}
}
}
}
}
#endif
sc_ufixed<8, 0> *X = new sc_ufixed<8, 0>[image_size * image_size * depth * N_images];
{
fstream input;
input.open("/home/jonathan/vgg19/dog.txt", ios::in);
char test[512];
char *end;
const int total_size = image_size * image_size * depth * N_images;
std::cout << total_size << std::endl;
int idx = 0;
for (int i = 0; i < N_images; i++) {
for (int x = 0; x < image_size; x++) {
for (int y = 0; y < image_size; y++) {
for (int z = 0; z < depth; z++) {
double tmp;
if (z < 3) {
input.getline(test, 512);
tmp = std::strtod(test, &end);
} else {
tmp = 0;
}
X[idx] = tmp;
std::cout << "W[" << i << "," << x << "," << y << "," << z << "] = " << X[idx].to_double()
<< "(" << tmp << ")" << std::endl;
idx++;
}
}
}
}
}
double *Y = new double[image_size * image_size * N_W * N_images];
{
int zN = 64;
fstream input;
input.open("/home/jonathan/vgg19/dog_out.txt", ios::in);
char test[512];
char *end;
input.getline(test, 512);
int idx = 0;
for (int i = 0; i < N_images; i++) {
for (int x = 0; x < image_size; x++) {
for (int y = 0; y < image_size; y++) {
for (int z = 0; z < zN; z++) {
input.getline(test, 512);
double tmp = std::strtod(test, &end);
std::cout << "Y[" << i << "," << x << "," << y << "," << z << "] = " << tmp << std::endl;
if (z < N_W) {
Y[idx] = tmp;
idx++;
}
}
}
}
}
}
// std::string line = ;
sc_data *W;
{
fstream conv1;
conv1.open("/home/jonathan/vgg19/weights.txt", ios::in);
char test[512];
conv1.getline(test, 512);
std::string line(test);
char *end;
int x = 3;
int y = 3;
int z = 3;
int w = 64;
W = new sc_data[(x * y * z * N_W) + N_W];
int idx = 0;
double tmp;
for (int wi = 0; wi < N_W; wi++) {
conv1.getline(test, 512);
tmp = std::strtod(test, &end);
W[idx] = tmp;
std::cout << "B[" << wi << "] = " << tmp << std::endl;
idx++;
for (int xi = 0; xi < x; xi++) {
for (int yi = 0; yi < y; yi++) {
for (int zi = 0; zi < depth; zi++) {
if (zi < z) {
conv1.getline(test, 512);
tmp = std::strtod(test, &end);
} else {
tmp = 0;
}
W[idx] = tmp;
idx++;
std::cout << "W[" << wi << "," << xi << "," << yi << "," << zi << "] = " << tmp
<< std::endl;
}
}
}
}
}
dma_pkg dmaX;
dma_pkg dmaW;
dma_pkg dmaY1;
int W_size = 3;
int new_W_size;
int new_depth;
// pre_data(X, dmaX, image_size, N_images, depth, new_depth);
pre_data_image(X, dmaX, image_size, N_images, new_depth);
pre_weight(W, dmaW, W_size, N_W, depth, new_depth, new_W_size);
{
ofstream of_w_dump;
of_w_dump.open("W_dma_dump_vgg19.txt");
for (int i = 0; i < dmaW.size; i++) {
auto tmp = dmaW.data_array[i];
of_w_dump << "dma[" << i << "] = [MSB ";
for (int a = dma_bw - 1; a >= 0; a--) {
auto sub = tmp((P_data_W * (a + 1)) - 1, P_data_W * a);
;
of_w_dump << " (" << (P_data_W * (a + 1)) - 1 << "," << P_data_W * a << ")"
<< sub.to_string(sc_dt::sc_numrep::SC_HEX) << (a == 0 ? "" : ",");
}
of_w_dump << " LSB]" << std::endl;
}
}
pre_output(dmaY1, image_size, W_size, depth, N_images, N_W, 1);
log_time("conv_start");
do_conv(dmaX, dmaW, dmaY1, new_W_size, new_depth, image_size, 1, N_images, N_W, 1, true);
double mse = 0.0f;
for (int i = 0; i < N_images; i++) {
for (int x = 0; x < image_size; x++) {
for (int y = 0; y < image_size; y++) {
for (int z = 0; z < N_W; z++) {
int Yindx = (i * image_size * image_size * N_W) + (x * image_size * N_W) + (y * N_W) + z;
int Yindx_add = Yindx / dma_bw;
int Yindx_cut = Yindx % dma_bw;
sc_fixed<P_data_W, P_data_P> got_fix = hwcore::hf::bv2fixed<P_data_W, P_data_P>(
dmaY1.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut));
debug_cout << "[i,a,b,c]:[" << i << "," << x << "," << y << "," << z << "]:[expected,got] = ["
<< Y[Yindx] << "," << got_fix.to_double() << "] Yindx = " << Yindx << "==>"
<< Yindx_add << "." << Yindx_cut << std::endl;
mse += (Y[Yindx] - got_fix.to_double()) * (Y[Yindx] - got_fix.to_double());
// sc_assert(got == expected);
//#warning fix W before uncomment
}
}
}
}
mse = mse / (double)(N_images * image_size * image_size * N_W);
std::cout << "mse: " << mse << std::endl;
log(std::string("mse: ") + std::to_string(mse));
double mse_tol = 1e-1;
// sc_assert(mse <= mse_tol);
log_time("conv_end");
log_time("pool_start");
dma_pkg dmaY2;
pre_output(dmaY2, image_size, 2, N_W, N_images, N_W, 0, 2);
do_pool(dmaY1, dmaY2, N_W, image_size, 2, N_images, 2, 0);
log_time("pool_end");
for (int i = 0; i < N_images; i++) {
for (int x = 0; x < image_size / 2; x++) {
for (int y = 0; y < image_size / 2; y++) {
for (int z = 0; z < N_W; z++) {
sc_fixed<P_data_W, P_data_P> exp_fix;
for (int px = 0; px < 2; px++) {
for (int py = 0; py < 2; py++) {
int Yindx = (i * (image_size) * (image_size)*N_W) +
(((x * 2) + px) * image_size * N_W) + (((y * 2) + py) * N_W) + z;
int Yindx_add = Yindx / dma_bw;
int Yindx_cut = Yindx % dma_bw;
sc_fixed<P_data_W, P_data_P> exp_fix_tmp = hwcore::hf::bv2fixed<P_data_W, P_data_P>(
dmaY1.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut));
if ((px == 0 && py == 0) || exp_fix < exp_fix_tmp) {
exp_fix = exp_fix_tmp;
}
std::cout << "exp pool [" << px << "," << py << "] [exp_fix, exp_tmp]=["
<< exp_fix.to_float() << ", " << exp_fix_tmp.to_float() << "]" << std::endl;
}
}
int Yindx = (i * (image_size / 2) * (image_size / 2) * N_W) + (x * (image_size / 2) * N_W) +
(y * N_W) + z;
int Yindx_add = Yindx / dma_bw;
int Yindx_cut = Yindx % dma_bw;
sc_fixed<P_data_W, P_data_P> got_fix = hwcore::hf::bv2fixed<P_data_W, P_data_P>(
dmaY2.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut));
debug_cout << "[i,a,b,c]:[" << i << "," << x << "," << y << "," << z << "]:[expected,got] = ["
<< exp_fix.to_double() << "," << got_fix.to_double() << "] Yindx = " << Yindx
<< "==>" << Yindx_add << "." << Yindx_cut << std::endl;
sc_assert(got_fix == exp_fix);
//#warning fix W before uncomment
}
}
}
}
fc_test(dmaY2, image_size / 2, N_W, N_images, 128);
{
/*
dma_pkg dmaWfc;
dma_pkg dmaY3;
int outputs = 2;
int inputs = (image_size / 2) * (image_size / 2) * N_W;
pre_fc_output(dmaY3, outputs * N_images);
int w_row_N;
sc_data *Wfc = new sc_data[outputs * (1 + inputs)];
for (int i = 0; i < outputs; i++) {
Wfc[i * (1 + inputs)] = sc_data(0.001f * (float)((rand() % 100) - 50));
for (int x = 0; x < inputs; x++) {
Wfc[(i * (1 + inputs)) + x + 1] = sc_data(0.001f * (float)((rand() % 100) - 50));
}
}
int outputs_raw;
pre_fc_weight(Wfc, dmaWfc, inputs, outputs, outputs_raw, w_row_N);
log_time("fc_start");
do_fc(dmaY2, dmaWfc, dmaY3, inputs, outputs_raw, N_images, w_row_N);
mse = 0.0;
for (int i = 0; i < N_images; i++) {
for (int x = 0; x < outputs; x++) {
double exp = Wfc[x * (1 + inputs)].to_double();
for (int in = 0; in < inputs; in++) {
int Yindx = (i * inputs) + in;
int Yindx_add = Yindx / dma_bw;
int Yindx_cut = Yindx % dma_bw;
sc_fixed<P_data_W, P_data_P, SC_TRN, SC_SAT> input_data = hwcore::hf::bv2fixed<P_data_W,
P_data_P>( dmaY2.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut)); exp += Wfc[(x
* (1 + inputs)) + in + 1].to_double() * input_data.to_double();
}
int Yindx = (i * outputs) + x;
int Yindx_add = Yindx / dma_bw;
int Yindx_cut = Yindx % dma_bw;
sc_fixed<P_data_W, P_data_P> input_data = hwcore::hf::bv2fixed<P_data_W, P_data_P>(
dmaY3.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut));
std::cout << "[" << i << "," << x << "] : [exp <==> got] = [" << exp << " <==> "
<< input_data.to_double() << "]" << std::endl;
mse += (exp - input_data.to_double()) * (exp - input_data.to_double());
// sc_assert(exp == input_data);
}
}
mse /= (double)(N_images * outputs);
std::cout << "mse: " << mse << std::endl;
log(std::string("mse: ") + std::to_string(mse));
// double mse_tol = 1e-1;
// sc_assert(mse <= mse_tol);
log_time("fc_end");
*/
}
sc_stop();
while (true) {
std::cout << "done" << std::endl;
wait();
}
}
void conv_test(int image_size, int N_images, int depth, int N_W) {
dma_pkg dmaX;
dma_pkg dmaW;
dma_pkg dmaY1;
int W_size = 3;
int new_W_size;
int new_depth;
pre_data(nullptr, dmaX, image_size, N_images, depth, new_depth);
// pre_data_image(X, dmaX, image_size, N_images, new_depth);
pre_weight(nullptr, dmaW, W_size, N_W, depth, new_depth, new_W_size);
pre_output(dmaY1, image_size, W_size, depth, N_images, N_W, 1);
log_time("conv_start-" + std::to_string(image_size) + "-" + std::to_string(depth) + "-" + std::to_string(N_W));
do_conv(dmaX, dmaW, dmaY1, new_W_size, new_depth, image_size, 1, N_images, N_W, 1, false);
log(std::string("mse: ") + std::to_string(0.0f));
// sc_assert(mse <= mse_tol);
log_time("conv_end-" + std::to_string(image_size) + "-" + std::to_string(depth) + "-" + std::to_string(N_W));
}
void fc_test(dma_pkg & dmaY2, int image_size, int depth, int N_images, int n_neurons) {
log_time("fc_start");
double mse = 0.0;
for (int i = 0; i < n_neurons / pe_n; i++) {
dma_pkg dmaWfc;
dma_pkg dmaY3;
int outputs = pe_n;
int inputs = image_size * image_size * depth;
pre_fc_output(dmaY3, outputs * N_images);
int w_row_N;
sc_data *Wfc = new sc_data[outputs * (1 + inputs)];
for (int i = 0; i < outputs; i++) {
Wfc[i * (1 + inputs)] = sc_data(0.001f * (float)((rand() % 100) - 50));
for (int x = 0; x < inputs; x++) {
Wfc[(i * (1 + inputs)) + x + 1] = sc_data(0.001f * (float)((rand() % 100) - 50));
}
}
int outputs_raw;
pre_fc_weight(Wfc, dmaWfc, inputs, outputs, outputs_raw, w_row_N);
do_fc(dmaY2, dmaWfc, dmaY3, inputs, outputs_raw, N_images, w_row_N);
for (int i = 0; i < N_images; i++) {
for (int x = 0; x < outputs; x++) {
double exp = Wfc[x * (1 + inputs)].to_double();
for (int in = 0; in < inputs; in++) {
int Yindx = (i * inputs) + in;
int Yindx_add = Yindx / dma_bw;
int Yindx_cut = Yindx % dma_bw;
sc_fixed<P_data_W, P_data_P, SC_TRN, SC_SAT> input_data =
hwcore::hf::bv2fixed<P_data_W, P_data_P>(
dmaY2.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut));
exp += Wfc[(x * (1 + inputs)) + in + 1].to_double() * input_data.to_double();
}
int Yindx = (i * outputs) + x;
int Yindx_add = Yindx / dma_bw;
int Yindx_cut = Yindx % dma_bw;
sc_fixed<P_data_W, P_data_P> input_data = hwcore::hf::bv2fixed<P_data_W, P_data_P>(
dmaY3.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut));
std::cout << "[" << i << "," << x << "] : [exp <==> got] = [" << exp << " <==> "
<< input_data.to_double() << "]" << std::endl;
mse += (sc_data(exp).to_double() - input_data.to_double()) *
(sc_data(exp).to_double() - input_data.to_double());
// sc_assert(exp == input_data);
}
}
}
mse /= (double)(N_images * n_neurons);
std::cout << "mse: " << mse << std::endl;
log(std::string("mse: ") + std::to_string(mse));
// double mse_tol = 1e-1;
// sc_assert(mse <= mse_tol);
log_time("fc_end");
}
void pooling_test_512() {
const int image_size = 28;
const int N_images = 1;
const int depth = 512;
sc_data *X = new sc_data[image_size * image_size * depth * N_images];
{
const int total_size = image_size * image_size * depth * N_images;
std::cout << total_size << std::endl;
int idx = 0;
for (int i = 0; i < N_images; i++) {
for (int x = 0; x < image_size; x++) {
for (int y = 0; y < image_size; y++) {
for (int z = 0; z < depth; z++) {
// input.getline(test, 512);
double tmp = 0.001 * ((rand() % 2000) - 1000);
std::cout << "W[" << i << "," << x << "," << y << "," << z << "] = " << tmp << std::endl;
X[idx] = tmp;
idx++;
}
}
}
}
}
dma_pkg dmaX;
int new_W_size;
int new_depth;
pre_data(X, dmaX, image_size, N_images, depth, new_depth);
log_time("pool512_start");
dma_pkg dmaY2;
pre_output(dmaY2, image_size, 2, depth, N_images, depth, 0, 2);
do_pool(dmaX, dmaY2, depth, image_size, 2, N_images, 2, 0);
log_time("pool512_end");
for (int i = 0; i < N_images; i++) {
for (int x = 0; x < image_size / 2; x++) {
for (int y = 0; y < image_size / 2; y++) {
for (int z = 0; z < depth; z++) {
sc_fixed<P_data_W, P_data_P> exp_fix;
for (int px = 0; px < 2; px++) {
for (int py = 0; py < 2; py++) {
int Yindx = (i * (image_size) * (image_size)*depth) +
(((x * 2) + px) * image_size * depth) + (((y * 2) + py) * depth) + z;
int Yindx_add = Yindx / dma_bw;
int Yindx_cut = Yindx % dma_bw;
sc_fixed<P_data_W, P_data_P> exp_fix_tmp = hwcore::hf::bv2fixed<P_data_W, P_data_P>(
dmaX.data_array[Yindx_add](P_da
|
ta_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut));
if ((px == 0 && py == 0) || exp_fix < exp_fix_tmp) {
exp_fix = exp_fix_tmp;
}
std::cout << "exp pool [" << px << "," << py << "] [exp_fix, exp_tmp]=["
<< exp_fix.to_float() << ", " << exp_fix_tmp.to_float() << "]" << std::endl;
}
}
int Yindx = (i * (image_size / 2) * (image_size / 2) * depth) + (x * (image_size / 2) * depth) +
(y * depth) + z;
int Yindx_add = Yindx / dma_bw;
int Yindx_cut = Yindx % dma_bw;
sc_fixed<P_data_W, P_data_P> got_fix = hwcore::hf::bv2fixed<P_data_W, P_data_P>(
dmaY2.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut));
debug_cout << "[i,a,b,c]:[" << i << "," << x << "," << y << "," << z << "]:[expected,got] = ["
<< exp_fix.to_double() << "," << got_fix.to_double() << "] Yindx = " << Yindx
<< "==>" << Yindx_add << "." << Yindx_cut << std::endl;
sc_assert(got_fix == exp_fix);
//#warning fix W before uncomment
}
}
}
}
}
void cpu_thread_fc_only() {
int N_images = 1;
int image_size = 16;
int depth = 8;
int N_W = 8;
sc_data *X = new sc_data[image_size * image_size * depth * N_images];
{
const int total_size = image_size * image_size * depth * N_images;
std::cout << total_size << std::endl;
int idx = 0;
for (int i = 0; i < N_images; i++) {
for (int x = 0; x < image_size * image_size * depth; x++) {
std::cout << "W[" << i << "," << x << "] = " << x << std::endl;
X[idx] = x;
idx++;
}
}
}
int new_depth;
dma_pkg dmaX;
pre_data(X, dmaX, image_size, N_images, depth, new_depth);
sc_assert(depth == new_depth);
dma_pkg dmaWfc;
dma_pkg dmaY3;
int outputs = pe_n;
int inputs = (image_size) * (image_size)*depth;
// int inputs_raw = (image_size) * (image_size)*new_depth;
int w_row_N;
sc_data *Wfc = new sc_data[outputs * (1 + inputs)];
for (int i = 0; i < outputs; i++) {
Wfc[i * (1 + inputs)] = 0; // sc_data(0.001f * (float)((rand() % 100) - 50));
for (int x = 0; x < inputs; x++) {
Wfc[(i * (1 + inputs)) + x + 1] = x; // sc_data(0.001f * (float)((rand() % 100) - 50));
}
}
int outputs_raw;
pre_fc_weight(Wfc, dmaWfc, inputs, outputs, outputs_raw, w_row_N);
pre_fc_output(dmaY3, outputs_raw * N_images);
log_time("fc_start");
do_fc(dmaX, dmaWfc, dmaY3, inputs, outputs_raw, N_images, w_row_N);
/*
mse = 0.0;
for (int i = 0; i < N_images; i++) {
for (int x = 0; x < outputs; x++) {
sc_fixed<P_data_W * 2, P_data_P * 2, SC_TRN, SC_SAT> exp = Wfc[x * (1 + inputs)];
for (int in = 0; in < inputs; in++) {
int Yindx = (i * inputs) + in;
int Yindx_add = Yindx / dma_bw;
int Yindx_cut = Yindx % dma_bw;
sc_fixed<P_data_W, P_data_P, SC_TRN, SC_SAT> input_data = hwcore::hf::bv2fixed<P_data_W, P_data_P>(
dmaY2.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut));
exp += (sc_fixed<P_data_W * 2, P_data_P * 2, SC_TRN, SC_SAT>)Wfc[(x * (1 + inputs)) + in + 1] *
(sc_fixed<P_data_W * 2, P_data_P * 2, SC_TRN, SC_SAT>)input_data;
}
sc_fixed<P_data_W, P_data_P, SC_TRN, SC_SAT> exp_small = exp;
int Yindx = (i * outputs) + x;
int Yindx_add = Yindx / dma_bw;
int Yindx_cut = Yindx % dma_bw;
sc_fixed<P_data_W, P_data_P> input_data = hwcore::hf::bv2fixed<P_data_W, P_data_P>(
dmaY3.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut));
std::cout << "[" << i << "," << x << "] : [exp <==> got] = [" << exp_small.to_double() << " <==> "
<< input_data.to_double() << "]" << std::endl;
mse +=
(exp_small.to_double() - input_data.to_double()) * (exp_small.to_double() - input_data.to_double());
// sc_assert(exp == input_data);
}
}
mse /= (double)(N_images * outputs);
std::cout << "mse: " << mse << std::endl;
log(std::string("mse: ") + std::to_string(mse));
// double mse_tol = 1e-1;
// sc_assert(mse <= mse_tol);
*/
log_time("fc_end");
sc_stop();
while (true) {
std::cout << "done" << std::endl;
wait();
}
}
void cpu_thread() {
std::cout << "dma_bw:" << dma_bw << ", pe_bw: " << pe_bw << ", pe_n: " << pe_n << ", db_out_n: " << P_data_out_n
<< std::endl;
reset.write(1);
for (int i = 0; i < 10; i++)
wait();
reset.write(0);
const int image_size = 8;
const int N_images = 1;
const int depth = fix_size(8, pe_bw);
const int W_size = 3;
const int N_W = 8;
sc_data *X = new sc_data[image_size * image_size * depth * N_images];
const int total_size = image_size * image_size * depth * N_images;
std::cout << total_size << std::endl;
int idx = 0;
for (int i = 0; i < N_images; i++) {
for (int x = 0; x < image_size; x++) {
for (int y = 0; y < image_size; y++) {
for (int z = 0; z < depth; z++) {
sc_data tmp = func(x, y, z, i);
std::cout << "image data: " << tmp.to_string() << std::endl;
X[idx] = tmp;
idx++;
}
}
}
}
sc_data *W = new sc_data[(W_size * W_size * depth * N_W) + N_W];
idx = 0;
const int w_indx = (int)floor(W_size / 2.0f);
for (int i = 0; i < N_W; i++) {
W[idx] = i;
idx++;
for (int x = 0; x < W_size; x++) {
for (int y = 0; y < W_size; y++) {
for (int z = 0; z < depth; z++) {
if (z == i % depth && y == (i / depth) % W_size && x == (i / (depth * W_size)) % W_size) {
W[idx] = 1;
} else {
W[idx] = 0;
}
std::cout << "w data: " << W[idx].to_string() << std::endl;
idx++;
}
}
}
}
dma_pkg dmaX;
dma_pkg dmaW;
dma_pkg dmaY1;
dma_pkg dmaY2;
dma_pkg dmaWfc;
dma_pkg dmaY3;
int new_W_size;
int new_depth;
int output_fc = 2;
pre_output(dmaY2, image_size, 2, N_W, N_images, N_W, 0, 2);
pre_fc_output(dmaY3, output_fc * N_images);
int w_row_N;
int output_raw_fc;
pre_fc_weight(nullptr, dmaWfc, (dmaY2.size * dma_bw) / N_images, 64, output_raw_fc, w_row_N);
pre_data(X, dmaX, image_size, N_images, depth, new_depth);
pre_weight(W, dmaW, W_size, N_W, depth, new_depth, new_W_size);
pre_output(dmaY1, image_size, W_size, depth, N_images, N_W, 1);
log_time("conv_start");
do_conv(dmaX, dmaW, dmaY1, new_W_size, new_depth, image_size, 1, N_images, N_W, 1);
int zp = 1;
for (int i = 0; i < N_images; i++) {
for (int x = 0; x < image_size; x++) {
for (int y = 0; y < image_size; y++) {
for (int z = 0; z < N_W; z++) {
int off_x = ((z / (new_depth * new_W_size)) % new_W_size) - zp;
int off_y = ((z / new_depth) % new_W_size) - zp;
int off_z = z % new_depth;
int expected = 0;
if (0 <= x + off_x && x + off_x < image_size && 0 <= y + off_y && y + off_y < image_size) {
expected = func(x + off_x, y + off_y, off_z, i);
}
int Yindx = (i * image_size * image_size * N_W) + (x * image_size * N_W) + (y * N_W) + z;
int Yindx_add = Yindx / dma_bw;
int Yindx_cut = Yindx % dma_bw;
sc_fixed<P_data_W, P_data_P> got_fix = hwcore::hf::bv2fixed<P_data_W, P_data_P>(
dmaY1.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut));
int got = got_fix.to_int() - z;
debug_cout << "[i,a,b,c]:[" << i << "," << x << "," << y << "," << z << "]- func(" << x + off_x
<< "," << y + off_y << "," << off_z << "," << i << ")=[expected,got]:[" << expected
<< "," << got << "] Yindx = " << Yindx << "==>" << Yindx_add << "." << Yindx_cut
<< std::endl;
int _x;
int _y;
int _z;
int _i;
func_inv(got_fix - sc_fixed<P_data_W, P_data_P>(z), _x, _y, _z, _i);
debug_cout << "invfunc got [x,y,z,i]:[" << _x << "," << _y << "," << _z << "," << _i << "]"
<< std::endl;
sc_assert(got == expected);
//#warning fix W before uncomment
}
}
}
}
log_time("conv_end");
log_time("pool_start");
do_pool(dmaY1, dmaY2, N_W, image_size, 2, N_images, 2, 0);
log_time("pool_end");
// pre_process(X, W, dmaX, dmaW, dmaY, image_size, W_size, depth, new_W_size, new_depth, N_images, N_W, 1);
log_time("fc_start");
do_fc(dmaY2, dmaWfc, dmaY3, dmaY2.size * dma_bw, dmaY3.size * dma_bw, N_images, w_row_N);
log_time("fc_end");
sc_stop();
while (true) {
std::cout << "done" << std::endl;
wait();
}
// do_conv(dmaX, dmaW, dmaY, new_W_size, new_depth, image_size, 1, N_images, N_W, 1);
}
void pre_fc_weight(sc_data * W, dma_pkg & dmaW, int N_input, int N_output, int &N_output_raw, int &w_row_N) {
N_output_raw = pe_n; // fix_size(N_output, pe_n);
sc_assert(N_output <= N_output_raw);
int w_bw = pe_bw * db_out_n;
w_row_N = fix_size(N_input, w_bw) + w_bw;
// w_row_N = //fix_size(w_row_N + 1, pe_bw * db_out_n);
sc_assert((w_row_N * N_output_raw) % dma_bw == 0);
int size_raw = w_row_N * N_output_raw;
dmaW.data_array = new dma_pkg::sc_data_raw[size_raw / dma_bw];
dmaW.size = size_raw / dma_bw;
for (int out = 0; out < N_output_raw; out++) {
int bias_ptr_from = out * (1 + N_input);
int bias_ptr_to = out * w_bw;
if (out < N_output)
insert_data_2_buf(dmaW, W[bias_ptr_from], bias_ptr_to, dma_bw);
else
insert_data_2_buf(dmaW, 0, bias_ptr_to, dma_bw);
for (int in = 0; in < N_input; in++) {
int ptr_from = (out * (1 + N_input)) + in + 1;
int in_ptr_sub = in % w_bw;
int in_ptr_big = in / w_bw;
int ptr_to = ((1 + in_ptr_big) * N_output_raw * w_bw) + out * w_bw + in_ptr_sub;
//= (out * w_row_N) + in + w_bw;
if (out < N_output)
insert_data_2_buf(dmaW, W[ptr_from], ptr_to, dma_bw);
else
insert_data_2_buf(dmaW, 0, ptr_to, dma_bw);
}
}
}
void pre_fc_output(dma_pkg & dmaY, int N_output) {
N_output = fix_size(N_output, dma_bw);
sc_assert((N_output) % dma_bw == 0);
dmaY.data_array = new dma_pkg::sc_data_raw[(N_output) / dma_bw];
dmaY.size = (N_output) / dma_bw;
}
int fix_size(int old, int align) {
int tmp = (old % align);
if (tmp == 0) {
return old;
} else {
return old + (align - tmp);
}
}
void realign_dma_buffer(sc_data * data, dma_pkg & dma_data, int depth, int new_depth, int dma_bw) {
int ori_i = 0;
for (int i = 0; i < dma_data.size * dma_bw; i++) {
int Yindx_add = i / dma_bw;
int Yindx_cut = i % dma_bw;
sc_bv<P_data_W> tmp;
if (i % new_depth < depth) {
// tmp <<= P_data_W;
std::cout << ori_i << ":" << (data ? data[ori_i].to_string() : "null") << std::endl;
tmp = hwcore::hf::fixed2bv((data ? data[ori_i] : sc_data(0)));
ori_i++;
} else {
tmp = 0;
}
dma_data.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut) = tmp;
if (Yindx_cut == dma_bw - 1) {
std::cout << "DMA data(" << Yindx_add << ", " << dma_data.size
<< "): " << dma_data.data_array[Yindx_add].to_string() << std::endl;
}
}
}
void insert_data_2_buf(dma_pkg & dma_data, sc_data tmp, int idx, int _dma_bw, int data_w = P_data_W) {
int Yindx_add = idx / _dma_bw;
int Yindx_cut = idx % _dma_bw;
sc_assert(Yindx_add < dma_data.size);
sc_assert(Yindx_cut < _dma_bw);
dma_data.data_array[Yindx_add](data_w * (Yindx_cut + 1) - 1, data_w * (Yindx_cut)) = hwcore::hf::fixed2bv(tmp);
}
void realign_dma_buffer_W(sc_data * data, dma_pkg & dma_data, int depth, int new_depth, int _dma_bw, int N,
int w_size, int bw) {
for (int i = 0; i < N; i++) {
int bias_ptr_from = i * (1 + (w_size * w_size * depth));
int pe_index_sub = i % pe_n;
int pe_index_ptr = i / pe_n;
// int bias_ptr_to = i * (bw + (w_size * w_size * new_depth));
int bias_ptr_to = (pe_index_sub * bw) + (pe_index_ptr * pe_n * (bw + (w_size * w_size * new_depth)));
insert_data_2_buf(dma_data, (data ? data[bias_ptr_from] : sc_data(0)), bias_ptr_to, _dma_bw);
for (int x = 0; x < w_size; x++) {
for (int y = 0; y < w_size; y++) {
for (int z = 0; z < depth; z++) {
int ptr_from =
(i * (1 + (w_size * w_size * depth))) + (x * w_size * depth) + (y * depth) + z + 1;
int z_sub = z % pe_bw;
int z_ptr = z / pe_bw;
// int ptr_to = (i * (bw + (w_size * w_size * new_depth))) + (y * w_size * new_depth) +
// (z_ptr * w_size * pe_bw) + ((w_size - x - 1) * pe_bw) + z_sub + bw;
int ptr_to_sub = ((y * w_size * new_depth) + (z_ptr * w_size * pe_bw) +
((w_size - x - 1) * pe_bw) + z_sub + bw);
int ptr_to_pe_sub = ptr_to_sub % (bw);
int ptr_to_pe_ptr = ptr_to_sub / (bw);
int ptr_to = bias_ptr_to + ptr_to_pe_ptr * (pe_n * bw) + ptr_to_pe_sub;
// int ptr_to = (i * (bw + (w_size * w_size * new_depth))) + (y * w_size * new_depth) +
// (z_ptr * w_size * pe_bw) + ((w_size - x - 1) * pe_bw) + z_sub + bw;
// ptr_to =
std::cout << "[x][y][z][w]=[" << x << "][" << y << "][" << z << "][" << i << "]=[from <=> to]["
<< ptr_from << "<=>" << ptr_to << "] rel [" << ptr_from - 1 << "<=>" << ptr_to - bw
<< "] : " << (data ? data[ptr_from].to_float() : 0.0f) << std::endl;
insert_data_2_buf(dma_data, (data ? data[ptr_from] : sc_data(0)), ptr_to, _dma_bw);
}
}
}
}
}
void pre_data(sc_data * X, dma_pkg & dmaX, int image_size, int Nimages, int depth, int &new_depth) {
new_depth = fix_size(depth, pe_bw);
sc_assert((image_size * image_size * new_depth) % pe_bw == 0);
dmaX.data_array = new dma_pkg::sc_data_raw[(image_size * image_size * new_depth * Nimages) / dma_bw];
dmaX.size = (image_size * image_size * new_depth * Nimages) / dma_bw;
realign_dma_buffer(X, dmaX, depth, new_depth, dma_bw);
}
void pre_data_image(sc_ufixed<8, 0> * X, dma_pkg & dmaX, int image_size, int Nimages, int &new_depth) {
new_depth = fix_size(3, pe_bw);
dmaX.size = (image_size * image_size * 3 * 8) / (dma_bw * P_data_W);
sc_assert(((image_size * image_size * 3 * 8) % (dma_bw * P_data_W)) == 0);
dmaX.data_array = new dma_pkg::sc_data_raw[dmaX.size];
for (int x = 0; x < image_size; x++) {
for (int y = 0; y < image_size; y++) {
for (int z = 0; z < 3; z++) {
int ptr_from = (x * image_size * 3) + (y * 3) + z;
int ptr_to = (x * image_size * 3) + (y * 3) + z;
int dma8bit_bw = (dma_bw * P_data_W) / 8;
int Yindx_add = ptr_to / dma8bit_bw;
int Yindx_cut = ptr_to % dma8bit_bw;
sc_assert(Yindx_add < dmaX.size);
sc_assert(Yindx_cut < dma8bit_bw);
sc_assert(dma8bit_bw * 8 == dma_bw * P_data_W);
sc_ufixed<8, 0> tmp = X[ptr_from];
dmaX.data_array[Yindx_add](8 * (Yindx_cut + 1) - 1, 8 * (Yindx_cut)) = hwcore::hf::ufixed2bv(tmp);
// insert_data_2_buf(dmaX, X[ptr_from], ptr_to, dma_bw, 8);
}
}
}
}
void pre_weight(sc_data * W, dma_pkg & dmaW, int W_size, int Nwindows, int depth, int &new_depth, int &new_W_size) {
new_depth = fix_size(depth, pe_bw);
int tmp = fix_size(W_size * W_size, db_out_n); //(pe_bw * db_out_n) / new_depth);
new_W_size = sqrt(tmp);
sc_assert(((new_W_size * new_W_size * new_depth) + (pe_bw * db_out_n)) % pe_bw * db_out_n == 0);
int bias_size = (pe_bw * db_out_n);
dmaW.data_array =
new dma_pkg::sc_data_raw[(((new_W_size * new_W_size * new_depth) + bias_size) * Nwindows) / dma_bw];
dmaW.size = (((new_W_size * new_W_size * new_depth) + bias_size) * Nwindows) / dma_bw;
sc_assert(new_W_size == W_size);
realign_dma_buffer_W(W, dmaW, depth, new_depth, dma_bw, Nwindows, W_size, pe_bw * db_out_n);
}
void pre_output(dma_pkg & dmaY, int image_size, int W_size, int depth, int Nimages, int Nwindows, int zp,
int stride = 1) {
// sc_assert(stride == 1); // todo add this.
// new_depth = fix_size(depth, pe_bw);
int Y_size = (int)ceil(
((float)image_size - ((floor(((float)W_size / 2.0f)) - (float)zp) * 2.0f / (float)stride)) / (float)stride);
int Y_depth = fix_size(Nwindows, pe_n); // * 2;
dmaY.data_array = new dma_pkg::sc_data_raw[(Y_size * Y_size * Y_depth * Nimages) / dma_bw];
dmaY.size = (Y_size * Y_size * Y_depth * Nimages) / dma_bw;
}
void pre_process(sc_data * X, sc_data * W, dma_pkg & dmaX, dma_pkg & dmaW, dma_pkg & dmaY, int image_size,
int W_size, int depth, int &new_W_size, int &new_depth, int Nimages, int Nwindows, int zp,
int stride = 1) {
sc_assert(stride == 1); // todo add this.
new_depth = fix_size(depth, pe_bw);
// new_depth_W = new_depth_X * db_out_n;
{
// sc_assert((pe_bw * db_out_n) % new_depth == 0);
int tmp = fix_size(W_size * W_size, db_out_n); //(pe_bw * db_out_n) / new_depth);
new_W_size = sqrt(tmp);
}
sc_assert((image_size * image_size * new_depth) % pe_bw == 0);
sc_assert(((new_W_size * new_W_size * new_depth) + (pe_bw * db_out_n)) % pe_bw * db_out_n == 0);
int bias_size = (pe_bw * db_out_n);
dmaX.data_array = new dma_pkg::sc_data_raw[(image_size * image_size * new_depth * Nimages) / dma_bw];
dmaX.size = (image_size * image_size * new_depth * Nimages) / dma_bw;
dmaW.data_array =
new dma_pkg::sc_data_raw[(((new_W_size * new_W_size * new_depth) + bias_size) * Nwindows) / dma_bw];
dmaW.size = (((new_W_size * new_W_size * new_depth) + bias_size) * Nwindows) / dma_bw;
int Y_size = image_size - (((int)floor(((float)W_size / 2.0f)) - zp) * 2);
int Y_depth = fix_size(Nwindows, pe_n); // * 2;
dmaY.data_array = new dma_pkg::sc_data_raw[(Y_size * Y_size * Y_depth * Nimages) / dma_bw];
dmaY.size = (Y_size * Y_size * Y_depth * Nimages) / dma_bw;
realign_dma_buffer(X, dmaX, depth, new_depth, dma_bw);
sc_assert(new_W_size == W_size);
realign_dma_buffer_W(W, dmaW, depth, new_depth, dma_bw, Nwindows, W_size, pe_bw * db_out_n);
}
struct P_data_Pkg {
sc_fixed<P_data_W, P_data_P> *data;
int depth;
int size;
int row_size;
};
int do_conv(dma_pkg & X, dma_pkg & W, dma_pkg & Y, int window, int depth, int row_size, int stride, int X_N,
int W_N, int zp, bool raw_image_data = false, sc_ufixed<15, 1> scale = 1.0) {
sc_time start = sc_time_stamp();
sc_assert(depth % pe_bw == 0);
int depth_raw = depth / pe_bw;
sc_assert((window * window * depth) % (pe_bw * db_out_n) == 0);
int wb_ctrl_row_N = ((window * window * depth) / (pe_bw * db_out_n)) + 1;
int db_replay = ceil(W_N / pe_n) - 1;
int row_size_Y = (row_size - (((int)floor((float)window / 2.0f) - zp) * 2)) / stride;
int image_size = depth_raw * row_size * row_size; // used for align multiple images.
// start CNNA
do_cmd(weight_ctrl, 0 | (wb_ctrl_row_N << 20));
// setup
do_cmd(ctrl_image_data, (raw_image_data ? 1 : 0));
do_cmd(ctrl_depth, depth_raw);
do_cmd(ctrl_stride, 0); // stride
do_cmd(ctrl_window_size, window);
do_cmd(ctrl_row_size_pkg, row_size);
do_cmd(ctrl_acf, 1 | (hwcore::hf::ufixed2bv<15, 1>(scale).to_uint() << 1)); // set to use ReLU
do_cmd(ctrl_output_channel, 0);
do_cmd(ctrl_db_output, 0);
// setup wb
// do_cmd(ctrl_row_N, 1); // wb_ctrl_row_N
do_cmd(weight_ctrl, (X_N * row_size_Y * row_size_Y)); // * );
// do_cmd(weight_ctrls_replay, row_size_Y);
// setup db
do_cmd(ctrl_zeropad, zp);
do_cmd(ctrl_replay, db_replay);
do_cmd(ctrl_image_size, image_size);
do_cmd(ctrl_stitch_depth, 0);
do_cmd(ctrl_stitch_buf_depth, 0);
sc_time setup = sc_time_stamp() - start;
// of << "paramsetup:" << (sc_time_stamp() - start).to_string() << std::endl;
// dma magic
dma_sink_ctrl.write(Y);
dma_source_w_ctrl.write(W);
dma_source_ctrl.write(X);
dma_source_w_done.read();
dma_source_done.read();
std::cout << "CNNA tb write done------------------------------------------------------------------>>>"
<< std::endl;
dma_sink_done.read();
std::cout << "CNNA tb done------------------------------------
|
------------------------------<<<" << std::endl;
}
int do_pool(dma_pkg & X, dma_pkg & Y, int depth, int row_size, int stride, int X_N, int window, int zp) {
// ofstream of;
// of.open("result.txt");
sc_time start = sc_time_stamp();
sc_assert(depth % pe_bw == 0);
int depth_raw = depth / pe_bw;
int db_replay = 1;
int row_size_Y = (row_size - (((int)floor((float)window / 2.0f) - zp) * 2)) / stride;
int image_size = depth_raw * row_size * row_size; // used for align multiple images.
// start CNNA
// setup
do_cmd(ctrl_image_data, 0);
do_cmd(ctrl_depth, depth_raw);
do_cmd(ctrl_stride, stride - 1); // stride
do_cmd(ctrl_window_size, window);
do_cmd(ctrl_row_size_pkg, row_size);
// do_cmd(ctrl_acf, 1); // set to use ReLU
do_cmd(ctrl_output_channel, 1);
do_cmd(ctrl_db_output, 1);
// setup wb
// do_cmd(ctrl_row_N, wb_ctrl_row_N);
// do_cmd(weight_ctrl, 0);
// do_cmd(weight_ctrl, X_N * row_size_Y * row_size_Y); // * );
// do_cmd(weight_ctrls_replay, row_size_Y);
// do_cmd(ctrl_channel, 0);
// setup db
do_cmd(ctrl_zeropad, zp);
do_cmd(ctrl_replay, db_replay);
do_cmd(ctrl_image_size, image_size);
// pool
do_cmd(ctrl_pool_size, window);
do_cmd(ctrl_pool_type, 0);
do_cmd(ctrl_pool_depth, depth);
do_cmd(ctrl_stitch_depth, 0);
do_cmd(ctrl_stitch_buf_depth, 0);
// do_cmd(ctrl_pool_N,0);
sc_time setup = sc_time_stamp() - start;
// of << "paramsetup:" << (sc_time_stamp() - start).to_string() << std::endl;
// dma magic
// Y.data_array
// Y.size *= 2;
dma_sink_ctrl.write(Y);
// dma_source_ctrl.write(W);
// of << "Wdone:" << (sc_time_stamp() - start).to_string() << std::endl;
dma_source_ctrl.write(X);
dma_source_done.read();
// of << "Xdone:" << (sc_time_stamp() - start).to_string() << std::endl;
std::cout << "CNNA tb write done------------------------------------------------------------------>>>"
<< std::endl;
dma_sink_done.read();
// of << "done:" << (sc_time_stamp() - start).to_string() << std::endl;
// of.close();
std::cout << "CNNA tb done------------------------------------------------------------------<<<" << std::endl;
for (int i = 0; i < Y.size; i++) {
// int expected = func(a + offset, b + offset, 0, i);
int Yindx = i;
int Yindx_add = Yindx / dma_bw;
int Yindx_cut = Yindx % dma_bw;
sc_fixed<P_data_W, P_data_P> got_fix = hwcore::hf::bv2fixed<P_data_W, P_data_P>(
Y.data_array[Yindx_add](P_data_W * (1 + Yindx_cut) - 1, P_data_W * Yindx_cut));
int got = got_fix.to_int();
debug_cout << "[" << i << "]: " << got_fix.to_float() << std::endl;
/*
debug_cout << "[i,a,b,c]:[" << i << "," << a << "," << b << "," << c << "]- func(" << a + offset << ","
<< b + offset << "," << 0 << "," << i << ")=[expected,got]:[" << expected << "," << got
<< "] Yindx = " << Yindx << "==>" << Yindx_add << "." << Yindx_cut << std::endl;
*/
}
}
void do_fc(dma_pkg & X, dma_pkg & W, dma_pkg & Y, int N_in, int N_out, int X_N, int w_row_N,
sc_ufixed<15, 1> scale = 1.0) {
// ofstream of;
// of.open("result.txt");
sc_time start = sc_time_stamp();
sc_assert(X.size * dma_bw == N_in);
// sc_assert(Y.size * dma_bw == N_out);
// sc_assert(W.size * dma_bw <= w_row_N * N_out);
// sc_assert(depth % pe_bw == 0);
int depth_raw = 1;
sc_assert((w_row_N) % (pe_bw * db_out_n) == 0);
int wb_ctrl_row_N = ((w_row_N) / (pe_bw * db_out_n));
int db_replay = ((N_out) / pe_n) - 1;
sc_assert(db_replay == 0);
int row_size_Y = N_out;
int image_size = (N_in / pe_bw); // used for align multiple images.
// setup
do_cmd(ctrl_image_data, 0);
do_cmd(ctrl_depth, 0);
do_cmd(ctrl_stride, 0); // stride
do_cmd(ctrl_window_size, 0);
do_cmd(ctrl_row_size_pkg, (N_in / pe_bw));
do_cmd(ctrl_acf, 0 | (hwcore::hf::ufixed2bv<15, 1>(scale).to_uint() << 1)); // set to use ReLU
do_cmd(ctrl_output_channel, 0);
do_cmd(ctrl_db_output, 0);
// setup wb
// do_cmd(ctrl_row_N, 1);
do_cmd(weight_ctrl, 1 << 30);
// do_cmd(weight_ctrl, X_N); // * );
// do_cmd(weight_ctrls_replay, row_size_Y);
// setup db
do_cmd(ctrl_zeropad, 0);
do_cmd(ctrl_replay, db_replay);
do_cmd(ctrl_image_size, image_size);
do_cmd(ctrl_stitch_depth, 0);
do_cmd(ctrl_stitch_buf_depth, 0);
sc_time setup = sc_time_stamp() - start;
// of << "paramsetup:" << (sc_time_stamp() - start).to_string() << std::endl;
// dma magic
dma_sink_ctrl.write(Y);
dma_source_w_ctrl.write(W);
dma_source_ctrl.write(X);
dma_source_w_done.read();
dma_source_done.read();
std::cout << "CNNA tb write done------------------------------------------------------------------>>>"
<< std::endl;
dma_sink_done.read();
std::cout << "CNNA tb done------------------------------------------------------------------<<<" << std::endl;
}
sc_fifo<dma_pkg> dma_source_ctrl;
sc_fifo<uint64> dma_source_done;
void dma_source_thread() {
while (true) {
dma_pkg tmp = dma_source_ctrl.read();
for (int i = 0; i < tmp.size; i++) {
hwcore::pipes::sc_data_stream_t<P_input_width> tmp_out;
tmp_out.data = tmp.data_array[i];
tmp_out.tlast = (i == tmp.size - 1);
tmp_out.setKeep();
dma_source.write(tmp_out);
HLS_DEBUG(1, 1, 0, "dma_x_source sending new data[%d,%d]: %s.", i + 1, tmp.size,
tmp_out.data.to_string().c_str());
}
HLS_DEBUG(1, 1, 0, "done");
dma_source_done.write(tmp.size);
}
}
sc_fifo<dma_pkg> dma_source_buf_ctrl;
sc_fifo<uint64> dma_source_buf_done;
void dma_source_buf_thread() {
while (true) {
dma_pkg tmp = dma_source_buf_ctrl.read();
for (int i = 0; i < tmp.size; i++) {
hwcore::pipes::sc_data_stream_t<P_input_width> tmp_out;
tmp_out.data = tmp.data_array[i];
tmp_out.tlast = (i == tmp.size - 1);
tmp_out.setKeep();
dma_buf_source.write(tmp_out);
HLS_DEBUG(1, 1, 0, "dma_buf_source sending new data[%d,%d]: %s.", i + 1, tmp.size,
tmp_out.data.to_string().c_str());
}
HLS_DEBUG(1, 1, 0, "done");
dma_source_buf_done.write(tmp.size);
}
}
sc_fifo<dma_pkg> dma_source_w_ctrl;
sc_fifo<uint64> dma_source_w_done;
void dma_source_w_thread() {
while (true) {
dma_pkg tmp = dma_source_w_ctrl.read();
for (int i = 0; i < tmp.size; i++) {
hwcore::pipes::sc_data_stream_t<P_input_width> tmp_out;
tmp_out.data = tmp.data_array[i];
tmp_out.tlast = (i == tmp.size - 1);
tmp_out.setKeep();
dma_w_source.write(tmp_out);
HLS_DEBUG(1, 1, 0, "dma_w_source sending new data[%d,%d]: %s.", i + 1, tmp.size,
tmp_out.data.to_string().c_str());
}
HLS_DEBUG(1, 1, 0, "done");
dma_source_w_done.write(tmp.size);
}
}
sc_fifo<sc_uint<64> > dma_source_ctrl_ctrl;
void dma_source_ctrl_thread() {
while (true) {
sc_uint<64> tmp = dma_source_ctrl_ctrl.read();
hwcore::pipes::sc_data_stream_t<64> tmp_out;
tmp_out.setKeep();
tmp_out.data = tmp;
tmp_out.tlast = 1;
dma_ctrl_source.write(tmp_out);
HLS_DEBUG(1, 1, 0, "dma_ctrl_source sending new data: %s.", tmp_out.data.to_string().c_str());
}
}
sc_fifo<dma_pkg> dma_sink_ctrl;
sc_fifo<uint64> dma_sink_done;
#if 0
void live_debug()
{
for(int x= 0; x < 14; x++)
{
for(int y=0; y < 14 ; y++)
{
for(int )
}
}
}
#endif
void dma_sink_thread() {
while (true) {
uint64 size = 0;
dma_pkg tmp = dma_sink_ctrl.read();
for (int i = 0; i < tmp.size; i++) {
size++;
hwcore::pipes::sc_data_stream_t<P_input_width> tmp_in;
dma_sink.read(tmp_in);
tmp.data_array[i] = tmp_in.data;
HLS_DEBUG(1, 1, 0, "dma_sink got new data[%d,%d]: %s.", i + 1, tmp.size,
tmp_in.data.to_string().c_str());
// sc_assert((tmp_in.tlast == 0 && i != tmp.size - 1) || (tmp_in.tlast == 1 && i == tmp.size - 1));
if (tmp_in.tlast == 1) {
// sc_assert(i == tmp.size - 1);
break;
}
}
HLS_DEBUG(1, 1, 0, "done");
dma_sink_done.write(size);
}
}
virtual ~tb_cnn_2d() { sc_close_vcd_trace_file(tracePtr); }
};
|
#ifndef TOP_HPP
#define TOP_HPP
#include <systemc.h>
#include "scheduler.hpp"
#include "processing_engine.hpp"
#include "verbose.hpp"
#define CORE_BIND(NAME, INDEX) \
NAME.clk(clk); \
NAME.reset(reset); \
NAME.from_scheduler_instructions(npu_instructions[INDEX]); \
NAME.from_scheduler_weight(npu_weight[INDEX]); \
NAME.from_scheduler_input(npu_input[INDEX]); \
NAME.to_scheduler(npu_output[INDEX]);
class top_module : public sc_core::sc_module
{
public:
sc_in<bool> clk;
sc_in<bool> reset;
// IO
sc_fifo_in< sc_uint<64> > dma_config;
sc_fifo_in<float> dma_weight;
sc_fifo_in<float> dma_input;
sc_fifo_out<float> dma_output;
sc_fifo<sc_uint<34>> npu_instructions[CORE];
sc_fifo<float> npu_weight[CORE];
sc_fifo<float> npu_input[CORE];
sc_fifo<float> npu_output[CORE];
// Modules
scheduler_module mod_scheduler;
// Cores
#if CORE == 8
processing_engine_module mod_core_1;
processing_engine_module mod_core_2;
processing_engine_module mod_core_3;
processing_engine_module mod_core_4;
processing_engine_module mod_core_5;
processing_engine_module mod_core_6;
processing_engine_module mod_core_7;
processing_engine_module mod_core_8;
#elif CORE == 4
processing_engine_module mod_core_1;
processing_engine_module mod_core_2;
processing_engine_module mod_core_3;
processing_engine_module mod_core_4;
#elif CORE == 2
processing_engine_module mod_core_1;
processing_engine_module mod_core_2;
#elif CORE == 1
processing_engine_module mod_core_1;
#endif
top_module(sc_module_name name);
SC_HAS_PROCESS(top_module);
};
#endif
|
#ifndef IPS_VGA_TLM_HPP
#define IPS_VGA_TLM_HPP
#include <systemc.h>
using namespace sc_core;
using namespace sc_dt;
using namespace std;
#include <tlm.h>
#include <tlm_utils/simple_initiator_socket.h>
#include <tlm_utils/simple_target_socket.h>
#include <tlm_utils/peq_with_cb_and_phase.h>
#include "common_func.hpp"
#include "important_defines.hpp"
#include "vga.hpp"
#include "../src/img_target.cpp"
// Extended Unification TLM
struct vga_tlm
: public vga<
IPS_BITS,
IPS_H_ACTIVE, IPS_H_FP, IPS_H_SYNC_PULSE, IPS_H_BP,
IPS_V_ACTIVE, IPS_V_FP, IPS_V_SYNC_PULSE, IPS_V_BP
>, public img_target
{
protected:
unsigned char* tmp_img;
public:
vga_tlm(sc_module_name name)
: vga<
IPS_BITS,
IPS_H_ACTIVE, IPS_H_FP, IPS_H_SYNC_PULSE, IPS_H_BP,
IPS_V_ACTIVE, IPS_V_FP, IPS_V_SYNC_PULSE, IPS_V_BP>((std::string(name) + "_HW_block").c_str()),
img_target((std::string(name) + "_target").c_str())
{
#ifdef DISABLE_VGA_DEBUG
this->use_prints = false;
#endif // DISABLE_VGA_DEBUG
checkprintenableimgtar(use_prints);
}
// Override do_when_transaction functions
virtual void do_when_read_transaction(unsigned char *&data, unsigned int data_length, sc_dt::uint64 address);
virtual void do_when_write_transaction(unsigned char *&data, unsigned int data_length, sc_dt::uint64 address);
};
#endif // IPS_VGA_TLM_HPP
|
/***************************************************************************\
*
*
* ___ ___ ___ ___
* / /\ / /\ / /\ / /\
* / /:/ / /::\ / /::\ / /::\
* / /:/ / /:/\:\ / /:/\:\ / /:/\:\
* / /:/ / /:/~/:/ / /:/~/::\ / /:/~/:/
* / /::\ /__/:/ /:/___ /__/:/ /:/\:\ /__/:/ /:/
* /__/:/\:\ \ \:\/:::::/ \ \:\/:/__\/ \ \:\/:/
* \__\/ \:\ \ \::/~~~~ \ \::/ \ \::/
* \ \:\ \ \:\ \ \:\ \ \:\
* \ \ \ \ \:\ \ \:\ \ \:\
* \__\/ \__\/ \__\/ \__\/
*
*
*
*
* This file is part of TRAP.
*
* TRAP is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* or see <http://www.gnu.org/licenses/>.
*
*
*
* (c) Luca Fossati, fossati@elet.polimi.it, fossati.l@gmail.com
*
\***************************************************************************/
#ifndef PINTARGET_HPP
#define PINTARGET_HPP
#include <systemc.h>
#include <tlm.h>
#include <tlm_utils/simple_target_socket.h>
#include <boost/lexical_cast.hpp>
#include <string>
#include <trap_utils.hpp>
namespace trap{
template<unsigned int sockSize> class PINTarget: public sc_module{
public:
tlm_utils::simple_target_socket<PINTarget, sockSize> socket;
PINTarget(sc_module_name name) : sc_module(name), socket(("pin_target_" + boost::lexical_cast<std::string>(name)).c_str()){
this->socket.register_b_transport(this, &PINTarget::b_transport);
end_module();
}
void b_transport(tlm::tlm_generic_payload& trans, sc_time& delay){
tlm::tlm_command cmd = trans.get_command();
sc_dt::uint64 adr = trans.get_address();
unsigned char* ptr = trans.get_data_ptr();
unsigned int len = trans.get_data_length();
unsigned char* byt = trans.get_byte_enable_ptr();
unsigned int wid = trans.get_streaming_width();
if(trans.get_command() == tlm::TLM_READ_COMMAND){
THROW_EXCEPTION("Error, the read request is not currently supported by external PINs");
}
else if(cmd == tlm::TLM_WRITE_COMMAND){
this->values[(unsigned int)adr] = *((unsigned int *)ptr);
}
trans.set_response_status(tlm::TLM_OK_RESPONSE);
}
// Method used to read the value of the just assigned PIN
unsigned int readPIN(unsigned int address){
if(this->values.find(address) == this->values.end()){
THROW_EXCEPTION("Address " << std::hex << std::showbase << address << " not yet written by PIN port");
}
return this->values[address];
}
private:
std::map<unsigned int, unsigned int> values;
};
};
#endif
|
#ifndef IPS_SEQ_ITEM_VGA_HPP
#define IPS_SEQ_ITEM_VGA_HPP
#define int64 systemc_int64
#define uint64 systemc_uint64
#include <systemc.h>
#include <systemc-ams.h>
#undef int64
#undef uint64
#define int64 opencv_int64
#define uint64 opencv_uint64
#include <opencv2/opencv.hpp>
#undef int64
#undef uint64
#include "vunit.hpp"
// Image path
#define IPS_IMG_PATH_TB "../../tools/datagen/src/imgs/car_rgb_noisy_image.jpg"
/**
* @brief This class is used to generate the data for the AMS test
*
* @tparam BITS - the number of output bits of the digital pixel
* @tparam H_ACTIVE - output horizontal active video pixels
* @tparam H_FP - wait after the display period before the sync
* horizontal pulse
* @tparam H_SYNC_PULSE - assert HSYNC
* @tparam H_BP - wait after the sync horizontal pulse before starting
* the next display period
* @tparam V_ACTIVE - output vertical active video pixels
* @tparam V_FP - wait after the display period before the sync
* vertical pulse
* @tparam V_SYNC_PULSE - assert VSYNC
* @tparam V_BP - wait after the sync vertical pulse before starting
* the next display period
*/
template <
unsigned int BITS = 8,
unsigned int H_ACTIVE = 640,
unsigned int H_FP = 16,
unsigned int H_SYNC_PULSE = 96,
unsigned int H_BP = 48,
unsigned int V_ACTIVE = 480,
unsigned int V_FP = 10,
unsigned int V_SYNC_PULSE = 2,
unsigned int V_BP = 33,
int VMIN = 0,
int VMAX = 5,
VUnit VU = VUnit::v>
SCA_TDF_MODULE(seq_item_vga)
{
protected:
cv::Mat tx_img;
// Min voltage value based on the voltage units
const double V_MIN = static_cast<double>(VMIN) / static_cast<double>(VU);
// Max voltage value based on the voltage units
const double V_MAX = static_cast<double>(VMAX) / static_cast<double>(VU);
// Max digital output code
const double MAX_DIG = static_cast<double>((1 << BITS) - 1);
public:
// Counters
sca_tdf::sca_de::sca_in<unsigned int> hcount;
sca_tdf::sca_de::sca_in<unsigned int> vcount;
// Output pixel
sca_tdf::sca_out<double> o_red;
sca_tdf::sca_out<double> o_green;
sca_tdf::sca_out<double> o_blue;
SC_CTOR(seq_item_vga)
{
// Read image
const std::string img_path = IPS_IMG_PATH_TB;
cv::Mat read_img = cv::imread(img_path, cv::IMREAD_COLOR);
// CV_8UC3 Type: 8-bit unsigned, 3 channels (e.g., for a color image)
read_img.convertTo(this->tx_img, CV_8UC3);
// Check if the image is loaded successfully
if (this->tx_img.empty())
{
std::cerr << "Error: Could not open or find the image!" << std::endl;
exit(EXIT_FAILURE);
}
}
void set_attributes()
{
// Propagation time from input to output
set_timestep(sca_core::sca_time(1, sc_core::SC_NS));
this->o_red.set_delay(17);
this->o_green.set_delay(17);
this->o_blue.set_delay(17);
}
void processing()
{
const int IMG_ROW = static_cast<int>(this->vcount.read()) - (V_SYNC_PULSE + V_BP);
const int IMG_COL = static_cast<int>(this->hcount.read()) - (H_SYNC_PULSE + H_BP);
if ((IMG_ROW < 0) || (IMG_COL < 0) || (IMG_ROW >= static_cast<int>(V_ACTIVE)) || (IMG_COL >= static_cast<int>(H_ACTIVE)))
{
this->o_red.write(0.0);
this->o_green.write(0.0);
this->o_blue.write(0.0);
}
else
{
if ((IMG_ROW >= this->tx_img.rows) || (IMG_COL >= this->tx_img.cols))
{
this->o_red.write(0.0);
this->o_green.write(0.0);
this->o_blue.write(0.0);
}
else
{
cv::Vec3b pixel = tx_img.at<cv::Vec3b>(IMG_ROW, IMG_COL, 0);
this->o_red.write(sc_uint2double(static_cast<sc_uint<BITS>>(pixel[0])));
this->o_green.write(sc_uint2double(static_cast<sc_uint<BITS>>(pixel[1])));
this->o_blue.write(sc_uint2double(static_cast<sc_uint<BITS>>(pixel[2])));
}
}
}
/**
* @brief Convert the digital signal into analog signal
* The N-bit digital code is converted into an analog signal in a voltage
* range from Vmin to Vmax
*/
double sc_uint2double(sc_uint<BITS> in)
{
double dig_in = static_cast<double>(in);
return V_MIN + (dig_in / MAX_DIG) * (V_MAX - V_MIN);
}
};
#endif // IPS_SEQ_ITEM_VGA_HPP
|
#pragma once
#include<string>
#include<systemc.h>
using std::string;
class write_if_f: virtual public sc_interface
{
public:
virtual void write(string) = 0;
virtual void nb_write(string) = 0;
};
class read_if_f: virtual public sc_interface
{
public:
virtual void read(string &) = 0;
virtual void nb_read(string &) = 0;
virtual void notify() = 0;
};
class write_if: virtual public sc_interface
{
public:
virtual void write(string) = 0;
};
class read_if: virtual public sc_interface
{
public:
virtual void read(string &) = 0;
};
|
/*
* Copyright (C) 2020 GreenWaves Technologies, SAS, ETH Zurich and
* University of Bologna
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Authors: Germain Haugou, GreenWaves Technologies (germain.haugou@greenwaves-technologies.com)
*/
#ifndef __VP_TIME_ENGINE_HPP__
#define __VP_TIME_ENGINE_HPP__
#include "vp/vp_data.hpp"
#include "vp/component.hpp"
#ifdef __VP_USE_SYSTEMC
#include <systemc.h>
#endif
namespace vp
{
class time_engine_client;
class time_engine : public component
{
public:
time_engine(js::config *config);
void start();
void run_loop();
int64_t step(int64_t timestamp);
void run();
void quit(int status);
int join();
int64_t get_next_event_time();
inline void lock_step();
inline void lock_step_cancel();
inline void lock();
inline void wait_running();
inline void unlock();
inline void stop_engine(int status=0, bool force = true, bool no_retain = false);
inline void stop_retain(int count);
inline void pause();
void stop_exec();
void req_stop_exec();
void register_exec_notifier(Notifier *notifier);
inline vp::time_engine *get_time_engine() { return this; }
bool dequeue(time_engine_client *client);
bool enqueue(time_engine_client *client, int64_t time);
int64_t get_time() { return time; }
inline void retain() { retain_count++; }
inline void release() { retain_count--; }
inline void fatal(const char *fmt, ...);
inline void update(int64_t time);
void wait_ready();
private:
time_engine_client *first_client = NULL;
bool locked = false;
bool locked_run_req;
bool run_req;
bool stop_req;
bool pause_req;
bool finished = false;
bool init = false;
bool running;
pthread_mutex_t mutex;
pthread_cond_t cond;
pthread_t run_thread;
int64_t time = 0;
int stop_status = -1;
bool engine_has_been_stopped = false;
int retain_count = 0;
bool no_exit;
int stop_retain_count = 0;
#ifdef __VP_USE_SYSTEMC
sc_event sync_event;
bool started = false;
#endif
private:
vp::component *stop_event;
std::vector<Notifier *> exec_notifiers;
};
class time_engine_client : public component
{
friend class time_engine;
public:
time_engine_client(js::config *config)
: vp::component(config)
{
}
inline bool is_running() { return running; }
inline bool enqueue_to_engine(int64_t time)
{
return engine->enqueue(this, time);
}
inline bool dequeue_from_engine()
{
return engine->dequeue(this);
}
inline int64_t get_time() { return engine->get_time(); }
virtual int64_t exec() = 0;
protected:
time_engine_client *next;
// This gives the time of the next event.
// It is only valid when the client is not the currently active one,
// and is then updated either when the client is not the active one
// anymore or when the client is enqueued to the engine.
int64_t next_event_time = 0;
vp::time_engine *engine;
bool running = false;
bool is_enqueued = false;
};
// This can be called from anywhere so just propagate the stop request
// to the main python thread which will take care of stopping the engine.
inline void vp::time_engine::stop_engine(int status, bool force, bool no_retain)
{
if (!this->engine_has_been_stopped)
{
this->engine_has_been_stopped = true;
stop_status = status;
}
else
{
stop_status |= status;
}
if (no_retain || stop_retain_count == 0 || stop_status != 0)
{
#ifdef __VP_USE_SYSTEMC
sync_event.notify();
#endif
if (force || !this->no_exit)
{
// In case the vp is connected to an external bridge, prevent the platform
// from exiting unless a ctrl-c is hit
pthread_mutex_lock(&mutex);
stop_req = true;
run_req = false;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
}
}
inline void vp::time_engine::stop_retain(int count)
{
this->stop_retain_count += count;
}
inline void vp::time_engine::pause()
{
pthread_mutex_lock(&mutex);
run_req = false;
pthread_cond_broadcast(&cond);
while(this->running)
{
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
}
inline void vp::time_engine::wait_running()
{
pthread_mutex_lock(&mutex);
while (!init)
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
}
inline void vp::time_engine::lock_step()
{
if (!locked)
{
locked = true;
locked_run_req = run_req;
run_req = false;
}
}
inline void vp::time_engine::lock_step_cancel()
{
pthread_mutex_lock(&mutex);
if (locked)
{
run_req = locked_run_req;
locked = false;
}
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
inline void vp::time_engine::lock()
{
pthread_mutex_lock(&mutex);
if (!locked)
{
locked_run_req = run_req;
run_req = false;
locked = true;
}
pthread_cond_broadcast(&cond);
while (running)
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
}
inline void vp::time_engine::unlock()
{
pthread_mutex_lock(&mutex);
run_req = locked_run_req;
locked = false;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
inline void vp::time_engine::fatal(const char *fmt, ...)
{
fprintf(stdout, "[\033[31mFATAL\033[0m] ");
va_list ap;
va_start(ap, fmt);
if (vfprintf(stdout, fmt, ap) < 0)
{
}
va_end(ap);
stop_engine(-1);
}
inline void vp::time_engine::update(int64_t time)
{
if (time > this->time)
this->time = time;
}
}; // namespace vp
#endif
|
/*
* Created on: 21. jun. 2019
* Author: Jonathan Horsted Schougaard
*/
#pragma once
#define SC_INCLUDE_FX
#include "hwcore/pipes/pipes.h"
#include <systemc.h>
#if __RTL_SIMULATION__
//#include "DMA_performance_tester_rtl_wrapper.h"
//#else
//#include "DMA_generic_performance_tester.hpp"
#endif
const long test_size = 250;
SC_MODULE(mon_bufferstreamer) {
sc_fifo_out<sc_uint<31> > ctrl_out;
sc_fifo_in<hwcore::pipes::sc_data_stream_t<16> > data_in;
SC_CTOR(mon_bufferstreamer) { SC_THREAD(mon_thread); }
void mon_thread() {
uint16_t data_gen = 0;
std::cout << "(mon) req. newset (start) " << std::endl;
ctrl_out.write(hwcore::pipes::sc_stream_buffer<>::ctrls::newset);
std::cout << "(mon) req. newset (done) " << std::endl;
hwcore::pipes::sc_data_stream_t<16> raw_tmp;
for (int a = 0; a < 5; a++) {
ctrl_out.write(hwcore::pipes::sc_stream_buffer<>::ctrls::reapeat);
for (int i = 0; i < test_size; i++) {
raw_tmp = data_in.read();
uint16_t tmp = raw_tmp.data.to_uint();
std::cout << "(mon) got new data: " << tmp << ", last? " << (raw_tmp.tlast ? "true" : "false")
<< std::endl;
sc_assert((i == test_size - 1) == (raw_tmp.tlast == 1));
sc_assert(tmp == i);
if (tmp != i) {
sc_stop();
}
}
raw_tmp = data_in.read();
uint16_t tmp = raw_tmp.data.to_uint();
std::cout << "(mon) got new data: " << tmp << ", last? " << (raw_tmp.tlast ? "true" : "false") << std::endl;
sc_assert(raw_tmp.EOP());
}
std::cout << "(mon) req. newset (start) " << std::endl;
ctrl_out.write(hwcore::pipes::sc_stream_buffer<>::ctrls::newset);
std::cout << "(mon) req. newset (done) " << std::endl;
for (int a = 0; a < 5; a++) {
ctrl_out.write(hwcore::pipes::sc_stream_buffer<>::ctrls::reapeat);
for (int i = 0; i < test_size; i++) {
raw_tmp = data_in.read();
uint16_t tmp = raw_tmp.data.to_uint();
std::cout << "(mon) got new data: " << tmp << ", last? " << (raw_tmp.tlast ? "true" : "false")
<< std::endl;
sc_assert((i == test_size - 1) == (raw_tmp.tlast == 1));
sc_assert(tmp == i + 0xBF);
if (tmp != i + 0xBF) {
sc_stop();
}
}
raw_tmp = data_in.read();
uint16_t tmp = raw_tmp.data.to_uint();
std::cout << "(mon) got new data: " << tmp << ", last? " << (raw_tmp.tlast ? "true" : "false") << std::endl;
sc_assert(raw_tmp.EOP());
}
std::cout << "Test finish no errors" << std::endl;
sc_stop();
}
};
SC_MODULE(wave_bufferstreamer) {
sc_fifo_out<hwcore::pipes::sc_data_stream_t<16> > data_out;
SC_CTOR(wave_bufferstreamer) { SC_THREAD(wave_thread); }
void wave_thread() {
hwcore::pipes::sc_data_stream_t<16> tmp;
for (int i = 0; i < test_size; i++) {
tmp.data = i;
std::cout << "(wave) write new data: " << i << std::endl;
tmp.tkeep = 0b11;
tmp.tlast = (i == test_size - 1);
std::cout << "(wave) tlast " << (tmp.tlast ? "true" : "false") << std::endl;
data_out.write(tmp);
}
tmp.setEOP();
data_out.write(tmp);
for (int i = 0; i < test_size; i++) {
tmp.data = i + 0xBF;
std::cout << "(wave) write new data: " << i << std::endl;
tmp.tkeep = 0b11;
tmp.tlast = (i == test_size - 1);
std::cout << "(wave) tlast " << (tmp.tlast ? "true" : "false") << std::endl;
data_out.write(tmp);
}
tmp.setEOP();
data_out.write(tmp);
}
};
SC_MODULE(tb_bufferstreamer) {
#if __RTL_SIMULATION__
// DMA_performance_tester_rtl_wrapper u1;
#else
// DMA_performance_tester u1;
#endif
sc_clock clk;
sc_signal<bool> reset;
hwcore::pipes::sc_stream_buffer_not_stream_while_write<16> bs_u1;
wave_bufferstreamer wave;
mon_bufferstreamer mon;
sc_fifo<hwcore::pipes::sc_data_stream_t<16> > bs2mon_data;
sc_fifo<sc_uint<31> > mon2bs_ctrl;
sc_fifo<hwcore::pipes::sc_data_stream_t<16> > wave2bs_data;
SC_CTOR(tb_bufferstreamer) : bs_u1("BS"), wave("wave"), mon("mon"), clk("clock", sc_time(10, SC_NS)) {
bs_u1.clk(clk);
bs_u1.reset(reset);
bs_u1.din(wave2bs_data);
bs_u1.dout(bs2mon_data);
bs_u1.ctrls_in(mon2bs_ctrl);
wave.data_out(wave2bs_data);
mon.ctrl_out(mon2bs_ctrl);
mon.data_in(bs2mon_data);
}
};
|
#include<systemc.h>
#include<vector>
#include "interfaces.hpp"
#include<nana/gui/widgets/listbox.hpp>
using std::vector;
class instruction_queue_rob: public sc_module
{
public:
sc_port<read_if> in;
sc_port<write_if_f> out;
sc_port<read_if> in_rob;
SC_HAS_PROCESS(instruction_queue_rob);
instruction_queue_rob(sc_module_name name, vector<string> inst_q,int rb_sz, nana::listbox &instr);
void main();
void leitura_rob();
bool queue_is_empty();
unsigned int get_instruction_counter();
private:
unsigned int pc;
struct instr_q
{
string instruction;
unsigned int pc;
};
vector<instr_q> instruct_queue;
vector<string> original_instruct;
vector<vector<instr_q>> last_instr;
vector<unsigned int> last_pc;
nana::listbox &instructions;
void replace_instructions(unsigned int pos,unsigned int index);
void add_instructions(unsigned int pos, vector<instr_q> instructions);
};
|
#ifndef IPS_VGA_MODEL_HPP
#define IPS_VGA_MODEL_HPP
#include <systemc.h>
#ifdef IPS_AMS
#include <systemc-ams.h>
#endif // IPS_AMS
#define IPS_VGA_ACTIVE true
#define IPS_VGA_INACTIVE false
// Main clock frequency in Hz - 25.175 MHz
#define CLK_FREQ 25175000
/**
* @brief VGA representation class
*
* @tparam BITS - the number of output bits of the digital pixel
* @tparam H_ACTIVE - output horizontal active video pixels
* @tparam H_FP - wait after the display period before the sync
* horizontal pulse
* @tparam H_SYNC_PULSE - assert HSYNC
* @tparam H_BP - wait after the sync horizontal pulse before starting
* the next display period
* @tparam V_ACTIVE - output vertical active video pixels
* @tparam V_FP - wait after the display period before the sync
* vertical pulse
* @tparam V_SYNC_PULSE - assert VSYNC
* @tparam V_BP - wait after the sync vertical pulse before starting
* the next display period
*/
template <
unsigned int BITS = 8,
unsigned int H_ACTIVE = 640,
unsigned int H_FP = 16,
unsigned int H_SYNC_PULSE = 96,
unsigned int H_BP = 48,
unsigned int V_ACTIVE = 480,
unsigned int V_FP = 10,
unsigned int V_SYNC_PULSE = 2,
unsigned int V_BP = 33
>
SC_MODULE(vga)
{
protected:
// Horizontal count
int h_count;
// Vertical count
int v_count;
public:
#ifndef USING_TLM_TB_EN
// Input clock
sc_core::sc_in<bool> clk;
#else
// Compute the clock time in seconds
const double CLK_TIME = 1.0 / static_cast<double>(CLK_FREQ);
// Internal clock
sc_core::sc_clock clk;
#endif // USING_TLM_TB_EN
// Input pixel
sc_core::sc_in<sc_uint<BITS> > red;
sc_core::sc_in<sc_uint<BITS> > green;
sc_core::sc_in<sc_uint<BITS> > blue;
// Counter outputs
sc_core::sc_out<unsigned int> o_h_count;
sc_core::sc_out<unsigned int> o_v_count;
// Output horizontal sync
sc_core::sc_out<bool> o_hsync;
// Output vertical sync
sc_core::sc_out<bool> o_vsync;
#ifndef USING_TLM_TB_EN
// Output pixel
sc_core::sc_out<sc_uint<BITS> > o_red;
sc_core::sc_out<sc_uint<BITS> > o_green;
sc_core::sc_out<sc_uint<BITS> > o_blue;
#else
unsigned char *tmp_img;
bool start;
bool done;
#endif // USING_TLM_TB_EN
SC_CTOR(vga)
: o_hsync("o_hsync"), o_vsync("o_vsync")
#ifdef USING_TLM_TB_EN
, clk("clk", CLK_TIME, sc_core::SC_SEC)
#endif
{
this->h_count = 0;
this->v_count = 0;
SC_METHOD(run);
#ifndef USING_TLM_TB_EN
sensitive << clk.pos();
#else
sensitive << clk;
this->tmp_img = new unsigned char[H_ACTIVE * V_ACTIVE * 3];
this->start = false;
this->done = false;
#endif // USING_TLM_TB_EN
}
/**
* @brief Override method
* Compute the values output of the VGA
*
*/
void run()
{
if (this->clk.read())
{
#ifdef USING_TLM_TB_EN
if (this->start)
{
#endif // USING_TLM_TB_EN
#ifdef IPS_DEBUG_EN
std::cout << "@" << sc_core::sc_time_stamp().to_seconds() * 1e6 << "us" << std::endl;
#endif // IPS_DEBUG_EN
// Increment H counter
this->h_count++;
// HSYNC pulse
if (this->h_count == H_SYNC_PULSE)
{
this->o_hsync.write(IPS_VGA_ACTIVE);
}
else if (this->h_count == (H_SYNC_PULSE + H_BP))
{
this->o_hsync.write(IPS_VGA_ACTIVE);
}
else if (this->h_count == (H_SYNC_PULSE + H_BP + H_ACTIVE))
{
this->o_hsync.write(IPS_VGA_ACTIVE);
}
// End of HSYNC
else if (this->h_count == (H_SYNC_PULSE + H_BP + H_ACTIVE + H_FP))
{
// Restart H counter
this->o_hsync.write(IPS_VGA_INACTIVE);
this->h_count = 0;
// Increment H counter
this->v_count++;
// VSYNC pulse
if (this->v_count == V_SYNC_PULSE)
{
this->o_vsync.write(IPS_VGA_ACTIVE);
}
// End of V-sync pulse
else if (this->v_count == (V_SYNC_PULSE + V_BP))
{
this->o_vsync.write(IPS_VGA_ACTIVE);
}
// V front porch
else if (this->v_count == (V_SYNC_PULSE + V_BP + V_ACTIVE))
{
this->o_vsync.write(IPS_VGA_ACTIVE);
}
// End of VSYNC
else if (this->v_count == (V_SYNC_PULSE + V_BP + V_ACTIVE + V_FP))
{
this->o_vsync.write(IPS_VGA_INACTIVE);
this->v_count = 0;
this->done = true;
this->start = false;
}
}
this->o_v_count.write(this->v_count);
this->o_h_count.write(this->h_count);
#ifndef USING_TLM_TB_EN
this->o_red.write(this->red.read());
this->o_green.write(this->green.read());
this->o_blue.write(this->blue.read());
#else
const int IMG_ROW = this->v_count - (V_SYNC_PULSE + V_BP);
const int IMG_COL = this->h_count - (H_SYNC_PULSE + H_BP);
if (!((IMG_ROW < 0) || (IMG_COL < 0) || (IMG_ROW >= V_ACTIVE) || (IMG_COL >= H_ACTIVE)))
{
const unsigned int INDEX = IMG_ROW * (3 * H_ACTIVE) + 3 * IMG_COL;
this->tmp_img[INDEX] = this->red.read();
this->tmp_img[INDEX + 1] = this->green.read();
this->tmp_img[INDEX + 2] = this->blue.read();
}
}
#endif // USING_TLM_TB_EN
}
}
};
#endif // IPS_VGA_MODEL_HPP
|
#ifndef SOBEL_EDGE_DETECTOR_TLM_CPP
#define SOBEL_EDGE_DETECTOR_TLM_CPP
#include <systemc.h>
using namespace sc_core;
using namespace sc_dt;
using namespace std;
#include <tlm.h>
#include <tlm_utils/simple_initiator_socket.h>
#include <tlm_utils/simple_target_socket.h>
#include <tlm_utils/peq_with_cb_and_phase.h>
#include "sobel_edge_detector_tlm.hpp"
#include "common_func.hpp"
void sobel_edge_detector_tlm::do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address){
short int sobel_results[4];
sc_int<16> local_result;
dbgimgtarmodprint(use_prints, "Calling do_when_read_transaction");
Edge_Detector::address = address;
read();
for (int i = 0; i < 4; i++)
{
local_result = Edge_Detector::data.range((i + 1) * 16 - 1, i * 16).to_int();
sobel_results[i] = (short int)local_result;
dbgimgtarmodprint(use_prints, "%0d", sobel_results[i]);
}
memcpy(data, sobel_results, 4 * sizeof(short int));
}
void sobel_edge_detector_tlm::do_when_write_transaction(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address)
{
sc_uint<8> values[8];
dbgimgtarmodprint(use_prints, "Calling do_when_write_transaction");
for (int i = 0; i < 8; i++)
{
values[i] = *(data + i);
}
Edge_Detector::data = (values[7], values[6], values[5], values[4], values[3], values[2], values[1], values[0]);
Edge_Detector::address = address;
write();
}
void sobel_edge_detector_tlm::read()
{
if ((Edge_Detector::address - SOBEL_OUTPUT_ADDRESS_LO) == 0)
{
Edge_Detector::data = (sc_uint<32>(0), resultSobelGradientY, resultSobelGradientX);
}
}
void sobel_edge_detector_tlm::write()
{
wr_t.notify(0, SC_NS);
}
#endif // SOBEL_EDGE_DETECTOR_TLM_CPP
|
/***************************************************************************\
*
*
* ___ ___ ___ ___
* / /\ / /\ / /\ / /\
* / /:/ / /::\ / /::\ / /::\
* / /:/ / /:/\:\ / /:/\:\ / /:/\:\
* / /:/ / /:/~/:/ / /:/~/::\ / /:/~/:/
* / /::\ /__/:/ /:/___ /__/:/ /:/\:\ /__/:/ /:/
* /__/:/\:\ \ \:\/:::::/ \ \:\/:/__\/ \ \:\/:/
* \__\/ \:\ \ \::/~~~~ \ \::/ \ \::/
* \ \:\ \ \:\ \ \:\ \ \:\
* \ \ \ \ \:\ \ \:\ \ \:\
* \__\/ \__\/ \__\/ \__\/
*
*
*
*
* This file is part of TRAP.
*
* TRAP is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* or see <http://www.gnu.org/licenses/>.
*
*
*
* (c) Luca Fossati, fossati@elet.polimi.it, fossati.l@gmail.com
*
\***************************************************************************/
#ifndef IRQGENERATOR_HPP
#define IRQGENERATOR_HPP
#include <iostream>
#include <systemc.h>
#include <trap_utils.hpp>
#include <boost/lexical_cast.hpp>
#include <tlm.h>
#include <tlm_utils/simple_initiator_socket.h>
//Now some stuff for generating random numbers
#include <ctime>
#include <boost/random/linear_congruential.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/uniform_real.hpp>
#include <boost/random/variate_generator.hpp>
#ifdef BOOST_NO_STDC_NAMESPACE
namespace std {
using ::time;
}
#endif
class IrqGenerator : public sc_module{
private:
sc_time latency;
int lastIrq;
// Random number generator to be used during algorithm execution
boost::minstd_rand generator;
public:
//The initiator socket is used for sending out, raising interrupts;
//the target socket for receiving the acknowledgement
tlm_utils::simple_initiator_socket< IrqGenerator, 32 > initSocket;
tlm_utils::simple_target_socket< IrqGenerator, 32 > targSocket;
SC_HAS_PROCESS( IrqGenerator );
IrqGenerator( sc_module_name generatorName, sc_time latency ) : sc_module(generatorName),
targSocket(("irq_target_" + boost::lexical_cast<std::string>(generatorName)).c_str()),
latency(latency), generator(static_cast<unsigned int>(std::time(NULL))){
this->targSocket.register_b_transport(this, &IrqGenerator::b_transport);
this->lastIrq = -1;
SC_THREAD(generateIrq);
end_module();
}
//Method used for receiving acknowledgements of interrupts; the ack consists of
//uninteresting data and the address corresponds to the interrupt signal to
//be lowered
//As a response, I lower the interrupt by sending a NULL pointer on the initSocket
void b_transport(tlm::tlm_generic_payload& trans, sc_time& delay){
if(this->lastIrq < 0){
THROW_EXCEPTION("Error, lowering an interrupt which hasn't been raised yet!!");
}
tlm::tlm_command cmd = trans.get_command();
sc_dt::uint64 adr = trans.get_address();
unsigned char* ptr = trans.get_data_ptr();
if(trans.get_command() == tlm::TLM_READ_COMMAND){
THROW_EXCEPTION("Error, the read request is not currently supported by external PINs");
}
else if(cmd == tlm::TLM_WRITE_COMMAND){
if(this->lastIrq != adr){
THROW_EXCEPTION("Error, lowering interrupt " << std::hex << std::showbase << (unsigned int)adr << " while " << std::hex << std::showbase << this->lastIrq << " was raised");
}
else{
//finally I can really lower the interrupt: I send 0 on
//the initSocked
unsigned char data = 0;
trans.set_data_ptr(&data);
trans.set_dmi_allowed(false);
trans.set_response_status( tlm::TLM_INCOMPLETE_RESPONSE );
sc_time delay;
this->initSocket->b_transport(trans, delay);
if(trans.is_response_error()){
std::string errorStr("Error in b_transport of PIN, response status = " + trans.get_response_string());
SC_REPORT_ERROR("TLM-2", errorStr.c_str());
}
this->lastIrq = -1;
}
}
trans.set_response_status(tlm::TLM_OK_RESPONSE);
}
//Simple systemc thread which keeps on generating interrupts;
//the number of the interrupt is printed to the screen before sending it to
//the processor
void generateIrq(){
while(true){
//An interrupt transaction is composed of a data pointer (containing
//0 if the interrupt has to be lowered, different if raised) and an
//address, corrisponding to the ID of the interrupt
if(this->lastIrq == -1){
unsigned char data = 1;
tlm::tlm_generic_payload trans;
boost::uniform_int<> degen_dist(0x1, 0xe);
boost::variate_generator<boost::minstd_rand&, boost::uniform_int<> > deg(this->generator, degen_dist);
this->lastIrq = deg();
std::cerr << "Sending out IRQ id=" << std::hex << std::showbase << this->lastIrq << std::endl;
trans.set_address(this->lastIrq);
trans.set_data_ptr(&data);
trans.set_data_length(0);
trans.set_byte_enable_ptr(0);
trans.set_dmi_allowed(false);
trans.set_response_status( tlm::TLM_INCOMPLETE_RESPONSE );
sc_time delay;
this->initSocket->b_transport(trans, delay);
if(trans.is_response_error()){
std::string errorStr("Error in generateIrq, response status = " + trans.get_response_string());
SC_REPORT_ERROR("TLM-2", errorStr.c_str());
}
}
wait(this->latency);
}
}
};
#endif
|
#include <iostream>
#include <systemc.h>
int run_mem_access_simulation(unsigned long int stack);
|
#ifndef __MESSY_CORE_H__
#define __MESSY_CORE_H__
#include <config.hpp>
#include <systemc.h>
#include <cstring>
#include <string.h>
#include <adapters/${adapter_filenames}.hpp>
#include <messy_request.hpp>
class Core : public sc_module
{
public:
void run();
void close();
void run_next_sc();
void continue_messy(bool handle_req_queue);
void handle_req_queue();
void request_delay(double start_time,int time_to_skip,int resolution);
void handle_req(MessyRequest *req);
// This gets called when an access from gvsoc side is reaching us
void access_request(MessyRequest *req);
// This gets called when one of our access gets granted
void grant_req(MessyRequest *req);
// This gets called when one of our access gets its response
void reply_to_req(MessyRequest *req);
int simulation_iters=0;
double tot_power=0.0;
sc_core::sc_out <int> request_address;
sc_core::sc_out <int> request_data;
sc_core::sc_out <bool> functional_bus_flag;
sc_core::sc_out <bool> request_ready;
sc_core::sc_in <bool> request_go;
sc_core::sc_in <int> request_value;
//Power Port
sc_core::sc_out <double> power_signal;
SC_CTOR(Core):
request_address("Address_From_Core_to_Func_Bus"),
request_data("Data_From_Core_to_Func_Bus"),
functional_bus_flag("Flag_From_Core_to_Func_Bus"),
request_ready("Master_Ready_to_Func_Bus"),
request_go("Master_GO_to_Func_Bus"),
request_value("Data_form_Bus_to_Master"),
power_signal("Func_to_Power_signal")
{
SC_THREAD(run);
sensitive << request_go;
}
void init_iss_adapter(){
iss_adapter=(${adapter_class}*) new ${adapter_class}();
}
private:
int64_t next_timestamp=0;
int64_t sc_timestamp=0;
${adapter_class} *iss_adapter;
};
#endif
|
/*
* Created on: 21. jun. 2019
* Author: Jonathan Horsted Schougaard
*/
#pragma once
#define SC_INCLUDE_FX
#include <systemc.h>
#include "hwcore/pipes/streamsplit.h"
#include "hwcore/pipes/streammerge.h"
#include "hwcore/pipes/streamresize.h"
#include "hwcore/pipes/data_types.h"
#if __RTL_SIMULATION__
//#include "DMA_performance_tester_rtl_wrapper.h"
//#else
//#include "DMA_generic_performance_tester.hpp"
#endif
#define split_N 64
const long test_size = 20*split_N;
SC_MODULE(mon_split_and_merge)
{
sc_fifo_in<hwcore::pipes::sc_data_stream_t<16> > data_in;
SC_CTOR(mon_split_and_merge)
{
SC_THREAD(mon_thread);
}
void mon_thread()
{
for(int a=0;a<2;a++)
{
uint16_t data_gen = 0;
hwcore::pipes::sc_data_stream_t<16> tmp_in;
do
{
tmp_in = data_in.read();
std::cout << "(mon) got signal." << std::endl;
//for(int i=0;i<split_N;i++)
//{
if(tmp_in.template getKeep<16>(0)==1)
{
int tmp = tmp_in.template getData<sc_uint, 16>(0).to_uint();
std::cout << "(mon) got new data: " <<tmp << std::endl;
sc_assert(tmp == data_gen);
data_gen++;
}
//}
}while(data_gen < test_size);
}
std::cout << "Test finish no errors" << std::endl;
sc_stop();
}
};
SC_MODULE(wave_split_and_merge)
{
sc_fifo_out<hwcore::pipes::sc_data_stream_t<16> > data_out;
SC_CTOR(wave_split_and_merge)
{
SC_THREAD(wave_thread);
}
void wave_thread()
{
hwcore::pipes::sc_data_stream_t<16> tmp;
for (int i = 0; i < test_size; i++)
{
tmp.data = i;
std::cout << "(wave) write new data: " << i << std::endl;
tmp.setKeep();
tmp.tlast = 1;
data_out.write(tmp);
}
tmp.setEOP();
data_out.write(tmp);
for (int i = 0; i < test_size; i++)
{
tmp.data = i;
std::cout << "(wave) write new data: " << i << std::endl;
tmp.setKeep();
tmp.tlast = 1;
data_out.write(tmp);
}
tmp.setEOP();
data_out.write(tmp);
}
};
SC_MODULE(tb_split_and_merge)
{
#if __RTL_SIMULATION__
//DMA_performance_tester_rtl_wrapper u1;
#else
//DMA_performance_tester u1;
#endif
sc_clock clk;
sc_signal<bool> reset;
wave_split_and_merge wave;
sc_fifo<hwcore::pipes::sc_data_stream_t<16> > wave_2_u1;
hwcore::pipes::sc_stream_splitter<16,split_N,false> u1_ss;
hwcore::hf::sc_static_list<sc_fifo<hwcore::pipes::sc_data_stream_t<16> >, split_N> u1_2_u2;
//sc_fifo<hwcore::pipes::DATA_STREAM_t<16> > u1_2_u2[32];
hwcore::pipes::sc_stream_merge_raw<16,split_N> u2_sm;
sc_fifo<hwcore::pipes::sc_data_stream_t<16*split_N> > u2_2_u3;
hwcore::pipes::sc_stream_resize<16*split_N, 16> u3_sr;
sc_fifo<hwcore::pipes::sc_data_stream_t<16> > u3_2_mon;
mon_split_and_merge mon;
SC_CTOR(tb_split_and_merge)
: u1_ss("u1_ss"),u2_sm("u2_sm"), u3_sr("u3_sr"), wave("wave"), mon("mon"),
clk("clock", sc_time(10, SC_NS)),wave_2_u1(64),u2_2_u3(64), u3_2_mon(64),u1_2_u2("fifo",1)
{
wave.data_out(wave_2_u1);
u1_ss.din(wave_2_u1);
u1_ss.clk(clk);
u1_ss.reset(reset);
for(int i=0;i<split_N;i++)
{
u1_ss.dout[i](u1_2_u2.get(i));
u2_sm.din[i](u1_2_u2.get(i));
}
u2_sm.clk(clk);
u2_sm.reset(reset);
u2_sm.dout(u2_2_u3);
u3_sr.din(u2_2_u3);
u3_sr.clk(clk);
u3_sr.reset(reset);
u3_sr.dout(u3_2_mon);
mon.data_in(u3_2_mon);
}
};
|
/***************************************************************************\
*
*
* ___ ___ ___ ___
* / /\ / /\ / /\ / /\
* / /:/ / /::\ / /::\ / /::\
* / /:/ / /:/\:\ / /:/\:\ / /:/\:\
* / /:/ / /:/~/:/ / /:/~/::\ / /:/~/:/
* / /::\ /__/:/ /:/___ /__/:/ /:/\:\ /__/:/ /:/
* /__/:/\:\ \ \:\/:::::/ \ \:\/:/__\/ \ \:\/:/
* \__\/ \:\ \ \::/~~~~ \ \::/ \ \::/
* \ \:\ \ \:\ \ \:\ \ \:\
* \ \ \ \ \:\ \ \:\ \ \:\
* \__\/ \__\/ \__\/ \__\/
*
*
*
*
* This file is part of TRAP.
*
* TRAP is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* or see <http://www.gnu.org/licenses/>.
*
*
*
* (c) Luca Fossati, fossati@elet.polimi.it, fossati.l@gmail.com
*
\***************************************************************************/
#ifndef PROFILER_HPP
#define PROFILER_HPP
#ifdef __GNUC__
#ifdef __GNUC_MINOR__
#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 3)
#include <tr1/unordered_map>
#define template_map std::tr1::unordered_map
#else
#include <ext/hash_map>
#define template_map __gnu_cxx::hash_map
#endif
#else
#include <ext/hash_map>
#define template_map __gnu_cxx::hash_map
#endif
#else
#ifdef _WIN32
#include <hash_map>
#define template_map stdext::hash_map
#else
#include <map>
#define template_map std::map
#endif
#endif
#include <set>
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <systemc.h>
#include "ToolsIf.hpp"
#include "ABIIf.hpp"
#include "instructionBase.hpp"
#include "elfFrontend.hpp"
#include "profInfo.hpp"
namespace trap{
/// Profiler: it keeps track of many runtime statistics on:
/// - number and percentage of instructions executed of each type.
/// - function stats: time and percentage in each function
/// - call graph: time of each call.
template<class issueWidth> class Profiler : public ToolsIf<issueWidth>{
private:
//Interface with the processor
ABIIf<issueWidth> &processorInstance;
//instance of the ELF parser containing information on the software
//running on the processor
ELFFrontend & elfInstance;
//Statistic on the instructions
template_map<unsigned int, ProfInstruction> instructions;
ProfInstruction *oldInstruction;
sc_time oldInstrTime;
template_map<unsigned int, ProfInstruction>::iterator instructionsEnd;
//Statistic on the functions
typename template_map<issueWidth, ProfFunction> functions;
std::vector<ProfFunction *> currentStack;
sc_time oldFunTime;
unsigned int oldFunInstructions;
typename template_map<issueWidth, ProfFunction>::iterator functionsEnd;
//names of the routines which should be ignored from
//entry or exit
std::set<std::string> ignored;
bool exited;
//address range inside which the instruction statistics are updated
issueWidth lowerAddr;
issueWidth higherAddr;
bool statsRunning;
bool disableFunctionProfiling;
///Based on the new instruction just issued, the statistics on the instructions
///are updated
inline void updateInstructionStats(const issueWidth &curPC, const InstructionBase *curInstr) throw(){
//Update the total number of instructions executed
ProfInstruction::numTotalCalls++;
//Update the old instruction elapsed time
if(this->oldInstruction != NULL){
this->oldInstruction->time += sc_time_stamp() - this->oldInstrTime;
this->oldInstrTime = sc_time_stamp();
}
//Update the new instruction statistics
unsigned int instrId = curInstr->getId();
template_map<unsigned int, ProfInstruction>::iterator foundInstr = this->instructions.find(instrId);
if(foundInstr != this->instructionsEnd){
foundInstr->second.numCalls++;
this->oldInstruction = &(foundInstr->second);
}
else{
this->instructions[instrId].name = curInstr->getInstructionName();
this->oldInstruction = &(this->instructions[instrId]);
this->instructionsEnd = this->instructions.end();
}
}
///Based on the new instruction just issued, the statistics on the functions
///are updated
inline void updateFunctionStats(const issueWidth &curPC, const InstructionBase *curInstr) throw(){
std::vector<ProfFunction *>::iterator stackIterator, stackEnd;
if(this->exited){
std::string curFunName = this->elfInstance.symbolAt(curPC);
if(this->currentStack.size() > 1 && this->currentStack.back()->name != curFunName){
// std::cerr << "Problem, exiting into " << curFunName << " while I should have gone into " << this->currentStack.back()->name << std::endl;
// There have been a problem ... we haven't come back to where we came from
std::vector<ProfFunction *>::reverse_iterator stackIterator_r, stackEnd_r;
stackIterator_r = this->currentStack.rbegin();
bool haveToPop = false;
unsigned int numToPop = 0;
for(stackIterator_r++, stackEnd_r = this->currentStack.rend(); stackIterator_r != stackEnd_r; stackIterator_r++){
if((*stackIterator_r)->name == curFunName){
haveToPop = true;
break;
}
numToPop++;
}
if(haveToPop){
this->currentStack.erase(this->currentStack.begin() + (this->currentStack.size() -numToPop -1), this->currentStack.end());
}
/* else
std::cerr << "just exited I should have gone into " << curFunName << std::endl;*/
}
this->exited = false;
}
//First of all I have to check whether I am entering in a new
//function. If we are not entering in a new function, I have
//to check whether we are exiting from the current function;
//if no of the two sitations happen, I do not perform anything
if(this->processorInstance.isRoutineEntry(curInstr)){
std::string funName = this->elfInstance.symbolAt(curPC);
if(this->ignored.find(funName) != this->ignored.end()){
this->oldFunInstructions++;
return;
}
ProfFunction::numTotalCalls++;
ProfFunction * curFun = NULL;
typename template_map<issueWidth, ProfFunction>::iterator curFunction = this->functions.find(curPC);
if(curFunction != this->functionsEnd){
curFun = &(curFunction->second);
curFun->numCalls++;
}
else{
curFun = &(this->functions[curPC]);
this->functionsEnd = this->functions.end();
curFun->name = funName;
curFun->address = curPC;
}
//std::cerr << "entering in " << curFun->name << " " << std::hex << std::showbase << curPC << " function at curPC " << funName << std::endl;
//Now I have to update the statistics on the number of instructions executed on the
//instruction stack so far
sc_time curTimeDelta = sc_time_stamp() - this->oldFunTime;
if(this->currentStack.size() > 0){
//std::cerr << "from " << this->currentStack.back()->name << " " << std::hex << std::showbase << this->prevPC << std::endl;
this->currentStack.back()->exclNumInstr += this->oldFunInstructions;
this->currentStack.back()->exclTime += curTimeDelta;
}
for(stackIterator = this->currentStack.begin(), stackEnd = this->currentStack.end(); stackIterator != stackEnd; stackIterator++){
if(!(*stackIterator)->alreadyExamined){
(*stackIterator)->totalNumInstr += this->oldFunInstructions;
(*stackIterator)->totalTime += curTimeDelta;
(*stackIterator)->alreadyExamined = true;
}
}
// finally I can push the element on the stack
this->currentStack.push_back(curFun);
//..and record the call time of the function
this->oldFunTime = sc_time_stamp();
this->oldFunInstructions = 0;
//and reset the already examined flag
for(stackIterator = this->currentStack.begin(), stackEnd = this->currentStack.end(); stackIterator != stackEnd; stackIterator++){
(*stackIterator)->alreadyExamined = false;
}
}
else if(this->processorInstance.isRoutineExit(curInstr)){
std::string funName = this->elfInstance.symbolAt(curPC);
if(this->ignored.find(funName) != this->ignored.end()){
this->oldFunInstructions++;
return;
}
//Here I have to update the timing statistics for the
//function on the top of the stack and pop it from
//the stack
if(this->currentStack.size() == 0){
THROW_ERROR("We are exiting from a routine at address " << std::hex << std::showbase << curPC << " name: -" << funName << "- but the stack is empty");
}
//Lets update the statistics for the current instruction
ProfFunction * curFun = this->currentStack.back();
curFun->exclNumInstr += this->oldFunInstructions;
sc_time curTimeDelta = sc_time_stamp() - this->oldFunTime;
curFun->exclTime += curTimeDelta;
//std::cerr << "exiting from " << curFun->name << " " << std::hex << std::showbase << curPC << " I am in " << funName << std::endl;
//Now I have to update the statistics on the number of instructions executed on the
//instruction stack
for(stackIterator = this->currentStack.begin(), stackEnd = this->currentStack.end(); stackIterator != stackEnd; stackIterator++){
if(!(*stackIterator)->alreadyExamined){
(*stackIterator)->totalNumInstr += this->oldFunInstructions;
(*stackIterator)->totalTime += curTimeDelta;
(*stackIterator)->alreadyExamined = true;
}
}
//I restore the already examined flag
for(stackIterator = this->currentStack.begin(), stackEnd = this->currentStack.end(); stackIterator != stackEnd; stackIterator++){
(*stackIterator)->alreadyExamined = false;
}
//Now I pop the instruction from the stack
this->currentStack.pop_back();
this->exited = true;
this->oldFunInstructions = 0;
this->oldFunTime = sc_time_stamp();
}
else{
this->oldFunInstructions++;
}
//this->prevPC = curPC;
}
public:
Profiler(ABIIf<issueWidth> &processorInstance, std::string execName, bool disableFunctionProfiling) :
processorInstance(processorInstance), disableFunctionProfiling(disableFunctionProfiling),
elfInstance(ELFFrontend::getInstance(execName)){
this->oldInstruction = NULL;
this->oldInstrTime = SC_ZERO_TIME;
this->instructionsEnd = this->instructions.end();
this->oldFunTime = SC_ZERO_TIME;
this->functionsEnd = this->functions.end();
this->oldFunInstructions = 0;
this->exited = false;
this->lowerAddr = 0;
this->higherAddr = (issueWidth)-1;
this->statsRunning = false;
}
~Profiler(){
}
///Prints the compuated statistics in the form of a csv file
void printCsvStats(std::string fileName){
//I simply have to iterate over the encountered functions and instructions
//and print the relative statistics.
//two files will be created: fileName_fun.csv and fileName_instr.csv
std::ofstream instructionFile((fileName + "_instr.csv").c_str());
instructionFile << ProfInstruction::printCsvHeader() << std::endl;
template_map<unsigned int, ProfInstruction>::iterator instrIter, instrEnd;
for(instrIter = this->instructions.begin(), instrEnd = this->instructions.end(); instrIter != instrEnd; instrIter++){
instructionFile << instrIter->second.printCsv() << std::endl;
}
instructionFile << ProfInstruction::printCsvSummary() << std::endl;
instructionFile.close();
if(!this->disableFunctionProfiling){
std::ofstream functionFile((fileName + "_fun.csv").c_str());
functionFile << ProfFunction::printCsvHeader() << std::endl;
typename template_map<issueWidth, ProfFunction>::iterator funIter, funEnd;
for(funIter = this->functions.begin(), funEnd = this->functions.end(); funIter != funEnd; funIter++){
functionFile << funIter->second.printCsv() << std::endl;
}
functionFile.close();
}
}
///Function called by the processor at every new instruction issue.
bool newIssue(const issueWidth &curPC, const InstructionBase *curInstr) throw(){
//I perform the update of the statistics only if they are included in the
//predefined range
if(!this->statsRunning && curPC == this->lowerAddr)
this->statsRunning = true;
else if(this->statsRunning && curPC == this->higherAddr)
this->statsRunning = false;
if(this->statsRunning)
this->updateInstructionStats(curPC, curInstr);
if(!this->disableFunctionProfiling)
this->updateFunctionStats(curPC, curInstr);
return false;
}
///Since the profiler does not perform any modification to the registers and it does
///not use any registers but the current program counter, it does not need the
///pipeline to be emptys
bool emptyPipeline(const issueWidth &curPC) const throw(){
return false;
}
void addIgnoredFunction(std::string &toIgnore){
this->ignored.insert(toIgnore);
}
void addIgnoredFunctions(const std::set<std::string> &toIgnore){
this->ignored.insert(toIgnore.begin(), toIgnore.end());
}
void setProfilingRange(const issueWidth &lowerAddr, const issueWidth &higherAddr){
this->lowerAddr = lowerAddr;
this->higherAddr = higherAddr;
}
};
}
#endif
|
#ifndef IPS_FILTER_TLM_HPP
#define IPS_FILTER_TLM_HPP
#include <systemc.h>
using namespace sc_core;
using namespace sc_dt;
using namespace std;
#include "ips_filter_lt_model.hpp"
#include "../src/img_target.cpp"
#include "important_defines.hpp"
//Extended Unification TLM
struct ips_filter_tlm : public Filter<IPS_IN_TYPE_TB, IPS_OUT_TYPE_TB, IPS_FILTER_KERNEL_SIZE>, public img_target
{
ips_filter_tlm(sc_module_name name, bool use_prints_) : Filter<IPS_IN_TYPE_TB, IPS_OUT_TYPE_TB, IPS_FILTER_KERNEL_SIZE>((std::string(name) + "_HW_block").c_str()), img_target((std::string(name) + "_target").c_str()) {
set_mem_attributes(IMG_FILTER_KERNEL_ADDRESS_LO, IMG_FILTER_KERNEL_SIZE+IMG_FILTER_OUTPUT_SIZE);
use_prints = use_prints_;
checkprintenableimgtar(use_prints);
}
//Override do_when_transaction functions
virtual void do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address);
virtual void do_when_write_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address);
IPS_IN_TYPE_TB img_window[IPS_FILTER_KERNEL_SIZE * IPS_FILTER_KERNEL_SIZE];
IPS_OUT_TYPE_TB img_result;
};
#endif // IPS_FILTER_TLM_HPP
|
#ifdef EDGE_DETECTOR_PV_EN
#ifndef SOBEL_EDGE_DETECTOR_HPP
#define SOBEL_EDGE_DETECTOR_HPP
#include <systemc.h>
SC_MODULE(Edge_Detector)
{
int localWindow[3][3];
const int sobelGradientX[3][3] = {{-1, 0, 1},
{-2, 0, 2},
{-1, 0, 1}};
const int sobelGradientY[3][3] = {{-1, -2, -1},
{ 0, 0, 0},
{ 1, 2, 1}};
int resultSobelGradientX;
int resultSobelGradientY;
SC_CTOR(Edge_Detector)
{
// SC_METHOD(hello_world);
}
void set_local_window(int window[3][3]);
void compute_sobel_gradient_x();
void compute_sobel_gradient_y();
int obtain_sobel_gradient_x();
int obtain_sobel_gradient_y();
};
#endif // SOBEL_EDGE_DETECTOR_HPP
#endif // EDGE_DETECTOR_PV_EN
|
#ifndef SOBEL_EDGE_DETECTOR_TLM_HPP
#define SOBEL_EDGE_DETECTOR_TLM_HPP
#include <systemc.h>
using namespace sc_core;
using namespace sc_dt;
using namespace std;
#include <tlm.h>
#include <tlm_utils/simple_initiator_socket.h>
#include <tlm_utils/simple_target_socket.h>
#include <tlm_utils/peq_with_cb_and_phase.h>
#include "sobel_edge_detector_at_model.hpp"
#include "../src/img_target.cpp"
//Extended Unification TLM
struct sobel_edge_detector_tlm : public Edge_Detector, public img_target
{
sobel_edge_detector_tlm(sc_module_name name) : Edge_Detector((std::string(name) + "_HW_block").c_str()), img_target((std::string(name) + "_target").c_str()) {
#ifdef DISABLE_SOBEL_DEBUG
this->use_prints = false;
#endif //DISABLE_SOBEL_DEBUG
checkprintenableimgtar(use_prints);
}
//Override do_when_transaction functions
virtual void do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address);
virtual void do_when_write_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address);
void read() override;
void write() override;
};
#endif // SOBEL_EDGE_DETECTOR_TLM_HPP
|
/* Copyright 2017 Columbia University, SLD Group */
//
// hl5.h - Robert Margelli
// Header file of the hl5 CPU container.
// This module instantiates the stages and interconnects them.
//
#ifndef __HL5__H
#define __HL5__H
#include <systemc.h>
#include "cynw_flex_channels.h"
#include "hl5_datatypes.hpp"
#include "defines.hpp"
#include "globals.hpp"
#include "fedec_wrap.h"
#include "execute_wrap.h"
#include "memwb_wrap.h"
SC_MODULE(hl5)
{
public:
// Declaration of clock and reset signals
sc_in_clk clk;
sc_in < bool > rst;
//End of simulation signal.
sc_out < bool > program_end;
// Fetch enable signal.
sc_in < bool > fetch_en;
// Entry point
sc_in < unsigned > entry_point;
// TODO: removeme
// sc_out < bool > main_start;
// sc_out < bool > main_end;
// Instruction counters
sc_out < long int > icount;
sc_out < long int > j_icount;
sc_out < long int > b_icount;
sc_out < long int > m_icount;
sc_out < long int > o_icount;
// Inter-stage Flex Channels.
put_get_channel< de_out_t > de2exe_ch;
put_get_channel< mem_out_t > wb2de_ch; // Writeback loop
put_get_channel< exe_out_t > exe2mem_ch;
// Forwarding
sc_signal< reg_forward_t > fwd_exe_ch;
SC_HAS_PROCESS(hl5);
hl5(sc_module_name name,
sc_uint<XLEN> imem[ICACHE_SIZE],
sc_uint<XLEN> dmem[DCACHE_SIZE])
: clk("clk")
, rst("rst")
, program_end("program_end")
, fetch_en("fetch_en")
// , main_start("main_start")
// , main_end("main_end")
, entry_point("entry_point")
, de2exe_ch("de2exe_ch")
, exe2mem_ch("exe2mem_ch")
, wb2de_ch("wb2de_ch")
, fwd_exe_ch("fwd_exe_ch")
, fede("Fedec", imem)
, exe("Execute")
, mewb("Memory", dmem)
{
// FEDEC
fede.clk(clk);
fede.rst(rst);
fede.dout(de2exe_ch);
fede.feed_from_wb(wb2de_ch);
fede.program_end(program_end);
fede.fetch_en(fetch_en);
fede.entry_point(entry_point);
// fede.main_start(main_start);
// fede.main_end(main_end);
fede.fwd_exe(fwd_exe_ch);
fede.icount(icount);
fede.j_icount(j_icount);
fede.b_icount(b_icount);
fede.m_icount(m_icount);
fede.o_icount(o_icount);
// EXE
exe.clk(clk);
exe.rst(rst);
exe.din(de2exe_ch);
exe.dout(exe2mem_ch);
exe.fwd_exe(fwd_exe_ch);
// MEM
mewb.clk(clk);
mewb.rst(rst);
mewb.din(exe2mem_ch);
mewb.dout(wb2de_ch);
mewb.fetch_en(fetch_en);
}
// Instantiate the modules
fedec_wrapper fede;
execute_wrapper exe;
memwb_wrapper mewb;
};
#endif // end __HL5__H
|
#ifndef IPS_FILTER_PV_MODEL_HPP
#define IPS_FILTER_PV_MODEL_HPP
#ifdef IPS_DEBUG_EN
#include <iostream>
#endif // IPS_DEBUG_ENi
#ifdef IPS_DUMP_EN
#include <sstream>
#endif // IPS_DUMP_EN
#include <systemc.h>
/**
* @brief Filter module.
* It takes care of filtering a image/kernel using a median filter or an
* equivalent convolution like:
* | 1/N^2 ... 1/N^2 | | img(row - N/2, col - N/2) ... img(row + N/2, col + N/2) |
* img(row, col) = | ... ... .... | * | ... ... ... |
* | 1/N^2 ... 1/N^2 | | img(row + N/2, col - N/2) ... img(row + N/2, col + N/2) |
*
* @tparam IN - data type of the inputs
* @tparam OUT - data type of the outputs
* @tparam N - size of the kernel
*/
template <typename IN = sc_uint<8>, typename OUT = sc_uint<8>, uint8_t N = 3>
SC_MODULE(Filter)
{
//-----------------------------Local Variables-----------------------------
#ifdef IPS_DUMP_EN
sc_trace_file* wf;
#endif // IPS_DUMP_EN
OUT* kernel;
/**
* @brief Default constructor for Filter
*/
SC_CTOR(Filter);
#ifdef IPS_DUMP_EN
/**
* @brief Construct a new Filter object
*
* @param name - name of the module
* @param wf - waveform file pointer
*/
Filter(sc_core::sc_module_name name, sc_core::sc_trace_file* wf)
: sc_core::sc_module(name), wf(wf)
#else
/**
* @brief Construct a new Filter object
*
* @param name - name of the module
*/
Filter(sc_core::sc_module_name name) : sc_core::sc_module(name)
#endif // IPS_DUMP_EN
{
SC_METHOD(init_kernel);
}
//---------------------------------Methods---------------------------------
void filter(IN* img_window, OUT& result);
void init_kernel();
};
/**
* @brief Filtering image
*
* @param img_window - image window to filter
* @param result - resultant pixel
*/
template <typename IN, typename OUT, uint8_t N>
void Filter<IN, OUT, N>::filter(IN* img_window, OUT& result)
{
size_t i;
size_t j;
// Default value for the result depending on the output datatype
result = static_cast<OUT >(0);
// Perform the convolution
for (i = 0; i < N; ++i)
for (j = 0; j < N; ++j)
result += this->kernel[i * N + j] * static_cast<OUT >(img_window[i * N + j]);
}
/**
* @brief Initializes a kernel of N x N with default value of 1 / (N^2)
*
*/
template <typename IN, typename OUT, uint8_t N>
void Filter<IN, OUT, N>::init_kernel()
{
// Init a kernel of N x N with default value of 1 / (N * N)
this->kernel = new OUT[N * N];
std::fill_n(this->kernel, N * N, static_cast<OUT >(1) / static_cast<OUT >(N * N));
#ifdef IPS_DEBUG_EN
// Print the initialized kernel
SC_REPORT_INFO(this->name(), "init_kernel result");
size_t i, j;
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
std::cout << "[" << this->kernel[i * N + j] << "]";
#ifdef IPS_DUMP_EN
// Adding the signals to the waveform
std::ostringstream var_name;
var_name << "kernel_" << i << "_" << j;
sc_trace(this->wf, this->kernel[i * N + j], var_name.str());
#endif // IPS_DUMP_EN
}
std::cout << std::endl;
}
#else
#ifdef IPS_DUMP_EN
size_t i, j;
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
// Adding the signals to the waveform
std::ostringstream var_name;
var_name << "kernel_" << i << "_" << j;
sc_trace(this->wf, this->kernel[i * N + j], var_name.str());
}
}
#endif // IPS_DUMP_EN
#endif // IPS_DEBUG_EN
}
#endif // IPS_FILTER_PV_MODEL_HPP
|
/**************************************************************************
* *
* Catapult(R) Machine Learning Reference Design Library *
* *
* Software Version: 1.8 *
* *
* Release Date : Sun Jul 16 19:01:51 PDT 2023 *
* Release Type : Production Release *
* Release Build : 1.8.0 *
* *
* Copyright 2021 Siemens *
* *
**************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *
* implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
**************************************************************************
* *
* The most recent version of this package is available at github. *
* *
*************************************************************************/
#include <systemc.h>
#include "types.h"
#include "sys_ram.h"
#include "accel_if.h"
#ifdef INCLUDE_UART
#include "uart_if.h"
#include "proc_fabric.h"
#else
#include "host_code_fabric.h"
#endif
#include "axi/axi4.h"
#include "axi4_segment.h"
#include "sysbus_axi_struct.h"
class systemc_subsystem : public sc_module, public sysbus_axi {
public:
//== Ports
sc_in<bool> clk;
sc_in<bool> reset_bar;
r_slave<> CCS_INIT_S1(r_cpu);
w_slave<> CCS_INIT_S1(w_cpu);
//== Local signals
r_chan<> CCS_INIT_S1(r_acc_regs);
w_chan<> CCS_INIT_S1(w_acc_regs);
r_chan<> CCS_INIT_S1(r_acc_master);
w_chan<> CCS_INIT_S1(w_acc_master);
r_chan<> CCS_INIT_S1(r_memory);
w_chan<> CCS_INIT_S1(w_memory);
#ifdef INCLUDE_UART
r_chan<> CCS_INIT_S1(r_uart);
w_chan<> CCS_INIT_S1(w_uart);
#endif
//== Instances
fabric CCS_INIT_S1(io_matrix);
accel_if CCS_INIT_S1(go_fast);
sys_ram CCS_INIT_S1(shared_memory);
#ifdef INCLUDE_UART
uart_if CCS_INIT_S1(uart);
#endif
//== Constructor
SC_CTOR(systemc_subsystem)
{
io_matrix.clk (clk);
io_matrix.rst_bar (reset_bar);
io_matrix.r_mem (r_memory);
io_matrix.w_mem (w_memory);
io_matrix.r_reg (r_acc_regs);
io_matrix.w_reg (w_acc_regs);
io_matrix.r_cpu (r_cpu);
io_matrix.w_cpu (w_cpu);
io_matrix.r_acc (r_acc_master);
io_matrix.w_acc (w_acc_master);
#ifdef INCLUDE_UART
io_matrix.r_uart (r_uart);
io_matrix.w_uart (w_uart);
#endif
shared_memory.clk (clk);
shared_memory.rst_bar (reset_bar);
shared_memory.r_slave0 (r_memory);
shared_memory.w_slave0 (w_memory);
go_fast.clk (clk);
go_fast.rst_bar (reset_bar);
go_fast.r_reg_if (r_acc_regs);
go_fast.w_reg_if (w_acc_regs);
go_fast.r_mem_if (r_acc_master);
go_fast.w_mem_if (w_acc_master);
#ifdef INCLUDE_UART
uart.clk (clk);
uart.rst_bar (reset_bar);
uart.r_uart_if (r_uart);
uart.w_uart_if (w_uart);
#endif
}
};
class systemc_subsystem_wrapper : public sc_module, public sysbus_axi {
public:
//== Ports
sc_in <bool> clk;
sc_in <bool> reset_bar;
sc_in <sc_lv<44>> aw_msg_port;
sc_in <bool> aw_valid_port;
sc_out<bool> aw_ready_port;
sc_in <sc_lv<37>> w_msg_port;
sc_in <bool> w_valid_port;
sc_out<bool> w_ready_port;
sc_out<sc_lv<6>> b_msg_port;
sc_out<bool> b_valid_port;
sc_in <bool> b_ready_port;
sc_in <sc_lv<44>> ar_msg_port;
sc_in <bool> ar_valid_port;
sc_out<bool> ar_ready_port;
sc_out<sc_lv<39>> r_msg_port;
sc_out<bool> r_valid_port;
sc_in <bool> r_ready_port;
sc_clock connections_clk;
sc_event check_event;
virtual void start_of_simulation() {
Connections::get_sim_clk().add_clock_alias(
connections_clk.posedge_event(), clk.posedge_event());
}
void check_clock() { check_event.notify(2, SC_PS);} // Let SC and Vlog delta cycles settle.
void check_event_method() {
if (connections_clk.read() == clk.read()) return;
CCS_LOG("clocks misaligned!:" << connections_clk.read() << " " << clk.read());
}
systemc_subsystem CCS_INIT_S1(scs);
SC_CTOR(systemc_subsystem_wrapper)
: connections_clk("connections_clk", CLOCK_PERIOD, SC_NS, 0.5, 0, SC_NS, true)
{
SC_METHOD(check_clock);
sensitive << connections_clk;
sensitive << clk;
SC_METHOD(check_event_method);
sensitive << check_event;
scs.clk(clk);
scs.reset_bar(reset_bar);
scs.w_cpu.aw.msg(aw_msg_port);
scs.w_cpu.aw.val(aw_valid_port);
scs.w_cpu.aw.rdy(aw_ready_port);
scs.w_cpu.w.msg(w_msg_port);
scs.w_cpu.w.val(w_valid_port);
scs.w_cpu.w.rdy(w_ready_port);
scs.w_cpu.b.msg(b_msg_port);
scs.w_cpu.b.val(b_valid_port);
scs.w_cpu.b.rdy(b_ready_port);
scs.r_cpu.ar.msg(ar_msg_port);
scs.r_cpu.ar.val(ar_valid_port);
scs.r_cpu.ar.rdy(ar_ready_port);
scs.r_cpu.r.msg(r_msg_port);
scs.r_cpu.r.val(r_valid_port);
scs.r_cpu.r.rdy(r_ready_port);
}
};
#ifdef QUESTA
SC_MODULE_EXPORT(systemc_subsystem_wrapper);
#endif
|
#include <systemc.h>
/**
* @brief jpg_output module. Federico Cruz
* It takes the image and compresses it into jpeg format
* It is done in 4 parts:
* 1. Divides the image in 8x8 pixel blocks; for 8-bit grayscale images the a level shift is done by substracting 128 from each pixel.
* 2. Discrete Cosine Transform (DCT) of the 8x8 image.
* 3. Each transformed 8x8 block is divided by a quantization value for each block entry.
* 4. Each quantized 8x8 block is reordered by a Zig-Zag sequence into a array of size 64.
* *5. Entropy compression by variable length encoding (huffman). Used to maximize compression. Not implemented here.
*/
#define PI 3.1415926535897932384626433832795
#define BLOCK_ROWS 8
#define BLOCK_COLS 8
SC_MODULE (jpg_output) {
//input signals
sc_in<sc_int<32> > pixel_value_signal;
sc_in<sc_int<32> > row_signal;
sc_in<sc_int<32> > col_signal;
//output signals
sc_out<sc_int<8> > element_signal;
sc_in<sc_int<32> > index_signal;
//compression signals
sc_out<sc_int<32> > output_size_signal;
//-----------Internal variables-------------------
//const int Block_rows = 8;
//const int Block_cols = 8;
double* image;
int image_rows = 480;
int image_cols = 640;
signed char eob = 127; // end of block
int quantificator[8][8] = { // quantization table
{16,11,10,16,24,40,51,61},
{12,12,14,19,26,58,60,55},
{14,13,16,24,40,57,69,56},
{14,17,22,29,51,87,80,62},
{18,22,37,56,68,109,103,77},
{24,35,55,64,81,104,113,92},
{49,64,78,87,103,121,120,101},
{72,92,95,98,112,100,103,99}};
int zigzag_index[64]={ // zigzag table
0,1,5,6,14,15,27,28,
2,4,7,13,16,26,29,42,
3,8,12,17,25,30,41,43,
9,11,18,24,31,40,44,53,
10,19,23,32,39,45,52,54,
20,22,33,38,46,51,55,60,
21,34,37,47,50,56,59,61,
35,36,48,49,57,58,62,63};
sc_event starter_event;
sc_event input_event;
sc_event output_event;
sc_event compression_event;
// Constructor for compressor
SC_HAS_PROCESS(jpg_output);
jpg_output(sc_module_name jpg_compressor): sc_module(jpg_compressor){
image = new double[image_rows*image_cols];
//initialize the image matrix to avoid nan
for(int i=0; i<(image_rows*image_cols);i++){
image[i]=0;
}
SC_THREAD(starter_operation);
SC_THREAD(input_operation);
SC_THREAD(output_operation);
SC_THREAD(compression_operation);
} // End of Constructor
//------------Code Starts Here-------------------------
void Starter() {
starter_event.notify(4, SC_NS);
}
void starter_operation(){
while(true) {
wait(starter_event);
int im_rows = row_signal.read();
if(im_rows%BLOCK_ROWS==0) {image_rows=im_rows;}
else {image_rows=(im_rows/BLOCK_ROWS+1)*BLOCK_ROWS;}
wait(4, SC_NS);
int im_cols = col_signal.read();
if(im_cols%BLOCK_COLS==0) {image_cols=im_cols;}
else {image_cols=(im_cols/BLOCK_COLS+1)*BLOCK_COLS;}
}
}
void input_pixel() {
input_event.notify(8, SC_NS);
}
void input_operation(){
while(true) {
wait(input_event);
double* i_row = &image[row_signal.read() * image_cols];
i_row[col_signal.read()] = double(pixel_value_signal.read());
}
}
//void OutputPixel(int *Pixel, int row, int col) {
// double* i_row = &image[row * image_cols];
// *Pixel = int(i_row[col]);
//}
void output_byte() {
output_event.notify(8, SC_NS);
}
void output_operation(){
while(true) {
wait(output_event);
element_signal = image[index_signal.read()];
}
}
void jpeg_compression() {
compression_event.notify(100, SC_NS);
}
void compression_operation() {
while(true) {
wait(compression_event);
int output_size = 0;
//Level shift
for(int i=0; i<(image_rows*image_cols);i++){
image[i]=image[i]-128;
}
wait(100, SC_NS);
int number_of_blocks = image_rows*image_cols/(BLOCK_ROWS*BLOCK_COLS);
int block_output[number_of_blocks][BLOCK_ROWS*BLOCK_COLS] = {0};
int block_output_size[number_of_blocks] = {0};
int block_counter = 0;
output_size = 0;
for(int row=0; row<image_rows; row+=BLOCK_ROWS) {
double* i_row = &image[row * image_cols];
for(int col=0; col<image_cols; col+=BLOCK_COLS) { //Divided the image in 8×8 blocks
dct(row,col);
quantization(row,col);
zigzag(row,col,&block_output_size[block_counter],block_output[block_counter]);
output_size += block_output_size[block_counter]+1;
block_counter++;
}
}
int output_counter = 0;
for(int block_index=0;block_index<number_of_blocks;block_index++){
for(int out_index=0; out_index<block_output_size[block_index];out_index++){
image[output_counter]=block_output[block_index][out_index];
output_counter++;
}
image[output_counter]=eob;
output_counter++;
}
output_size_signal = output_size;
}
}
void dct(int row_offset, int col_offset) {
wait(400, SC_NS);
double cos_table[BLOCK_ROWS][BLOCK_COLS];
for (int row = 0; row < BLOCK_ROWS; row++) //make the cosine table
{
for (int col = 0; col < BLOCK_COLS; col++) {
cos_table[row][col] = cos((((2*row)+1)*col*PI)/16);
}
}
double temp;
for(int row=row_offset; row<row_offset+BLOCK_ROWS; row++)
{
double* i_row = &image[row * image_cols];
for(int col=col_offset; col<col_offset+BLOCK_COLS; col++) {
//i_row[col] = cos_table[row-row_offset][col-col_offset];
temp = 0.0;
for (int x = 0; x < 8; x++){
double* x_row = &image[(x+row_offset) * image_cols];
for (int y = 0; y < 8; y++) {
temp += x_row[y+col_offset] * cos_table[x][row-row_offset] * cos_table[y][col-col_offset];
}
}
if ((row-row_offset == 0) && (col-col_offset == 0)) {
temp /= 8.0;
}
else if (((row-row_offset == 0) && (col-col_offset != 0)) || ((row-row_offset != 0) && (col-col_offset == 0))){
temp /= (4.0*sqrt(2.0));
}
else {
temp /= 4.0;
}
i_row[col] = temp;
}
}
}
void quantization(int row_offset, int col_offset) {
wait(100, SC_NS);
for(int row=row_offset; row<row_offset+BLOCK_ROWS; row++)
{
double* i_row = &image[row * image_cols];
for(int col=col_offset; col<col_offset+BLOCK_COLS; col++) {
i_row[col] = round(i_row[col]/quantificator[row-row_offset][col-col_offset]);
}
}
}
void zigzag(int row_offset, int col_offset, int *block_output_size, int *block_output) {
wait(200, SC_NS);
int index_last_non_zero_value = 0; // index to last non-zero in a block zigzag array
for(int row=row_offset; row<row_offset+BLOCK_ROWS; row++)
{
double* i_row = &image[row * image_cols];
for(int col=col_offset; col<col_offset+BLOCK_COLS; col++) {
int temp_index = zigzag_index[(row-row_offset)*8+(col-col_offset)];
block_output[temp_index]=i_row[col];
if(i_row[col] !=0 && temp_index>index_last_non_zero_value) {index_last_non_zero_value = temp_index+1;}
}
}
*block_output_size = index_last_non_zero_value;
}
};
|
#ifndef IPS_MEMORY_HPP
#define IPS_MEMORY_HPP
#include <systemc.h>
template <unsigned int SIZE>
SC_MODULE(memory)
{
protected:
int *mem;
public:
sc_core::sc_in<bool> clk;
sc_core::sc_in<bool> we;
sc_core::sc_in<unsigned long long int> address;
sc_core::sc_in<sc_uint<24>> wdata;
sc_core::sc_out<sc_uint<24>> rdata;
// Constructor for memory
SC_CTOR(memory)
{
this->mem = new int[SIZE];
SC_METHOD(run);
sensitive << clk.pos();
}
void run()
{
if (clk.read())
{
const unsigned long long int ADDR = static_cast<unsigned long long int>(this->address.read());
if (we.read())
{
this->mem[ADDR] = this->wdata.read();
}
this->rdata.write(this->mem[ADDR]);
}
}
};
#endif // IPS_MEMORY_HPP
|
/*
* Copyright (C) 2020 GreenWaves Technologies, SAS, ETH Zurich and
* University of Bologna
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Authors: Germain Haugou, GreenWaves Technologies (germain.haugou@greenwaves-technologies.com)
*/
#ifndef __VP_TIME_ENGINE_HPP__
#define __VP_TIME_ENGINE_HPP__
#include "vp/vp_data.hpp"
#include "vp/component.hpp"
#ifdef __VP_USE_SYSTEMC
#include <systemc.h>
#endif
namespace vp
{
class time_engine_client;
class time_engine : public component
{
public:
time_engine(js::config *config);
void start();
void run_loop();
int64_t step(int64_t timestamp);
void run();
void quit(int status);
int join();
int64_t get_next_event_time();
inline void lock_step();
inline void lock_step_cancel();
inline void lock();
inline void wait_running();
inline void unlock();
inline void stop_engine(int status=0, bool force = true, bool no_retain = false);
inline void stop_retain(int count);
inline void pause();
void stop_exec();
void req_stop_exec();
void register_exec_notifier(Notifier *notifier);
inline vp::time_engine *get_time_engine() { return this; }
bool dequeue(time_engine_client *client);
bool enqueue(time_engine_client *client, int64_t time);
int64_t get_time() { return time; }
inline void retain() { retain_count++; }
inline void release() { retain_count--; }
inline void fatal(const char *fmt, ...);
inline void update(int64_t time);
void wait_ready();
private:
time_engine_client *first_client = NULL;
bool locked = false;
bool locked_run_req;
bool run_req;
bool stop_req;
bool pause_req;
bool finished = false;
bool init = false;
bool running;
pthread_mutex_t mutex;
pthread_cond_t cond;
pthread_t run_thread;
int64_t time = 0;
int stop_status = -1;
bool engine_has_been_stopped = false;
int retain_count = 0;
bool no_exit;
int stop_retain_count = 0;
#ifdef __VP_USE_SYSTEMC
sc_event sync_event;
bool started = false;
#endif
private:
vp::component *stop_event;
std::vector<Notifier *> exec_notifiers;
};
class time_engine_client : public component
{
friend class time_engine;
public:
time_engine_client(js::config *config)
: vp::component(config)
{
}
inline bool is_running() { return running; }
inline bool enqueue_to_engine(int64_t time)
{
return engine->enqueue(this, time);
}
inline bool dequeue_from_engine()
{
return engine->dequeue(this);
}
inline int64_t get_time() { return engine->get_time(); }
virtual int64_t exec() = 0;
protected:
time_engine_client *next;
// This gives the time of the next event.
// It is only valid when the client is not the currently active one,
// and is then updated either when the client is not the active one
// anymore or when the client is enqueued to the engine.
int64_t next_event_time = 0;
vp::time_engine *engine;
bool running = false;
bool is_enqueued = false;
};
// This can be called from anywhere so just propagate the stop request
// to the main python thread which will take care of stopping the engine.
inline void vp::time_engine::stop_engine(int status, bool force, bool no_retain)
{
if (!this->engine_has_been_stopped)
{
this->engine_has_been_stopped = true;
stop_status = status;
}
else
{
stop_status |= status;
}
if (no_retain || stop_retain_count == 0 || stop_status != 0)
{
#ifdef __VP_USE_SYSTEMC
sync_event.notify();
#endif
if (force || !this->no_exit)
{
// In case the vp is connected to an external bridge, prevent the platform
// from exiting unless a ctrl-c is hit
pthread_mutex_lock(&mutex);
stop_req = true;
run_req = false;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
}
}
inline void vp::time_engine::stop_retain(int count)
{
this->stop_retain_count += count;
}
inline void vp::time_engine::pause()
{
pthread_mutex_lock(&mutex);
run_req = false;
pthread_cond_broadcast(&cond);
while(this->running)
{
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
}
inline void vp::time_engine::wait_running()
{
pthread_mutex_lock(&mutex);
while (!init)
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
}
inline void vp::time_engine::lock_step()
{
if (!locked)
{
locked = true;
locked_run_req = run_req;
run_req = false;
}
}
inline void vp::time_engine::lock_step_cancel()
{
pthread_mutex_lock(&mutex);
if (locked)
{
run_req = locked_run_req;
locked = false;
}
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
inline void vp::time_engine::lock()
{
pthread_mutex_lock(&mutex);
if (!locked)
{
locked_run_req = run_req;
run_req = false;
locked = true;
}
pthread_cond_broadcast(&cond);
while (running)
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
}
inline void vp::time_engine::unlock()
{
pthread_mutex_lock(&mutex);
run_req = locked_run_req;
locked = false;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
inline void vp::time_engine::fatal(const char *fmt, ...)
{
fprintf(stdout, "[\033[31mFATAL\033[0m] ");
va_list ap;
va_start(ap, fmt);
if (vfprintf(stdout, fmt, ap) < 0)
{
}
va_end(ap);
stop_engine(-1);
}
inline void vp::time_engine::update(int64_t time)
{
if (time > this->time)
this->time = time;
}
}; // namespace vp
#endif
|
/*
* Copyright (C) 2020 GreenWaves Technologies, SAS, ETH Zurich and
* University of Bologna
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Authors: Germain Haugou, GreenWaves Technologies (germain.haugou@greenwaves-technologies.com)
*/
#ifndef __VP_TIME_ENGINE_HPP__
#define __VP_TIME_ENGINE_HPP__
#include "vp/vp_data.hpp"
#include "vp/component.hpp"
#ifdef __VP_USE_SYSTEMC
#include <systemc.h>
#endif
namespace vp
{
class time_engine_client;
class time_engine : public component
{
public:
time_engine(js::config *config);
void start();
void run_loop();
int64_t step(int64_t timestamp);
void run();
void quit(int status);
int join();
int64_t get_next_event_time();
inline void lock_step();
inline void lock_step_cancel();
inline void lock();
inline void wait_running();
inline void unlock();
inline void stop_engine(int status=0, bool force = true, bool no_retain = false);
inline void stop_retain(int count);
inline void pause();
void stop_exec();
void req_stop_exec();
void register_exec_notifier(Notifier *notifier);
inline vp::time_engine *get_time_engine() { return this; }
bool dequeue(time_engine_client *client);
bool enqueue(time_engine_client *client, int64_t time);
int64_t get_time() { return time; }
inline void retain() { retain_count++; }
inline void release() { retain_count--; }
inline void fatal(const char *fmt, ...);
inline void update(int64_t time);
void wait_ready();
private:
time_engine_client *first_client = NULL;
bool locked = false;
bool locked_run_req;
bool run_req;
bool stop_req;
bool pause_req;
bool finished = false;
bool init = false;
bool running;
pthread_mutex_t mutex;
pthread_cond_t cond;
pthread_t run_thread;
int64_t time = 0;
int stop_status = -1;
bool engine_has_been_stopped = false;
int retain_count = 0;
bool no_exit;
int stop_retain_count = 0;
#ifdef __VP_USE_SYSTEMC
sc_event sync_event;
bool started = false;
#endif
private:
vp::component *stop_event;
std::vector<Notifier *> exec_notifiers;
};
class time_engine_client : public component
{
friend class time_engine;
public:
time_engine_client(js::config *config)
: vp::component(config)
{
}
inline bool is_running() { return running; }
inline bool enqueue_to_engine(int64_t time)
{
return engine->enqueue(this, time);
}
inline bool dequeue_from_engine()
{
return engine->dequeue(this);
}
inline int64_t get_time() { return engine->get_time(); }
virtual int64_t exec() = 0;
protected:
time_engine_client *next;
// This gives the time of the next event.
// It is only valid when the client is not the currently active one,
// and is then updated either when the client is not the active one
// anymore or when the client is enqueued to the engine.
int64_t next_event_time = 0;
vp::time_engine *engine;
bool running = false;
bool is_enqueued = false;
};
// This can be called from anywhere so just propagate the stop request
// to the main python thread which will take care of stopping the engine.
inline void vp::time_engine::stop_engine(int status, bool force, bool no_retain)
{
if (!this->engine_has_been_stopped)
{
this->engine_has_been_stopped = true;
stop_status = status;
}
else
{
stop_status |= status;
}
if (no_retain || stop_retain_count == 0 || stop_status != 0)
{
#ifdef __VP_USE_SYSTEMC
sync_event.notify();
#endif
if (force || !this->no_exit)
{
// In case the vp is connected to an external bridge, prevent the platform
// from exiting unless a ctrl-c is hit
pthread_mutex_lock(&mutex);
stop_req = true;
run_req = false;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
}
}
inline void vp::time_engine::stop_retain(int count)
{
this->stop_retain_count += count;
}
inline void vp::time_engine::pause()
{
pthread_mutex_lock(&mutex);
run_req = false;
pthread_cond_broadcast(&cond);
while(this->running)
{
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
}
inline void vp::time_engine::wait_running()
{
pthread_mutex_lock(&mutex);
while (!init)
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
}
inline void vp::time_engine::lock_step()
{
if (!locked)
{
locked = true;
locked_run_req = run_req;
run_req = false;
}
}
inline void vp::time_engine::lock_step_cancel()
{
pthread_mutex_lock(&mutex);
if (locked)
{
run_req = locked_run_req;
locked = false;
}
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
inline void vp::time_engine::lock()
{
pthread_mutex_lock(&mutex);
if (!locked)
{
locked_run_req = run_req;
run_req = false;
locked = true;
}
pthread_cond_broadcast(&cond);
while (running)
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
}
inline void vp::time_engine::unlock()
{
pthread_mutex_lock(&mutex);
run_req = locked_run_req;
locked = false;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
inline void vp::time_engine::fatal(const char *fmt, ...)
{
fprintf(stdout, "[\033[31mFATAL\033[0m] ");
va_list ap;
va_start(ap, fmt);
if (vfprintf(stdout, fmt, ap) < 0)
{
}
va_end(ap);
stop_engine(-1);
}
inline void vp::time_engine::update(int64_t time)
{
if (time > this->time)
this->time = time;
}
}; // namespace vp
#endif
|
#include<systemc.h>
#include<vector>
#include "interfaces.hpp"
#include<nana/gui/widgets/listbox.hpp>
using std::vector;
class instruction_queue_rob: public sc_module
{
public:
sc_port<read_if> in;
sc_port<write_if_f> out;
sc_port<read_if> in_rob;
SC_HAS_PROCESS(instruction_queue_rob);
instruction_queue_rob(sc_module_name name, vector<string> inst_q,int rb_sz, nana::listbox &instr);
void main();
void leitura_rob();
bool queue_is_empty();
unsigned int get_instruction_counter();
private:
unsigned int pc;
struct instr_q
{
string instruction;
unsigned int pc;
};
vector<instr_q> instruct_queue;
vector<string> original_instruct;
vector<vector<instr_q>> last_instr;
vector<unsigned int> last_pc;
nana::listbox &instructions;
void replace_instructions(unsigned int pos,unsigned int index);
void add_instructions(unsigned int pos, vector<instr_q> instructions);
};
|
/* Copyright 2017 Columbia University, SLD Group */
//
// fedec.h - Robert Margelli
// fetch + decoding logic header file.
//
#ifndef __FEDEC__H
#define __FEDEC__H
#include <systemc.h>
#include "cynw_flex_channels.h"
#include "defines.hpp"
#include "globals.hpp"
#include "syn_directives.hpp"
#include "hl5_datatypes.hpp"
SC_MODULE(fedec)
{
public:
// FlexChannel initiators
put_initiator< de_out_t > dout;
get_initiator< mem_out_t > feed_from_wb;
// Forward
sc_in< reg_forward_t > fwd_exe;
// End of simulation signal.
sc_out < bool > program_end;
// Fetch enable signal.
sc_in < bool > fetch_en;
// Entry point
sc_in < unsigned > entry_point;
// Clock and reset signals
sc_in_clk clk;
sc_in< bool > rst;
// TODO: removeme
// sc_out < bool > main_start;
// sc_out < bool > main_end;
// Instruction counters
sc_out < long int > icount;
sc_out < long int > j_icount;
sc_out < long int > b_icount;
sc_out < long int > m_icount;
sc_out < long int > o_icount;
// Trap signals. TODO: not used. Left for future implementations.
sc_signal< bool > trap; //sc_out
sc_signal< sc_uint<LOG2_NUM_CAUSES> > trap_cause; //sc_out
// Instruction cache pointer to external memory
sc_uint<XLEN> *imem;
// Thread prototype
void fedec_th(void);
// Function prototypes.
sc_bv<PC_LEN> sign_extend_jump(sc_bv<21> imm);
sc_bv<PC_LEN> sign_extend_branch(sc_bv<13> imm);
SC_HAS_PROCESS(fedec);
fedec(sc_module_name name, sc_uint<XLEN> _imem[ICACHE_SIZE])
: dout("dout")
, feed_from_wb("feed_from_wb")
, fwd_exe("fwd_exe")
, program_end("program_end")
, fetch_en("fetch_en")
, entry_point("entry_point")
// , main_start("main_start")
// , main_end("main_end")
, j_icount("j_icount")
, b_icount("b_icount")
, m_icount("m_icount")
, o_icount("o_icount")
, clk("clk")
, rst("rst")
, trap("trap")
, trap_cause("trap_cause")
, imem(_imem)
{
SC_CTHREAD(fedec_th, clk.pos());
reset_signal_is(rst, false);
dout.clk_rst(clk, rst);
feed_from_wb.clk_rst(clk, rst);
FLAT_REGFILE;
FLAT_SENTINEL;
MAP_ICACHE;
}
sc_uint<PC_LEN> pc; // Init. to -4, then before first insn fetch it will be updated to 0.
sc_bv<INSN_LEN> insn; // Contains full instruction fetched from IMEM. Used in decoding.
fe_in_t self_feed; // Contains branch and jump data.
// Member variables (DECODE)
mem_out_t feedinput;
de_out_t output;
// NB. x0 is included in this regfile so it is not a real hardcoded 0
// constant. The writeback section of fedec has a guard fro writes on
// x0. For double protection, some instructions that want to write into
// x0 will have their regwrite signal forced to false.
sc_bv<XLEN> regfile[REG_NUM];
// Keeps track of in-flight instructions that are going to overwrite a
// register. Implements a primitive stall mechanism for RAW hazards.
sc_uint<TAG_WIDTH> sentinel[REG_NUM];
// TODO: Used for synchronizing with the wb stage and avoid
// 'hiccuping'. It magically works.
sc_uint<2> position;
bool freeze;
sc_uint<TAG_WIDTH> tag;
sc_uint<PC_LEN> return_address;
};
#endif
|
/*
* SPDX-FileCopyrightText: Copyright (c) 2019-2021 NVIDIA CORPORATION &
* AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __INTERCONNECT_TYPE_CONFIG_H__
#define __INTERCONNECT_TYPE_CONFIG_H__
#include <systemc.h>
#include <nvhls_connections.h>
#include "InterconnectChannels.hpp"
#include <tuple>
namespace interconnect {
#ifdef CONNECTIONS_SIM_ONLY
template <typename IM>
struct InterconnectTypeConfig {
typedef IM IM_t;
typedef Connections::OutBlocking<IM> IM_src_t;
typedef Connections::InBlocking<IM> IM_dest_t;
typedef Connections::Combinational<IM> IM_chan_t;
typedef interconnect::CombinationalLink<IM> IM_chanlink_t;
typedef std::vector<IM_src_t*> srcs_t;
typedef std::vector<IM_dest_t*> dests_t;
typedef std::map<IM_src_t*, IM_chan_t*> channels_begin_t;
typedef std::map<IM_dest_t*, IM_chanlink_t*> channels_middle_inner_t;
typedef std::map<IM_src_t*, channels_middle_inner_t> channels_middle_t;
typedef std::map<IM_dest_t*, IM_chan_t*> channels_end_t;
typedef std::map<IM_src_t*, std::size_t> srcs_typeid_t;
typedef std::map<IM_dest_t*, std::size_t> dests_typeid_t;
typedef std::map<IM_src_t*, int> srcs_user_typeid_t;
typedef std::map<IM_dest_t*, int> dests_user_typeid_t;
typedef std::map<IM_src_t*, unsigned int> srcs_width_t;
typedef std::map<IM_dest_t*, unsigned int> dests_width_t;
typedef std::vector<IM_src_t*> channels_valid_pairs_reverse_inner_t;
typedef std::map<IM_dest_t*, channels_valid_pairs_reverse_inner_t>
channels_valid_pairs_reverse_t;
typedef NVUINT32 idx_t;
typedef NVUINT32 dest_map_idx_t;
typedef std::map<dest_map_idx_t, std::map<idx_t, idx_t> > dest_maps_t;
typedef std::vector<dest_map_idx_t> dest_maps_idx_vec_t;
typedef NVUINT64 cycles_count_t;
typedef std::map<IM_src_t*, std::map<IM_dest_t*, cycles_count_t> >
cycle_count_channel_t;
};
#endif
};
#endif // __INTERCONNECT_TYPE_CONFIG_H__
|
#ifndef IMG_GENERIC_EXTENSION_HPP
#define IMG_GENERIC_EXTENSION_HPP
#include <systemc.h>
using namespace sc_core;
using namespace sc_dt;
using namespace std;
#include <tlm.h>
#include <tlm_utils/simple_initiator_socket.h>
#include <tlm_utils/simple_target_socket.h>
#include <tlm_utils/peq_with_cb_and_phase.h>
struct img_generic_extension : tlm::tlm_extension<img_generic_extension>
{
img_generic_extension() : transaction_number(0) {}
virtual tlm::tlm_extension_base* clone() const;
virtual void copy_from(tlm::tlm_extension_base const &ext);
unsigned int transaction_number;
};
#endif // IMG_GENERIC_EXTENSION_HPP
|
#pragma once
#include <systemc.h>
using namespace sc_core;
class plugin;
class timed_callback : public sc_process_b {
public:
timed_callback(
SC_ENTRY_FUNC func,
sc_process_host *host,
const sc_time &t) : sc_process_b(
0,
false,
false,
func, host, 0) {
add_static_event(m_ev);
m_ev.notify(t);
}
virtual void disable_process(
sc_descendant_inclusion_info descendants = SC_NO_DESCENDANTS ) {
fprintf(stdout, "disable_process\n");
}
virtual void enable_process(
sc_descendant_inclusion_info descendants = SC_NO_DESCENDANTS ) {
fprintf(stdout, "enable_process\n");
}
virtual void kill_process(
sc_descendant_inclusion_info descendants = SC_NO_DESCENDANTS ) {
fprintf(stdout, "kill_process\n");
}
virtual void resume_process(
sc_descendant_inclusion_info descendants = SC_NO_DESCENDANTS ) {
fprintf(stdout, "resume_process\n");
}
virtual void suspend_process(
sc_descendant_inclusion_info descendants = SC_NO_DESCENDANTS ) {
fprintf(stdout, "suspend_process\n");
}
virtual void throw_user( const sc_throw_it_helper& helper,
sc_descendant_inclusion_info descendants = SC_NO_DESCENDANTS ) {
fprintf(stdout, "throw_user\n");
}
virtual void throw_reset( bool async ) {
fprintf(stdout, "throw_reset\n");
}
private:
sc_event m_ev;
};
class callback_host : public sc_process_host {
public:
callback_host(const sc_time &t) : m_count(0), m_time(t) {
::sc_core::sc_process_handle handle =
sc_core::sc_get_curr_simcontext()->create_method_process(
"foo", true, SC_MAKE_FUNC_PTR(callback_host,callback),
this, 0);
// handle << m_ev;
}
void callback() {
fprintf(stdout, "callback: count=%d\n", m_count);
if (m_count == 0) {
next_trigger(m_time, sc_get_curr_simcontext());
// notify(m_time, m_ev);
}
m_count++;
}
private:
uint32_t m_count;
sc_event m_ev;
sc_time m_time;
};
class plugin : public sc_module {
public:
plugin(const sc_module_name &name) : sc_module(name) {
fprintf(stdout, "plugin\n");
}
SC_HAS_PROCESS(plugin);
void end_of_elaboration() {
fprintf(stdout, "end_of_elaboration\n");
for (uint32_t i=1; i<sc_argc(); i++) {
const char *arg = sc_argv()[i];
fprintf(stdout, "arg=%s\n", arg);
}
// ::sc_core::sc_process_handle handle =
// sc_core::sc_get_curr_simcontext()->create_method_process(
// "foo", false, SC_MAKE_FUNC_PTR(plugin,callback),
// this, 0);
// timed_callback *cb = new timed_callback(
// SC_MAKE_FUNC_PTR(plugin, callback),
// this,
// sc_time(1, SC_NS));
callback_host *h = new callback_host(sc_time(1, SC_NS));
}
void callback() {
fprintf(stdout, "callback\n");
}
};
static plugin p("__plugin");
|
#ifndef SCHEDULER_HPP
#define SCHEDULER_HPP
#include <systemc.h>
#include "verbose.hpp"
#define CORE 4
#define INSTRUCTION_BUFFER 512
#define INPUT_BUFFER 65536
SC_MODULE(scheduler_module)
{
// PORTS
sc_in<bool> clk;
sc_in<bool> reset;
sc_fifo_in<float> from_dma_weight;
sc_fifo_in<float> from_dma_input;
sc_fifo_in< sc_uint<64> > from_dma_instructions;
sc_fifo_out<float> to_dma;
// PROCESSING ENGINES
sc_fifo_out< sc_uint<34> > npu_instructions[CORE];
sc_fifo_out<float> npu_weight[CORE];
sc_fifo_out<float> npu_input[CORE];
sc_fifo_in<float> npu_output[CORE];
// STATES
sc_uint<64> state_instruction_counter;
sc_uint<64> state_instruction_buffer[INSTRUCTION_BUFFER];
float state_input_buffer[INPUT_BUFFER];
float state_output_buffer[INPUT_BUFFER];
// PROCESS
void process(void);
SC_CTOR(scheduler_module)
{
// Init STATES
state_instruction_counter = 0;
SC_CTHREAD(process, clk.pos());
reset_signal_is(reset, true);
}
};
#endif
|
/*
Problem 1 Testbench
*/
#include<systemc.h>
#include<sd.cpp>
SC_MODULE(sequenceDetectorTB) {
sc_signal<bool> clock , reset , clear , input , output , state;
void clockSignal();
void resetSignal();
void clearSignal();
void inputSignal();
sequenceDetector* sd;
SC_CTOR(sequenceDetectorTB) {
sd = new sequenceDetector ("SD");
sd->clock(clock);
sd->reset(reset);
sd->clear(clear);
sd->input(input);
sd->output(output);
sd->state(state);
SC_THREAD(clockSignal);
SC_THREAD(resetSignal);
SC_THREAD(clearSignal);
SC_THREAD(inputSignal);
}
};
void sequenceDetectorTB::clockSignal() {
while (true){
wait(20 , SC_NS);
clock = false;
wait(20 , SC_NS);
clock = true;
}
}
void sequenceDetectorTB::resetSignal() {
while (true){
wait(10 , SC_NS);
reset = true;
wait(90 , SC_NS);
reset = false;
wait(10 , SC_NS);
reset = true;
wait(1040 , SC_NS);
}
}
void sequenceDetectorTB::clearSignal() {
while (true) {
wait(50 , SC_NS);
clear = false;
wait(90 , SC_NS);
clear = true;
wait(10 , SC_NS);
clear = false;
wait(760 , SC_NS);
}
}
void sequenceDetectorTB::inputSignal() {
while (true) {
wait(25 , SC_NS);
input = true;
wait(65, SC_NS);
input = false;
wait(30 , SC_NS);
input = true;
wait(40 , SC_NS);
input = false;
}
}
int sc_main(int argc , char* argv[]) {
cout<<"@ "<<sc_time_stamp()<<"----------Start---------"<<endl;
sequenceDetectorTB* sdTB = new sequenceDetectorTB ("SDTB");
cout<<"@ "<<sc_time_stamp()<<"----------Testbench Instance Created---------"<<endl;
sc_trace_file* VCDFile;
VCDFile = sc_create_vcd_trace_file("sequence-detector");
cout<<"@ "<<sc_time_stamp()<<"----------VCD File Created---------"<<endl;
sc_trace(VCDFile, sdTB->clock, "Clock");
sc_trace(VCDFile, sdTB->reset, "Reset");
sc_trace(VCDFile, sdTB->clear, "Clear");
sc_trace(VCDFile, sdTB->input, "Input");
sc_trace(VCDFile, sdTB->state, "State");
sc_trace(VCDFile, sdTB->output, "Output");
cout<<"@ "<<sc_time_stamp()<<"----------Start Simulation---------"<<endl;
sc_start(4000, SC_NS);
cout<<"@ "<<sc_time_stamp()<<"----------End Simulation---------"<<endl;
return 0;
}
|
/***************************************************************************\
*
*
* ___ ___ ___ ___
* / /\ / /\ / /\ / /\
* / /:/ / /::\ / /::\ / /::\
* / /:/ / /:/\:\ / /:/\:\ / /:/\:\
* / /:/ / /:/~/:/ / /:/~/::\ / /:/~/:/
* / /::\ /__/:/ /:/___ /__/:/ /:/\:\ /__/:/ /:/
* /__/:/\:\ \ \:\/:::::/ \ \:\/:/__\/ \ \:\/:/
* \__\/ \:\ \ \::/~~~~ \ \::/ \ \::/
* \ \:\ \ \:\ \ \:\ \ \:\
* \ \ \ \ \:\ \ \:\ \ \:\
* \__\/ \__\/ \__\/ \__\/
*
*
*
*
* This file is part of TRAP.
*
* TRAP is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* or see <http://www.gnu.org/licenses/>.
*
*
*
* (c) Luca Fossati, fossati@elet.polimi.it, fossati.l@gmail.com
*
\***************************************************************************/
#ifndef OSEMULATOR_HPP
#define OSEMULATOR_HPP
#include <map>
#include <string>
#include <systemc.h>
#ifdef __GNUC__
#ifdef __GNUC_MINOR__
#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 3)
#include <tr1/unordered_map>
#define template_map std::tr1::unordered_map
#else
#include <ext/hash_map>
#define template_map __gnu_cxx::hash_map
#endif
#else
#include <ext/hash_map>
#define template_map __gnu_cxx::hash_map
#endif
#else
#ifdef _WIN32
#include <hash_map>
#define template_map stdext::hash_map
#else
#include <map>
#define template_map std::map
#endif
#endif
#include "ABIIf.hpp"
#include "ToolsIf.hpp"
#ifndef EXTERNAL_BFD
#include "elfFrontend.hpp"
#else
#include "bfdWrapper.hpp"
#define BFDFrontend BFDWrapper
#endif
#include "syscCallB.hpp"
#include "instructionBase.hpp"
namespace trap{
template<class issueWidth> class OSEmulator : public ToolsIf<issueWidth>, public OSEmulatorBase{
private:
template_map<issueWidth, SyscallCB<issueWidth>* > syscCallbacks;
ABIIf<issueWidth> &processorInstance;
typename template_map<issueWidth, SyscallCB<issueWidth>* >::const_iterator syscCallbacksEnd;
ELFFrontend *elfFrontend;
unsigned int countBits(issueWidth bits){
unsigned int numBits = 0;
for(unsigned int i = 0; i < sizeof(issueWidth)*8; i++){
if((bits & (0x1 << i)) != 0)
numBits++;
}
return numBits;
}
bool register_syscall(std::string funName, SyscallCB<issueWidth> &callBack){
bool valid = false;
unsigned int symAddr = this->elfFrontend->getSymAddr(funName, valid);
if(!valid){
return false;
}
typename template_map<issueWidth, SyscallCB<issueWidth>* >::iterator foundSysc = this->syscCallbacks.find(symAddr);
if(foundSysc != this->syscCallbacks.end()){
int numMatch = 0;
typename template_map<issueWidth, SyscallCB<issueWidth>* >::iterator allCallIter, allCallEnd;
for(allCallIter = this->syscCallbacks.begin(), allCallEnd = this->syscCallbacks.end(); allCallIter != allCallEnd; allCallIter++){
if(allCallIter->second == foundSysc->second)
numMatch++;
}
if(numMatch <= 1){
delete foundSysc->second;
}
}
this->syscCallbacks[symAddr] = &callBack;
this->syscCallbacksEnd = this->syscCallbacks.end();
return true;
}
bool register_syscall(issueWidth address, SyscallCB<issueWidth> &callBack){
typename template_map<issueWidth, SyscallCB<issueWidth>* >::iterator foundSysc = this->syscCallbacks.find(address);
if(foundSysc != this->syscCallbacks.end()){
int numMatch = 0;
typename template_map<issueWidth, SyscallCB<issueWidth>* >::iterator allCallIter, allCallEnd;
for(allCallIter = this->syscCallbacks.begin(), allCallEnd = this->syscCallbacks.end(); allCallIter != allCallEnd; allCallIter++){
if(allCallIter->second == foundSysc->second)
numMatch++;
}
if(numMatch <= 1){
delete foundSysc->second;
}
}
this->syscCallbacks[address] = &callBack;
this->syscCallbacksEnd = this->syscCallbacks.end();
return true;
}
public:
OSEmulator(ABIIf<issueWidth> &processorInstance) : processorInstance(processorInstance){
this->syscCallbacksEnd = this->syscCallbacks.end();
}
std::set<std::string> getRegisteredFunctions(){
std::set<std::string> registeredFunctions;
typename template_map<issueWidth, SyscallCB<issueWidth>* >::iterator emuIter, emuEnd;
for(emuIter = this->syscCallbacks.begin(), emuEnd = this->syscCallbacks.end(); emuIter != emuEnd; emuIter++){
registeredFunctions.insert(this->elfFrontend->symbolAt(emuIter->first));
}
return registeredFunctions;
}
void initSysCalls(std::string execName, int group = 0){
std::map<std::string, sc_time> emptyLatMap;
this->initSysCalls(execName, emptyLatMap, group);
}
void initSysCalls(std::string execName, std::map<std::string, sc_time> latencies, int group = 0){
if(find (groupIDs.begin(), groupIDs.end(), group) == groupIDs.end()){
groupIDs.push_back(group);
programsCount++;
}
//First of all I initialize the heap pointer according to the group it belongs to
this->heapPointer = (unsigned int)this->processorInstance.getCodeLimit() + sizeof(issueWidth);
this->elfFrontend = &ELFFrontend::getInstance(execName);
//Now I perform the registration of the basic System Calls
bool registered = false;
openSysCall<issueWidth> *a = NULL;
if(latencies.find("open") != latencies.end())
a = new openSysCall<issueWidth>(this->processorInstance, *this, latencies["open"]);
else if(latencies.find("_open") != latencies.end())
a = new openSysCall<issueWidth>(this->processorInstance, *this, latencies["_open"]);
else
a = new openSysCall<issueWidth>(this->processorInstance, *this);
registered = this->register_syscall("open", *a);
registered |= this->register_syscall("_open", *a);
if(!registered)
delete a;
creatSysCall<issueWidth> *b = NULL;
if(latencies.find("creat") != latencies.end())
b = new creatSysCall<issueWidth>(this->processorInstance, latencies["creat"]);
else if(latencies.find("_creat") != latencies.end())
b = new creatSysCall<issueWidth>(this->processorInstance, latencies["_creat"]);
else
b = new creatSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("creat", *b);
registered |= this->register_syscall("_creat", *b);
if(!registered)
delete b;
closeSysCall<issueWidth> *c = NULL;
if(latencies.find("close") != latencies.end())
c = new closeSysCall<issueWidth>(this->processorInstance, latencies["close"]);
else if(latencies.find("_close") != latencies.end())
c = new closeSysCall<issueWidth>(this->processorInstance, latencies["_close"]);
else
c = new closeSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("close", *c);
registered |= this->register_syscall("_close", *c);
if(!registered)
delete c;
readSysCall<issueWidth> *d = NULL;
if(latencies.find("read") != latencies.end())
d = new readSysCall<issueWidth>(this->processorInstance, latencies["read"]);
else if(latencies.find("_read") != latencies.end())
d = new readSysCall<issueWidth>(this->processorInstance, latencies["_read"]);
else
d = new readSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("read", *d);
registered |= this->register_syscall("_read", *d);
if(!registered)
delete d;
writeSysCall<issueWidth> *e = NULL;
if(latencies.find("write") != latencies.end())
e = new writeSysCall<issueWidth>(this->processorInstance, latencies["write"]);
else if(latencies.find("_write") != latencies.end())
e = new writeSysCall<issueWidth>(this->processorInstance, latencies["_write"]);
else
e = new writeSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("write", *e);
registered |= this->register_syscall("_write", *e);
if(!registered)
delete e;
isattySysCall<issueWidth> *f = NULL;
if(latencies.find("isatty") != latencies.end())
f = new isattySysCall<issueWidth>(this->processorInstance, latencies["isatty"]);
else if(latencies.find("_isatty") != latencies.end())
f = new isattySysCall<issueWidth>(this->processorInstance, latencies["_isatty"]);
else
f = new isattySysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("isatty", *f);
registered |= this->register_syscall("_isatty", *f);
if(!registered)
delete f;
sbrkSysCall<issueWidth> *g = NULL;
if(latencies.find("sbrk") != latencies.end())
g = new sbrkSysCall<issueWidth>(this->processorInstance, this->heapPointer, latencies["sbrk"]);
else if(latencies.find("_sbrk") != latencies.end())
g = new sbrkSysCall<issueWidth>(this->processorInstance, this->heapPointer, latencies["_sbrk"]);
else
g = new sbrkSysCall<issueWidth>(this->processorInstance, this->heapPointer);
registered = this->register_syscall("sbrk", *g);
registered |= this->register_syscall("_sbrk", *g);
if(!registered)
delete g;
lseekSysCall<issueWidth> *h = NULL;
if(latencies.find("lseek") != latencies.end())
h = new lseekSysCall<issueWidth>(this->processorInstance, latencies["lseek"]);
else if(latencies.find("_lseek") != latencies.end())
h = new lseekSysCall<issueWidth>(this->processorInstance, latencies["_lseek"]);
else
h = new lseekSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("lseek", *h);
registered |= this->register_syscall("_lseek", *h);
if(!registered)
delete h;
fstatSysCall<issueWidth> *i = NULL;
if(latencies.find("fstat") != latencies.end())
i = new fstatSysCall<issueWidth>(this->processorInstance, latencies["fstat"]);
else if(latencies.find("_fstat") != latencies.end())
i = new fstatSysCall<issueWidth>(this->processorInstance, latencies["_fstat"]);
else
i = new fstatSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("fstat", *i);
registered |= this->register_syscall("_fstat", *i);
if(!registered)
delete i;
_exitSysCall<issueWidth> *j = NULL;
if(latencies.find("_exit") != latencies.end())
j = new _exitSysCall<issueWidth>(this->processorInstance, latencies["_exit"]);
else
j = new _exitSysCall<issueWidth>(this->processorInstance);
if(!this->register_syscall("_exit", *j))
delete j;
timesSysCall<issueWidth> *k = NULL;
if(latencies.find("times") != latencies.end())
k = new timesSysCall<issueWidth>(this->processorInstance, latencies["times"]);
else if(latencies.find("_times") != latencies.end())
k = new timesSysCall<issueWidth>(this->processorInstance, latencies["_times"]);
else
k = new timesSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("times", *k);
registered |= this->register_syscall("_times", *k);
if(!registered)
delete k;
timeSysCall<issueWidth> *l = NULL;
if(latencies.find("time") != latencies.end())
l = new timeSysCall<issueWidth>(this->processorInstance, latencies["time"]);
else if(latencies.find("_time") != latencies.end())
l = new timeSysCall<issueWidth>(this->processorInstance, latencies["_time"]);
else
l = new timeSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("time", *l);
registered |= this->register_syscall("_time", *l);
if(!registered)
delete l;
randomSysCall<issueWidth> *m = NULL;
if(latencies.find("random") != latencies.end())
m = new randomSysCall<issueWidth>(this->processorInstance, latencies["random"]);
else if(latencies.find("_random") != latencies.end())
m = new randomSysCall<issueWidth>(this->processorInstance, latencies["_random"]);
else
m = new randomSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("random", *m);
registered |= this->register_syscall("_random", *m);
if(!registered)
delete m;
getpidSysCall<issueWidth> * n = NULL;
if(latencies.find("getpid") != latencies.end())
n = new getpidSysCall<issueWidth>(this->processorInstance, latencies["getpid"]);
else if(latencies.find("_getpid") != latencies.end())
n = new getpidSysCall<issueWidth>(this->processorInstance, latencies["_getpid"]);
else
n = new getpidSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("getpid", *n);
registered |= this->register_syscall("_getpid", *n);
if(!registered)
delete n;
chmodSysCall<issueWidth> * o = NULL;
if(latencies.find("chmod") != latencies.end())
o = new chmodSysCall<issueWidth>(this->processorInstance, latencies["chmod"]);
else if(latencies.find("_chmod") != latencies.end())
o = new chmodSysCall<issueWidth>(this->processorInstance, latencies["_chmod"]);
else
o = new chmodSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("chmod", *o);
registered |= this->register_syscall("_chmod", *o);
if(!registered)
delete o;
dupSysCall<issueWidth> * p = NULL;
if(latencies.find("dup") != latencies.end())
p = new dupSysCall<issueWidth>(this->processorInstance, latencies["dup"]);
else if(latencies.find("_dup") != latencies.end())
p = new dupSysCall<issueWidth>(this->processorInstance, latencies["_dup"]);
else
p = new dupSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("dup", *p);
registered |= this->register_syscall("_dup", *p);
if(!registered)
delete p;
dup2SysCall<issueWidth> * q = NULL;
if(latencies.find("dup2") != latencies.end())
q = new dup2SysCall<issueWidth>(this->processorInstance, latencies["dup2"]);
else if(latencies.find("_dup2") != latencies.end())
q = new dup2SysCall<issueWidth>(this->processorInstance, latencies["_dup2"]);
else
q = new dup2SysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("dup2", *q);
registered |= this->register_syscall("_dup2", *q);
if(!registered)
delete q;
getenvSysCall<issueWidth> *r = NULL;
if(latencies.find("getenv") != latencies.end())
r = new getenvSysCall<issueWidth>(this->processorInstance, this->heapPointer, this->env, latencies["getenv"]);
else if(latencies.find("_getenv") != latencies.end())
r = new getenvSysCall<issueWidth>(this->processorInstance, this->heapPointer, this->env, latencies["_getenv"]);
else
r = new getenvSysCall<issueWidth>(this->processorInstance, this->heapPointer, this->env);
registered = this->register_syscall("getenv", *r);
registered |= this->register_syscall("_getenv", *r);
if(!registered)
delete r;
sysconfSysCall<issueWidth> *s = NULL;
if(latencies.find("sysconf") != latencies.end())
s = new sysconfSysCall<issueWidth>(this->processorInstance, this->sysconfmap, latencies["sysconf"]);
else
s = new sysconfSysCall<issueWidth>(this->processorInstance, this->sysconfmap);
if(!this->register_syscall("sysconf", *s))
delete s;
gettimeofdaySysCall<issueWidth> *t = NULL;
if(latencies.find("gettimeofday") != latencies.end())
t = new gettimeofdaySysCall<issueWidth>(this->processorInstance, latencies["gettimeofday"]);
else if(latencies.find("_gettimeofday") != latencies.end())
t = new gettimeofdaySysCall<issueWidth>(this->processorInstance, latencies["_gettimeofday"]);
else
t = new gettimeofdaySysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("gettimeofday", *t);
registered |= this->register_syscall("_gettimeofday", *t);
if(!registered)
delete t;
killSysCall<issueWidth> *u = NULL;
if(latencies.find("kill") != latencies.end())
u = new killSysCall<issueWidth>(this->processorInstance, latencies["kill"]);
else if(latencies.find("_kill") != latencies.end())
u = new killSysCall<issueWidth>(this->processorInstance, latencies["_kill"]);
else
u = new killSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("kill", *u);
registered |= this->register_syscall("_kill", *u);
if(!registered)
delete u;
errorSysCall<issueWidth> *v = NULL;
if(latencies.find("error") != latencies.end())
v = new errorSysCall<issueWidth>(this->processorInstance, latencies["error"]);
else if(latencies.find("_error") != latencies.end())
v = new errorSysCall<issueWidth>(this->processorInstance, latencies["_error"]);
else
v = new errorSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("error", *v);
registered |= this->register_syscall("_error", *v);
if(!registered)
delete v;
chownSysCall<issueWidth> *w = NULL;
if(latencies.find("chown") != latencies.end())
w = new chownSysCall<issueWidth>(this->processorInstance, latencies["chown"]);
else if(latencies.find("_chown") != latencies.end())
w = new chownSysCall<issueWidth>(this->processorInstance, latencies["_chown"]);
else
w = new chownSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("chown", *w);
registered |= this->register_syscall("_chown", *w);
if(!registered)
delete w;
unlinkSysCall<issueWidth> *x = NULL;
if(latencies.find("unlink") != latencies.end())
x = new unlinkSysCall<issueWidth>(this->processorInstance, latencies[
|
"unlink"]);
else if(latencies.find("_unlink") != latencies.end())
x = new unlinkSysCall<issueWidth>(this->processorInstance, latencies["_unlink"]);
else
x = new unlinkSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("unlink", *x);
registered |= this->register_syscall("_unlink", *x);
if(!registered)
delete x;
usleepSysCall<issueWidth> *y = NULL;
if(latencies.find("usleep") != latencies.end())
y = new usleepSysCall<issueWidth>(this->processorInstance, latencies["usleep"]);
else if(latencies.find("_usleep") != latencies.end())
y = new usleepSysCall<issueWidth>(this->processorInstance, latencies["_usleep"]);
else
y = new usleepSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("usleep", *y);
registered |= this->register_syscall("_usleep", *y);
if(!registered)
delete y;
statSysCall<issueWidth> *z = NULL;
if(latencies.find("stat") != latencies.end())
z = new statSysCall<issueWidth>(this->processorInstance, latencies["stat"]);
else if(latencies.find("_stat") != latencies.end())
z = new statSysCall<issueWidth>(this->processorInstance, latencies["_stat"]);
else
z = new statSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("stat", *z);
registered |= this->register_syscall("_stat", *z);
if(!registered)
delete z;
lstatSysCall<issueWidth> *A = NULL;
if(latencies.find("lstat") != latencies.end())
A = new lstatSysCall<issueWidth>(this->processorInstance, latencies["lstat"]);
else if(latencies.find("_lstat") != latencies.end())
A = new lstatSysCall<issueWidth>(this->processorInstance, latencies["_lstat"]);
else
A = new lstatSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("lstat", *A);
registered |= this->register_syscall("_lstat", *A);
if(!registered)
delete A;
utimesSysCall<issueWidth> *B = NULL;
if(latencies.find("utimes") != latencies.end())
B = new utimesSysCall<issueWidth>(this->processorInstance, latencies["utimes"]);
else if(latencies.find("_utimes") != latencies.end())
B = new utimesSysCall<issueWidth>(this->processorInstance, latencies["_utimes"]);
else
B = new utimesSysCall<issueWidth>(this->processorInstance);
registered = this->register_syscall("utimes", *B);
registered |= this->register_syscall("_utimes", *B);
if(!registered)
delete B;
mainSysCall<issueWidth> * mainCallBack = new mainSysCall<issueWidth>(this->processorInstance, this->heapPointer, this->programArgs);
if(!this->register_syscall("main", *mainCallBack))
THROW_EXCEPTION("Fatal Error, unable to find main function in current application");
}
///Method called at every instruction issue, it returns true in case the instruction
///has to be skipped, false otherwise
bool newIssue(const issueWidth &curPC, const InstructionBase *curInstr) throw(){
//I have to go over all the registered system calls and check if there is one
//that matches the current program counter. In case I simply call the corresponding
//callback.
typename template_map<issueWidth, SyscallCB<issueWidth>* >::const_iterator foundSysc = this->syscCallbacks.find(curPC);
if(foundSysc != this->syscCallbacksEnd){
return (*(foundSysc->second))();
}
return false;
}
///Method called to know if the instruction at the current address has to be skipped:
///if true the instruction has to be skipped, otherwise the instruction can
///be executed
bool emptyPipeline(const issueWidth &curPC) const throw(){
if(this->syscCallbacks.find(curPC) != this->syscCallbacksEnd){
return true;
}
return false;
}
///Resets the whole concurrency emulator, reinitializing it and preparing it for a new simulation
void reset(){
this->syscCallbacks.clear();
this->syscCallbacksEnd = this->syscCallbacks.end();
this->env.clear();
this->sysconfmap.clear();
this->programArgs.clear();
this->heapPointer = 0;
this->groupIDs.clear();
this->programsCount = 0;
}
//The destructor calls the reset method
~OSEmulator(){
reset();
}
};
};
#endif
|
#ifndef IMG_RECEIVER_HPP
#define IMG_RECEIVER_HPP
#include <systemc.h>
#include "address_map.hpp"
SC_MODULE(img_receiver)
{
//Array for input image
unsigned char* input_image;
sc_dt::uint64 address_offset;
SC_CTOR(img_receiver)
{
input_image = new unsigned char[IMG_INPUT_SIZE];
address_offset = IMG_INPUT_ADDRESS_LO;
}
//Backdoor access to memory
void backdoor_write(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address);
void backdoor_read(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address);
};
#endif // IMG_RECEIVER_HPP
|
#ifndef PACKET_GENERATOR_TLM_HPP
#define PACKET_GENERATOR_TLM_HPP
#include <systemc.h>
using namespace sc_core;
using namespace sc_dt;
using namespace std;
#include <tlm.h>
#include <tlm_utils/simple_initiator_socket.h>
#include <tlm_utils/simple_target_socket.h>
#include <tlm_utils/peq_with_cb_and_phase.h>
#include <systemc-ams.h>
#include "packetGenerator.h"
#include "../src/img_target.cpp"
#include "address_map.hpp"
//Extended Unification TLM
struct packetGenerator_tlm : public packetGenerator, public img_target
{
packetGenerator_tlm(sc_module_name name, sca_core::sca_time sample_time) : packetGenerator((std::string(name) + "_AMS_HW_block").c_str(), sample_time), img_target((std::string(name) + "_target").c_str()), tmp_data_length(0) {
tmp_data = new unsigned char[IMG_OUTPUT_SIZE];
#ifdef DISABLE_PACKET_GENERATOR_DEBUG
this->use_prints = false;
#endif // DISABLE_PACKET_GENERATOR_DEBUG
checkprintenableimgtar(use_prints);
}
//Override do_when_transaction functions
virtual void do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address);
virtual void do_when_write_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address);
unsigned int tmp_data_length;
unsigned char* tmp_data;
};
#endif // PACKET_GENERATOR_TLM_HPP
|
#ifndef __MESSY_CORE_H__
#define __MESSY_CORE_H__
#include <config.hpp>
#include <systemc.h>
#include <cstring>
#include <string.h>
#include <adapters/${adapter_filenames}.hpp>
#include <messy_request.hpp>
class Core : public sc_module
{
public:
void run();
void close();
void run_next_sc();
void continue_messy(bool handle_req_queue);
void handle_req_queue();
void request_delay(double start_time,int time_to_skip,int resolution);
void handle_req(MessyRequest *req);
// This gets called when an access from gvsoc side is reaching us
void access_request(MessyRequest *req);
// This gets called when one of our access gets granted
void grant_req(MessyRequest *req);
// This gets called when one of our access gets its response
void reply_to_req(MessyRequest *req);
int simulation_iters=0;
double tot_power=0.0;
sc_core::sc_out <unsigned int> request_address;
sc_core::sc_out <uint8_t*> request_data;
sc_core::sc_out <unsigned int> request_size;
sc_core::sc_out <bool> functional_bus_flag;
sc_core::sc_out <bool> request_ready;
sc_core::sc_in <bool> request_go;
sc_core::sc_in <uint8_t*> request_value;
sc_core::sc_in <int> idx_sensor;
//Power Port
sc_core::sc_out <double> power_signal;
SC_CTOR(Core):
request_address("Address_From_Core_to_Func_Bus"),
request_data("Data_From_Core_to_Func_Bus"),
functional_bus_flag("Flag_From_Core_to_Func_Bus"),
request_ready("Master_Ready_to_Func_Bus"),
request_go("Master_GO_to_Func_Bus"),
request_value("Data_form_Bus_to_Master"),
power_signal("Func_to_Power_signal"),
idx_sensor("selected_sensor_of_request")
{
iss_adapter=(${adapter_class}*) new ${adapter_class}();
SC_THREAD(run);
sensitive << request_go;
}
~Core(){
delete iss_adapter;
}
private:
int64_t next_timestamp=0;
int64_t sc_timestamp=0;
${adapter_class} *iss_adapter;
};
#endif
|
/***************************************************************************\
*
*
* ___ ___ ___ ___
* / /\ / /\ / /\ / /\
* / /:/ / /::\ / /::\ / /::\
* / /:/ / /:/\:\ / /:/\:\ / /:/\:\
* / /:/ / /:/~/:/ / /:/~/::\ / /:/~/:/
* / /::\ /__/:/ /:/___ /__/:/ /:/\:\ /__/:/ /:/
* /__/:/\:\ \ \:\/:::::/ \ \:\/:/__\/ \ \:\/:/
* \__\/ \:\ \ \::/~~~~ \ \::/ \ \::/
* \ \:\ \ \:\ \ \:\ \ \:\
* \ \ \ \ \:\ \ \:\ \ \:\
* \__\/ \__\/ \__\/ \__\/
*
*
*
*
* This file is part of TRAP.
*
* TRAP is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* or see <http://www.gnu.org/licenses/>.
*
*
*
* (c) Luca Fossati, fossati@elet.polimi.it, fossati.l@gmail.com
*
\***************************************************************************/
#ifndef SYSCCALLB_H
#define SYSCCALLB_H
#ifdef _WIN32
#pragma warning( disable : 4244 )
#endif
#include "trap_utils.hpp"
#include "ABIIf.hpp"
#include <systemc.h>
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <systemc.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <utime.h>
#include <sys/time.h>
#ifdef __GNUC__
#include <unistd.h>
#else
#include <io.h>
#endif
#ifdef __GNUC__
#if !(defined(__MACOSX__) || defined(__DARWIN__) || defined(__APPLE__) || defined(__CYGWIN__))
#include <error.h>
#endif
#endif
#include <cerrno>
#if !defined(errno) && !defined(HAVE_ERRNO_DECL)
extern int errno;
#endif
#include <sstream>
#ifdef __GNUC__
#include <sys/times.h>
#endif
#include <ctime>
#include "elfFrontend.hpp"
namespace trap{
class OSEmulatorBase{
public:
virtual std::set<std::string> getRegisteredFunctions() = 0;
void set_program_args(const std::vector<std::string> args);
void correct_flags(int &val);
void set_environ(const std::string name, const std::string value);
void set_sysconf(const std::string name, int value);
void reset();
std::map<std::string, std::string> env;
std::map<std::string, int> sysconfmap;
std::vector<std::string> programArgs;
unsigned int heapPointer;
static std::vector<unsigned int> groupIDs;
static unsigned int programsCount;
};
///Base class for each emulated system call;
///Operator () implements the behaviour of the
///emulated call
template<class wordSize> class SyscallCB{
protected:
ABIIf<wordSize> &processorInstance;
sc_time latency;
public:
SyscallCB(ABIIf<wordSize> &processorInstance, sc_time latency) : processorInstance(processorInstance), latency(latency){}
virtual ~SyscallCB(){}
virtual bool operator()() = 0;
};
template<class wordSize> class openSysCall : public SyscallCB<wordSize>{
private:
OSEmulatorBase& osEmu;
public:
openSysCall(ABIIf<wordSize> &processorInstance, OSEmulatorBase &osEmu, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency), osEmu(osEmu){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
//Lets read the name of the file to be opened
char pathname[256];
for(int i = 0; i < 256; i++){
pathname[i] = (char)this->processorInstance.readCharMem(callArgs[0] + i);
if(pathname[i] == '\x0')
break;
}
int flags = callArgs[1];
osEmu.correct_flags(flags);
int mode = callArgs[2];
#ifdef __GNUC__
int ret = ::open(pathname, flags, mode);
#else
int ret = ::_open(pathname, flags, mode);
#endif
this->processorInstance.setRetVal(ret);
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class creatSysCall : public SyscallCB<wordSize>{
public:
creatSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
//Lets read the name of the file to be opened
char pathname[256];
for(int i = 0; i < 256; i++){
pathname[i] = (char)this->processorInstance.readCharMem(callArgs[0] + i);
if(pathname[i] == '\x0')
break;
}
int mode = callArgs[1];
#ifdef __GNUC__
int ret = ::creat((char*)pathname, mode);
#else
int ret = ::_creat((char*)pathname, mode);
#endif
this->processorInstance.setRetVal(ret);
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class closeSysCall : public SyscallCB<wordSize>{
public:
closeSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
int fd = callArgs[0];
if(fd < 0){
THROW_EXCEPTION("File descriptor " << fd << " not valid");
}
#ifdef __GNUC__
if( fd == fileno(stdin) || fd == fileno(stdout) || fd == fileno(stderr) ){
#else
if( fd == _fileno(stdin) || fd == _fileno(stdout) || fd == _fileno(stderr) ){
#endif
this->processorInstance.setRetVal(0);
this->processorInstance.returnFromCall();
}
else{
#ifdef __GNUC__
int ret = ::close(fd);
#else
int ret = ::_close(fd);
#endif
this->processorInstance.setRetVal(ret);
this->processorInstance.returnFromCall();
}
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class readSysCall : public SyscallCB<wordSize>{
public:
readSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
int fd = callArgs[0];
if(fd < 0){
THROW_EXCEPTION("File descriptor " << fd << " not valid");
}
unsigned count = callArgs[2];
unsigned char *buf = new unsigned char[count];
#ifdef __GNUC__
int ret = ::read(fd, buf, count);
#else
int ret = ::_read(fd, buf, count);
#endif
// Now I have to write the read content into memory
wordSize destAddress = callArgs[1];
for(int i = 0; i < ret; i++){
this->processorInstance.writeCharMem(destAddress + i, buf[i]);
}
this->processorInstance.setRetVal(ret);
this->processorInstance.returnFromCall();
delete [] buf;
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class writeSysCall : public SyscallCB<wordSize>{
public:
writeSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
int fd = callArgs[0];
if(fd < 0){
THROW_EXCEPTION("File descriptor " << fd << " not valid");
}
unsigned count = callArgs[2];
wordSize destAddress = callArgs[1];
unsigned char *buf = new unsigned char[count];
for(unsigned int i = 0; i < count; i++){
buf[i] = this->processorInstance.readCharMem(destAddress + i);
}
#ifdef __GNUC__
int ret = ::write(fd, buf, count);
#else
int ret = ::_write(fd, buf, count);
#endif
this->processorInstance.setRetVal(ret);
this->processorInstance.returnFromCall();
delete [] buf;
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class isattySysCall : public SyscallCB<wordSize>{
public:
isattySysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
int desc = callArgs[0];
#ifdef __GNUC__
int ret = ::isatty(desc);
#else
int ret = ::_isatty(desc);
#endif
this->processorInstance.setRetVal(ret);
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class sbrkSysCall : public SyscallCB<wordSize>{
private:
unsigned int &heapPointer;
public:
sbrkSysCall(ABIIf<wordSize> &processorInstance, unsigned int &heapPointer, sc_time latency = SC_ZERO_TIME) :
SyscallCB<wordSize>(processorInstance, latency), heapPointer(heapPointer){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
wordSize base = this->heapPointer;
long long increment = callArgs[0];
this->heapPointer += increment;
//I try to read from meory to see if it is possible to access the just allocated address;
//In case it is not it means that I'm out of memory and I signal the error
try{
this->processorInstance.readMem(this->heapPointer);
this->processorInstance.setRetVal(base);
}
catch(...){
this->processorInstance.setRetVal(-1);
std::cerr << "SBRK: tried to allocate " << increment << " bytes of memory starting at address " << std::hex << std::showbase << base << std::dec << " but it seems there is not enough memory" << std::endl;
}
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class lseekSysCall : public SyscallCB<wordSize>{
public:
lseekSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
int fd = callArgs[0];
if(fd < 0){
THROW_EXCEPTION("File descriptor " << fd << " not valid");
}
int offset = callArgs[1];
int whence = callArgs[2];
#ifdef __GNUC__
int ret = ::lseek(fd, offset, whence);
#else
int ret = ::_lseek(fd, offset, whence);
#endif
this->processorInstance.setRetVal(ret);
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class fstatSysCall : public SyscallCB<wordSize>{
public:
fstatSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
#ifdef __GNUC__
struct stat buf_stat;
#else
struct _stat buf_stat;
#endif
int fd = callArgs[0];
if(fd < 0){
THROW_EXCEPTION("File descriptor " << fd << " not valid");
}
int retAddr = callArgs[1];
#ifdef __GNUC__
int ret = ::fstat(fd, &buf_stat);
#else
int ret = ::_fstat(fd, &buf_stat);
#endif
if(ret >= 0 && retAddr != 0){
this->processorInstance.writeMem(retAddr, buf_stat.st_dev);
this->processorInstance.writeMem(retAddr + 2, buf_stat.st_ino);
this->processorInstance.writeMem(retAddr + 4, buf_stat.st_mode);
this->processorInstance.writeMem(retAddr + 8, buf_stat.st_nlink);
this->processorInstance.writeMem(retAddr + 10, buf_stat.st_uid);
this->processorInstance.writeMem(retAddr + 12, buf_stat.st_gid);
this->processorInstance.writeMem(retAddr + 14, buf_stat.st_rdev);
this->processorInstance.writeMem(retAddr + 16, buf_stat.st_size);
this->processorInstance.writeMem(retAddr + 20, buf_stat.st_atime);
this->processorInstance.writeMem(retAddr + 28, buf_stat.st_mtime);
this->processorInstance.writeMem(retAddr + 36, buf_stat.st_ctime);
#ifdef __GNUC__
this->processorInstance.writeMem(retAddr + 44, buf_stat.st_blksize);
this->processorInstance.writeMem(retAddr + 48, buf_stat.st_blocks);
#endif
}
this->processorInstance.setRetVal(ret);
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class statSysCall : public SyscallCB<wordSize>{
public:
statSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
#ifdef __GNUC__
struct stat buf_stat;
#else
struct _stat buf_stat;
#endif
char pathname[256];
for(int i = 0; i < 256; i++){
pathname[i] = (char)this->processorInstance.readCharMem(callArgs[0] + i);
if(pathname[i] == '\x0')
break;
}
int retAddr = callArgs[1];
#ifdef __GNUC__
int ret = ::stat((char *)pathname, &buf_stat);
#else
int ret = ::_stat((char *)pathname, &buf_stat);
#endif
if(ret >= 0 && retAddr != 0){
this->processorInstance.writeMem(retAddr, buf_stat.st_dev);
this->processorInstance.writeMem(retAddr + 2, buf_stat.st_ino);
this->processorInstance.writeMem(retAddr + 4, buf_stat.st_mode);
this->processorInstance.writeMem(retAddr + 8, buf_stat.st_nlink);
this->processorInstance.writeMem(retAddr + 10, buf_stat.st_uid);
this->processorInstance.writeMem(retAddr + 12, buf_stat.st_gid);
this->processorInstance.writeMem(retAddr + 14, buf_stat.st_rdev);
this->processorInstance.writeMem(retAddr + 16, buf_stat.st_size);
this->processorInstance.writeMem(retAddr + 20, buf_stat.st_atime);
this->processorInstance.writeMem(retAddr + 28, buf_stat.st_mtime);
this->processorInstance.writeMem(retAddr + 36, buf_stat.st_ctime);
#ifdef __GNUC__
this->processorInstance.writeMem(retAddr + 44, buf_stat.st_blksize);
this->processorInstance.writeMem(retAddr + 48, buf_stat.st_blocks);
#endif
}
this->processorInstance.setRetVal(ret);
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class _exitSysCall : public SyscallCB<wordSize>{
public:
_exitSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
extern int exitValue;
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
exitValue = (int)callArgs[0];
std::cout << std::endl << "Program exited with value " << exitValue << std::endl << std::endl;
if(sc_is_running()){
OSEmulatorBase::programsCount--;
if(OSEmulatorBase::programsCount>0){ //in case there are other programs still running, block the current processor
sc_event endEv;
wait(endEv);
}else //ok, this is the last running program, it is possible to call sc_stop()
sc_stop();
wait(SC_ZERO_TIME);
}
return true;
}
};
template<class wordSize> class timesSysCall : public SyscallCB<wordSize>{
public:
timesSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
unsigned int curSimTime = (unsigned int)(sc_time_stamp().to_double()/1.0e+6);
wordSize timesRetLoc = callArgs[0];
if(timesRetLoc != 0){
#ifndef __GNUC__
struct tms {
clock_t tms_utime; /* user time */
clock_t tms_stime; /* system time */
clock_t tms_cutime; /* user time of children */
clock_t tms_cstime; /* system time of children */
};
#endif
struct tms buf;
buf.tms_utime = curSimTime;
buf.tms_stime = curSimTime;
buf.tms_cutime = curSimTime;
buf.tms_cstime = curSimTime;
this->processorInstance.writeMem(timesRetLoc, buf.tms_utime);
timesRetLoc += 4;
this->processorInstance.writeMem(timesRetLoc, buf.tms_stime);
timesRetLoc += 4;
this->processorInstance.writeMem(timesRetLoc, buf.tms_cutime);
|
timesRetLoc += 4;
this->processorInstance.writeMem(timesRetLoc, buf.tms_cstime);
}
this->processorInstance.setRetVal(curSimTime);
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class timeSysCall : public SyscallCB<wordSize>{
private:
int initialTime;
public:
timeSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){
this->initialTime = time(0);
}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
int t = callArgs[0];
int ret = this->initialTime + (int)(sc_time_stamp().to_double()/1.0e+12);
if (t != 0)
this->processorInstance.writeMem(t, ret);
this->processorInstance.setRetVal(ret);
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class randomSysCall : public SyscallCB<wordSize>{
public:
randomSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
int ret = ::rand();
this->processorInstance.setRetVal(ret);
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class utimesSysCall : public SyscallCB<wordSize>{
public:
utimesSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
char pathname[256];
for(int i = 0; i < 256; i++){
pathname[i] = (char)this->processorInstance.readCharMem(callArgs[0] + i);
if(pathname[i] == '\x0')
break;
}
int ret = -1;
int timesAddr = callArgs[1];
if(timesAddr == 0){
ret = ::utimes((char *)pathname, NULL);
}
else{
struct timeval times[2];
times[0].tv_sec = this->processorInstance.readMem(timesAddr);
times[0].tv_usec = this->processorInstance.readMem(timesAddr + 4);
times[1].tv_sec = this->processorInstance.readMem(timesAddr + 8);
times[1].tv_usec = this->processorInstance.readMem(timesAddr + 12);
ret = ::utimes((char *)pathname, times);
}
this->processorInstance.setRetVal(ret);
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class lstatSysCall : public SyscallCB<wordSize>{
public:
lstatSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
#ifdef __GNUC__
struct stat buf_stat;
#else
struct _stat buf_stat;
#endif
char pathname[256];
for(int i = 0; i < 256; i++){
pathname[i] = (char)this->processorInstance.readCharMem(callArgs[0] + i);
if(pathname[i] == '\x0')
break;
}
int retAddr = callArgs[1];
#ifdef __GNUC__
int ret = ::lstat((char *)pathname, &buf_stat);
#else
int ret = ::_lstat((char *)pathname, &buf_stat);
#endif
if(ret >= 0 && retAddr != 0){
this->processorInstance.writeMem(retAddr, buf_stat.st_dev);
this->processorInstance.writeMem(retAddr + 2, buf_stat.st_ino);
this->processorInstance.writeMem(retAddr + 4, buf_stat.st_mode);
this->processorInstance.writeMem(retAddr + 8, buf_stat.st_nlink);
this->processorInstance.writeMem(retAddr + 10, buf_stat.st_uid);
this->processorInstance.writeMem(retAddr + 12, buf_stat.st_gid);
this->processorInstance.writeMem(retAddr + 14, buf_stat.st_rdev);
this->processorInstance.writeMem(retAddr + 16, buf_stat.st_size);
this->processorInstance.writeMem(retAddr + 20, buf_stat.st_atime);
this->processorInstance.writeMem(retAddr + 28, buf_stat.st_mtime);
this->processorInstance.writeMem(retAddr + 36, buf_stat.st_ctime);
#ifdef __GNUC__
this->processorInstance.writeMem(retAddr + 44, buf_stat.st_blksize);
this->processorInstance.writeMem(retAddr + 48, buf_stat.st_blocks);
#endif
}
this->processorInstance.setRetVal(ret);
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class getpidSysCall : public SyscallCB<wordSize>{
public:
getpidSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
this->processorInstance.setRetVal(123);
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class chmodSysCall : public SyscallCB<wordSize>{
public:
chmodSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
char pathname[256];
for(int i = 0; i < 256; i++){
pathname[i] = (char)this->processorInstance.readCharMem(callArgs[0] + i);
if(pathname[i] == '\x0')
break;
}
int mode = callArgs[1];
#ifdef __GNUC__
int ret = ::chmod((char*)pathname, mode);
#else
int ret = ::_chmod((char*)pathname, mode);
#endif
this->processorInstance.setRetVal(ret);
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class dupSysCall : public SyscallCB<wordSize>{
public:
dupSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
int fd = callArgs[0];
if(fd < 0){
THROW_EXCEPTION("File descriptor not valid");
}
#ifdef __GNUC__
int ret = ::dup(fd);
#else
int ret = ::_dup(fd);
#endif
this->processorInstance.setRetVal(ret);
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class dup2SysCall : public SyscallCB<wordSize>{
public:
dup2SysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
int fd = callArgs[0];
if(fd < 0){
THROW_EXCEPTION("File descriptor not valid");
}
int newfd = callArgs[1];
#ifdef __GNUC__
int ret = ::dup2(fd, newfd);
#else
int ret = ::_dup2(fd, newfd);
#endif
this->processorInstance.setRetVal(ret);
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class getenvSysCall : public SyscallCB<wordSize>{
private:
unsigned int &heapPointer;
std::map<std::string, std::string>& env;
public:
getenvSysCall(ABIIf<wordSize> &processorInstance, unsigned int &heapPointer, std::map<std::string, std::string>& env, sc_time latency = SC_ZERO_TIME) :
SyscallCB<wordSize>(processorInstance, latency), heapPointer(heapPointer), env(env){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
char envname[256];
int envNameAddr = callArgs[0];
if(envNameAddr != 0){
for(int i = 0; i < 256; i++){
envname[i] = (char)this->processorInstance.readCharMem(envNameAddr + i);
if(envname[i] == '\x0')
break;
}
std::map<std::string, std::string>::iterator curEnv = this->env.find((std::string(envname)));
if(curEnv == this->env.end()){
this->processorInstance.setRetVal(0);
this->processorInstance.returnFromCall();
}
else{
//I have to allocate memory for the result on the simulated memory;
//I then have to copy the read environment variable here and return
//the pointer to it
unsigned int base = this->heapPointer;
this->heapPointer += curEnv->second.size() + 1;
for(unsigned int i = 0; i < curEnv->second.size(); i++){
this->processorInstance.writeCharMem(base + i, curEnv->second[i]);
}
this->processorInstance.writeCharMem(base + curEnv->second.size(), 0);
this->processorInstance.setRetVal(base);
this->processorInstance.returnFromCall();
}
}
else{
this->processorInstance.setRetVal(0);
this->processorInstance.returnFromCall();
}
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class gettimeofdaySysCall : public SyscallCB<wordSize>{
public:
gettimeofdaySysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
int timesRetLoc = callArgs[0];
if(timesRetLoc != 0){
double curSimTime = sc_time_stamp().to_double();
unsigned int tv_sec = (unsigned int)(curSimTime/1.0e+12);
unsigned int tv_usec = (unsigned int)((curSimTime - tv_sec*1.0e+12)/1.0e+6);
this->processorInstance.writeMem(timesRetLoc, tv_sec);
timesRetLoc += 4;
this->processorInstance.writeMem(timesRetLoc, tv_usec);
}
this->processorInstance.setRetVal(0);
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class killSysCall : public SyscallCB<wordSize>{
public:
killSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
THROW_EXCEPTION("KILL SystemCall not yet implemented");
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class errorSysCall : public SyscallCB<wordSize>{
public:
errorSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
int status = callArgs[0];
int errnum = callArgs[1];
char* errorString = ::strerror(errnum);
if(status != 0){
std::cerr << std::endl << "Program exited with value " << status << std::endl << " Error message: " << errorString << std::endl;
if(sc_is_running())
sc_stop();
}
else{
std::cerr << "An error occurred in the execution of the program: message = " << errorString << std::endl;
this->processorInstance.setRetVal(0);
this->processorInstance.returnFromCall();
}
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class chownSysCall : public SyscallCB<wordSize>{
public:
chownSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
#ifdef __GNUC__
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
char pathname[256];
for(int i = 0; i < 256; i++){
pathname[i] = (char)this->processorInstance.readCharMem(callArgs[0] + i);
if(pathname[i] == '\x0')
break;
}
uid_t owner = callArgs[1];
gid_t group = callArgs[2];
int ret = ::chown((char*)pathname, owner, group);
#else
int ret = 0;
#endif
this->processorInstance.setRetVal(ret);
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class unlinkSysCall : public SyscallCB<wordSize>{
public:
unlinkSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
char pathname[256];
for(int i = 0; i < 256; i++){
pathname[i] = (char)this->processorInstance.readCharMem(callArgs[0] + i);
if(pathname[i] == '\x0')
break;
}
#ifdef __GNUC__
int ret = ::unlink((char*)pathname);
#else
int ret = ::_unlink((char*)pathname);
#endif
this->processorInstance.setRetVal(ret);
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class usleepSysCall : public SyscallCB<wordSize>{
public:
usleepSysCall(ABIIf<wordSize> &processorInstance, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency){}
bool operator()(){
this->processorInstance.preCall();
//Since we have a single process this function doesn't do anything :-)
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
template<class wordSize> class mainSysCall : public SyscallCB<wordSize>{
private:
unsigned int &heapPointer;
std::vector<std::string>& programArgs;
public:
mainSysCall(ABIIf<wordSize> &processorInstance, unsigned int &heapPointer, std::vector<std::string>& programArgs) :
SyscallCB<wordSize>(processorInstance, SC_ZERO_TIME), heapPointer(heapPointer), programArgs(programArgs){}
bool operator()(){
this->processorInstance.preCall();
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
if(callArgs[0] != 0){
this->processorInstance.postCall();
return false;
}
std::vector< wordSize > mainArgs;
if(this->programArgs.size() == 0){
mainArgs.push_back(0);
mainArgs.push_back(0);
this->processorInstance.setArgs(mainArgs);
this->processorInstance.postCall();
return false;
}
unsigned int argAddr = ((unsigned int)this->heapPointer) + (this->programArgs.size() + 1)*4;
unsigned int argNumAddr = this->heapPointer;
std::vector<std::string>::iterator argsIter, argsEnd;
for(argsIter = this->programArgs.begin(), argsEnd = this->programArgs.end(); argsIter != argsEnd; argsIter++){
this->processorInstance.writeMem(argNumAddr, argAddr);
argNumAddr += 4;
for(unsigned int i = 0; i < argsIter->size(); i++){
this->processorInstance.writeCharMem(argAddr + i, argsIter->c_str()[i]);
}
this->processorInstance.writeCharMem(argAddr + argsIter->size(), 0);
argAddr += argsIter->size() + 1;
}
this->processorInstance.writeMem(argNumAddr, 0);
mainArgs.push_back(this->programArgs.size());
mainArgs.push_back(this->heapPointer);
this->processorInstance.setArgs(mainArgs);
this->heapPointer = argAddr;
this->processorInstance.postCall();
return false;
}
};
/*
* sysconf values per IEEE Std 1003.1, 2004 Edition
*/
#define NEWLIB_SC_ARG_MAX 0
#define NEWLIB_SC_CHILD_MAX 1
#define NEWLIB_SC_CLK_TCK 2
#define NEWLIB_SC_NGROUPS_MAX 3
#define NEWLIB_SC_OPEN_MAX 4
#define NEWLIB_SC_JOB_CONTROL 5
#define NEWLIB_SC_SAVED_IDS 6
#define NEWLIB_SC_VERSION 7
#define NEWLIB_SC_PAGESIZE 8
#define NEWLIB_SC_PAGE_SIZE NEWLIB_SC_PAGESIZE
/* These are non-POSIX values we accidentally introduced in 2000 without
guarding them. Keeping them unguarded for backward compatibility. */
#define NEWLIB_SC_NPROCESSORS_CONF 9
#define NEWLIB_SC_NPROCESSORS_ONLN 10
#define NEWLIB_SC_PHYS_PAGES 11
#define NEWLIB_SC_AVPHYS_PAGES 12
/* End of non-POSIX values. */
#define NEWLIB_SC_MQ_OPEN_MAX 13
#define NEWLIB_SC_MQ_PRIO_MAX 14
#define NEWLIB_SC_RTSIG_MAX 15
#define NEWLIB_SC_SEM_NSEMS_MAX 16
#define NEWLIB_SC_SEM_VALUE_MAX 17
#define
|
NEWLIB_SC_SIGQUEUE_MAX 18
#define NEWLIB_SC_TIMER_MAX 19
#define NEWLIB_SC_TZNAME_MAX 20
#define NEWLIB_SC_ASYNCHRONOUS_IO 21
#define NEWLIB_SC_FSYNC 22
#define NEWLIB_SC_MAPPED_FILES 23
#define NEWLIB_SC_MEMLOCK 24
#define NEWLIB_SC_MEMLOCK_RANGE 25
#define NEWLIB_SC_MEMORY_PROTECTION 26
#define NEWLIB_SC_MESSAGE_PASSING 27
#define NEWLIB_SC_PRIORITIZED_IO 28
#define NEWLIB_SC_REALTIME_SIGNALS 29
#define NEWLIB_SC_SEMAPHORES 30
#define NEWLIB_SC_SHARED_MEMORY_OBJECTS 31
#define NEWLIB_SC_SYNCHRONIZED_IO 32
#define NEWLIB_SC_TIMERS 33
#define NEWLIB_SC_AIO_LISTIO_MAX 34
#define NEWLIB_SC_AIO_MAX 35
#define NEWLIB_SC_AIO_PRIO_DELTA_MAX 36
#define NEWLIB_SC_DELAYTIMER_MAX 37
#define NEWLIB_SC_THREAD_KEYS_MAX 38
#define NEWLIB_SC_THREAD_STACK_MIN 39
#define NEWLIB_SC_THREAD_THREADS_MAX 40
#define NEWLIB_SC_TTY_NAME_MAX 41
#define NEWLIB_SC_THREADS 42
#define NEWLIB_SC_THREAD_ATTR_STACKADDR 43
#define NEWLIB_SC_THREAD_ATTR_STACKSIZE 44
#define NEWLIB_SC_THREAD_PRIORITY_SCHEDULING 45
#define NEWLIB_SC_THREAD_PRIO_INHERIT 46
/* NEWLIB_SC_THREAD_PRIO_PROTECT was NEWLIB_SC_THREAD_PRIO_CEILING in early drafts */
#define NEWLIB_SC_THREAD_PRIO_PROTECT 47
#define NEWLIB_SC_THREAD_PRIO_CEILING NEWLIB_SC_THREAD_PRIO_PROTECT
#define NEWLIB_SC_THREAD_PROCESS_SHARED 48
#define NEWLIB_SC_THREAD_SAFE_FUNCTIONS 49
#define NEWLIB_SC_GETGR_R_SIZE_MAX 50
#define NEWLIB_SC_GETPW_R_SIZE_MAX 51
#define NEWLIB_SC_LOGIN_NAME_MAX 52
#define NEWLIB_SC_THREAD_DESTRUCTOR_ITERATIONS 53
#define NEWLIB_SC_ADVISORY_INFO 54
#define NEWLIB_SC_ATEXIT_MAX 55
#define NEWLIB_SC_BARRIERS 56
#define NEWLIB_SC_BC_BASE_MAX 57
#define NEWLIB_SC_BC_DIM_MAX 58
#define NEWLIB_SC_BC_SCALE_MAX 59
#define NEWLIB_SC_BC_STRING_MAX 60
#define NEWLIB_SC_CLOCK_SELECTION 61
#define NEWLIB_SC_COLL_WEIGHTS_MAX 62
#define NEWLIB_SC_CPUTIME 63
#define NEWLIB_SC_EXPR_NEST_MAX 64
#define NEWLIB_SC_HOST_NAME_MAX 65
#define NEWLIB_SC_IOV_MAX 66
#define NEWLIB_SC_IPV6 67
#define NEWLIB_SC_LINE_MAX 68
#define NEWLIB_SC_MONOTONIC_CLOCK 69
#define NEWLIB_SC_RAW_SOCKETS 70
#define NEWLIB_SC_READER_WRITER_LOCKS 71
#define NEWLIB_SC_REGEXP 72
#define NEWLIB_SC_RE_DUP_MAX 73
#define NEWLIB_SC_SHELL 74
#define NEWLIB_SC_SPAWN 75
#define NEWLIB_SC_SPIN_LOCKS 76
#define NEWLIB_SC_SPORADIC_SERVER 77
#define NEWLIB_SC_SS_REPL_MAX 78
#define NEWLIB_SC_SYMLOOP_MAX 79
#define NEWLIB_SC_THREAD_CPUTIME 80
#define NEWLIB_SC_THREAD_SPORADIC_SERVER 81
#define NEWLIB_SC_TIMEOUTS 82
#define NEWLIB_SC_TRACE 83
#define NEWLIB_SC_TRACE_EVENT_FILTER 84
#define NEWLIB_SC_TRACE_EVENT_NAME_MAX 85
#define NEWLIB_SC_TRACE_INHERIT 86
#define NEWLIB_SC_TRACE_LOG 87
#define NEWLIB_SC_TRACE_NAME_MAX 88
#define NEWLIB_SC_TRACE_SYS_MAX 89
#define NEWLIB_SC_TRACE_USER_EVENT_MAX 90
#define NEWLIB_SC_TYPED_MEMORY_OBJECTS 91
#define NEWLIB_SC_V6_ILP32_OFF32 92
#define NEWLIB_SC_XBS5_ILP32_OFF32 NEWLIB_SC_V6_ILP32_OFF32
#define NEWLIB_SC_V6_ILP32_OFFBIG 93
#define NEWLIB_SC_XBS5_ILP32_OFFBIG NEWLIB_SC_V6_ILP32_OFFBIG
#define NEWLIB_SC_V6_LP64_OFF64 94
#define NEWLIB_SC_XBS5_LP64_OFF64 NEWLIB_SC_V6_LP64_OFF64
#define NEWLIB_SC_V6_LPBIG_OFFBIG 95
#define NEWLIB_SC_XBS5_LPBIG_OFFBIG NEWLIB_SC_V6_LPBIG_OFFBIG
#define NEWLIB_SC_XOPEN_CRYPT 96
#define NEWLIB_SC_XOPEN_ENH_I18N 97
#define NEWLIB_SC_XOPEN_LEGACY 98
#define NEWLIB_SC_XOPEN_REALTIME 99
#define NEWLIB_SC_STREAM_MAX 100
#define NEWLIB_SC_PRIORITY_SCHEDULING 101
#define NEWLIB_SC_XOPEN_REALTIME_THREADS 102
#define NEWLIB_SC_XOPEN_SHM 103
#define NEWLIB_SC_XOPEN_STREAMS 104
#define NEWLIB_SC_XOPEN_UNIX 105
#define NEWLIB_SC_XOPEN_VERSION 106
#define NEWLIB_SC_2_CHAR_TERM 107
#define NEWLIB_SC_2_C_BIND 108
#define NEWLIB_SC_2_C_DEV 109
#define NEWLIB_SC_2_FORT_DEV 110
#define NEWLIB_SC_2_FORT_RUN 111
#define NEWLIB_SC_2_LOCALEDEF 112
#define NEWLIB_SC_2_PBS 113
#define NEWLIB_SC_2_PBS_ACCOUNTING 114
#define NEWLIB_SC_2_PBS_CHECKPOINT 115
#define NEWLIB_SC_2_PBS_LOCATE 116
#define NEWLIB_SC_2_PBS_MESSAGE 117
#define NEWLIB_SC_2_PBS_TRACK 118
#define NEWLIB_SC_2_SW_DEV 119
#define NEWLIB_SC_2_UPE 120
#define NEWLIB_SC_2_VERSION 121
template<class wordSize> class sysconfSysCall : public SyscallCB<wordSize>{
private:
std::map<std::string, int>& sysconfmap;
public:
sysconfSysCall(ABIIf<wordSize> &processorInstance, std::map<std::string, int>& sysconfmap, sc_time latency = SC_ZERO_TIME) : SyscallCB<wordSize>(processorInstance, latency), sysconfmap(sysconfmap){}
bool operator()(){
this->processorInstance.preCall();
//Lets get the system call arguments
std::vector< wordSize > callArgs = this->processorInstance.readArgs();
int argId = callArgs[0];
int ret = -1;
switch(argId){
case NEWLIB_SC_NPROCESSORS_ONLN:
if(this->sysconfmap.find("_SC_NPROCESSORS_ONLN") == this->sysconfmap.end())
ret = 1;
else
ret = this->sysconfmap["_SC_NPROCESSORS_ONLN"];
break;
case NEWLIB_SC_CLK_TCK:
if(this->sysconfmap.find("_SC_CLK_TCK") == this->sysconfmap.end())
ret = 1000000;
else
ret = this->sysconfmap["_SC_CLK_TCK"];
break;
default:
ret = -1;
break;
}
this->processorInstance.setRetVal(ret);
this->processorInstance.returnFromCall();
this->processorInstance.postCall();
if(this->latency.to_double() > 0)
wait(this->latency);
return true;
}
};
}
#endif
|
/*
* SPDX-FileCopyrightText: Copyright (c) 2021 NVIDIA CORPORATION & AFFILIATES.
* All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __PRODUCER_CONSUMER_H__
#define __PRODUCER_CONSUMER_H__
#include <systemc.h>
#include <nvhls_connections.h>
#include <nvhls_packet.h>
#include <arbitrated_crossbar.h>
#include <interconnect/Interconnect.hpp>
#include "interconnect_config.hpp"
#ifdef INTERCONNECT_GEN
#include ic_header(INTERCONNECT_GEN)
#endif // ifdef INTERCONNECT_GEN
#include "ProducerConsumerPart.hpp"
class ProducerConsumerArray : public match::Module {
public:
SC_HAS_PROCESS(ProducerConsumerArray);
static const int kPEWidth = PE_WIDTH;
static const int kPEHeight = PE_HEIGHT;
ProducerConsumerPart *pe_part_inst[kPEWidth * kPEHeight];
IC_HAS_INTERCONNECT(pcmodulearray);
ProducerConsumerArray(sc_module_name nm) : match::Module(nm) {
ic.clk(clk);
ic.rst(rst);
for (int i = 0; i < kPEWidth * kPEHeight; i++) {
pe_part_inst[i] =
new ProducerConsumerPart(sc_gen_unique_name("pe_part_inst"), i);
pe_part_inst[i]->clk(clk);
pe_part_inst[i]->rst(rst);
IC_PART_BIND(*pe_part_inst[i], i);
}
}
};
#endif
|
#ifndef IMG_RECEIVER_HPP
#define IMG_RECEIVER_HPP
#include <systemc.h>
#include "address_map.hpp"
SC_MODULE(img_receiver)
{
//Array for input image
unsigned char* input_image;
sc_dt::uint64 address_offset;
SC_CTOR(img_receiver)
{
input_image = new unsigned char[IMG_INPUT_SIZE];
address_offset = IMG_INPUT_ADDRESS_LO;
}
//Backdoor access to memory
void backdoor_write(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address);
void backdoor_read(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address);
};
#endif // IMG_RECEIVER_HPP
|
#ifndef __ROM_3840_32_H__
#define __ROM_3840_32_H__
#include <fstream>
#include <systemc.h>
class rom_3840x32_t : public sc_module
{
public:
sc_in<uint32_t> addr1;
sc_in<uint32_t> addr2;
sc_out<uint32_t> data1;
sc_out<uint32_t> data2;
uint32_t data[3840];
void port1() {
while(true) {
uint32_t addrw32 = addr1.read();
uint32_t addrw11 = addrw32 % 4096;
data1.write(data[addrw11]);
wait();
}
}
void port2() {
while(true) {
uint32_t addrw32 = addr2.read();
uint32_t addrw11 = addrw32 % 4096;
data2.write(data[addrw11]);
wait();
}
}
void clear_memory() {
for (int i=0; i<3840; ++i) data[i] = 0;
update.write(!update.read());
}
bool load_binary(const std::string& path)
{
clear_memory();
ifstream f(path, std::ios::binary);
if (f.is_open()) {
f.seekg(0, f.end);
int size = f.tellg();
f.seekg(0, f.beg);
auto buf = new char[size];
f.read(buf, size);
// std::vector<unsigned char> buf
// (std::istreambuf_iterator<char>(f), {});
if (size == 0) return false;
if (size % 4 != 0) return false;
auto words = (uint32_t*) buf;
for (int i=0; i<size/4; ++i) {
data[i] = words[i];
}
f.close();
delete[] buf;
update.write(!update.read());
return true;
}
else {
return false;
}
}
SC_CTOR(rom_3840x32_t)
: update("update")
{
update.write(false);
SC_THREAD(port1);
sensitive << addr1;
sensitive << update;
SC_THREAD(port2);
sensitive << addr2;
sensitive << update;
}
private:
sc_signal<bool> update;
};
#endif
|
/*
* Adder.h
* SystemC_SimpleAdder
*
* Created by Le Gal on 07/05/07.
* Copyright 2007 __MyCompanyName__. All rights reserved.
*
*/
#ifndef _FrameProcessing_
#define _FrameProcessing_
#include "systemc.h"
#include <cstdint>
#include "constantes.hpp"
SC_MODULE(FrameProcessing)
{
public:
sc_in < bool > clock;
sc_in < bool > reset;
sc_fifo_in < sc_uint< 8> > e;
sc_fifo_out< sc_uint<32> > addr;
sc_fifo_out< sc_uint<24> > rgbv;
SC_CTOR(FrameProcessing)
{
SC_CTHREAD(do_gen, clock.pos());
reset_signal_is(reset,true);
}
private:
void do_gen( )
{
cout << "(II) RAWReader :: START" << endl;
uint32_t curr_adr;
// uint16_t curr_x;
// uint16_t curr_y;
while(true)
{
// uint8_t type = e.read();
// uint16_t special = e.read();
uint16_t type = e.read(); type |= ((uint16_t)e.read()) << 8;
uint16_t mot1 = e.read(); mot1 |= ((uint16_t)e.read()) << 8;
uint16_t mot2 = e.read(); mot2 |= ((uint16_t)e.read()) << 8;
uint16_t mot3 = e.read(); mot3 |= ((uint16_t)e.read()) << 8;
if( type == FRAME_NEW_IMAGE )
{
cout << "(II) FrameProcessing :: FRAME_NEW_IMAGE" << endl;
curr_adr = 0;
// curr_y = 0;
for(uint16_t i = 0; i < _BYTE_PAYLOAD_; i += 1)
e.read();
}
else if( type == FRAME_END_IMAGE )
{
cout << "(II) FrameProcessing :: FRAME_END_IMAGE" << endl;
#ifdef _SIMULATION_
wait( 10, SC_US );
sc_stop();
#endif
curr_adr = 0;
// curr_y = 0;
for(uint16_t i = 0; i < _BYTE_PAYLOAD_; i += 1)
e.read();
}
// else if( type == FRAME_NEW_LINE )
// {
// sc_uint< 8> r0 = e.read();
// sc_uint< 8> r1 = e.read();
// sc_uint<16> r2 = (r1, r0);
// curr_y = r2;
// curr_adr = _IMAGE_WIDTH_ * curr_y;
//
// for(uint16_t i = 2; i < _BYTE_PAYLOAD_; i += 1)
// e.read();
// cout << "(II) FrameProcessing :: FRAME_NEW_LINE (" << curr_y << ")" << endl;
// }
// else if( type == FRAME_END_LINE )
// {
// sc_uint< 8> r0 = e.read();
// sc_uint< 8> r1 = e.read();
// sc_uint<16> r2 = (r1, r0);
// curr_y = r2;
// curr_adr = _IMAGE_WIDTH_ * curr_y;
//
// for(uint16_t i = 2; i < _BYTE_PAYLOAD_; i += 1)
// e.read();
// }
else if( type == FRAME_INFOS )
{
//
// On utilise les données provenant de la trame pour calculer
// la position du bloc de pixel dans l'image
//
// cout << mot1 << mot2 << endl;
uint32_t curr_off = mot1 + _IMAGE_WIDTH_ * mot2;
// cout << "(II) FrameProcessing :: FRAME_INFOS :: curr_y = " << curr_y << " :: special = " << special << " :: curr_off = " << curr_off << endl;
for(uint16_t i = 0; i < _BYTE_PAYLOAD_; i += 3)
{
sc_uint< 8> R = e.read();
sc_uint< 8> G = e.read();
sc_uint< 8> B = e.read();
sc_uint<24> RGB = (R, G, B);
rgbv.write( RGB );
addr.write( curr_off );
curr_off += 1;
}
}
else
{
//
// Le type de trame n'est pas reconnu, on met directement a la bin les données
//
cout << "(EE) Error detected on frame type :: flusing data to the bin..." << endl;
for(uint16_t i = 0; i < _BYTE_PAYLOAD_ + _BYTE_CRC_; i += 1)
e.read();
}
}
}
};
#endif
|
#ifndef PACKET_GENERATOR_TLM_HPP
#define PACKET_GENERATOR_TLM_HPP
#include <systemc.h>
using namespace sc_core;
using namespace sc_dt;
using namespace std;
#include <tlm.h>
#include <tlm_utils/simple_initiator_socket.h>
#include <tlm_utils/simple_target_socket.h>
#include <tlm_utils/peq_with_cb_and_phase.h>
#include <systemc-ams.h>
#include "packetGenerator.h"
#include "../src/img_target.cpp"
#include "address_map.hpp"
//Extended Unification TLM
struct packetGenerator_tlm : public packetGenerator, public img_target
{
packetGenerator_tlm(sc_module_name name, sca_core::sca_time sample_time) : packetGenerator((std::string(name) + "_AMS_HW_block").c_str(), sample_time), img_target((std::string(name) + "_target").c_str()), tmp_data_length(0) {
tmp_data = new unsigned char[IMG_OUTPUT_SIZE];
#ifdef DISABLE_PACKET_GENERATOR_DEBUG
this->use_prints = false;
#endif // DISABLE_PACKET_GENERATOR_DEBUG
checkprintenableimgtar(use_prints);
}
//Override do_when_transaction functions
virtual void do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address);
virtual void do_when_write_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address);
unsigned int tmp_data_length;
unsigned char* tmp_data;
};
#endif // PACKET_GENERATOR_TLM_HPP
|
/*
* Created on: 21. jun. 2019
* Author: Jonathan Horsted Schougaard
*/
#ifdef HW_COSIM
//#define __GMP_WITHIN_CONFIGURE
#endif
#define DEBUG_SYSTEMC
#define HLS_APPROX_TIME
#define SC_INCLUDE_FX
#include "hwcore/tb/pipes/tb_imagedatafix.h"
#include <systemc.h>
unsigned errors = 0;
const char simulation_name[] = "tb_imagedatafix";
int sc_main(int argc, char *argv[]) {
cout << "INFO: Elaborating " << simulation_name << endl;
sc_core::sc_report_handler::set_actions("/IEEE_Std_1666/deprecated", sc_core::SC_DO_NOTHING);
sc_report_handler::set_actions(SC_ID_LOGIC_X_TO_BOOL_, SC_LOG);
sc_report_handler::set_actions(SC_ID_VECTOR_CONTAINS_LOGIC_VALUE_, SC_LOG);
// sc_report_handler::set_actions( SC_ID_OBJECT_EXISTS_, SC_LOG);
// sc_set_time_resolution(1,SC_PS);
// sc_set_default_time_unit(1,SC_NS);
// ModuleSingle modulesingle("modulesingle_i");
tb_top_imagedata_fix tb_01("tb_top_imagedata_fix");
cout << "INFO: Simulating " << simulation_name << endl;
sc_time time_out(1000, SC_US);
sc_start(time_out);
cout << "INFO: end time is: " << sc_time_stamp().to_string() << ", and max time is: " << time_out.to_string()
<< std::endl
<< std::flush;
sc_assert(sc_time_stamp() != time_out);
cout << "INFO: Post-processing " << simulation_name << endl;
cout << "INFO: Simulation " << simulation_name << " " << (errors ? "FAILED" : "PASSED") << " with " << errors
<< " errors" << std::endl;
#ifdef __RTL_SIMULATION__
cout << "HW cosim done" << endl;
#endif
return errors ? 1 : 0;
}
|
#pragma once
#include "systemc.hpp"
#include "common.hpp"
struct Behavior_module : sc_core::sc_module
{
sc_core::sc_in<Data_t> recv_port { "recv_port" };
sc_core::sc_out<Data_t> send_port { "send_port" };
Behavior_module( sc_core::sc_module_name instance );
void start_of_simulation();
void behavior_thread();
private:
Data_t recv_value{ 0 };
Data_t send_value{ 0xFFFFu };
};
|
// Copyright (c) 2011-2024 Columbia University, System Level Design Group
// SPDX-License-Identifier: Apache-2.0
#ifndef __CACHE_UTILS_HPP__
#define __CACHE_UTILS_HPP__
#include <iostream>
#include <utility>
#include "utils/esp_systemc.hpp"
#include "utils/esp_utils.hpp"
#include "cache_consts.hpp"
#include "cache_types.hpp"
#define CACHE_REPORT_INFO(text) \
cerr << "Info: " << sc_object::basename() << ".\t " << text << endl;
#define CACHE_REPORT_ERROR(text, var) \
cerr << hex << "ERROR: " << sc_object::basename() << ".\t " << text << " : " \
<< var << endl;
#define CACHE_REPORT_TIME(time, text) \
cerr << "Info: " << sc_object::basename() << ".\t @" << time << " : " \
<< text << endl;
#define CACHE_REPORT_VAR(time, text, var) \
cerr << "Info: " << sc_object::basename() << ".\t @" << time << " : " \
<< text << " : " << var << endl;
#define CACHE_REPORT_DEBUG(time, text, var) \
cerr << "Debug: " << sc_object::basename() << ".\t @" << time << " : " \
<< text << " : " << var << endl;
#define __str(s) #s
#define __xstr(s) __str(s)
#define IMP_MEM_NAME(A, B, C, D) \
A ## _ ## B ## _ ## C ## sets_ ## D ## ways
#define IMP_MEM_NAME_STRING(a, b, c, d) \
__xstr(IMP_MEM_NAME(a, b, c, d))
#define EXP_MEM_TYPE(A, B, C, D) \
A ## _ ## B ## _ ## C ## sets_ ## D ## ways_t
#define EXP_MEM_TYPE_STRING(a, b, c, d) \
EXP_MEM_TYPE(a, b, c, d)
#define EXP_MEM_INCLUDE(A, B, C, D) \
A ## _ ## B ## _ ## C ## sets_ ## D ## ways.hpp
#define EXP_MEM_INCLUDE_STRING(a, b, c, d) \
__xstr(EXP_MEM_INCLUDE(a, b, c, d))
inline void write_word(line_t &line, word_t word, word_offset_t w_off, byte_offset_t b_off, hsize_t hsize)
{
uint32_t b_off_tmp = 0;
#ifdef ENDIAN_BIG_ENDIAN
switch (hsize) {
case BYTE:
b_off_tmp = BYTES_PER_WORD - 1 - b_off;
break;
case HALFWORD:
b_off_tmp = BYTES_PER_WORD - BYTES_PER_WORD/2 - b_off;
break;
#if (BYTES_PER_WORD == 4)
default:
b_off_tmp = 0;
break;
#else
case WORD_32:
b_off_tmp = BYTES_PER_WORD - BYTES_PER_WORD/4 - b_off;
break;
default:
b_off_tmp = 0;
break;
#endif
}
#else // ENDIAN_LITTLE_ENDIAN
b_off_tmp = b_off;
#endif
uint32_t w_off_bits = BITS_PER_WORD * w_off;
uint32_t b_off_bits = 8 * b_off_tmp;
uint32_t off_bits = w_off_bits + b_off_bits;
// uint32_t word_range_hi = b_off_bits + size - 1;
// uint32_t line_range_hi = off_bits + size - 1;
// cerr << "line_range_hi: " << line_range_hi << ", word_range_hi: " << word_range_hi << endl;
// cerr << "off_bits: " << off_bits << ", b_off_bits: " << b_off_bits << endl;
if (hsize == BYTE)
line.range(off_bits + 7, off_bits) = word.range(b_off_bits + 7, b_off_bits);
else if (hsize == HALFWORD)
line.range(off_bits + 15, off_bits) = word.range(b_off_bits + 15, b_off_bits);
else if (hsize == WORD_32)
line.range(off_bits + 31, off_bits) = word.range(b_off_bits + 31, b_off_bits);
else if (BYTE_BITS != 2)
line.range(off_bits + 63, off_bits) = word.range(b_off_bits + 63, b_off_bits);
}
inline word_t read_word(line_t line, word_offset_t w_off)
{
word_t word;
word = (sc_uint<BITS_PER_WORD>) line.range(BITS_PER_WORD*w_off+BITS_PER_WORD-1, BITS_PER_WORD*w_off);
return word;
}
inline void rand_wait()
{
int waits = rand() % 5;
for (int i=0; i < waits; i++) wait();
}
inline addr_breakdown_t rand_addr()
{
addr_t addr = (rand() % (1 << ADDR_BITS-1)); // MSB always set to 0
addr.range(OFFSET_BITS - 1, 0) = 0;
addr_breakdown_t addr_br;
addr_br.breakdown(addr);
return addr_br;
}
inline addr_breakdown_llc_t rand_addr_llc()
{
addr_t addr = (rand() % (1 << ADDR_BITS-1)); // MSB always set to 0
addr.range(OFFSET_BITS - 1, 0) = 0;
addr_breakdown_llc_t addr_br;
addr_br.breakdown(addr);
return addr_br;
}
inline word_t rand_word()
{
word_t word;
#if (BITS_PER_WORD == 64)
word = (((word_t) (rand() % (1 << 31))) << 32) + (rand() % (1 << 31));
#else
word = (rand() % (1 << BITS_PER_WORD-1));
#endif
return word;
}
inline line_t line_of_addr(addr_t addr)
{
line_t line;
for (int i = 0; i < WORDS_PER_LINE; ++i) {
#if (BITS_PER_WORD == 64)
addr_t tmp_addr = addr + (i * WORD_OFFSET);
write_word(line, (tmp_addr << 32) + tmp_addr, i, 0, WORD);
#else
write_word(line, addr + (i * WORD_OFFSET), i, 0, WORD);
#endif
}
return line;
}
inline word_t word_of_addr(addr_t addr)
{
word_t word;
#if (BITS_PER_WORD == 64)
word = ((word_t) addr << 32) + addr;
#else
word = addr;
#endif
return word;
}
#endif /* __CACHE_UTILS_HPP__ */
|
#ifndef _my_module1_
#define _my_module1_
#include "systemc.h"
#include "ModuleCompute_old.hpp"
#include "Detecteur1.hpp"
#include "DownSampling.hpp"
#include "BitDecider.hpp"
#include "BitsToBytes.hpp"
#include "CRCCheck.hpp"
#include "FrameProcessing.hpp"
SC_MODULE(my_module1)
{
public:
sc_in < bool > clock;
sc_in < bool > reset;
sc_fifo_in < sc_int <8> > e;
sc_fifo_out< sc_uint<32> > addr;
sc_fifo_out< sc_uint<24> > rgbv;
// sc_fifo_out< bool > detect1;
SC_CTOR(my_module1) :
mod("mod"),
// dbl("dbl"),
det("det"),
dow("dow"),
bit("bit"),
byt("byt"),
crc("crc"),
fra("fra"),
mod2dbl("mod2dbl", 1024),
// dbl2det1("dbl2det1", 32),
// dbl2det2("dbl2det2", 32),
det2dow("det2dow", 32),
dow2bit("dow2bit", 32),
bit2byt("bit2byt", 32),
byt2crc("byt2crc", 32),
crc2fra("crc2fra", 32)
{
// cout<<"Modcompute starting "<<endl;
mod.clock( clock );
mod.reset( reset );
mod.e( e );
mod.s(mod2dbl );
// mod.s2(mod2det2 );
// cout<<"Modcompute ending "<<endl;
// cout<<"Modcompute starting "<<endl;
// dbl.clock( clock );
// dbl.reset( reset );
// dbl.e(mod2dbl);
// dbl.s1(dbl2det1);
// dbl.s2(dbl2det2);
// cout<<"Modcompute ending "<<endl;
det.clock( clock );
det.reset( reset );
det.e(mod2dbl);
// det.e2(dbl2det2);
det.s(det2dow);
// det.detect1(detect1);
dow.clock( clock );
dow.reset( reset );
dow.e(det2dow);
dow.s(dow2bit);
bit.clock( clock );
bit.reset( reset );
bit.e(dow2bit);
bit.s(bit2byt);
byt.clock( clock );
byt.reset( reset );
byt.e(bit2byt);
byt.s(byt2crc);
crc.clock( clock );
crc.reset( reset );
crc.e(byt2crc);
crc.s(crc2fra);
fra.clock( clock );
fra.reset( reset );
fra.e(crc2fra);
fra.addr(addr);
fra.rgbv(rgbv);
}
private:
ModuleCompute mod;
// DOUBLEUR_U dbl;
Detecteur1 det;
DownSampling dow;
BitDecider bit;
BitsToBytes byt;
CRCCheck crc;
FrameProcessing fra;
sc_fifo< sc_uint<8> > mod2dbl;
sc_fifo< sc_uint<8> > dbl2det1;
sc_fifo< sc_uint<8> > dbl2det2;
sc_fifo< sc_uint<8> > det2dow;
sc_fifo< sc_uint<8> > dow2bit;
sc_fifo< sc_uint<1> > bit2byt;
sc_fifo< sc_uint<8> > byt2crc;
sc_fifo< sc_uint<8> > crc2fra;
};
#endif
|
/*
* Adder.h
* SystemC_SimpleAdder
*
* Created by Le Gal on 07/05/07.
* Copyright 2007 __MyCompanyName__. All rights reserved.
*
*/
#include "systemc.h"
#include "constantes.hpp"
#include "../../Tools/BMP.hpp"
#include <string>
SC_MODULE(BMPWriter_fixed)
{
public:
sc_fifo_in< sc_uint<32> > addr;
sc_fifo_in< sc_uint<24> > rgbv;
SC_CTOR(BMPWriter_fixed)
{
SC_THREAD(do_gen);
}
~BMPWriter_fixed( )
{
string fn;
fn = "received_image_fixed";
string filename = fn + ".bmp";
if (fopen(filename.c_str(), "rb")== NULL )
bmp->write( filename.c_str() );
else
{
uint32_t k = 1;
filename = fn+std::to_string(k)+".bmp";
while (fopen(filename.c_str(), "rb")!= NULL )
{
filename = fn+std::to_string(k)+".bmp";
k++;
}
// const char* filename = ("received_image"+std::to_string(k)+".bmp").c_str();
bmp->write(filename.c_str());
}
delete bmp;
}
private:
BMP* bmp;
void do_gen( )
{
bmp = new BMP(640, 480);
uint8_t* ptr = bmp->data.data();
//
// On initilise l'image de sortie dans la couleur rouge pour mieux voir
// les defauts
//
for (uint32_t i = 0; i < (3 * 640 * 480); i += 3)
{
ptr[i + 0] = 0xFF;
ptr[i + 0] = 0x00;
ptr[i + 0] = 0x00;
}
while( true )
{
uint32_t adr = addr.read();
sc_uint<24> rgb = rgbv.read();
uint32_t r = rgb.range(23, 16);
uint32_t g = rgb.range(15, 8);
uint32_t b = rgb.range( 7, 0);
if( (3 * adr) >= (3 * 640 *480) )
{
std::cout << "(WW) Address value is out of image bounds !" << std::endl;
continue;
}
ptr[3 * adr + 0 ] = r;
ptr[3 * adr + 1 ] = g;
ptr[3 * adr + 2 ] = b;
}
}
};
|
#include <iostream>
#include <systemc.h>
int run_mem_access_simulation(unsigned long int stack);
|
#ifndef IPS_VGA_MODEL_HPP
#define IPS_VGA_MODEL_HPP
#include <systemc.h>
#ifdef IPS_AMS
#include <systemc-ams.h>
#endif // IPS_AMS
#define IPS_VGA_ACTIVE true
#define IPS_VGA_INACTIVE false
// Main clock frequency in Hz - 25.175 MHz
#define CLK_FREQ 25175000
/**
* @brief VGA representation class
*
* @tparam BITS - the number of output bits of the digital pixel
* @tparam H_ACTIVE - output horizontal active video pixels
* @tparam H_FP - wait after the display period before the sync
* horizontal pulse
* @tparam H_SYNC_PULSE - assert HSYNC
* @tparam H_BP - wait after the sync horizontal pulse before starting
* the next display period
* @tparam V_ACTIVE - output vertical active video pixels
* @tparam V_FP - wait after the display period before the sync
* vertical pulse
* @tparam V_SYNC_PULSE - assert VSYNC
* @tparam V_BP - wait after the sync vertical pulse before starting
* the next display period
*/
template <
unsigned int BITS = 8,
unsigned int H_ACTIVE = 640,
unsigned int H_FP = 16,
unsigned int H_SYNC_PULSE = 96,
unsigned int H_BP = 48,
unsigned int V_ACTIVE = 480,
unsigned int V_FP = 10,
unsigned int V_SYNC_PULSE = 2,
unsigned int V_BP = 33
>
SC_MODULE(vga)
{
protected:
// Horizontal count
int h_count;
// Vertical count
int v_count;
public:
#ifndef USING_TLM_TB_EN
// Input clock
sc_core::sc_in<bool> clk;
#else
// Compute the clock time in seconds
const double CLK_TIME = 1.0 / static_cast<double>(CLK_FREQ);
// Internal clock
sc_core::sc_clock clk;
#endif // USING_TLM_TB_EN
// Input pixel
sc_core::sc_in<sc_uint<BITS> > red;
sc_core::sc_in<sc_uint<BITS> > green;
sc_core::sc_in<sc_uint<BITS> > blue;
// Counter outputs
sc_core::sc_out<unsigned int> o_h_count;
sc_core::sc_out<unsigned int> o_v_count;
// Output horizontal sync
sc_core::sc_out<bool> o_hsync;
// Output vertical sync
sc_core::sc_out<bool> o_vsync;
#ifndef USING_TLM_TB_EN
// Output pixel
sc_core::sc_out<sc_uint<BITS> > o_red;
sc_core::sc_out<sc_uint<BITS> > o_green;
sc_core::sc_out<sc_uint<BITS> > o_blue;
#else
unsigned char *tmp_img;
bool start;
bool done;
#endif // USING_TLM_TB_EN
SC_CTOR(vga)
: o_hsync("o_hsync"), o_vsync("o_vsync")
#ifdef USING_TLM_TB_EN
, clk("clk", CLK_TIME, sc_core::SC_SEC)
#endif
{
this->h_count = 0;
this->v_count = 0;
SC_METHOD(run);
#ifndef USING_TLM_TB_EN
sensitive << clk.pos();
#else
sensitive << clk;
this->tmp_img = new unsigned char[H_ACTIVE * V_ACTIVE * 3];
this->start = false;
this->done = false;
#endif // USING_TLM_TB_EN
}
/**
* @brief Override method
* Compute the values output of the VGA
*
*/
void run()
{
if (this->clk.read())
{
#ifdef USING_TLM_TB_EN
if (this->start)
{
#endif // USING_TLM_TB_EN
#ifdef IPS_DEBUG_EN
std::cout << "@" << sc_core::sc_time_stamp().to_seconds() * 1e6 << "us" << std::endl;
#endif // IPS_DEBUG_EN
// Increment H counter
this->h_count++;
// HSYNC pulse
if (this->h_count == H_SYNC_PULSE)
{
this->o_hsync.write(IPS_VGA_ACTIVE);
}
else if (this->h_count == (H_SYNC_PULSE + H_BP))
{
this->o_hsync.write(IPS_VGA_ACTIVE);
}
else if (this->h_count == (H_SYNC_PULSE + H_BP + H_ACTIVE))
{
this->o_hsync.write(IPS_VGA_ACTIVE);
}
// End of HSYNC
else if (this->h_count == (H_SYNC_PULSE + H_BP + H_ACTIVE + H_FP))
{
// Restart H counter
this->o_hsync.write(IPS_VGA_INACTIVE);
this->h_count = 0;
// Increment H counter
this->v_count++;
// VSYNC pulse
if (this->v_count == V_SYNC_PULSE)
{
this->o_vsync.write(IPS_VGA_ACTIVE);
}
// End of V-sync pulse
else if (this->v_count == (V_SYNC_PULSE + V_BP))
{
this->o_vsync.write(IPS_VGA_ACTIVE);
}
// V front porch
else if (this->v_count == (V_SYNC_PULSE + V_BP + V_ACTIVE))
{
this->o_vsync.write(IPS_VGA_ACTIVE);
}
// End of VSYNC
else if (this->v_count == (V_SYNC_PULSE + V_BP + V_ACTIVE + V_FP))
{
this->o_vsync.write(IPS_VGA_INACTIVE);
this->v_count = 0;
this->done = true;
this->start = false;
}
}
this->o_v_count.write(this->v_count);
this->o_h_count.write(this->h_count);
#ifndef USING_TLM_TB_EN
this->o_red.write(this->red.read());
this->o_green.write(this->green.read());
this->o_blue.write(this->blue.read());
#else
const int IMG_ROW = this->v_count - (V_SYNC_PULSE + V_BP);
const int IMG_COL = this->h_count - (H_SYNC_PULSE + H_BP);
if (!((IMG_ROW < 0) || (IMG_COL < 0) || (IMG_ROW >= V_ACTIVE) || (IMG_COL >= H_ACTIVE)))
{
const unsigned int INDEX = IMG_ROW * (3 * H_ACTIVE) + 3 * IMG_COL;
this->tmp_img[INDEX] = this->red.read();
this->tmp_img[INDEX + 1] = this->green.read();
this->tmp_img[INDEX + 2] = this->blue.read();
}
}
#endif // USING_TLM_TB_EN
}
}
};
#endif // IPS_VGA_MODEL_HPP
|
//-----------------------------------------------------
//Module: Image Unification (PV) Header
//By: Roger Morales Monge
//Description: Programmer's View Model of unification
//process for two images (magnitude)
//-----------------------------------------------------
#ifdef IMG_UNIFICATE_PV_EN
#ifndef IMG_UNIFICATE_HPP
#define IMG_UNIFICATE_HPP
#include <systemc.h>
#include <math.h>
SC_MODULE (img_unification_module) {
//-----------Internal Variables-----------
unsigned char x_pixel, y_pixel;
unsigned char *unificated_pixel;
//-----------Constructor-----------
SC_CTOR(img_unification_module) {
} // End of Constructor
//------------Methods------------
void unificate_pixel(int x_pixel, int y_pixel, unsigned char * unificated_pixel);
void unificate_img(unsigned char *x_img, unsigned char *y_img, unsigned char *unificated_img, int img_size, int channels);
int norm(int a, int b);
};
#endif //IMG_UNIFICATE_HPP
#endif //IMG_UNIFICATE_PV_EN
|
/* Copyright 2017 Columbia University, SLD Group */
//
// execute.h - Robert Margelli
// execute stage header file.
//
// Division algorithm for DIV, DIVU, REM, REMU instructions. Division by zero
// and overflow semantics are compliant with the RISC-V specs (page 32).
//
#include <systemc.h>
#include "cynw_flex_channels.h"
#include "defines.hpp"
#include "globals.hpp"
#include "hl5_datatypes.hpp"
#include "syn_directives.hpp"
#ifndef __EXECUTE__H
#define __EXECUTE__H
#define BIT(_N) (1 << _N)
// Signed division quotient and remainder struct.
struct div_res_t{
sc_int<XLEN> quotient;
sc_int<XLEN> remainder;
};
// Unsigned division quotient and remainder struct.
struct u_div_res_t{
sc_uint<XLEN> quotient;
sc_uint<XLEN> remainder;
};
SC_MODULE(execute)
{
// FlexChannel initiators
get_initiator< de_out_t > din;
put_initiator< exe_out_t > dout;
// Forward
sc_out< reg_forward_t > fwd_exe;
// Clock and reset signals
sc_in_clk clk;
sc_in<bool> rst;
// Thread prototype
void execute_th(void);
void perf_th(void);
// Support functions
sc_bv<XLEN> sign_extend_imm_s(sc_bv<12> imm); // Sign extend the S-type immediate field.
sc_bv<XLEN> zero_ext_zimm(sc_bv<ZIMM_SIZE> zimm); // Zero extend the zimm field for CSRRxI instructions.
sc_uint<CSR_IDX_LEN> get_csr_index(sc_bv<CSR_ADDR> csr_addr); // Get csr index given the 12-bit CSR address.
void set_csr_value(sc_uint<CSR_IDX_LEN> csr_index, sc_bv<XLEN> rs1, sc_uint<LOG2_CSR_OP_NUM> operation, sc_bv<2> rw_permission); // Perform requested CSR operation (write/set/clear).
// Divider functions
u_div_res_t udiv_func(sc_uint<XLEN> num, sc_uint<XLEN> den);
div_res_t div_func(sc_int<XLEN> num, sc_int<XLEN> den);
// Constructor
SC_CTOR(execute)
: din("din")
, dout("dout")
, fwd_exe("fwd_exe")
, clk("clk")
, rst("rst")
{
SC_CTHREAD(execute_th, clk.pos());
reset_signal_is(rst, false);
SC_CTHREAD(perf_th, clk.pos());
reset_signal_is(rst, false);
din.clk_rst(clk, rst);
dout.clk_rst(clk, rst);
HLS_FLATTEN_ARRAY(csr);
}
// Member variables
de_out_t input;
exe_out_t output;
sc_uint<XLEN> csr[CSR_NUM]; // Control and status registers.
};
#endif
|
#ifndef _my_module_
#define _my_module_
#include "systemc.h"
#include "ModuleCompute_old.hpp"
#include "Detecteur.hpp"
#include "DownSampling.hpp"
#include "BitDecider.hpp"
#include "BitsToBytes.hpp"
#include "CRCCheck.hpp"
#include "FrameProcessing.hpp"
SC_MODULE(my_module)
{
public:
sc_in < bool > clock;
sc_in < bool > reset;
sc_fifo_in < sc_int <8> > e;
sc_fifo_out< sc_uint<32> > addr;
sc_fifo_out< sc_uint<24> > rgbv;
SC_CTOR(my_module) :
mod("mod"),
// dbl("dbl"),
det("det"),
dow("dow"),
bit("bit"),
byt("byt"),
crc("crc"),
fra("fra"),
mod2dbl("mod2dbl", 1024),
// dbl2det1("dbl2det1", 32),
// dbl2det2("dbl2det2", 32),
det2dow("det2dow", 32),
dow2bit("dow2bit", 32),
bit2byt("bit2byt", 32),
byt2crc("byt2crc", 32),
crc2fra("crc2fra", 32)
{
// cout<<"Modcompute starting "<<endl;
mod.clock( clock );
mod.reset( reset );
mod.e( e );
mod.s(mod2dbl );
// mod.s2(mod2det2 );
// cout<<"Modcompute ending "<<endl;
// cout<<"Modcompute starting "<<endl;
// dbl.clock( clock );
// dbl.reset( reset );
// dbl.e(mod2dbl);
// dbl.s1(dbl2det1);
// dbl.s2(dbl2det2);
// cout<<"Modcompute ending "<<endl;
det.clock( clock );
det.reset( reset );
det.e(mod2dbl);
// det.e2(dbl2det2);
det.s(det2dow);
dow.clock( clock );
dow.reset( reset );
dow.e(det2dow);
dow.s(dow2bit);
bit.clock( clock );
bit.reset( reset );
bit.e(dow2bit);
bit.s(bit2byt);
byt.clock( clock );
byt.reset( reset );
byt.e(bit2byt);
byt.s(byt2crc);
crc.clock( clock );
crc.reset( reset );
crc.e(byt2crc);
crc.s(crc2fra);
fra.clock( clock );
fra.reset( reset );
fra.e(crc2fra);
fra.addr(addr);
fra.rgbv(rgbv);
}
private:
ModuleCompute mod;
// DOUBLEUR_U dbl;
Detecteur det;
DownSampling dow;
BitDecider bit;
BitsToBytes byt;
CRCCheck crc;
FrameProcessing fra;
sc_fifo< sc_uint<8> > mod2dbl;
sc_fifo< sc_uint<8> > dbl2det1;
sc_fifo< sc_uint<8> > dbl2det2;
sc_fifo< sc_uint<8> > det2dow;
sc_fifo< sc_uint<8> > dow2bit;
sc_fifo< sc_uint<1> > bit2byt;
sc_fifo< sc_uint<8> > byt2crc;
sc_fifo< sc_uint<8> > crc2fra;
};
#endif
|
// Copyright (c) 2011-2024 Columbia University, System Level Design Group
// SPDX-License-Identifier: MIT
#ifndef __ESP_SYSTEM_HPP__
#define __ESP_SYSTEM_HPP__
#include "utils/esp_types.hpp"
#include "utils/esp_systemc.hpp"
#include "esp_dma_controller.hpp"
template <
size_t _DMA_WIDTH_,
size_t _MEM_SIZE_
>
class esp_system : public sc_module
{
public:
// Input ports
// Clock signal
sc_in<bool> clk;
// Reset signal
sc_in<bool> rst;
#if 1
// DMA read control
put_get_channel< dma_info_t> dma_read_ctrl;
// DMA write control
put_get_channel< dma_info_t> dma_write_ctrl;
// DMA read channel
put_get_channel< sc_dt::sc_bv<_DMA_WIDTH_> > dma_read_chnl;
// DMA write channel
put_get_channel< sc_dt::sc_bv<_DMA_WIDTH_> > dma_write_chnl;
#else
// DMA read control
cynw_p2p< dma_info_t> dma_read_ctrl;
// DMA write control
cynw_p2p< dma_info_t> dma_write_ctrl;
// DMA read channel
cynw_p2p< sc_dt::sc_bv<32> > dma_read_chnl;
// DMA write channel
cynw_p2p< sc_dt::sc_bv<32> > dma_write_chnl;
#endif
// Internal signals
// Configuration information
sc_signal<conf_info_t> conf_info;
// Accelerator starts
sc_signal<bool> conf_done;
// Accelerator reset
sc_signal<bool> acc_rst;
// Accelerator is done
sc_signal<bool> acc_done;
// Debug port
sc_signal<debug_info_t> debug;
// Shared memory buffer model
sc_dt::sc_bv<_DMA_WIDTH_> *mem;
// DMA controller instace
esp_dma_controller<_DMA_WIDTH_, _MEM_SIZE_> *dmac;
// Constructor
SC_HAS_PROCESS(esp_system);
esp_system(sc_module_name name)
: sc_module(name)
, clk("clk")
, rst("rst")
, dma_read_ctrl("dma_read_ctrl")
, dma_write_ctrl("dma_write_ctrl")
, dma_read_chnl("dma_read_chnl")
, dma_write_chnl("dma_write_chnl")
, conf_info("conf_info")
, conf_done("conf_done")
, acc_rst("acc_rst")
, acc_done("acc_done")
, debug("debug")
, mem(new sc_dt::sc_bv<_DMA_WIDTH_>[_MEM_SIZE_])
, dmac(new esp_dma_controller<_DMA_WIDTH_, _MEM_SIZE_>("dma-controller", mem))
{
SC_CTHREAD(config_proc, clk.pos());
reset_signal_is(rst, false);
// set_stack_size(0x400000);
// Binding
dmac->clk(clk);
dmac->rst(rst);
dmac->dma_read_ctrl(dma_read_ctrl);
dmac->dma_read_chnl(dma_read_chnl);
dmac->dma_write_ctrl(dma_write_ctrl);
dmac->dma_write_chnl(dma_write_chnl);
dmac->acc_done(acc_done);
dmac->acc_rst(acc_rst);
}
// Processes
// Configure accelerator
virtual void config_proc() = 0;
// Load internal memory
virtual void load_memory() = 0;
// Dump internal memory
virtual void dump_memory() = 0;
// Validate results
virtual int validate() = 0;
// Function
// Profiling
inline int clock_cycle(sc_time _time);
};
// Implementation
#include "esp_system.i.hpp"
#endif // __ESP_SYSTEM_HPP__
|
#include <systemc.h>
//here we create a module called hello_world
SC_MODULE(hello_world) {
private int meaning_of_life; // easter egg
//SC_CTOR -- systemC constructor
SC_CTOR(hello_world) {
meaning_of_life=42;
}
void say_hello() {
cout << "Hello Systemc-2.3.1!\n";
}
void open_magic_box() {
cout << meaning_of_life << endl;
}
};
int sc_main(int argc, char* argv[]) {
hello_world hello("HELLO");
hello.say_hello();
hello.open_magic_box();
return(0);
}
|
/*******************************************************************************
* pcnttest.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design
*******************************************************************************
* Description:
* This is the main testbench for the pcnt.ino test.
*******************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************
*/
#include <systemc.h>
#include "pcnttest.h"
#include <string>
#include <vector>
#include "info.h"
/**********************
* Function: trace()
* inputs: trace file
* outputs: none
* return: none
* globals: none
*
* Traces all signals in the design. For a signal to be traced it must be listed
* here. This function should also call tracing in any subblocks, if desired.
*/
void pcnttest::trace(sc_trace_file *tf) {
sc_trace(tf, led, led.name());
sc_trace(tf, rx, rx.name());
sc_trace(tf, tx, tx.name());
sc_trace(tf, pwm0, pwm0.name());
sc_trace(tf, pwm1, pwm1.name());
sc_trace(tf, pwm2, pwm2.name());
sc_trace(tf, pwm3, pwm3.name());
sc_trace(tf, ctrl0, ctrl0.name());
sc_trace(tf, ctrl1, ctrl1.name());
sc_trace(tf, ctrl2, ctrl2.name());
i_esp.trace(tf);
}
/**********************
* Task: serflush():
* inputs: none
* outputs: none
* return: none
* globals: none
*
* Dumps everything comming from the serial interface.
*/
void pcnttest::serflush() {
i_uartclient.dump();
}
/**********************
* Task: drivewave():
* inputs: none
* outputs: none
* return: none
* globals: none
*
* Drives a waveform onto the pwm0 pin.
*/
void pcnttest::drivewave() {
int c;
pwm0.write(false);
pwm1.write(false);
pwm2.write(false);
pwm3.write(false);
while(true) {
ctrl1.write(false);
for(c = 0; c < 20; c = c + 1) {
wait(1, SC_MS);
pwm0.write(true);
wait(300, SC_NS);
pwm1.write(true);
pwm2.write(true);
wait(200, SC_NS);
pwm0.write(false);
wait(300, SC_NS);
pwm1.write(false);
pwm2.write(false);
}
ctrl1.write(true);
for(c = 0; c < 20; c = c + 1) {
wait(1, SC_MS);
pwm0.write(true);
wait(300, SC_NS);
pwm1.write(true);
pwm3.write(true);
wait(200, SC_NS);
pwm0.write(false);
wait(300, SC_NS);
pwm1.write(false);
pwm3.write(false);
}
}
}
/*******************************************************************************
** Testbenches *****************************************************************
*******************************************************************************/
void pcnttest::t0(void) {
SC_REPORT_INFO("TEST", "Running Test T0.");
PRINTF_INFO("TEST", "Waiting for power-up");
ctrl0.write(false);
ctrl2.write(false);
wait(500, SC_MS);
}
void pcnttest::testbench(void) {
/* Now we check the test case and run the correct TB. */
printf("Starting Testbench Test%d @%s\n", tn,
sc_time_stamp().to_string().c_str());
if (tn == 0) t0();
else SC_REPORT_ERROR("TEST", "Test number too large.");
sc_stop();
}
|
//****************************************************************************************
// MIT License
//****************************************************************************************
// Copyright (c) 2012-2020 University of Bremen, Germany.
// Copyright (c) 2015-2020 DFKI GmbH Bremen, Germany.
// Copyright (c) 2020 Johannes Kepler University Linz, Austria.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//****************************************************************************************
#pragma once
#include "frontend/SystemC.hpp"
|
/*
* Adder.h
* SystemC_SimpleAdder
*
* Created by Le Gal on 07/05/07.
* Copyright 2007 __MyCompanyName__. All rights reserved.
*
*/
#ifndef _trames_separ1_
#define _trames_separ1_
#include "systemc.h"
#include <cstdint>
#include "constantes.hpp"
using namespace std;
// #define _DEBUG_SYNCHRO_
SC_MODULE(trames_separ1)
{
public:
sc_in < bool > clock;
sc_in < bool > reset;
sc_fifo_in < sc_uint<8> > e;
sc_fifo_in <bool> detect;
sc_fifo_out< sc_uint<8> > s;
SC_CTOR(trames_separ1)
{
SC_CTHREAD(do_gen, clock.pos());
reset_signal_is(reset,true);
}
private:
void do_gen( )
{
// #ifdef _DEBUG_SYNCHRO_
// uint64_t counter = 0;
// #endif
// sc_uint<8> buffer[32];
//#pragma HLS ARRAY_PARTITION variable=buffer complete dim=0
while( true )
{
const uint8_t data = e.read();
const bool valid = detect.read();
if( valid)
{
const int factor = 2 * 2; // PPM modulation + UpSampling(2)
for(uint16_t i = 0; i < factor * _BITS_HEADER_; i += 1)
{
s.write( e.read() );
detect.read();
}
for(uint16_t i = 0; i < factor * _BITS_PAYLOAD_; i += 1)
{
s.write( e.read() );
detect.read();
}
for(uint16_t i = 0; i < factor * _BITS_CRC_; i += 1)
{
s.write( e.read() );
detect.read();
}
}
}
}
};
#endif
|
/*
* Adder.h
* SystemC_SimpleAdder
*
* Created by Le Gal on 07/05/07.
* Copyright 2007 __MyCompanyName__. All rights reserved.
*
*/
#ifndef _DOUBLEUR_U_
#define _DOUBLEUR_U_
#include "systemc.h"
#include <cstdint>
SC_MODULE(DOUBLEUR_U)
{
public:
sc_in < bool > clock;
sc_in < bool > reset;
sc_fifo_in < sc_uint<8> > e;
sc_fifo_out< sc_uint<8> > s1;
sc_fifo_out< sc_uint<8> > s2;
SC_CTOR(DOUBLEUR_U)
{
SC_CTHREAD(do_gen, clock.pos());
reset_signal_is(reset,true);
}
private:
void do_gen( )
{
while ( true )
{
const uint8_t data = e.read();
s1.write( data );
s2.write( data );
}
}
};
#endif
|
/***************************************************************************\
*
*
* ___ ___ ___ ___
* / /\ / /\ / /\ / /\
* / /:/ / /::\ / /::\ / /::\
* / /:/ / /:/\:\ / /:/\:\ / /:/\:\
* / /:/ / /:/~/:/ / /:/~/::\ / /:/~/:/
* / /::\ /__/:/ /:/___ /__/:/ /:/\:\ /__/:/ /:/
* /__/:/\:\ \ \:\/:::::/ \ \:\/:/__\/ \ \:\/:/
* \__\/ \:\ \ \::/~~~~ \ \::/ \ \::/
* \ \:\ \ \:\ \ \:\ \ \:\
* \ \ \ \ \:\ \ \:\ \ \:\
* \__\/ \__\/ \__\/ \__\/
*
*
*
*
* This file is part of TRAP.
*
* TRAP is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* or see <http://www.gnu.org/licenses/>.
*
*
*
* (c) Luca Fossati, fossati@elet.polimi.it, fossati.l@gmail.com
*
\***************************************************************************/
#ifndef PINTARGET_HPP
#define PINTARGET_HPP
#include <systemc.h>
#include <tlm.h>
#include <tlm_utils/simple_target_socket.h>
#include <boost/lexical_cast.hpp>
#include <string>
#include <trap_utils.hpp>
namespace trap{
template<unsigned int sockSize> class PINTarget: public sc_module{
public:
tlm_utils::simple_target_socket<PINTarget, sockSize> socket;
PINTarget(sc_module_name name) : sc_module(name), socket(("pin_target_" + boost::lexical_cast<std::string>(name)).c_str()){
this->socket.register_b_transport(this, &PINTarget::b_transport);
end_module();
}
void b_transport(tlm::tlm_generic_payload& trans, sc_time& delay){
tlm::tlm_command cmd = trans.get_command();
sc_dt::uint64 adr = trans.get_address();
unsigned char* ptr = trans.get_data_ptr();
unsigned int len = trans.get_data_length();
unsigned char* byt = trans.get_byte_enable_ptr();
unsigned int wid = trans.get_streaming_width();
if(trans.get_command() == tlm::TLM_READ_COMMAND){
THROW_EXCEPTION("Error, the read request is not currently supported by external PINs");
}
else if(cmd == tlm::TLM_WRITE_COMMAND){
this->values[(unsigned int)adr] = *((unsigned int *)ptr);
}
trans.set_response_status(tlm::TLM_OK_RESPONSE);
}
// Method used to read the value of the just assigned PIN
unsigned int readPIN(unsigned int address){
if(this->values.find(address) == this->values.end()){
THROW_EXCEPTION("Address " << std::hex << std::showbase << address << " not yet written by PIN port");
}
return this->values[address];
}
private:
std::map<unsigned int, unsigned int> values;
};
};
#endif
|
/*
* Copyright (C) 2024 Commissariat à l'énergie atomique et aux énergies alternatives (CEA)
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WRAPPERNOC_HPP
#define WRAPPERNOC_HPP
#include "systemc.h"
//#include "ac_tlm_protocol.H"
#include "NoCBasicTypes.hpp"
#include <algorithm>
namespace vpsim
{
//this wrapper updates the id field in incoming ac_tlm_req so that they match the router ID
class C_BasicWrapperMasterNoC: public sc_module, public ac_tlm_transport_if
{
unsigned int ID;
public:
sc_export<ac_tlm_transport_if> MasterIn;
sc_port<ac_tlm_transport_if> MasterOut;
C_BasicWrapperMasterNoC(sc_module_name name, unsigned int _ID);
//ac_tlm_rsp transport(ac_tlm_req const & req);
void b_transport( tlm::tlm_generic_payload& trans, sc_time& delay );
};
class C_WrapperMasterNoCToFifo: public sc_module, public ac_tlm_transport_if
{
unsigned int ID;
//NoC speed parameters
float FrequencyScaling;
//sc_time NoCCycle;
unsigned int LinkSizeInBytes;
unsigned int volatile ParallelAccessCount;
T_MemoryMap* MemMap;
//to find the Target_ID for a given address
T_TargetID GetTargetIDFromAddress(T_MemoryAddress MemoryAddress);
//we use the request address to address the response address
// the response address is null as long as no response has been received,
// i.e it is the response status
std::map<tlm::tlm_generic_payload*,bool> ResponseReceived;
std::map<tlm::tlm_generic_payload*,bool> DEBUG_CurRequests;
public:
sc_in_clk clk;
sc_export<ac_tlm_transport_if> MasterIn;
sc_fifo_out<NoCFlit> FifoOut; //to send flits on the NoC
sc_fifo_in<NoCFlit> FifoIn; //to receive response flits
C_WrapperMasterNoCToFifo(sc_module_name name, unsigned int _ID, unsigned int _LinkSizeInBytes, float _FrequencyScaling, bool NoTiming);
SC_HAS_PROCESS(C_WrapperMasterNoCToFifo);
void SetMemoryMap(T_MemoryMap* _MemMap);
//the transport interface that creates NoCFlit messages and send them to the wrapper Fifo
//then waits for a response handled by the RouteBW thread
//ac_tlm_rsp transport(ac_tlm_req const & req);
void b_transport( tlm::tlm_generic_payload& trans, sc_time& delay );
//thread handling response Flits for requests sent by the transport IF
void RouteBW();
};
class C_WrapperSlaveFifoToNoC: public sc_module
{
unsigned int ID;
//NoC speed parameters
float FrequencyScaling;
//sc_time NoCCycle;
unsigned int LinkSizeInBytes;
public:
sc_in_clk clk;
//std::map<T_PortID, sc_port<ac_tlm_transport_if>*> SlaveOuts;
sc_port<ac_tlm_transport_if> SlaveOut;
sc_fifo_out<NoCFlit> FifoOut; //to send response flits on the NoC
sc_fifo_in<NoCFlit> FifoIn; //to receive request flits on the NoC
//Constructor
C_WrapperSlaveFifoToNoC(sc_module_name name, unsigned int _ID, unsigned int _LinkSizeInBytes, float _FrequencyScaling, bool NoTiming);
SC_HAS_PROCESS(C_WrapperSlaveFifoToNoC);
//binding function that instantiates as many slave ports as required
void bind(sc_export<ac_tlm_transport_if> & SlavePort);
//The slave wrapper thread that deals with input NoCFlit to send a TLM request to slave
//and re-emmit Backward NoCFlit response
void RouteFW();
};
};//namespace vpsim
#endif
|
/* Copyright 2018 Tymoteusz Blazejczyk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LOGIC_TRACE_HPP
#define LOGIC_TRACE_HPP
#include "trace_systemc.hpp"
#include "trace_verilated.hpp"
#include <cstddef>
#include <limits>
#include <type_traits>
namespace logic {
template<typename T, typename enable = void>
class trace final : public trace_systemc {
public:
explicit trace(T& module, const std::string& filename = {},
std::size_t level = std::numeric_limits<std::size_t>::max()) :
trace_systemc{module, filename, level}
{ }
trace(trace&&) = delete;
trace(const trace&) = delete;
trace& operator=(trace&&) = delete;
trace& operator=(const trace&) = delete;
~trace() override = default;
};
template<typename T>
class trace<T, typename std::enable_if<has_verilated_vcd_trace_method<T>::value
>::type> final : public trace_verilated {
public:
explicit trace(T& module, const std::string& filename = {},
std::size_t level = std::numeric_limits<std::size_t>::max()) :
trace_verilated{module, filename, level}
{ }
trace(trace&&) = delete;
trace(const trace&) = delete;
trace& operator=(trace&&) = delete;
trace& operator=(const trace&) = delete;
~trace() override = default;
};
} /* namespace logic */
#endif /* LOGIC_TRACE_HPP */
|
/* Copyright 2017 Columbia University, SLD Group */
//
// hl5_datatypes.h - Robert Margelli
// Definition of custom data structs for storing and exchanging
// data among pipeline stages.
// Besides struct fields, all required operators for using them on Flex Channels are defined.
// Additionally, although not currently useful (but it may be in future works) operators for
// cynware metaports are defined.
//
#ifndef HL5_DATATYPES_H
#define HL5_DATATYPES_H
#include "systemc.h"
#include "defines.hpp"
#include "globals.hpp"
// Fetch
// ------------ fe_in_t
#ifndef fe_in_t_SC_WRAPPER_TYPE
#define fe_in_t_SC_WRAPPER_TYPE 1
struct fe_in_t
{
//
// Member declarations.
//
sc_bv< 1 > jump;
sc_bv< 1 > branch;
sc_bv< PC_LEN > jump_address;
sc_bv< PC_LEN > branch_address;
//
// Default constructor.
//
fe_in_t()
{
jump = "0";
branch = "0";
jump_address = (sc_bv< PC_LEN >)0;
branch_address = (sc_bv< PC_LEN >)0;
}
//
// Copy constructor.
//
fe_in_t( const fe_in_t& other )
{
jump = other.jump;
branch = other.branch;
jump_address = other.jump_address;
branch_address = other.branch_address;
}
//
// Comparison operator.
//
inline bool operator == ( const fe_in_t& other )
{
if ( !(jump == other.jump) )
return false;
if ( !(branch == other.branch) )
return false;
if ( !(jump_address == other.jump_address) )
return false;
if ( !(branch_address == other.branch_address) )
return false;
return true;
}
//
// Assignment operator from fe_in_t.
//
inline fe_in_t& operator = ( const fe_in_t& other )
{
jump = other.jump;
branch = other.branch;
jump_address = other.jump_address;
branch_address = other.branch_address;
return *this;
}
};
//
// sc_trace function.
//
inline void sc_trace( sc_trace_file* tf, const fe_in_t& object, const std::string& in_name )
{
if (tf)
{
tf->trace( object.jump, in_name + std::string(".jump"));
tf->trace( object.branch, in_name + std::string(".branch"));
tf->trace( object.jump_address, in_name + std::string(".jump_address"));
tf->trace( object.branch_address, in_name + std::string(".branch_address"));
}
}
//
// stream operator.
//
inline ostream & operator << ( ostream & os, const fe_in_t& object )
{
#ifndef STRATUS_HLS
os << "(";
os << object.jump;
os << "," << object.branch;
os << "," << object.jump_address;
os << "," << object.branch_address;
os << ")";
#endif
return os;
}
#endif
// ------------ END fe_in_t
// Decode
// ------------ de_out_t
#ifndef de_out_t_SC_WRAPPER_TYPE
#define de_out_t_SC_WRAPPER_TYPE 1
struct de_out_t
{
//
// Member declarations.
//
sc_bv< 1 > regwrite;
sc_bv< 1 > memtoreg;
sc_bv< 3 > ld;
sc_bv< 2 > st;
sc_bv< ALUOP_SIZE > alu_op;
sc_bv< ALUSRC_SIZE > alu_src;
sc_bv< XLEN > rs1;
sc_bv< XLEN > rs2;
sc_bv< REG_ADDR > dest_reg;
sc_bv< PC_LEN > pc;
sc_bv< XLEN-12 > imm_u;
sc_uint< TAG_WIDTH > tag;
//
// Default constructor.
//
de_out_t()
{
regwrite = "0";
memtoreg = "0";
ld = NO_LOAD;
st = NO_STORE;
alu_op = (sc_bv< ALUOP_SIZE >)0;
alu_src = (sc_bv< ALUSRC_SIZE >)0;
rs1 = (sc_bv< XLEN >)0;
rs2 = (sc_bv< XLEN >)0;
dest_reg = (sc_bv< REG_ADDR >)0;
pc = (sc_bv< PC_LEN >)0;
imm_u = (sc_bv< XLEN-12 >)0;
tag = (sc_uint< TAG_WIDTH >)0;
}
//
// Copy constructor.
//
de_out_t( const de_out_t& other )
{
regwrite = other.regwrite;
memtoreg = other.memtoreg;
ld = other.ld;
st = other.st;
alu_op = other.alu_op;
alu_src = other.alu_src;
rs1 = other.rs1;
rs2 = other.rs2;
dest_reg = other.dest_reg;
pc = other.pc;
imm_u = other.imm_u;
tag = other.tag;
}
//
// Comparison operator.
//
inline bool operator == ( const de_out_t& other )
{
if ( !(regwrite == other.regwrite) )
return false;
if ( !(memtoreg == other.memtoreg) )
return false;
if ( !(ld == other.ld) )
return false;
if ( !(st == other.st) )
return false;
if ( !(alu_op == other.alu_op) )
return false;
if ( !(alu_src == other.alu_src) )
return false;
if ( !(rs1 == other.rs1) )
return false;
if ( !(rs2 == other.rs2) )
return false;
if ( !(dest_reg == other.dest_reg) )
return false;
if ( !(pc == other.pc) )
return false;
if ( !(imm_u == other.imm_u) )
return false;
if ( !(tag == other.tag) )
return false;
return true;
}
//
// Assignment operator from de_out_t.
//
inline de_out_t& operator = ( const de_out_t& other )
{
regwrite = other.regwrite;
memtoreg = other.memtoreg;
ld = other.ld;
st = other.st;
alu_op = other.alu_op;
alu_src = other.alu_src;
rs1 = other.rs1;
rs2 = other.rs2;
dest_reg = other.dest_reg;
pc = other.pc;
imm_u = other.imm_u;
tag = other.tag;
return *this;
}
};
//
// sc_trace function.
//
inline void sc_trace( sc_trace_file* tf, const de_out_t& object, const std::string& in_name )
{
if (tf)
{
tf->trace( object.regwrite, in_name + std::string(".regwrite"));
tf->trace( object.memtoreg, in_name + std::string(".memtoreg"));
tf->trace( object.ld, in_name + std::string(".ld"));
tf->trace( object.st, in_name + std::string(".st"));
tf->trace( object.alu_op, in_name + std::string(".alu_op"));
tf->trace( object.alu_src, in_name + std::string(".alu_src"));
tf->trace( object.rs1, in_name + std::string(".rs1"));
tf->trace( object.rs2, in_name + std::string(".rs2"));
tf->trace( object.dest_reg, in_name + std::string(".dest_reg"));
tf->trace( object.pc, in_name + std::string(".pc"));
tf->trace( object.imm_u, in_name + std::string(".imm_u"));
tf->trace( object.tag, in_name + std::string(".tag"));
}
}
//
// stream operator.
//
inline ostream & operator << ( ostream & os, const de_out_t& object )
{
#ifndef STRATUS_HLS
os << "(";
os << object.regwrite;
os << "," << object.memtoreg;
os << "," << object.ld;
os << "," << object.st;
os << "," << object.alu_op;
os << "," << object.alu_src;
os << "," << object.rs1;
os << "," << object.rs2;
os << "," << object.dest_reg;
os << "," << object.pc;
os << "," << object.imm_u;
os << "," << object.tag;
os << ")";
#endif
return os;
}
#endif
// ------------ END de_out_t
// Execute
// ------------ exe_out_t
#ifndef exe_out_t_SC_WRAPPER_TYPE
#define exe_out_t_SC_WRAPPER_TYPE 1
struct exe_out_t // TODO: fix all sizes
{
//
// Member declarations.
//
sc_bv< 3 > ld;
sc_bv< 2 > st;
sc_bv< 1 > memtoreg;
sc_bv< 1 > regwrite;
sc_bv< XLEN > alu_res;
sc_bv< DATA_SIZE > mem_datain;
sc_bv< REG_ADDR > dest_reg;
sc_uint< TAG_WIDTH > tag;
//
// Default constructor.
//
exe_out_t()
{
ld = NO_LOAD;
st = NO_STORE;
memtoreg = "0";
regwrite = "0";
alu_res = (sc_bv< XLEN >)0;
mem_datain = (sc_bv< DATA_SIZE >)0;
dest_reg = (sc_bv< REG_ADDR >)0;
tag = (sc_uint< TAG_WIDTH >)0;
}
//
// Copy constructor.
//
exe_out_t( const exe_out_t& other )
{
ld = other.ld;
st = other.st;
memtoreg = other.memtoreg;
regwrite = other.regwrite;
alu_res = other.alu_res;
mem_datain = other.mem_datain;
dest_reg = other.dest_reg;
tag = other.tag;
}
//
// Comparison operator.
//
inline bool operator == ( const exe_out_t& other )
{
if ( !(ld == other.ld) )
return false;
if ( !(st == other.st) )
return false;
if ( !(memtoreg == other.memtoreg) )
return false;
if ( !(regwrite == other.regwrite) )
return false;
if ( !(alu_res == other.alu_res) )
return false;
if ( !(mem_datain == other.mem_datain) )
return false;
if ( !(dest_reg == other.dest_reg) )
return false;
if ( !(tag == other.tag) )
return false;
return true;
}
//
// Assignment operator from exe_out_t.
//
inline exe_out_t& operator = ( const exe_out_t& other )
{
ld = other.ld;
st = other.st;
memtoreg = other.memtoreg;
regwrite = other.regwrite;
alu_res = other.alu_res;
mem_datain = other.mem_datain;
dest_reg = other.dest_reg;
tag = other.tag;
return *this;
}
};
//
// sc_trace function.
//
inline void sc_trace( sc_trace_file* tf, const exe_out_t& object, const std::string& in_name )
{
if (tf)
{
tf->trace( object.ld, in_name + std::string(".ld"));
tf->trace( object.st, in_name + std::string(".st"));
tf->trace( object.memtoreg, in_name + std::string(".memtoreg"));
tf->trace( object.regwrite, in_name + std::string(".regwrite"));
tf->trace( object.alu_res, in_name + std::string(".alu_res"));
tf->trace( object.mem_datain, in_name + std::string(".mem_datain"));
tf->trace( object.dest_reg, in_name + std::string(".dest_reg"));
tf->trace( object.tag, in_name + std::string(".tag"));
}
}
//
// stream operator.
//
inline ostream & operator << ( ostream & os, const exe_out_t& object )
{
#ifndef STRATUS_HLS
os << "(";
os << object.ld;
os << "," << object.st;
os << "," << object.memtoreg;
os << "," << object.regwrite;
os << "," << object.alu_res;
os << "," << object.mem_datain;
os << "," << object.dest_reg;
os << "," << object.tag;
os << ")";
#endif
return os;
}
#endif
// ------------ END exe_out_t
// Memory
// ------------ mem_out_t
#ifndef mem_out_t_SC_WRAPPER_TYPE
#define mem_out_t_SC_WRAPPER_TYPE 1
struct mem_out_t
{
//
// Member declarations.
//
sc_bv< 1 > regwrite;
sc_bv< REG_ADDR > regfile_address;
sc_bv< XLEN > regfile_data;
sc_uint< TAG_WIDTH > tag;
//
// Default constructor.
//
mem_out_t()
{
regwrite = "0";
regfile_data = (sc_bv< XLEN >)0;
regfile_address = (sc_bv< REG_ADDR >)0;
tag = (sc_uint< TAG_WIDTH >)0;
}
//
// Copy constructor.
//
mem_out_t( const mem_out_t& other )
{
regwrite = other.regwrite;
regfile_data = other.regfile_data;
regfile_address = other.regfile_address;
tag = other.tag;
}
//
// Comparison operator.
//
inline bool operator == ( const mem_out_t& other )
{
if ( !(regwrite == other.regwrite) )
return false;
if ( !(regfile_data == other.regfile_data) )
return false;
if ( !(regfile_address == other.regfile_address) )
return false;
if ( !(tag == other.tag) )
return false;
return true;
}
//
// Assignment operator from mem_out_t.
//
inline mem_out_t& operator = ( const mem_out_t& other )
{
regwrite = other.regwrite;
regfile_data = other.regfile_data;
regfile_address = other.regfile_address;
tag = other.tag;
return *this;
}
};
//
// sc_trace function.
//
inline void sc_trace( sc_trace_file* tf, const mem_out_t& object, const std::string& in_name )
{
if (tf)
{
tf->trace( object.regwrite, in_name + std::string(".regwrite"));
tf->trace( object.regfile_data, in_name + std::string(".regfile_data"));
tf->trace( object.regfile_address, in_name + std::string(".regfile_address"));
tf->trace( object.tag, in_name + std::string(".tag"));
}
}
//
// stream operator.
//
inline ostream & operator << ( ostream & os, const mem_out_t& object )
{
#ifndef STRATUS_HLS
os << "(";
os << object.regwrite;
os << "," << object.regfile_data;
os << "," << object.regfile_address;
os << "," << object.tag;
os << ")";
#endif
return os;
}
#endif
// ------------ mem_out_t
// Forward
// ------------ reg_forward_t
#ifndef reg_forward_t_SC_WRAPPER_TYPE
#define reg_forward_t_SC_WRAPPER_TYPE 1
struct reg_forward_t
{
//
// Member declarations.
//
sc_bv< XLEN > regfile_data;
bool ldst;
sc_uint< TAG_WIDTH > tag;
//
// Default constructor.
//
reg_forward_t()
{
regfile_data = (sc_bv< XLEN >)0;
ldst = false;
tag = (sc_uint< TAG_WIDTH >)0;
}
//
// Copy constructor.
//
reg_forward_t( const reg_forward_t& other )
{
regfile_data = other.regfile_data;
ldst = other.ldst;
tag = other.tag;
}
//
// Comparison operator.
//
inline bool operator == ( const reg_forward_t& other )
{
if ( !(regfile_data == other.regfile_data) )
return false;
if ( !(ldst == other.ldst) )
return false;
if ( !(tag == other.tag) )
return false;
return true;
}
//
// Assignment operator from reg_forward_t.
//
inline reg_forward_t& operator = ( const reg_forward_t& other )
{
regfile_data = other.regfile_data;
ldst = other.ldst;
tag = other.tag;
return *this;
}
};
//
// sc_trace function.
//
inline void sc_trace( sc_trace_file* tf, const reg_forward_t& object, const std::string& in_name )
{
if (tf)
{
tf->trace( object.regfile_data, in_name + std::string(".regfile_data"));
tf->trace( object.ldst, in_name + std::string(".ldst"));
tf->trace( object.tag, in_name + std::string(".tag"));
}
}
//
// stream operator.
//
inline ostream & operator << ( ostream & os, const reg_forward_t& object )
{
#ifndef STRATUS_HLS
os << "(";
os << std::hex << object.regfile_data.to_uint() << std::dec;
if (object.ldst)
os << "," << " mem";
os << "," << object.tag;
os << ")";
#endif
return os;
}
#endif
// ------------ reg_forward_t
#endif // ------------ hl5_datatypes.h include guard
|
/***************************************************************************\
*
*
* ___ ___ ___ ___
* / /\ / /\ / /\ / /\
* / /:/ / /::\ / /::\ / /::\
* / /:/ / /:/\:\ / /:/\:\ / /:/\:\
* / /:/ / /:/~/:/ / /:/~/::\ / /:/~/:/
* / /::\ /__/:/ /:/___ /__/:/ /:/\:\ /__/:/ /:/
* /__/:/\:\ \ \:\/:::::/ \ \:\/:/__\/ \ \:\/:/
* \__\/ \:\ \ \::/~~~~ \ \::/ \ \::/
* \ \:\ \ \:\ \ \:\ \ \:\
* \ \ \ \ \:\ \ \:\ \ \:\
* \__\/ \__\/ \__\/ \__\/
*
*
*
*
* This file is part of TRAP.
*
* TRAP is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* or see <http://www.gnu.org/licenses/>.
*
*
*
* (c) Luca Fossati, fossati@elet.polimi.it, fossati.l@gmail.com
*
\***************************************************************************/
/**
* This file contains the methods necessary to communicate with GDB in
* order to debug software running on simulators. Source code takes inspiration
* from the linux kernel (sparc-stub.c) and from ac_gdb.H in the ArchC sources
* In order to debug the remote protocol (as a help in the development of this
* stub, issue the "set debug remote 1" command in GDB)
* "set remotelogfile file" logs all the remote communication on the specified file
*/
//// **** TODO: it seeems that watchpoints are completely ignored ... :-(
//// **** TODO: sometimes segmentation fault when GDB is closed while the program is
//still running; it seems there is a race condition with the GDB thread...
#ifndef GDBSTUB_HPP
#define GDBSTUB_HPP
#include <csignal>
#ifndef SIGTRAP
#define SIGTRAP 5
#endif
#ifndef SIGQUIT
#define SIGQUIT 3
#endif
#include <systemc.h>
#include <vector>
#include "trap_utils.hpp"
#include "ABIIf.hpp"
#include "ToolsIf.hpp"
#include "instructionBase.hpp"
#include "BreakpointManager.hpp"
#include "WatchpointManager.hpp"
#include "GDBConnectionManager.hpp"
#include <boost/thread/thread.hpp>
#include <boost/thread/xtime.hpp>
#include <boost/thread/condition.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/circular_buffer.hpp>
namespace trap{
template<class issueWidth> class GDBStub : public ToolsIf<issueWidth>, public MemoryToolsIf<issueWidth>, public sc_module{
public:
bool simulationPaused;
private:
enum stopType {BREAK_stop=0, WATCH_stop, STEP_stop, SEG_stop, TIMEOUT_stop, PAUSED_stop, UNK_stop};
///Thread used to send and receive responses with the GDB debugger
struct GDBThread{
GDBStub<issueWidth> &gdbStub;
GDBThread(GDBStub<issueWidth> &gdbStub) : gdbStub(gdbStub){}
void operator()(){
while(!gdbStub.isKilled){
if(gdbStub.connManager.checkInterrupt()){
gdbStub.step = 2;
}
else{
//An Error happened: First of all I have to perform some cleanup
if(!gdbStub.isKilled){
boost::mutex::scoped_lock lk(gdbStub.cleanupMutex);
gdbStub.breakManager.clearAllBreaks();
gdbStub.watchManager.clearAllWatchs();
gdbStub.step = 0;
gdbStub.isConnected = false;
}
break;
}
}
}
};
///Manages connection among the GDB target stub (this class) and
///the GDB debugger
GDBConnectionManager connManager;
///Interface for communication with the internal processor's structure
ABIIf<issueWidth> &processorInstance;
///Handles the breakpoints which have been set in the system
BreakpointManager<issueWidth> breakManager;
///Handles the watchpoints which have been set in the system
WatchpointManager<issueWidth> watchManager;
///Determines whether the processor has to halt as a consequence of a
///step command
unsigned int step;
///Keeps track of the last breakpoint encountered by this processor
Breakpoint<issueWidth> * breakReached;
///Keeps track of the last watchpoint encountered by this processor
Watchpoint<issueWidth> * watchReached;
///Specifies whether the breakpoints are enabled or not
bool breakEnabled;
///Specifies whether the watchpoints are enabled or not
bool watchEnabled;
///Specifies whether GDB server side killed the simulation
bool isKilled;
///In case we decided to run the simulation only for a limited ammount of time
///this variable contains that time
double timeToGo;
///In case we decided to jump onwards or backwards for a specified ammount of time,
///this variable contains that time
double timeToJump;
///In case the simulation is run only for a specified ammount of time, this variable
///contains the simulation time at that start time
double simStartTime;
///Specifies that we have to stop because a timeout was encountered
bool timeout;
///Event used to manage execution for a specified ammount of time
sc_event pauseEvent;
///Condition used to stop processor execution until simulation is restarted
boost::condition gdbPausedEvent;
///Mutex used to access the condition
boost::mutex global_mutex;
///Sepecifies if GDB is connected to this stub or not
bool isConnected;
///Specifies that the first run is being made
bool firstRun;
///Mutex controlling the cleanup of GDB status
boost::mutex cleanupMutex;
/********************************************************************/
///Checks if a breakpoint is present at the current address and
///in case it halts execution
#ifndef NDEBUG
inline void checkBreakpoint(const issueWidth &address){
#else
inline void checkBreakpoint(const issueWidth &address) throw(){
#endif
if(this->breakEnabled && this->breakManager.hasBreakpoint(address)){
this->breakReached = this->breakManager.getBreakPoint(address);
#ifndef NDEBUG
if(this->breakReached == NULL){
THROW_EXCEPTION("I stopped because of a breakpoint, but no breakpoint was found");
}
#endif
this->setStopped(BREAK_stop);
}
}
///If true, the system is in the step mode and, as such, execution
///needs to be stopped
inline bool goingToBreak(const issueWidth &address) const throw(){
return this->breakEnabled && this->breakManager.hasBreakpoint(address);
}
///Checks if execution must be stopped because of a step command
inline void checkStep() throw(){
if(this->step == 1){
this->step++;
}
else if(this->step == 2){
this->step = 0;
if(this->timeout){
this->timeout = false;
this->setStopped(TIMEOUT_stop);
}
else{
this->setStopped(STEP_stop);
}
}
}
///If true, the system is in the step mode and, as such, execution
///needs to be stopped
inline bool goingToStep() const throw(){
return this->step == 2;
}
///Starts the thread which will manage the connection with the
///GDB debugger
void startThread(){
GDBThread thread(*this);
boost::thread th(thread);
}
///This method is called when we need asynchronously halt the
///execution of the processor this instance of the stub is
///connected to; it is usually used when a processor is halted
///and it has to communicated to the other processor that they have
///to halt too; note that this method halts SystemC execution and
///it also starts new threads (one for each processor) which will
///deal with communication with the stub; when a continue or
///step signal is met, then the receving thread is killed. When
///all the threads are killed execution can be resumed (this means
///that all GDBs pressed the resume button)
///This method is also called at the beginning of the simulation by
///the first processor which starts execution
void setStopped(stopType stopReason = UNK_stop){
//saving current simulation time
double curSimTime = sc_time_stamp().to_double();
//Now I have to behave differently depending on whether database support is enabled or not
//if it is enabled I do not stop simulation, while if it is not enabled I have to stop simulation in
//order to be able to inspect the content of the processor - memory - etc...
//Computing the next simulation time instant
if(this->timeToGo > 0){
this->timeToGo -= (curSimTime - this->simStartTime);
if(this->timeToGo < 0)
this->timeToGo = 0;
this->simStartTime = curSimTime;
}
//Disabling break and watch points
this->breakEnabled = false;
this->watchEnabled = false;
this->awakeGDB(stopReason);
//pausing simulation
while(this->waitForRequest())
;
}
///Sends a TRAP message to GDB so that it is awaken
void awakeGDB(stopType stopReason = UNK_stop){
switch(stopReason){
case STEP_stop:{
GDBResponse response;
response.type = GDBResponse::S_rsp;
response.payload = SIGTRAP;
this->connManager.sendResponse(response);
break;}
case BREAK_stop:{
#ifndef NDEBUG
if(this->breakReached == NULL){
THROW_EXCEPTION("I stopped because of a breakpoint, but it is NULL");
}
#endif
GDBResponse response;
response.type = GDBResponse::S_rsp;
response.payload = SIGTRAP;
this->connManager.sendResponse(response);
break;}
case WATCH_stop:{
#ifndef NDEBUG
if(this->watchReached == NULL){
THROW_EXCEPTION("I stopped because of a breakpoint, but it is NULL");
}
#endif
GDBResponse response;
response.type = GDBResponse::T_rsp;
response.payload = SIGTRAP;
std::pair<std::string, unsigned int> info;
info.second = this->watchReached->address;
switch(this->watchReached->type){
case Watchpoint<issueWidth>::WRITE_watch:
info.first = "watch";
break;
case Watchpoint<issueWidth>::READ_watch:
info.first = "rwatch";
break;
case Watchpoint<issueWidth>::ACCESS_watch:
info.first = "awatch";
break;
default:
info.first = "none";
break;
}
response.size = sizeof(issueWidth);
response.info.push_back(info);
this->connManager.sendResponse(response);
break;}
case SEG_stop:{
//An error has occurred during processor execution (illelgal instruction, reading out of memory, ...);
GDBResponse response;
response.type = GDBResponse::S_rsp;
response.payload = SIGILL;
this->connManager.sendResponse(response);
break;}
case TIMEOUT_stop:{
//the simulation time specified has elapsed, so simulation halted
GDBResponse resp;
resp.type = GDBResponse::OUTPUT_rsp;
resp.message = "Specified Simulation time completed - Current simulation time: " + sc_time_stamp().to_string() + " (ps)\n";
this->connManager.sendResponse(resp);
this->connManager.sendInterrupt();
break;}
case PAUSED_stop:{
//the simulation time specified has elapsed, so simulation halted
GDBResponse resp;
resp.type = GDBResponse::OUTPUT_rsp;
resp.message = "Simulation Paused - Current simulation time: " + sc_time_stamp().to_string() + " (ps)\n";
this->connManager.sendResponse(resp);
this->connManager.sendInterrupt();
break;}
default:
this->connManager.sendInterrupt();
break;
}
}
///Signals to the GDB debugger that simulation ended; the error variable specifies
///if the program ended with an error
void signalProgramEnd(bool error = false){
if(!this->isKilled || error){
GDBResponse response;
//Now I just print a message to the GDB console signaling the user that the program is ending
if(error){
//I start anyway by signaling an error
GDBResponse rsp;
rsp.type = GDBResponse::ERROR_rsp;
this->connManager.sendResponse(rsp);
}
response.type = GDBResponse::OUTPUT_rsp;
if(error){
response.message = "\nProgram Ended With an Error\n";
}
else
response.message = "\nProgram Correctly Ended\n";
this->connManager.sendResponse(response);
//Now I really communicate to GDB that the program ended
response.type = GDBResponse::W_rsp;
if(error)
response.payload = SIGABRT;
else{
extern int exitValue;
response.payload = exitValue;
}
this->connManager.sendResponse(response);
}
}
///Waits for an incoming request by the GDB debugger and, once it
///has been received, it routes it to the appropriate handler
///Returns whether we must be listening for other incoming data or not
bool waitForRequest(){
this->simulationPaused = true;
GDBRequest req = connManager.processRequest();
this->simulationPaused = false;
switch(req.type){
case GDBRequest::QUEST_req:
//? request: it asks the target the reason why it halted
return this->reqStopReason();
break;
case GDBRequest::EXCL_req:
// ! request: it asks if extended mode is supported
return this->emptyAction(req);
break;
case GDBRequest::c_req:
//c request: Continue command
return this->cont(req.address);
break;
case GDBRequest::C_req:
//C request: Continue with signal command, currently not supported
return this->emptyAction(req);
break;
case GDBRequest::D_req:
//D request: disconnection from the remote target
return this->detach(req);
break;
case GDBRequest::g_req:
//g request: read general register
return this->readRegisters();
break;
case GDBRequest::G_req:
//G request: write general register
return this->writeRegisters(req);
break;
case GDBRequest::H_req:
//H request: multithreading stuff, not currently supported
return this->emptyAction(req);
break;
case GDBRequest::i_req:
//i request: single clock cycle step; currently it is not supported
//since it requires advancing systemc by a specified ammont of
//time equal to the clock cycle (or one of its multiple) and I still
//have to think how to know the clock cycle of the processor and
//how to awake again all the processors after simulation stopped again
return this->emptyAction(req);
break;
case GDBRequest::I_req:
//i request: signal and single clock cycle step
return this->emptyAction(req);
break;
case GDBRequest::k_req:
//i request: kill application: I simply call the sc_stop method
return this->killApp();
break;
case GDBRequest::m_req:
//m request: read memory
return this->readMemory(req);
break;
case GDBRequest::M_req:
// case GDBRequest::X_req:
//M request: write memory
return this->writeMemory(req);
break;
case GDBRequest::p_req:
//p request: register read
return this->readRegister(req);
break;
case GDBRequest::P_req:
//P request: register write
return this->writeRegister(req);
break;
case GDBRequest::q_req:
//q request: generic query
return this->genericQuery(req);
break;
case GDBRequest::s_req:
//s request: single step
return this->doStep(req.address);
break;
case GDBRequest::S_req:
//S request: single step with signal
return this->emptyAction(req);
break;
case GDBRequest::t_req:
//t request: backward search: currently not supported
return this->emptyAction(req);
break;
case GDBRequest::T_req:
//T request: thread stuff: currently not supported
return this->emptyAction(req);
break;
case GDBRequest::v_req:{
//Note that I support only the vCont packets; in particular, the only
//supported actions are continue and stop
std::size_t foundCont = req.command.find("Cont");
if(foundCont == std::string::npos){
return this->emptyAction(req);
}
if(req.command.find_last_of('?') == (req.command.size() - 1)){
// Query of the supported commands: I support only the
// c, and s commands
return this->vContQuery(req);
}
else{
req.command = req.command.substr(foundCont + 5);
std::vector<std::string> lineElements;
boost::split( lineElements, req.command, boost::is_any_of(";"));
// Actual continue/step command; note that I should have only
// one element in the vCont command (since only one thread is supported)
if(lineElements.size() != 1){
GDBResponse resp;
resp.type = GDBResponse::ERROR_rsp;
this->connManager.sendResponse(resp);
return t
|
rue;
}
// Here I check whether I have to issue a continue or a step command
if(lineElements[0][0] == 'c'){
return this->cont();
}
else if(lineElements[0][0] == 's'){
return this->doStep();
}
else{
GDBResponse resp;
resp.type = GDBResponse::ERROR_rsp;
this->connManager.sendResponse(resp);
return true;
}
}
break;}
case GDBRequest::z_req:
//z request: breakpoint/watch removal
return this->removeBreakWatch(req);
break;
case GDBRequest::Z_req:
//z request: breakpoint/watch addition
return this->addBreakWatch(req);
break;
case GDBRequest::INTR_req:
//received an iterrupt from GDB: I pause simulation and signal GDB that I stopped
return this->recvIntr();
break;
case GDBRequest::ERROR_req:
this->isConnected = false;
this->resumeExecution();
this->breakEnabled = false;
this->watchEnabled = false;
return false;
break;
default:
return this->emptyAction(req);
break;
}
}
///Method used to resume execution after GDB has issued
///the continue or step signal
void resumeExecution(){
//I'm going to restart execution, so I can again re-enable watch and break points
this->breakEnabled = true;
this->watchEnabled = true;
this->simStartTime = sc_time_stamp().to_double();
if(this->timeToGo > 0){
this->pauseEvent.notify(sc_time(this->timeToGo, SC_PS));
}
}
/** Here start all the methods to handle the different GDB requests **/
///It does nothing, it simply sends an empty string back to the
///GDB debugger
bool emptyAction(GDBRequest &req){
GDBResponse resp;
resp.type = GDBResponse::NOT_SUPPORTED_rsp;
this->connManager.sendResponse(resp);
return true;
}
/// Queries the supported vCont commands; only the c and s commands
/// are supported
bool vContQuery(GDBRequest &req){
GDBResponse resp;
resp.type = GDBResponse::CONT_rsp;
resp.data.push_back('c');
resp.data.push_back('s');
this->connManager.sendResponse(resp);
return true;
}
///Asks for the reason why the processor is stopped
bool reqStopReason(){
this->awakeGDB();
return true;
}
///Reads the value of a register;
bool readRegister(GDBRequest &req){
GDBResponse rsp;
rsp.type = GDBResponse::REG_READ_rsp;
try{
if(req.reg < this->processorInstance.nGDBRegs()){
issueWidth regContent = this->processorInstance.readGDBReg(req.reg);
this->valueToBytes(rsp.data, regContent);
}
else{
this->valueToBytes(rsp.data, 0);
}
}
catch(...){
this->valueToBytes(rsp.data, 0);
}
this->connManager.sendResponse(rsp);
return true;
}
///Reads the value of a memory location
bool readMemory(GDBRequest &req){
GDBResponse rsp;
rsp.type = GDBResponse::MEM_READ_rsp;
for(unsigned int i = 0; i < req.length; i++){
try{
unsigned char memContent = this->processorInstance.readCharMem(req.address + i);
this->valueToBytes(rsp.data, memContent);
}
catch(...){
std::cerr << "GDB Stub: error in reading memory at address " << std::hex << std::showbase << req.address + i << std::endl;
this->valueToBytes(rsp.data, 0);
}
}
this->connManager.sendResponse(rsp);
return true;
}
bool cont(unsigned int address = 0){
if(address != 0){
this->processorInstance.setPC(address);
}
//Now, I have to restart SystemC, since the processor
//has to go on; note that actually SystemC restarts only
//after all the gdbs has issued some kind of start command
//(either a continue, a step ...)
this->resumeExecution();
return false;
}
bool detach(GDBRequest &req){
boost::mutex::scoped_lock lk(this->cleanupMutex);
//First of all I have to perform some cleanup
this->breakManager.clearAllBreaks();
this->watchManager.clearAllWatchs();
this->step = 0;
this->isConnected = false;
//Finally I can send a positive response
GDBResponse resp;
resp.type = GDBResponse::OK_rsp;
this->connManager.sendResponse(resp);
this->resumeExecution();
this->breakEnabled = false;
this->watchEnabled = false;
return false;
}
bool readRegisters(){
//I have to read all the general purpose registers and
//send their content back to GDB
GDBResponse resp;
resp.type = GDBResponse::REG_READ_rsp;
for(unsigned int i = 0; i < this->processorInstance.nGDBRegs(); i++){
try{
issueWidth regContent = this->processorInstance.readGDBReg(i);
this->valueToBytes(resp.data, regContent);
}
catch(...){
this->valueToBytes(resp.data, 0);
}
}
this->connManager.sendResponse(resp);
return true;
}
bool writeRegisters(GDBRequest &req){
std::vector<issueWidth> regContent;
this->bytesToValue(req.data, regContent);
typename std::vector<issueWidth>::iterator dataIter, dataEnd;
bool error = false;
unsigned int i = 0;
for(dataIter = regContent.begin(), dataEnd = regContent.end();
dataIter != dataEnd; dataIter++){
try{
this->processorInstance.setGDBReg(*dataIter, i);
}
catch(...){
error = true;
}
i++;
}
GDBResponse resp;
if(i != (unsigned int)this->processorInstance.nGDBRegs() || error)
resp.type = GDBResponse::ERROR_rsp;
else
resp.type = GDBResponse::OK_rsp;
this->connManager.sendResponse(resp);
return true;
}
bool writeMemory(GDBRequest &req){
bool error = false;
unsigned int bytes = 0;
std::vector<unsigned char>::iterator dataIter, dataEnd;
for(dataIter = req.data.begin(), dataEnd = req.data.end(); dataIter != dataEnd; dataIter++){
try{
this->processorInstance.writeCharMem(req.address + bytes, *dataIter);
bytes++;
}
catch(...){
std::cerr << "Error in writing in memory " << std::hex << std::showbase << (unsigned int)*dataIter << " at address " << std::hex << std::showbase << req.address + bytes << std::endl;
error = true;
break;
}
}
GDBResponse resp;
resp.type = GDBResponse::OK_rsp;
if(bytes != (unsigned int)req.length || error){
resp.type = GDBResponse::ERROR_rsp;
}
this->connManager.sendResponse(resp);
return true;
}
bool writeRegister(GDBRequest &req){
GDBResponse rsp;
if(req.reg <= this->processorInstance.nGDBRegs()){
try{
this->processorInstance.setGDBReg(req.value, req.reg);
rsp.type = GDBResponse::OK_rsp;
}
catch(...){
rsp.type = GDBResponse::ERROR_rsp;
}
}
else{
rsp.type = GDBResponse::ERROR_rsp;
}
this->connManager.sendResponse(rsp);
return true;
}
bool killApp(){
std::cerr << std::endl << "Killing the program according to GDB request" << std::endl << std::endl;
this->isKilled = true;
sc_stop();
wait();
return true;
}
bool doStep(unsigned int address = 0){
if(address != 0){
this->processorInstance.setPC(address);
}
this->step = 1;
this->resumeExecution();
return false;
}
bool recvIntr(){
boost::mutex::scoped_lock lk(this->cleanupMutex);
this->breakManager.clearAllBreaks();
this->watchManager.clearAllWatchs();
this->step = 0;
this->isConnected = false;
return true;
}
bool addBreakWatch(GDBRequest &req){
GDBResponse resp;
switch(req.value){
case 0:
case 1:
if(this->breakManager.addBreakpoint(Breakpoint<issueWidth>::HW_break, req.address, req.length))
resp.type = GDBResponse::OK_rsp;
else
resp.type = GDBResponse::ERROR_rsp;
break;
case 2:
if(this->watchManager.addWatchpoint(Watchpoint<issueWidth>::WRITE_watch, req.address, req.length))
resp.type = GDBResponse::OK_rsp;
else
resp.type = GDBResponse::ERROR_rsp;
break;
case 3:
if(this->watchManager.addWatchpoint(Watchpoint<issueWidth>::READ_watch, req.address, req.length))
resp.type = GDBResponse::OK_rsp;
else
resp.type = GDBResponse::ERROR_rsp;
break;
case 4:
if(this->watchManager.addWatchpoint(Watchpoint<issueWidth>::ACCESS_watch, req.address, req.length))
resp.type = GDBResponse::OK_rsp;
else
resp.type = GDBResponse::ERROR_rsp;
break;
default:
resp.type = GDBResponse::NOT_SUPPORTED_rsp;
break;
}
this->connManager.sendResponse(resp);
return true;
}
bool removeBreakWatch(GDBRequest &req){
GDBResponse resp;
if(this->breakManager.removeBreakpoint(req.address) or this->watchManager.removeWatchpoint(req.address, req.length))
resp.type = GDBResponse::OK_rsp;
else
resp.type = GDBResponse::ERROR_rsp;
this->connManager.sendResponse(resp);
return true;
}
//Note that to add additional custom commands you simply have to extend the following chain of
//if clauses
bool genericQuery(GDBRequest &req){
//I have to determine the query packet; in case it is Rcmd I deal with it
GDBResponse resp;
if(req.command != "Rcmd"){
resp.type = GDBResponse::NOT_SUPPORTED_rsp;
}
else{
//lets see which is the custom command being sent
std::string::size_type spacePos = req.extension.find(' ');
std::string custComm;
if(spacePos == std::string::npos)
custComm = req.extension;
else
custComm = req.extension.substr(0, spacePos);
if(custComm == "go"){
//Ok, finally I got the right command: lets see for
//how many nanoseconds I have to execute the continue
this->timeToGo = boost::lexical_cast<double>(req.extension.substr(spacePos + 1))*1e3;
if(this->timeToGo < 0){
resp.type = GDBResponse::OUTPUT_rsp;
resp.message = "Please specify a positive offset";
this->connManager.sendResponse(resp);
resp.type = GDBResponse::NOT_SUPPORTED_rsp;
this->timeToGo = 0;
}
else
resp.type = GDBResponse::OK_rsp;
}
else if(custComm == "go_abs"){
//This command specify to go up to a specified simulation time; the time is specified in nanoseconds
this->timeToGo = boost::lexical_cast<double>(req.extension.substr(spacePos + 1))*1e3 - sc_time_stamp().to_double();
if(this->timeToGo < 0){
resp.type = GDBResponse::OUTPUT_rsp;
resp.message = "Please specify a positive offset";
this->connManager.sendResponse(resp);
resp.type = GDBResponse::NOT_SUPPORTED_rsp;
this->timeToGo = 0;
}
else{
resp.type = GDBResponse::OK_rsp;
}
}
else if(custComm == "status"){
//Returns the current status of the STUB
resp.type = GDBResponse::OUTPUT_rsp;
resp.message = "Current simulation time: " + boost::lexical_cast<std::string>((sc_time_stamp().to_default_time_units())/(sc_time(1, \
SC_US).to_default_time_units())) + " (us)\n";
if(this->timeToGo != 0)
resp.message += "Simulating for : " + boost::lexical_cast<std::string>(this->timeToGo) + " Nanoseconds\n";
this->connManager.sendResponse(resp);
resp.type = GDBResponse::OK_rsp;
}
else if(custComm == "time"){
//This command is simply a query to know the current simulation time
resp.type = GDBResponse::OUTPUT_rsp;
resp.message = "Current simulation time: " + boost::lexical_cast<std::string>((sc_time_stamp().to_default_time_units())/(sc_time(1, \
SC_US).to_default_time_units())) + " (us)\n";
this->connManager.sendResponse(resp);
resp.type = GDBResponse::OK_rsp;
}
else if(custComm == "hist"){
//Now I have to print the last n executed instructions; lets first get such number n
resp.type = GDBResponse::OUTPUT_rsp;
#ifndef ENABLE_HISTORY
resp.message = "\nInstruction History not enabled at compile time: please reconfigure the project with the --enable-history option\n\n";
#else
unsigned int histLen = 0;
try{
histLen = boost::lexical_cast<unsigned int>(req.extension.substr(spacePos + 1));
}
catch(...){
resp.message = "\nPlease specify a correct history length\n\n";
}
if(histLen > 1000){
resp.message = "\nAt maximum 1000 instructions are kept in the history\n\n";
}
// Lets now print the history
boost::circular_buffer<HistoryInstrType> & historyQueue = processorInstance.getInstructionHistory();
std::vector<std::string> histVec;
boost::circular_buffer<HistoryInstrType>::const_reverse_iterator beg, end;
unsigned int histRead = 0;
for(histRead = 0, beg = historyQueue.rbegin(), end = historyQueue.rend(); beg != end && histRead < histLen; beg++, histRead++){
histVec.push_back(beg->toStr());
}
resp.message += "\nAddress\t\tname\t\t\tmnemonic\t\tcycle\n\n";
std::vector<std::string>::const_reverse_iterator histVecBeg, histVecEnd;
unsigned int sentLines = 0;
for(histVecBeg = histVec.rbegin(), histVecEnd = histVec.rend(); histVecBeg != histVecEnd; histVecBeg++){
resp.message += *histVecBeg + "\n";
sentLines++;
if(sentLines == 5){
sentLines = 0;
this->connManager.sendResponse(resp);
resp.message = "";
}
}
#endif
this->connManager.sendResponse(resp);
resp.type = GDBResponse::OK_rsp;
}
else if(custComm == "help"){
//This command is simply a query to know the current simulation time
resp.type = GDBResponse::OUTPUT_rsp;
resp.message = "Help about the custom GDB commands available for TRAP generated simulators:\n";
resp.message += " monitor help: prints the current message\n";
resp.message += " monitor time: returns the current simulation time\n";
resp.message += " monitor status: returns the status of the simulation\n";
this->connManager.sendResponse(resp);
resp.message = " monitor hist n: prints the last n (up to a maximum of 1000) instructions\n";
resp.message += " monitor go n: after the \'continue\' command is given, it simulates for n (ns) starting from the current time\n";
resp.message += " monitor go_abs n: after the \'continue\' command is given, it simulates up to instant n (ns)\n";
this->connManager.sendResponse(resp);
resp.type = GDBResponse::OK_rsp;
}
else{
resp.type = GDBResponse::NOT_SUPPORTED_rsp;
}
}
this->connManager.sendResponse(resp);
return true;
}
///Separates the bytes which form an integer value and puts them
///into an array of bytes
template <class ValueType> void valueToBytes(std::vector<char> &byteHolder, ValueType value, bool ConvertEndian = true){
if(this->processorInstance.matchEndian() || !ConvertEndian){
for(unsigned int i = 0; i < sizeof(ValueType); i++){
byteHolder.push_back((char)((value & (0x0FF << 8*i)) >> 8*i));
}
}
else{
for(int i = sizeof(ValueType) - 1; i >= 0; i--){
byteHolder.push_back((char)((value & (0x0FF << 8*i)) >> 8*i));
}
}
}
///Converts a vector of bytes into a vector of integer values
void bytesToValue(std::vector<unsigned char> &byteHolder, std::vector<issueWidth> &values){
for(unsigned int i = 0; i < byteHolder.size(); i += sizeof(issueWidth)){
issueWidth buf = 0;
for(unsigned int k = 0; k < sizeof(issueWidth); k++){
buf |= (byteHolder[i + k] << 8*k);
}
values.push_back(buf);
}
}
public:
SC_HAS_PROCESS(GDBStub);
GDBStub(ABIIf<issueWidth> &processorInstance) :
sc_module(sc_module_name("debugger")), connManager(processorInstance.matchEndian()), processorInstance(processorInstance),
step(0), breakReached(NULL), breakEnabled(true), watchEnabled(true), isKilled(false), timeout(false), isConnected(false),
timeToGo(0), timeToJump(0), simStartTime(0), firstRun(true), simulationPaused(false){
SC_METHOD(pauseMethod);
sensitive << this->pauseEvent;
dont_initialize();
end_module();
}
///Method used to pause simulation
void pauseMethod(){
this->step = 2;
this->timeout = true;
}
///Overloading of the end_of_simulation method; it can be used to execute methods
///at the end of the simulation
void end_of_simulation(){
if(this->isConnected){
this->isKilled = false;
this->signalProgramEnd();
this->isKilled = true;
}
}
///Starts the connection with the GDB client
void initialize(unsigned int port = 1500){
this->connManager.initialize(port);
this->isConnected = true;
//Now I have to listen for incoming GDB messages; this will
//be done in a new thread.
this->startThread();
}
///Method called at eve
|
ry cycle from the processor's main loop
bool newIssue(const issueWidth &curPC, const InstructionBase *curInstr) throw(){
if(!this->firstRun){
this->checkStep();
this->checkBreakpoint(curPC);
}
else{
this->firstRun = false;
this->breakEnabled = false;
this->watchEnabled = false;
while(this->waitForRequest())
;
}
return false;
}
///The debugger needs the pipeline to be empty only in case it is going to be stopped
///because, for exmple, we hitted a breakpoint or we are in step mode
bool emptyPipeline(const issueWidth &curPC) const throw(){
return !this->firstRun && (this->goingToStep() || this->goingToBreak(curPC));
}
///Method called whenever a particular address is written into memory
#ifndef NDEBUG
inline void notifyAddress(issueWidth address, unsigned int size) throw(){
#else
inline void notifyAddress(issueWidth address, unsigned int size){
#endif
if(this->watchEnabled && this->watchManager.hasWatchpoint(address, size)){
this->watchReached = this->watchManager.getWatchPoint(address, size);
#ifndef NDEBUG
if(this->watchReached == NULL){
THROW_EXCEPTION("I stopped because of a watchpoint, but no watchpoint was found");
}
#endif
this->setStopped(WATCH_stop);
}
}
};
};
#endif
|
//****************************************************************************************
// MIT License
//****************************************************************************************
// Copyright (c) 2012-2020 University of Bremen, Germany.
// Copyright (c) 2015-2020 DFKI GmbH Bremen, Germany.
// Copyright (c) 2020 Johannes Kepler University Linz, Austria.
// Copyright (c) 2022 - 2023 Coseda Technologies GmbH.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//****************************************************************************************
#pragma once
#include "VariableBase.hpp"
#include "../frontend/Operators.hpp"
#include "../frontend/WeightedRange.hpp"
#include "../frontend/Distribution.hpp"
#include "../ir/UserExpression.hpp"
#include "Constraint.hpp"
namespace crave {
/**
* \ingroup newAPI
* \brief Creates a distribution_tag to be used directly in constraints from a single weighted range.
* Convenient function, which calls distribution::create.
*
* \param range a weighted range.
* \return A distribution_tag of a distribution to be used in constraints.
*/
template <typename T>
distribution_tag<T> make_distribution(weighted_range<T> const& range) {
return distribution<T>::create(range);
}
/**
* \ingroup newAPI
* \brief Creates a distribution_tag to be used directly in constraints from the given ranges.
*
* Convenient function, which should be preferred to chaining calls of distribution::create and distribution::operator().
*
* \param range the first range.
* \param args the following ranges.
* \return A distribution_tag of a distribution to be used in constraints.
*/
template <typename T, typename... Args>
distribution_tag<T> make_distribution(weighted_range<T> const& range, Args... args) {
return make_distribution(args...)(range);
}
/**
* constructor
* @param name name of the variable
*/
#define CRV_VARIABLE_COMMON_CONSTRUCTORS(Typename) \
public: \
crv_variable(crv_object_name name = "var") {create_default_cstr ();} \
crv_variable(const crv_variable& other) : crv_variable_base<Typename>(other) {}
/**
* assignment operator
* @param i value for the assignment
*/
#define CRV_VARIABLE_ASSIGNMENT_INTERFACE(Typename) \
public: \
crv_variable<Typename>& operator=(const crv_variable<Typename>& i) { \
this->value = i.value; \
return *this; \
} \
crv_variable<Typename>& operator=(Typename i) { \
this->value = i; \
return *this; \
}
/**
* arithmetic operations
* @param i value for arithmetic operation
*/
#define CRV_VARIABLE_ARITHMETIC_INTERFACE(Typename) \
public: \
crv_variable<Typename>& operator++() { \
++(this->value); \
return *this; \
} \
Typename operator++(int) { \
Typename tmp = this->value; \
++(this->value); \
return tmp; \
} \
crv_variable<Typename>& operator--() { \
--(this->value); \
return *this; \
} \
Typename operator--(int) { \
Typename tmp = this->value; \
--(this->value); \
return tmp; \
} \
crv_variable<Typename>& operator+=(Typename i) { \
this->value += i; \
return *this; \
} \
crv_variable<Typename>& operator-=(Typename i) { \
this->value -= i; \
return *this; \
} \
crv_variable<Typename>& operator*=(Typename i) { \
this->value *= i; \
return *this; \
} \
crv_variable<Typename>& operator/=(Typename i) { \
this->value /= i; \
return *this; \
} \
crv_variable<Typename>& operator%=(Typename i) { \
this->value %= i; \
return *this; \
}
/**
* bitwise operators
* @param i value for bitwise operation
*/
#define CRV_VARIABLE_BITWISE_INTERFACE(Typename) \
public: \
crv_variable<Typename>& operator&=(Typename i) { \
this->value &= i; \
return *this; \
} \
crv_variable<Typename>& operator|=(Typename i) { \
this->value |= i; \
return *this; \
} \
crv_variable<Typename>& operator^=(Typename i) { \
this->value ^= i; \
return *this; \
} \
crv_variable<Typename>& operator<<=(Typename i) { \
this->value <<= i; \
return *this; \
} \
crv_variable<Typename>& operator>>=(Typename i) { \
this->value >>= i; \
return *this; \
}
/**
* boolean operators
* @param i value for bitwise operation
*/
#define CRV_VARIABLE_BOOLEAN_INTERFACE(Typename) \
public: \
crv_variable<Typename>& operator&=(Typename i) { \
this->value &= i; \
return *this; \
} \
crv_variable<Typename>& operator|=(Typename i) { \
this->value |= i; \
return *this; \
} \
crv_variable<Typename>& operator^=(Typename i) { \
this->value ^= i; \
return *this; \
} \
/*!
*\ingroup newAPI
*\brief A randomizable variable of type T in new API.
*
* <p>This class is the type for all randomizable variables of type T.
* Default the following types of C++ are supported:
* <ul>
* <li>bool</li>
* <li>(unsigned) int</li>
* <li>(signed|unsigned) char</li>
* <li>(unsigned) short</li>
* <li>(unsigned) long</li>
* <li>(unsigned) long long</li>
* </ul>
* You can add support for SystemC Datatypes by including experimental/SystemC.hpp.
* This adds support for
* <ul>
* <li>sc_bv<n></li>
* <li>sc_(u)int<n></li>
* </ul>
* It is also possible to randomize enumerations.
* To randomize an enumeration, you must previously declare it with the macro \ref CRAVE_BETTER_ENUM </p><p>
* A crv_variable<T> also supports basic binary and arithmetic operations +=,-=,*=,/=,=,|=,&=,%=,<<=,>>=,^=.
* A very important operator is the operator ().
* This operator can be used to get a WriteReference which is to be used in the definition of constraints.
* For details see crave::crv_constraint</p><p>
* For coverage aspects there is a method named bind() for a crv_variable.
* Bind takes another crv_variable as a parameter.
* If two variables are bound together, they share the same value.
* </p>
*/
class crv_var {
public:
virtual ~crv_var() {}
virtual unsigned getVarID() = 0;
};
template <typename T, typename Enable = void>
class crv_variable {};
/**
* class for randomisation of a variable
*/
template <typename T >
class crv_variable<T, typename std::enable_if<std::is_integral<T>::value>::type> : public crv_var, public crv_variable_base<T> {
CRV_VARIABLE_COMMON_CONSTRUCTORS(T);
CRV_VARIABLE_ASSIGNMENT_INTERFACE(T);
CRV_VARIABLE_ARITHMETIC_INTERFACE(T);
CRV_VARIABLE_BITWISE_INTERFACE(T);
crv_constraint c_var_uniform;
public:
/**
* generate random value
*/
bool randomize() override {
static distribution<T> dist;
this->value = dist.nextValue();
return true;
}
void create_default_cstr () {
c_var_uniform = { dist(this->var, make_distribution(range<T>(std::numeric_limits<T>::min(), std::numeric_limits<T>::max())))};
}
unsigned getVarID() override {
return crv_variable_base<T>::id();
}
};
/**
* class for randomisation of a variable
*/
template <>
class crv_variable<bool> : public crv_var, public crv_variable_base<bool> {
CRV_VARIABLE_COMMON_CONSTRUCTORS(bool);
CRV_VARIABLE_ASSIGNMENT_INTERFACE(bool);
//CRV_VARIABLE_ARITHMETIC_INTERFACE(bool);
CRV_VARIABLE_BOOLEAN_INTERFACE(bool);
crv_constraint c_var_uniform;
public:
/**
* generate random value
*/
bool randomize() override {
static distribution<bool> dist;
this->value = dist.nextValue();
return true;
}
void create_default_cstr () {
c_var_uniform = { dist(this->var, distribution<bool>::create(0.5))};
}
unsigned getVarID() override {
return crv_variable_base<bool>::id();
}
};
template <typename T>
struct bitsize_traits<crv_variable<T>> : public bitsize_traits<T> {};
} // namespace crave
|
#ifndef PROCESSING_ENGINE_HPP
#define PROCESSING_ENGINE_HPP
#include <systemc.h>
#include "verbose.hpp"
SC_MODULE(processing_engine_module)
{
// PORTS
sc_in<bool> clk;
sc_in<bool> reset;
sc_fifo_in<float> from_scheduler_weight;
sc_fifo_in<float> from_scheduler_input;
sc_fifo_in< sc_uint<34> > from_scheduler_instructions;
sc_fifo_out<float> to_scheduler;
// STATES
sc_uint<30> state_length;
sc_uint<4> state_activation_function;
// PROCESS
void process(void);
// UTIL
float sigmoid(float input);
float relu(float input);
float softmax(float input);
SC_CTOR(processing_engine_module)
{
state_length = 0;
state_activation_function = 0;
SC_CTHREAD(process, clk.pos());
reset_signal_is(reset,true);
}
};
#endif
|
/*
* Created on: 21. jun. 2019
* Author: Jonathan Horsted Schougaard
*/
#ifdef HW_COSIM
//#define __GMP_WITHIN_CONFIGURE
#endif
#define SC_INCLUDE_FX
#include <systemc.h>
#include "hwcore/tb/improc/tb_imfilter.h"
unsigned errors = 0;
const char simulation_name[] = "dma tester test";
int sc_main(int argc, char* argv[]) {
cout << "INFO: Elaborating "<< simulation_name << endl;
sc_core::sc_report_handler::set_actions( "/IEEE_Std_1666/deprecated",
sc_core::SC_DO_NOTHING );
sc_report_handler::set_actions( SC_ID_LOGIC_X_TO_BOOL_, SC_LOG);
sc_report_handler::set_actions( SC_ID_VECTOR_CONTAINS_LOGIC_VALUE_, SC_LOG);
sc_report_handler::set_actions( SC_ID_OBJECT_EXISTS_, SC_LOG);
//sc_set_time_resolution(1,SC_PS);
//sc_set_default_time_unit(1,SC_NS);
//ModuleSingle modulesingle("modulesingle_i");
TB_imfilter_top tb_01;
cout << "INFO: Simulating "<< simulation_name << endl;
sc_start();
cout << "INFO: Post-processing "<< simulation_name << endl;
cout << "INFO: Simulation " << simulation_name
<< " " << (errors?"FAILED":"PASSED")
<< " with " << errors << " errors"
<< std::endl;
#ifdef __RTL_SIMULATION__
cout << "HW cosim done" << endl;
#endif
return errors?1:0;
}
|
#pragma once
#include "hwcore/cnn/pe.h"
#include <systemc.h>
#define debug_cout std::cout << "[" << sc_time_stamp().to_string() << "] - " << __FILE__ << " - "
template <int W, int P, int N> SC_MODULE(tb_pe) {
typedef typename hwcore::pipes::SC_DATA_STREAM_T_trait<1 * W>::interface_T interface_T;
typedef typename hwcore::pipes::SC_DATA_STREAM_T_trait<1 * W + 1 * W>::interface_T interface_W_T;
typedef typename hwcore::pipes::SC_DATA_STREAM_T_trait<1 * W>::interface_T interface_out_T;
sc_clock clk;
sc_in<bool> iclk;
sc_signal<bool> reset;
hwcore::cnn::PE<W, P, N> pe;
sc_fifo<interface_T> xin; // in
sc_fifo<interface_W_T> win;
sc_fifo<interface_out_T> dout; // out
sc_fifo<sc_uint<16> > ctrl_acf; // out
SC_CTOR(tb_pe) : clk("clock", sc_time(10, SC_NS)), pe("pe"), xin(1), dout(1), win(1), ctrl_acf(1) {
iclk(clk);
pe.clk(clk);
pe.reset(reset);
pe.Win(win);
pe.Xin(xin);
pe.dout(dout);
pe.ctrl_acf(ctrl_acf);
SC_CTHREAD(waveform, iclk.pos());
SC_CTHREAD(monitor, iclk.pos());
}
int func(int a, int b) {
int tmpSum = (a << 16) + (b << 16);
return tmpSum;
}
void waveform() {
debug_cout << " - [waveform start]" << std::endl;
interface_W_T Wtmp_out;
interface_T Xtmp_out;
interface_T tmp_out;
reset.write(1);
for (int i = 0; i < 5; i++)
wait();
reset.write(0);
int size = 5;
int repeat = 7;
for (int r = 0; r < repeat; r++) {
ctrl_acf.write(0 | (hwcore::hf::ufixed2bv<15, 1>(1.0).to_uint() << 1));
for (int a = 0; a < size; a++) {
for (int b = 0; b < size; b++) {
Xtmp_out.data = func(a, b);
Xtmp_out.setKeep();
Xtmp_out.tlast = (a == size - 1 && b == size - 1 ? 1 : 0);
Wtmp_out.data = ((2 << 16) << 32) | (0 << 16);
Wtmp_out.setKeep();
Wtmp_out.tlast = (a == size - 1 && b == size - 1 ? 1 : 0);
debug_cout << "(waveform)[r]=[" << r << "],[a,b]=[" << a << "," << b << "][data]=[" << func(a, b)
<< "]" << std::endl;
xin.write(Xtmp_out);
win.write(Wtmp_out);
}
}
tmp_out.setEOP();
Wtmp_out.setEOP();
xin.write(tmp_out);
win.write(Wtmp_out);
// dout.write(tmp_out);
debug_cout << "(waveform)[EOP]" << std::endl;
wait();
}
Xtmp_out.data = 2 << 29;
Xtmp_out.setKeep();
Wtmp_out.data = (4 << 16) << 32;
Wtmp_out.setKeep();
ctrl_acf.write(1 | (hwcore::hf::ufixed2bv<15, 1>(1.0).to_uint() << 1)); // use ReLU
for (int i = 0; i < 20; i++) {
Wtmp_out.tlast = (i == 20 - 1 ? 1 : 0);
Xtmp_out.tlast = Wtmp_out.tlast;
xin.write(Xtmp_out);
win.write(Wtmp_out);
}
tmp_out.setEOP();
Wtmp_out.setEOP();
xin.write(tmp_out);
win.write(Wtmp_out);
debug_cout << " - [waveform done]" << std::endl;
while (true) {
wait();
}
}
void monitor() {
debug_cout << " - [waveform monitor]" << std::endl;
sc_int<W> tmp[2];
interface_out_T tmp_in;
int size = 5;
int repeat = 7;
for (int r = 0; r < repeat; r++) {
dout.read(tmp_in);
tmp_in.template getData<sc_int, W, 1>(tmp);
debug_cout << "(monitor)[r]=[" << r << "],[data]=[" << tmp[0].to_int() << "]<=>[expected][" << (200 << 16)
<< "]" << std::endl;
sc_assert((200 << 16) == tmp[0].to_int());
dout.read(tmp_in);
sc_assert(tmp_in.EOP());
debug_cout << "(monitor)[r]=[" << r << "] looking for EOP" << std::endl;
}
dout.read(tmp_in);
sc_assert(!tmp_in.EOP());
for (int i = 0; i < W; i++) {
if (i == W - 1)
sc_assert(tmp_in.data[i] == 0);
else
sc_assert(tmp_in.data[i] == 1);
}
sc_stop();
while (true) {
wait();
}
}
void monitor_vec() {}
};
|
#ifndef IPS_FILTER_AT_MODEL_HPP
#define IPS_FILTER_AT_MODEL_HPP
#ifdef IPS_DEBUG_EN
#include <iostream>
#endif // IPS_DEBUG_ENi
#ifdef IPS_DUMP_EN
#include <sstream>
#endif // IPS_DUMP_EN
#include <systemc.h>
/**
* @brief Filter module.
* It takes care of filtering a image/kernel using a median filter or an
* equivalent convolution like:
* | 1/N^2 ... 1/N^2 | | img(row - N/2, col - N/2) ... img(row + N/2, col + N/2) |
* img(row, col) = | ... ... .... | * | ... ... ... |
* | 1/N^2 ... 1/N^2 | | img(row + N/2, col - N/2) ... img(row + N/2, col + N/2) |
*
* @tparam IN - data type of the inputs
* @tparam OUT - data type of the outputs
* @tparam N - size of the kernel
*/
template <typename IN = sc_uint<8>, typename OUT = sc_uint<8>, uint8_t N = 3>
SC_MODULE(Filter)
{
protected:
//----------------------------Internal Variables----------------------------
#ifdef IPS_DUMP_EN
sc_trace_file* wf;
#endif // IPS_DUMP_EN
OUT* kernel;
// Event to trigger the filter execution
sc_event event;
//-----------------------------Internal Methods-----------------------------
void exec_filter();
void init();
public:
sc_in<IN* > img_window;
sc_out<OUT > result;
/**
* @brief Default constructor for Filter
*/
SC_HAS_PROCESS(Filter);
#ifdef IPS_DUMP_EN
/**
* @brief Construct a new Filter object
*
* @param name - name of the module
* @param wf - waveform file pointer
*/
Filter(sc_core::sc_module_name name, sc_core::sc_trace_file* wf)
: sc_core::sc_module(name), wf(wf)
#else
/**
* @brief Construct a new Filter object
*
* @param name - name of the module
*/
Filter(sc_core::sc_module_name name) : sc_core::sc_module(name)
#endif // IPS_DUMP_EN
{
// Calling this method by default since it is no time consumer
// It is assumed that this kernel is already loaded in the model
// Kernel does not change after synthesis
SC_METHOD(init);
// Thread waiting for the request
SC_THREAD(exec_filter);
}
//---------------------------------Methods---------------------------------
void filter();
};
/**
* @brief Execute the image filtering
*
*/
template <typename IN, typename OUT, uint8_t N>
void Filter<IN, OUT, N>::exec_filter()
{
size_t i;
size_t j;
OUT result_tmp;
while (true)
{
// Wait to peform the convolution
wait(this->event);
// Default value for the result depending on the output datatype
result_tmp = static_cast<OUT >(0);
// Getting the image window to filter
IN* img_window_tmp = this->img_window.read();
// Perform the convolution
for (i = 0; i < N; ++i)
for (j = 0; j < N; ++j)
result_tmp += this->kernel[i * N + j] * static_cast<OUT >(img_window_tmp[i * N + j]);
this->result.write(result_tmp);
}
}
/**
* @brief Filtering image
*
* @param img_window - image window to filter
* @param result - resultant pixel
*/
template <typename IN, typename OUT, uint8_t N>
void Filter<IN, OUT, N>::filter()
{
this->event.notify(DELAY_TIME, SC_NS);
}
/**
* @brief Initializes a kernel of N x N with default value of 1 / (N^2)
*
*/
template <typename IN, typename OUT, uint8_t N>
void Filter<IN, OUT, N>::init()
{
// Init a kernel of N x N with default value of 1 / (N * N)
this->kernel = new OUT[N * N];
std::fill_n(this->kernel, N * N, static_cast<OUT >(1) / static_cast<OUT >(N * N));
#ifdef IPS_DEBUG_EN
// Print the initialized kernel
SC_REPORT_INFO(this->name(), "init result");
size_t i, j;
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
std::cout << "[" << this->kernel[i * N + j] << "]";
#ifdef IPS_DUMP_EN
// Adding the signals to the waveform
std::ostringstream var_name;
var_name << "kernel_" << i << "_" << j;
sc_trace(this->wf, this->kernel[i * N + j], var_name.str());
#endif // IPS_DUMP_EN
}
std::cout << std::endl;
}
#else
#ifdef IPS_DUMP_EN
size_t i, j;
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
// Adding the signals to the waveform
std::ostringstream var_name;
var_name << "kernel_" << i << "_" << j;
sc_trace(this->wf, this->kernel[i * N + j], var_name.str());
}
}
#endif // IPS_DUMP_EN
#endif // IPS_DEBUG_EN
}
#endif // IPS_FILTER_AT_MODEL_HPP
|
// Copyright (c) 2011-2024 Columbia University, System Level Design Group
// SPDX-License-Identifier: MIT
#ifndef __ESP_UTILS_HPP__
#define __ESP_UTILS_HPP__
#include "esp_data.hpp"
#include "esp_systemc.hpp"
#define ESP_REPORT_INFO(...) \
fprintf(stderr, "Info: %s: ", sc_object::basename()); \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\n\n");
#define ESP_REPORT_ERROR(...) \
fprintf(stderr, "Error: %s: ", sc_object::basename()); \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\n\n");
#define ESP_REPORT_TIME(time, ...) \
{ std::stringstream _ss; _ss << time; \
std::string _s = _ss.str(); const char * _time = _s.c_str(); \
fprintf(stderr, "Info: %s: ", sc_object::basename()); \
fprintf(stderr, "@%s ", _time); \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\n\n"); } \
template <unsigned int n>
struct slog_2 { enum { value = 1 + slog_2<n/2>::value }; };
template <> struct slog_2<1> { enum { value = 0 }; };
// Helper macros
#define __str(s) #s
#define __xstr(s) __str(s)
#define MYPPCAT_4(A,B,C,D) A ## _DMA ## B ## _CHK ## C ## _PP ## D
#define MYPPCAT_41(A,B,C,D) A ## _DMA ## B ## _CHK ## C ## _PP ## D ## _t
#define MYPPCAT_42(A,B,C,D) A ## _DMA ## B ## _CHK ## C ## _PP ## D.hpp
// Macros for users
#define GENERATE_PLM_TYPE(mem, dma, chk, pp) \
MYPPCAT_41(mem, dma, chk, pp)
#define GENERATE_PLM_NAME(mem, dma, chk, pp) \
__xstr(MYPPCAT_4(mem, dma, chk, pp))
#define GENERATE_PLM_HDR(mem, dma, chk, pp) \
__xstr(MYPPCAT_42(mem, dma, chk, pp))
#ifdef ESP_DEBUG
// Print info only if debug
#define ESP_REPORT_DEBUG(...) \
fprintf(stderr, "Debug: %s: ", sc_object::basename()); \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\n\n");
#else
#define ESP_REPORT_DEBUG(...)
#endif
#endif /* __ESP_UTILS_HPP__ */
|
#include <systemc.h>
/**
* @brief jpg_output module. Federico Cruz
* It takes the image and compresses it into jpeg format
* It is done in 4 parts:
* 1. Divides the image in 8x8 pixel blocks; for 8-bit grayscale images the a level shift is done by substracting 128 from each pixel.
* 2. Discrete Cosine Transform (DCT) of the 8x8 image.
* 3. Each transformed 8x8 block is divided by a quantization value for each block entry.
* 4. Each quantized 8x8 block is reordered by a Zig-Zag sequence into a array of size 64.
* *5. Entropy compression by variable length encoding (huffman). Used to maximize compression. Not implemented here.
*/
#define PI 3.1415926535897932384626433832795
#define BLOCK_ROWS 8
#define BLOCK_COLS 8
SC_MODULE (jpg_output) {
//-----------Internal variables-------------------
//const int Block_rows = 8;
//const int Block_cols = 8;
double* image;
int image_rows = 480;
int image_cols = 640;
signed char eob = 127; // end of block
//input variables
int pixel_value = 0;
int row = 0;
int col = 0;
//output variables
signed char *element;
int index = 0;
//compression variables
int *output_size = 0;
int quantificator[8][8] = { // quantization table
{16,11,10,16,24,40,51,61},
{12,12,14,19,26,58,60,55},
{14,13,16,24,40,57,69,56},
{14,17,22,29,51,87,80,62},
{18,22,37,56,68,109,103,77},
{24,35,55,64,81,104,113,92},
{49,64,78,87,103,121,120,101},
{72,92,95,98,112,100,103,99}};
int zigzag_index[64]={ // zigzag table
0,1,5,6,14,15,27,28,
2,4,7,13,16,26,29,42,
3,8,12,17,25,30,41,43,
9,11,18,24,31,40,44,53,
10,19,23,32,39,45,52,54,
20,22,33,38,46,51,55,60,
21,34,37,47,50,56,59,61,
35,36,48,49,57,58,62,63};
sc_event input_event, output_event, compression_event;
// Constructor for compressor
SC_HAS_PROCESS(jpg_output);
jpg_output(sc_module_name jpg_compressor, int im_rows = 480, int im_cols = 640): sc_module(jpg_compressor){
if(im_rows%BLOCK_ROWS==0) {image_rows=im_rows;}
else {image_rows=(im_rows/BLOCK_ROWS+1)*BLOCK_ROWS;}
if(im_cols%BLOCK_COLS==0) {image_cols=im_cols;}
else {image_cols=(im_cols/BLOCK_COLS+1)*BLOCK_COLS;}
image = new double[image_rows*image_cols];
//initialize the image matrix to avoid nan
for(int i=0; i<(image_rows*image_cols);i++){
image[i]=0;
}
SC_THREAD(input_operation);
SC_THREAD(output_operation);
SC_THREAD(compression_operation);
} // End of Constructor
//------------Code Starts Here-------------------------
void input_pixel(int pixel_value_local, int row_local, int col_local) {
pixel_value = pixel_value_local;
row = row_local;
col = col_local;
input_event.notify(8, SC_NS);
}
void input_operation(){
while(true) {
wait(output_event);
double* i_row = &image[row * image_cols];
i_row[col] = double(pixel_value);
}
}
//void OutputPixel(int *Pixel, int row, int col) {
// double* i_row = &image[row * image_cols];
// *Pixel = int(i_row[col]);
//}
void output_byte(signed char *element_local, int index_local) {
element = element_local;
index = index_local;
output_event.notify(8, SC_NS);
}
void output_operation(){
while(true) {
wait(output_event);
element[index] = image[index];
}
}
void jpeg_compression(int *output_size_local) {
output_size = output_size_local;
compression_event.notify(9000, SC_NS);
}
void compression_operation() {
while(true) {
wait(compression_event);
//Level shift
for(int i=0; i<(image_rows*image_cols);i++){
image[i]=image[i]-128;
}
int number_of_blocks = image_rows*image_cols/(BLOCK_ROWS*BLOCK_COLS);
int block_output[number_of_blocks][BLOCK_ROWS*BLOCK_COLS] = {0};
int block_output_size[number_of_blocks] = {0};
int block_counter = 0;
*output_size = 0;
for(int row=0; row<image_rows; row+=BLOCK_ROWS) {
double* i_row = &image[row * image_cols];
for(int col=0; col<image_cols; col+=BLOCK_COLS) { //Divided the image in 8×8 blocks
dct(row,col);
quantization(row,col);
zigzag(row,col,&block_output_size[block_counter],block_output[block_counter]);
*output_size += block_output_size[block_counter]+1;
block_counter++;
}
}
int output_counter = 0;
for(int block_index=0;block_index<number_of_blocks;block_index++){
for(int out_index=0; out_index<block_output_size[block_index];out_index++){
image[output_counter]=block_output[block_index][out_index];
output_counter++;
}
image[output_counter]=eob;
output_counter++;
}
}
}
void dct(int row_offset, int col_offset) {
double cos_table[BLOCK_ROWS][BLOCK_COLS];
for (int row = 0; row < BLOCK_ROWS; row++) //make the cosine table
{
for (int col = 0; col < BLOCK_COLS; col++) {
cos_table[row][col] = cos((((2*row)+1)*col*PI)/16);
}
}
double temp = 0.0;
for(int row=row_offset; row<row_offset+BLOCK_ROWS; row++)
{
double* i_row = &image[row * image_cols];
for(int col=col_offset; col<col_offset+BLOCK_COLS; col++) {
//i_row[col] = cos_table[row-row_offset][col-col_offset];
temp = 0.0;
for (int x = 0; x < 8; x++){
double* x_row = &image[(x+row_offset) * image_cols];
for (int y = 0; y < 8; y++) {
temp += x_row[y+col_offset] * cos_table[x][row-row_offset] * cos_table[y][col-col_offset];
}
}
if ((row-row_offset == 0) && (col-col_offset == 0)) {
temp /= 8.0;
}
else if (((row-row_offset == 0) && (col-col_offset != 0)) || ((row-row_offset != 0) && (col-col_offset == 0))){
temp /= (4.0*sqrt(2.0));
}
else {
temp /= 4.0;
}
i_row[col] = temp;
}
}
}
void quantization(int row_offset, int col_offset) {
for(int row=row_offset; row<row_offset+BLOCK_ROWS; row++)
{
double* i_row = &image[row * image_cols];
for(int col=col_offset; col<col_offset+BLOCK_COLS; col++) {
i_row[col] = round(i_row[col]/quantificator[row-row_offset][col-col_offset]);
}
}
}
void zigzag(int row_offset, int col_offset, int *block_output_size, int *block_output) {
int index_last_non_zero_value = 0; // index to last non-zero in a block zigzag array
for(int row=row_offset; row<row_offset+BLOCK_ROWS; row++)
{
double* i_row = &image[row * image_cols];
for(int col=col_offset; col<col_offset+BLOCK_COLS; col++) {
int temp_index = zigzag_index[(row-row_offset)*8+(col-col_offset)];
block_output[temp_index]=i_row[col];
if(i_row[col] !=0 && temp_index>index_last_non_zero_value) {index_last_non_zero_value = temp_index+1;}
}
}
*block_output_size = index_last_non_zero_value;
}
};
|
// Copyright (c) 2011-2024 Columbia University, System Level Design Group
// SPDX-License-Identifier: MIT
#ifndef __ESP_DMA_INFO_HPP__
#define __ESP_DMA_INFO_HPP__
#include <sstream>
#include "utils/esp_types.hpp"
#include "utils/esp_systemc.hpp"
#define SIZE_BYTE sc_dt::sc_bv<3>(0)
#define SIZE_HWORD sc_dt::sc_bv<3>(1)
#define SIZE_WORD sc_dt::sc_bv<3>(2)
#define SIZE_DWORD sc_dt::sc_bv<3>(3)
#define SIZE_4WORD sc_dt::sc_bv<3>(4)
#define SIZE_8WORD sc_dt::sc_bv<3>(5)
#define SIZE_16WORD sc_dt::sc_bv<3>(6)
#define SIZE_32WORD sc_dt::sc_bv<3>(7)
class dma_info_t
{
public:
// Index
uint32_t index;
// Length
uint32_t length;
// Length
sc_dt::sc_bv<3> size;
// User
sc_dt::sc_bv<5> user;
// Constructors
dma_info_t()
: index(0), length(0), size(SIZE_WORD), user(0) { }
dma_info_t(uint32_t i, uint32_t l, sc_dt::sc_bv<3> s, sc_dt::sc_bv<5> u)
: index(i), length(l), size(s), user(u) { }
dma_info_t(const dma_info_t &other)
: index(other.index), length(other.length), size(other.size), user(other.user) { }
// Operators
// Assign operator
inline dma_info_t &operator=(const dma_info_t &other);
// Equals operator
inline bool operator==(const dma_info_t &rhs) const;
// Friend zone
// Dump operator
friend inline ostream &operator<<(ostream &os, dma_info_t const &dma_info);
// Makes this type traceable by SystemC
friend inline void sc_trace(sc_trace_file *tf, const dma_info_t &v,
const std::string &name);
};
// Implementation
#include "esp_dma_info.i.hpp"
#endif // __ESP_DMA_INFO_HPP__
|
#ifndef IPS_VGA_TLM_HPP
#define IPS_VGA_TLM_HPP
#include <systemc.h>
using namespace sc_core;
using namespace sc_dt;
using namespace std;
#include <tlm.h>
#include <tlm_utils/simple_initiator_socket.h>
#include <tlm_utils/simple_target_socket.h>
#include <tlm_utils/peq_with_cb_and_phase.h>
#include "common_func.hpp"
#include "important_defines.hpp"
#include "vga.hpp"
#include "../src/img_target.cpp"
// Extended Unification TLM
struct vga_tlm
: public vga<
IPS_BITS,
IPS_H_ACTIVE, IPS_H_FP, IPS_H_SYNC_PULSE, IPS_H_BP,
IPS_V_ACTIVE, IPS_V_FP, IPS_V_SYNC_PULSE, IPS_V_BP
>, public img_target
{
protected:
unsigned char* tmp_img;
public:
vga_tlm(sc_module_name name, bool use_prints_)
: vga<
IPS_BITS,
IPS_H_ACTIVE, IPS_H_FP, IPS_H_SYNC_PULSE, IPS_H_BP,
IPS_V_ACTIVE, IPS_V_FP, IPS_V_SYNC_PULSE, IPS_V_BP>((std::string(name) + "_HW_block").c_str()),
img_target((std::string(name) + "_target").c_str())
{
this->use_prints = use_prints_;
checkprintenableimgtar(use_prints);
set_mem_attributes(IMG_INPUT_ADDRESS_LO, IMG_INPUT_SIZE+IMG_INPUT_START_SIZE+IMG_INPUT_DONE_SIZE);
}
// Override do_when_transaction functions
virtual void do_when_read_transaction(unsigned char *&data, unsigned int data_length, sc_dt::uint64 address);
virtual void do_when_write_transaction(unsigned char *&data, unsigned int data_length, sc_dt::uint64 address);
//Backdoor access to memory
void backdoor_write(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address);
void backdoor_read(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address);
unsigned char *return_mem_ptr();
};
#endif // IPS_VGA_TLM_HPP
|
#include <config.hpp>
#include <core.hpp>
#include <systemc.h>
SC_MODULE(Sensor_${sensor_name}_functional)
{
Core* core;
//Input Port
sc_core::sc_in <bool> enable;
sc_core::sc_in <int> address;
sc_core::sc_in <int> data_in;
sc_core::sc_in <bool> flag_wr;
sc_core::sc_in <bool> ready;
//Output Port
sc_core::sc_out <int> data_out;
sc_core::sc_out <bool> go;
//Power Port
sc_core::sc_out <int> power_signal;
//Thermal Port
//sc_core::sc_out <int> thermal_signal;
SC_CTOR(Sensor_${sensor_name}_functional):
enable("Enable_signal"),
address("Address"),
data_in("Data_in"),
flag_wr("Flag"),
ready("Ready"),
data_out("Data_out"),
go("Go"),
power_signal("Func_to_Power_signal")
{
//printf("SENSOR :: systemc constructor");
register_memory = new uint8_t[${register_memory}];
SC_THREAD(sensor_logic);
sensitive << ready;
}
void sensor_logic();
Sensor_${sensor_name}_functional(){
//printf("SENSOR :: constructor");
}
~Sensor_${sensor_name}_functional(){
delete[]register_memory;
}
//Register Map
private:
uint8_t* register_memory;
int register_memory_size=${register_memory};
};
|
/*
* SPDX-FileCopyrightText: Copyright (c) 2020-2021 NVIDIA CORPORATION &
* AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This is a stub needed for the generated interconnect, so that downstream flow
// and simulation knows where to look for it.
#ifndef GROUT_0_H
#define GROUT_0_H
#include <systemc.h>
#include <nvhls_connections.h>
#include <nvhls_packet.h>
#include <interconnect/Interconnect.hpp>
#include "interconnect_config.hpp"
#if defined(INTERCONNECT_GEN)
#include ic_header(INTERCONNECT_GEN)
#endif // if defined(INTERCONNECT_GEN)
#endif
|
/***************************************************************************\
*
*
* ___ ___ ___ ___
* / /\ / /\ / /\ / /\
* / /:/ / /::\ / /::\ / /::\
* / /:/ / /:/\:\ / /:/\:\ / /:/\:\
* / /:/ / /:/~/:/ / /:/~/::\ / /:/~/:/
* / /::\ /__/:/ /:/___ /__/:/ /:/\:\ /__/:/ /:/
* /__/:/\:\ \ \:\/:::::/ \ \:\/:/__\/ \ \:\/:/
* \__\/ \:\ \ \::/~~~~ \ \::/ \ \::/
* \ \:\ \ \:\ \ \:\ \ \:\
* \ \ \ \ \:\ \ \:\ \ \:\
* \__\/ \__\/ \__\/ \__\/
*
*
*
*
* This file is part of TRAP.
*
* TRAP is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* or see <http://www.gnu.org/licenses/>.
*
*
*
* (c) Luca Fossati, fossati@elet.polimi.it, fossati.l@gmail.com
*
\***************************************************************************/
#ifndef MEMORYLT_HPP
#define MEMORYLT_HPP
#include <systemc.h>
#include <tlm.h>
#include <tlm_utils/simple_target_socket.h>
#include <boost/lexical_cast.hpp>
#include <string>
#include <trap_utils.hpp>
namespace trap{
template<unsigned int N_INITIATORS, unsigned int sockSize> class MemoryLT: public sc_module{
public:
tlm_utils::simple_target_socket<MemoryLT, sockSize> * socket[N_INITIATORS];
MemoryLT(sc_module_name name, unsigned int size, sc_time latency = SC_ZERO_TIME) :
sc_module(name), size(size), latency(latency){
for(int i = 0; i < N_INITIATORS; i++){
this->socket[i] = new tlm_utils::simple_target_socket<MemoryLT, sockSize>(("mem_socket_" + boost::lexical_cast<std::string>(i)).c_str());
this->socket[i]->register_b_transport(this, &MemoryLT::b_transport);
this->socket[i]->register_get_direct_mem_ptr(this, &MemoryLT::get_direct_mem_ptr);
this->socket[i]->register_transport_dbg(this, &MemoryLT::transport_dbg);
}
// Reset memory
this->mem = new unsigned char[this->size];
memset(this->mem, 0, size);
end_module();
}
~MemoryLT(){
delete this->mem;
for(int i = 0; i < N_INITIATORS; i++){
delete this->socket[i];
}
}
void b_transport(tlm::tlm_generic_payload& trans, sc_time& delay){
tlm::tlm_command cmd = trans.get_command();
sc_dt::uint64 adr = trans.get_address();
unsigned char* ptr = trans.get_data_ptr();
unsigned int len = trans.get_data_length();
unsigned char* byt = trans.get_byte_enable_ptr();
unsigned int wid = trans.get_streaming_width();
if(adr > this->size){
trans.set_response_status(tlm::TLM_ADDRESS_ERROR_RESPONSE);
std::cerr << "Error requesting address " << std::showbase << std::hex << adr << std::dec << std::endl;
return;
}
if(byt != 0){
trans.set_response_status(tlm::TLM_BYTE_ENABLE_ERROR_RESPONSE);
return;
}
if(cmd == tlm::TLM_READ_COMMAND){
memcpy(ptr, &this->mem[adr], len);
}
else if(cmd == tlm::TLM_WRITE_COMMAND){
memcpy(&this->mem[adr], ptr, len);
}
// Use temporal decoupling: add memory latency to delay argument
delay += this->latency;
trans.set_dmi_allowed(true);
trans.set_response_status(tlm::TLM_OK_RESPONSE);
}
// TLM-2 DMI method
bool get_direct_mem_ptr(tlm::tlm_generic_payload& trans, tlm::tlm_dmi& dmi_data){
// Allow read and write access
dmi_data.allow_read_write();
// Set other details of DMI region
dmi_data.set_dmi_ptr(this->mem);
dmi_data.set_start_address(0);
dmi_data.set_end_address(this->size);
dmi_data.set_read_latency(this->latency);
dmi_data.set_write_latency(this->latency);
return true;
}
// TLM-2 debug transaction method
unsigned int transport_dbg(tlm::tlm_generic_payload& trans){
tlm::tlm_command cmd = trans.get_command();
sc_dt::uint64 adr = trans.get_address();
unsigned char* ptr = trans.get_data_ptr();
unsigned int len = trans.get_data_length();
// Calculate the number of bytes to be actually copied
unsigned int num_bytes = (len < this->size - adr) ? len : this->size - adr;
if(cmd == tlm::TLM_READ_COMMAND)
memcpy(ptr, &this->mem[adr], num_bytes);
else if(cmd == tlm::TLM_WRITE_COMMAND)
memcpy(&this->mem[adr], ptr, num_bytes);
return num_bytes;
}
//Method used to directly write a word into memory; it is mainly used to load the
//application program into memory
inline void write_byte_dbg(const unsigned int & address, const unsigned char & datum) throw(){
if(address >= this->size){
THROW_ERROR("Address " << std::hex << std::showbase << address << " out of memory");
}
this->mem[address] = datum;
}
private:
const sc_time latency;
unsigned int size;
unsigned char * mem;
};
};
#endif
|
#pragma once
#include "systemc.hpp"
#include "tlm.hpp"
#include "common.hpp"
struct Observer_module : sc_core::sc_module
{
sc_core::sc_export<sc_core::sc_signal_out_if<Data_t>> actual_export { "actual_export" };
sc_core::sc_port<sc_core::sc_signal_in_if<Data_t>> expect_port { "expect_port" };
sc_core::sc_port<sc_core::sc_signal_in_if<bool>> running_port { "running_port" };
Observer_module( sc_core::sc_module_name instance );
void start_of_simulation();
void prepare_thread();
void checker_thread();
private:
uint16_t observed_count{ 0 };
uint16_t failures_count{ 0 };
sc_core::sc_signal<Data_t> actual_data;
tlm::tlm_fifo<Data_t> expected_fifo{ -1 }; // unbounded
// Following are here only for tracing purposes
Data_t received_value{};
Data_t expected_value{};
Data_t actual_value{};
};
|
//****************************************************************************************
// MIT License
//****************************************************************************************
// Copyright (c) 2012-2020 University of Bremen, Germany.
// Copyright (c) 2015-2020 DFKI GmbH Bremen, Germany.
// Copyright (c) 2020 Johannes Kepler University Linz, Austria.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//****************************************************************************************
#include <crave/SystemC.hpp>
#include <crave/ConstrainedRandom.hpp>
#include <systemc.h>
#include <boost/timer.hpp>
using crave::rand_obj;
using crave::randv;
using sc_dt::sc_bv;
using sc_dt::sc_uint;
struct ALU16 : public rand_obj {
randv<sc_bv<2> > op;
randv<sc_uint<16> > a, b;
ALU16(rand_obj* parent = 0) : rand_obj(parent), op(this), a(this), b(this) {
constraint((op() != 0x0) || (65535 >= a() + b()));
constraint((op() != 0x1) || ((65535 >= a() - b()) && (b() <= a())));
constraint((op() != 0x2) || (65535 >= a() * b()));
constraint((op() != 0x3) || (b() != 0));
}
friend std::ostream& operator<<(std::ostream& o, ALU16 const& alu) {
o << alu.op << ' ' << alu.a << ' ' << alu.b;
return o;
}
};
int sc_main(int argc, char** argv) {
crave::init("crave.cfg");
boost::timer timer;
ALU16 c;
CHECK(c.next());
std::cout << "first: " << timer.elapsed() << "\n";
for (int i = 0; i < 1000; ++i) {
CHECK(c.next());
}
std::cout << "complete: " << timer.elapsed() << "\n";
return 0;
}
|
#ifndef _my_module2_
#define _my_module2_
#include "systemc.h"
#include "ModuleCompute_old.hpp"
#include "Detecteur2.hpp"
#include "DownSampling.hpp"
#include "BitDecider.hpp"
#include "BitsToBytes.hpp"
#include "CRCCheck.hpp"
#include "FrameProcessing.hpp"
SC_MODULE(my_module2)
{
public:
sc_in < bool > clock;
sc_in < bool > reset;
sc_fifo_in < sc_int <8> > e;
sc_fifo_out< sc_uint<32> > addr;
sc_fifo_out< sc_uint<24> > rgbv;
// sc_fifo_out< bool > detect1;
SC_CTOR(my_module2) :
mod("mod"),
// dbl("dbl"),
det("det"),
dow("dow"),
bit("bit"),
byt("byt"),
crc("crc"),
fra("fra"),
mod2dbl("mod2dbl", 1024),
// dbl2det1("dbl2det1", 32),
// dbl2det2("dbl2det2", 32),
det2dow("det2dow", 32),
dow2bit("dow2bit", 32),
bit2byt("bit2byt", 32),
byt2crc("byt2crc", 32),
crc2fra("crc2fra", 32)
{
// cout<<"Modcompute starting "<<endl;
mod.clock( clock );
mod.reset( reset );
mod.e( e );
mod.s(mod2dbl );
// mod.s2(mod2det2 );
// cout<<"Modcompute ending "<<endl;
// cout<<"Modcompute starting "<<endl;
// dbl.clock( clock );
// dbl.reset( reset );
// dbl.e(mod2dbl);
// dbl.s1(dbl2det1);
// dbl.s2(dbl2det2);
// cout<<"Modcompute ending "<<endl;
det.clock( clock );
det.reset( reset );
det.e(mod2dbl);
// det.e2(dbl2det2);
det.s(det2dow);
// det.detect1(detect1);
dow.clock( clock );
dow.reset( reset );
dow.e(det2dow);
dow.s(dow2bit);
bit.clock( clock );
bit.reset( reset );
bit.e(dow2bit);
bit.s(bit2byt);
byt.clock( clock );
byt.reset( reset );
byt.e(bit2byt);
byt.s(byt2crc);
crc.clock( clock );
crc.reset( reset );
crc.e(byt2crc);
crc.s(crc2fra);
fra.clock( clock );
fra.reset( reset );
fra.e(crc2fra);
fra.addr(addr);
fra.rgbv(rgbv);
}
private:
ModuleCompute mod;
// DOUBLEUR_U dbl;
Detecteur2 det;
DownSampling dow;
BitDecider bit;
BitsToBytes byt;
CRCCheck crc;
FrameProcessing fra;
sc_fifo< sc_uint<8> > mod2dbl;
sc_fifo< sc_uint<8> > dbl2det1;
sc_fifo< sc_uint<8> > dbl2det2;
sc_fifo< sc_uint<8> > det2dow;
sc_fifo< sc_uint<8> > dow2bit;
sc_fifo< sc_uint<1> > bit2byt;
sc_fifo< sc_uint<8> > byt2crc;
sc_fifo< sc_uint<8> > crc2fra;
};
#endif
|
#include <config.hpp>
#include <core.hpp>
#include <systemc.h>
SC_MODULE(Sensor_${sensor_name}_functional)
{
Core* core;
//Input Port
sc_core::sc_in <bool> enable;
sc_core::sc_in <unsigned int> address;
sc_core::sc_in <uint8_t*> data_in;
sc_core::sc_in <unsigned int> req_size;
sc_core::sc_in <bool> flag_wr;
sc_core::sc_in <bool> ready;
//Output Port
sc_core::sc_out <uint8_t*> data_out;
sc_core::sc_out <bool> go;
//Power Port
sc_core::sc_out <int> power_signal;
//Thermal Port
//sc_core::sc_out <int> thermal_signal;
SC_CTOR(Sensor_${sensor_name}_functional):
enable("Enable_signal"),
address("Address"),
data_in("Data_in"),
flag_wr("Flag"),
ready("Ready"),
data_out("Data_out"),
go("Go"),
power_signal("Func_to_Power_signal")
{
//printf("SENSOR :: systemc constructor");
register_memory = new uint8_t[${register_memory}];
SC_THREAD(sensor_logic);
sensitive << ready;
}
void sensor_logic();
Sensor_${sensor_name}_functional(){
//printf("SENSOR :: constructor");
}
~Sensor_${sensor_name}_functional(){
delete[]register_memory;
}
//Register Map
private:
uint8_t* register_memory;
int register_memory_size=${register_memory};
};
|
#ifndef IMG_RECEIVER_TLM_HPP
#define IMG_RECEIVER_TLM_HPP
#include <systemc.h>
#include "img_receiver.hpp"
#include "../src/img_target.cpp"
#include "address_map.hpp"
struct img_receiver_tlm: public img_receiver, public img_target
{
SC_CTOR(img_receiver_tlm): img_receiver(img_receiver::name()), img_target(img_target::name()) {
set_mem_attributes(IMG_INPUT_ADDRESS_LO, IMG_INPUT_SIZE);
}
//Override do_when_transaction functions
virtual void do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address);
virtual void do_when_write_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address);
};
#endif // IMG_RECEIVER_TLM_HPP
|
#ifndef IMG_TRANSMITER_HPP
#define IMG_TRANSMITER_HPP
#include <systemc.h>
#include "address_map.hpp"
SC_MODULE(img_transmiter)
{
//Array for input image
unsigned char* output_image;
sc_dt::uint64 address_offset;
SC_CTOR(img_transmiter)
{
output_image = new unsigned char[IMG_INPUT_SIZE];
address_offset = IMG_OUTPUT_ADDRESS_LO;
}
//Backdoor access to memory
void backdoor_write(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address);
void backdoor_read(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address);
};
#endif // IMG_TRANSMITER_HPP
|
/*
* Copyright (C) 2024 Commissariat à l'énergie atomique et aux énergies alternatives (CEA)
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NOCBASE_HPP
#define NOCBASE_HPP
#include "systemc.h"
#include <list>
#include <map>
#include <set>
#include "dijkstra.hpp"
#include <semaphore.h> //TODO consider deleting
#include "NoCIF.hpp"
using namespace std;
namespace vpsim
{
//!
//! C_NoCBase is an sc_module that provides all necessary function for NoC topology and routing declaration
//! it does not provide actual implementation of the NoC which is performed by
//! derived classes that specialize the instanciation depending on the necessary accuracy level.
//!
class C_NoCBase: public sc_module, public C_NoCIF
{
friend class C_NoCCycleAccurate;
friend class C_NoCNoContention;
friend class C_NoCTLMBase;
protected:
unsigned int RouterCount; //!< number of routers in the NoC
unsigned int LinkCount;//!< number of links between routers in the NoC
unsigned int MasterCount;//!< number of initiators on the NoC
unsigned int SlaveCount; //!< number of slaves on the NoC
//----------------------------------//
// slow structs used at build time
//----------------------------------//
set<T_RouterID> SlowRouterIDs; //!< keeps all data from AddRouteur
std::map<std::pair<T_RouterID,T_PortID>,std::pair<T_RouterID,T_PortID> > Links; //!< keeps all data from AddLink
std::map<std::pair<T_RouterID,T_RouterID>,T_PortID > Routers2Port; //!< keeps all data from AddLink
std::map<T_RouterID, std::map<T_RouterID, T_PortID> > RoutingTables;
//the number of input ports for each router, used for implicit port instanciation
std::map<T_RouterID, unsigned int> RouterInputPortsCount;
std::map<T_RouterID, unsigned int> RouterOutputPortsCount;
std::map<T_RouterID, std::list<TLMMasterBindInfo> > TLMMasterBindInfoList;
std::map<T_RouterID, std::list<TLMSlaveBindInfo > > TLMSlaveBindInfoList;
std::map<T_RouterID, std::list<CABAMasterBindInfo> > CABAMasterBindInfoList;
std::map<T_RouterID, std::list<CABASlaveBindInfo > > CABASlaveBindInfoList;
T_MemoryMap MemMap; //! the memory map of the NoC i.e. a map between Target ID (Router ID + out port ID) and address ranges
std::map<T_RouterID, std::list< std::pair<T_PortID,T_PortID> > >TrafficEndpointInfoList;
//NoC building status
bool RoutingDone; //! status flag representing whether or not routing was performed on the NoC
bool BeforeElaborationDone; //! status flag representing whether or not the before_end_of_elaboration() step occured
bool ElaborationDone; //! status flag representing whether end_of_elaboration() step occured
#ifdef STORE_NOC_STATS
std::map<T_RouterID, std::map<T_SlavePortID, unsigned int > > StatsSlaveAccessCounters; //! statistic of access count to every TLM slave (or Target) in the NoC
std::map<T_RouterID, std::map<T_SlavePortID, timespec > > total_time_wait_for_lock; //! statistic of parallel access contention for every TLM slave (or Target) in the NoC
#endif
//NoC speed parameters
float FrequencyScaling; //! the ratio between NoC speed and compute speed.
unsigned int LinkSizeInBytes; //! number of data Bytes that can transit in one flit on a NoC link
//timing flag
bool NoTiming; //! status flag representing whether or not NoC accesses shall be timed
bool TraceActivation; //! status flag representing whether or not statistics shall be displayed
timespec res; //! seems to be used for contention statistics, to be confirmed
ofstream CONNECTTopo;
private:
Graph NoCGraph; //a graph representation of the NoC structure used by Auto routing
public:
std::list<T_TargetID> ValidTargets;
//!
//! Constructor that builds an empty sc_module NoC with instance name @param [in] name
//!
C_NoCBase(sc_module_name name);
//!
//! default destructor that produces statistics output and deallocation of C_NoCBase alloc'd structs
//!
~C_NoCBase();
//!
//! Creates a new router as part of the C_NoCBase
//!
void AddRouter(unsigned RouterID);
//!
//! Creates a new link between two Routers, and create Routers if they do not exist yet. Ports arautomatically added for the link
//! @param [in] RouterSrcID : a unique ID identifying the source Router
//! @param [in] RouterDestID : a unique ID identifying the target Router
//! @param [in] debug : optional parameter set to false by default, enables printing of debug messages
//!
void AddLink(unsigned int RouterSrcID, unsigned int RouterDestID, bool debug=false);
// void AddTargetLink(unsigned int RouterSrcID, unsigned int RouterSrcPortID, unsigned int TargetID);
//!
//! Creates a new entry in the routing table of a Router for routing packets to a target Router on the NoC (not necessarily directly linked to it)
//! If a routing entry already exists for this slave, routing insertion is ignored and false is returned.
//! @param [in] RouterSrcID : a unique ID identifying the source Router
//! @param [in] TargetID : a unique ID identifying the final target Router
//! @param [in] OutPortID : the Router port to which packets shall be transferred to in order to reach the slave
//! @param [in] debug : optional parameter set to false by default, enables printing of debug messages
//! @return true if successful, false if the Routing table already has an entry for TargetID (the previous entry is kept)
//!
bool AddRouting(unsigned int RouterSrcID, unsigned int TargetID, unsigned int OutPortID, bool debug=false);
//!
//! Performs an automated routing of the NoC using Dijkstra shortest path method
//! @note this is not an ideal routing method as it can create congestions and deadlock, but can be useful
//! in first steps of developments
//! @param [in] debug : optional parameter set to false by default, enables printing of debug messages
//!
void BuildDefaultRoutingBidirectional(bool debug=false);
void DebugRoutingTables();
void CMUDumpRouting();
// TODO implement a unidirectional default routing
// Note: To implement the same method on unidirectional NoC you need to keep a first list of masters and a second list of slaves
// this could be specified by 2 new methods SetAsSlave(ID) SetAsMaster(ID)
//void SetRouterAsInitiator(T_RouterID InitiatorID); // connect an initiator to router InitiatorID
//void SetRouterAsTarget(T_RouterID TargetID); //connect a target to router RouterID
private:
//!
//! Associates an T_MemoryRegion to a TargetID, i.e all data transfers targetting an address in this region shall
//! be transferred to this given TargetID
//! @note although no memory region overlapping is tested by this function
//! calls to CheckMemoryMap allow to verify this
//! @param [in] TargetID : a unique ID identifying a final target Router
//! @param [in] MemRegion : A memory region that must addressable through the TargetID
//!
void AddMemoryMapping( T_TargetID TargetID, T_MemoryRegion MemRegion);
public:
//!
//! Asserts that no T_MemoryRegion connected to the NoC do overlap
//! If overlapping is detected the program reaches early termination
//!
void CheckMemoryMap();
//!
//! Searches for the unique ID of the Router associated with a given address
//! @return unique ID of the Router associated with a given address
//!
T_TargetID GetTargetIDFromAddress(T_MemoryAddress);
//!
//! Searches for the base address of memory associated to a given TargetID
//! @return Address of the beginning of the memory space associated with a Router
//!
T_MemoryAddress GetBaseAddressFromTargetID(T_TargetID TargetID);
//!
//! connects a master to a router (actual binding is postponed until end of elaboration)
//! @param [in] MasterPort : the tlm master port
//! @param [in] RouterID : a unique ID identifying the Router
//!
void bind( sc_port<ac_tlm_transport_if>* MasterPort, T_RouterID RouterID);
//!
//! Connects a slave to a router with its address map (this creates a new targetID) (actual binding is postponed until end of elaboration)
//! @param [in] SlavePort : the tlm slave port
//! @param [in] RouterID : a unique ID identifying the target router
//! @param [in] MemRegion : a memory region to be associated to a given SlavePort
//!
void bind( sc_export<ac_tlm_transport_if>* SlavePort, T_RouterID RouterID, T_MemoryRegion MemRegion);
T_TargetID bind( sc_fifo_out<NoCFlit>* Master, T_RouterID RouterID);
T_TargetID BindBiDir(sc_fifo_in<NoCFlit>* Slave, sc_fifo_out<NoCFlit>* Master, T_RouterID RouterID);
//!
//! Connects a slave to a router with its address map (this creates a new targetID) (actual binding is postponed until end of elaboration)
//! @param [in] _FrequencyScaling : the ratio between NoC speed and compute speed. (e.g if NoC runs @1GHz but platform runs at 500MHz, _FrequencyScaling equals 2)
//!
void SetFrequencyScaling(float _FrequencyScaling);
//!
//! Defines the datawidth of NoC links. This impacts the way data transfer latency is computed in the NoC
//! @param [in] _LinkSizeInBytes : number of data Bytes that can transit in one flit on a NoC link
//!
void SetNoCLinkSize(unsigned int _LinkSizeInBytes);
//!
//! Defines whether the TLM accesses on the NoC shall be timed or not
//! @param [in] _TimingActivation : true if NoC shall compute timings, false otherwise
//!
void SetTimingActivation(bool _TimingActivation = false);
//!
//! Defines whether the NoC shall display debug traces or not
//! @param [in] _TraceActivation : true if NoC shall display traces, false otherwise
//!
void SetTraceActivation(bool _TraceActivation = false);
//!
//! Creates a full NoC topology from CMU's CONNECT NoC configuration files
//! @warning unimplemented features
//! @param [in] TopologyFilePath : file path for CONNECT topology configuration file
//! @param [in] TopologyFilePath : file path for CONNECT RoutingFilePathconfiguration file
//!
void ParseCONNECTConfig(const char * TopologyFilePath, const char * RoutingFilePath );
//!
//! Stores NoC statistics to a standard output file STAT_PATH/w_noc/stats_NOC_NAME
//! @note : dump only occurs if TraceActivation is set to True
//!
void display_allstats();
};
};//end namespace vpsim
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.