text
stringlengths 41
20k
|
---|
/*
* 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
|
#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_lt_model.hpp"
#include "img_target.hpp"
//Extended Unification TLM
struct sobel_edge_detector_tlm : public Edge_Detector, public img_target
{
SC_CTOR(sobel_edge_detector_tlm): Edge_Detector(Edge_Detector::name()), img_target(img_target::name()) {
}
//Override do_when_transaction functions
virtual void do_when_read_transaction(unsigned char*& data);
virtual void do_when_write_transaction(unsigned char*& data);
};
#endif // SOBEL_EDGE_DETECTOR_TLM_HPP
|
/*
* Adder.h
* SystemC_SimpleAdder
*
* Created by Le Gal on 07/05/07.
* Copyright 2007 __MyCompanyName__. All rights reserved.
*
*/
#ifndef _Detecteur2_
#define _Detecteur2_
#include "systemc.h"
#include <cstdint>
#include "Doubleur_uint.hpp"
#include "trames_separ2.hpp"
#include "Seuil_calc2.hpp"
// #define _DEBUG_SYNCHRO_
SC_MODULE(Detecteur2)
{
public:
sc_in < bool > clock;
sc_in < bool > reset;
sc_fifo_in < sc_uint<8> > e;
// sc_fifo_in < sc_uint<8> > e2;
sc_fifo_out< sc_uint<8> > s;
// sc_fifo_out< bool > detect1;
SC_CTOR(Detecteur2):
s_calc("s_calc"),
t_sep("t_sep"),
dbl("dbl"),
dbl2scalc("dbl2scalc",1024),
dbl2tsep("dbl2tsep",1024),
detect("detect", 1024)
// detect1("detect1", 4096)
{
dbl.clock(clock);
dbl.reset(reset);
dbl.e(e);
dbl.s1(dbl2scalc);
dbl.s2(dbl2tsep);
s_calc.clock(clock);
s_calc.reset(reset);
s_calc.e(dbl2scalc);
s_calc.detect(detect);
// s_calc.detect1(detect1);
t_sep.clock(clock);
t_sep.reset(reset);
t_sep.e(dbl2tsep);
t_sep.detect(detect);
t_sep.s(s);
}
private:
Seuil_calc2 s_calc;
trames_separ2 t_sep;
DOUBLEUR_U dbl;
sc_fifo< sc_uint<8> > dbl2scalc;
sc_fifo< sc_uint<8> > dbl2tsep;
sc_fifo <bool> detect;
};
#endif
|
/*******************************************************************************
* clkpacer.cpp -- Copyright 2019 Glenn Ramalho - RFIDo Design
*******************************************************************************
* Description:
* Implements functions to step time. No clock was implemented to avoid the
* delay. Instead use these variables and functions for the same purpose.
*******************************************************************************
* 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 "clockpacer.h"
clockpacer_t clockpacer;
void clockpacer_t::wait_next_cpu_clk() {
long int nanoseconds;
nanoseconds = (long int)floor(sc_time_stamp().to_seconds() * 1e9);
long int offset = nanoseconds % cpu_period;
wait(sc_time(cpu_period - offset, SC_NS));
}
void clockpacer_t::wait_next_apb_clk() {
long int nanoseconds;
nanoseconds = (long int)floor(sc_time_stamp().to_seconds() * 1e9);
long int offset = nanoseconds % apb_period;
wait(sc_time(apb_period - offset, SC_NS));
}
void clockpacer_t::wait_next_ref_clk() {
long int nanoseconds;
nanoseconds = (long int)floor(sc_time_stamp().to_seconds() * 1e9);
long int offset = nanoseconds % ref_period;
wait(sc_time(ref_period - offset, SC_NS));
}
void clockpacer_t::wait_next_rtc8m_clk() {
long int nanoseconds;
nanoseconds = (long int)floor(sc_time_stamp().to_seconds() * 1e9);
long int offset = nanoseconds % rtc8m_period;
wait(sc_time(rtc8m_period - offset, SC_NS));
}
|
/********************************************************************************
* University of L'Aquila - HEPSYCODE Source Code License *
* *
* *
* (c) 2018-2019 Centre of Excellence DEWS All rights reserved *
********************************************************************************
* <one line to give the program's name and a brief idea of what it does.> *
* Copyright (C) 2022 Vittoriano Muttillo, Luigi Pomante * *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU 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 General Public License for more details. *
* *
********************************************************************************
* *
* Created on: 09/May/2023 *
* Authors: Vittoriano Muttillo, Marco Santic, Luigi Pomante *
* *
* email: vittoriano.muttillo@guest.univaq.it *
* marco.santic@guest.univaq.it *
* luigi.pomante@univaq.it *
* *
********************************************************************************
* This code has been developed from an HEPSYCODE model used as demonstrator by *
* University of L'Aquila. *
*******************************************************************************/
#include <systemc.h>
#include "../mainsystem.h"
#include <math.h>
#define cD_01_ANN_INPUTS 2 // Number of inputs
#define cD_01_ANN_OUTPUTS 1 // Number of outputs
//-----------------------------------------------------------------------------
// Physical constants
//-----------------------------------------------------------------------------
static double cD_01_I_0 = 77.3 ; // [A] Nominal current
static double cD_01_T_0 = 298.15 ; // [K] Ambient temperature
static double cD_01_R_0 = 0.01 ; // [Ω] Data-sheet R_DS_On (Drain-Source resistance in the On State)
static double cD_01_V_0 = 47.2 ; // [V] Nominal voltage
static double cD_01_Alpha = 0.002 ; // [Ω/K] Temperature coefficient of Drain-Source resistance in the On State
static double cD_01_ThermalConstant = 0.75 ;
static double cD_01_Tau = 0.02 ; // [s] Sampling period
//-----------------------------------------------------------------------------
// Status descriptors
//-----------------------------------------------------------------------------
typedef struct cD_01_DEVICE // Descriptor of the state of the device
{
double t ; // Operating temperature
double r ; // Operating Drain-Source resistance in the On State
double i ; // Operating current
double v ; // Operating voltage
double time_Ex ;
int fault ;
} cD_01_DEVICE ;
static cD_01_DEVICE cD_01_device;
//-----------------------------------------------------------------------------
// Mnemonics to access the array that contains the sampled data
//-----------------------------------------------------------------------------
#define cD_01_SAMPLE_LEN 3 // Array of SAMPLE_LEN elements
#define cD_01_I_INDEX 0 // Current
#define cD_01_V_INDEX 1 // Voltage
#define cD_01_TIME_INDEX 2 // Time
///-----------------------------------------------------------------------------
// Forward references
//-----------------------------------------------------------------------------
static int cD_01_initDescriptors(cD_01_DEVICE device) ;
//static void getSample(int index, double sample[SAMPLE_LEN]) ;
static void cD_01_cleanData(int index, double sample[cD_01_SAMPLE_LEN]) ;
static double cD_01_extractFeatures(double tPrev, double iPrev, double iNow, double rPrev) ;
static void cD_01_normalize(int index, double x[cD_01_ANN_INPUTS]) ;
static double cD_01_degradationModel(double tNow) ;
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
int cD_01_initDescriptors(cD_01_DEVICE device)
{
// for (int i = 0; i < NUM_DEV; i++)
// {
device.t = cD_01_T_0 ; // Operating temperature = Ambient temperature
device.r = cD_01_R_0 ; // Operating R_DS_On = Data-sheet R_DS_On
// printf("Init %d \n",i);
// }
return( EXIT_SUCCESS );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void cD_01_cleanData(int index, double sample[cD_01_SAMPLE_LEN])
{
// the parameter "index" could be useful to retrieve the characteristics of the device
if ( sample[cD_01_I_INDEX] < 0 )
sample[cD_01_I_INDEX] = 0 ;
else if ( sample[cD_01_I_INDEX] > (2.0 * cD_01_I_0) )
sample[cD_01_I_INDEX] = (2.0 * cD_01_I_0) ;
// Postcondition: (0 <= sample[I_INDEX] <= 2.0*I_0)
if ( sample[cD_01_V_INDEX] < 0 )
sample[cD_01_V_INDEX] = 0 ;
else if ( sample[cD_01_V_INDEX] > (2.0 * cD_01_V_0 ) )
sample[cD_01_V_INDEX] = (2.0 * cD_01_V_0) ;
// Postcondition: (0 <= sample[V_INDEX] <= 2.0*V_0)
}
//-----------------------------------------------------------------------------
// Input:
// - tPrev = temperature at previous step
// - iPrev = current at previous step
// - iNow = current at this step
// - rPrev = resistance at the previous step
// Return:
// - The new temperature
// Very simple model:
// - one constant for dissipation and heat capacity
// - temperature considered constant during the step
//-----------------------------------------------------------------------------
double cD_01_extractFeatures(double tPrev, double iPrev, double iNow, double rPrev)
{
double t ; // Temperature
double i = 0.5*(iPrev + iNow); // Average current
//printf("cD_01_extractFeatures tPrev=%f\n",tPrev);
t = tPrev + // Previous temperature
rPrev * (i * i) * cD_01_Tau - // Heat generated: P = I·R^2
cD_01_ThermalConstant * (tPrev - cD_01_T_0) * cD_01_Tau ; // Dissipation and heat capacity
return( t );
}
//-----------------------------------------------------------------------------
// Input:
// - tNow: temperature at this step
// Return:
// - the resistance
// The model isn't realistic because the even the simpler law is exponential
//-----------------------------------------------------------------------------
double cD_01_degradationModel(double tNow)
{
double r ;
//r = R_0 + Alpha * tNow ;
r = cD_01_R_0 * ( 2 - exp(-cD_01_Alpha*tNow) );
return( r );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void cD_01_normalize(int index, double sample[cD_01_ANN_INPUTS])
{
double i ; double v ;
// Precondition: (0 <= sample[I_INDEX] <= 2*I_0) && (0 <= sample[V_INDEX] <= 2*V_0)
i = sample[cD_01_I_INDEX] <= cD_01_I_0 ? 0.0 : 1.0;
v = sample[cD_01_V_INDEX] <= cD_01_V_0 ? 0.0 : 1.0;
// Postcondition: (i in {0.0, 1.0}) and (v in {0.0, 1.0})
sample[cD_01_I_INDEX] = i ;
sample[cD_01_V_INDEX] = v ;
}
void mainsystem::cleanData_01_main()
{
// datatype for channels
sampleTimCord_cleanData_xx_payload sampleTimCord_cleanData_xx_payload_var;
cleanData_xx_ann_xx_payload cleanData_xx_ann_xx_payload_var;
//device var
uint8_t dev;
//step var
uint16_t step;
// ex_time (for extractFeatures...)
double ex_time;
//samples i and v
double sample_i;
double sample_v;
//var for samples, to re-use cleanData()
double cD_01_sample[cD_01_SAMPLE_LEN] ;
double x[cD_01_ANN_INPUTS + cD_01_ANN_OUTPUTS] ;
// NOTE: commented, should be changed param by ref...
//cD_01_initDescriptors(cD_01_device);
cD_01_device.t = cD_01_T_0 ; // Operating temperature = Ambient temperature
cD_01_device.r = cD_01_R_0 ; // Operating R_DS_On = Data-sheet R_DS_On
// ### added for time related dynamics
//static double cD_01_Tau = 0.02 ; // [s] Sampling period
double cD_01_last_sample_time = 0;
//implementation
HEPSY_S(cleanData_01_id) while(1)
{HEPSY_S(cleanData_01_id)
// content
sampleTimCord_cleanData_xx_payload_var = sampleTimCord_cleanData_01_channel->read();
dev = sampleTimCord_cleanData_xx_payload_var.dev;
step = sampleTimCord_cleanData_xx_payload_var.step;
ex_time = sampleTimCord_cleanData_xx_payload_var.ex_time;
sample_i = sampleTimCord_cleanData_xx_payload_var.sample_i;
sample_v = sampleTimCord_cleanData_xx_payload_var.sample_v;
// cout << "cleanData_01 rcv \t dev: " << dev
// <<"\t step: " << step
// <<"\t time_ex:" << ex_time
// <<"\t i:" << sample_i
// <<"\t v:" << sample_v
// << endl;
// reconstruct sample
cD_01_sample[cD_01_I_INDEX] = sample_i;
cD_01_sample[cD_01_V_INDEX] = sample_v;
cD_01_sample[cD_01_TIME_INDEX] = ex_time;
// ### C L E A N D A T A (0 <= I <= 2.0*I_0) and (0 <= V <= 2.0*V_0)
cD_01_cleanData(dev, cD_01_sample) ;
cD_01_device.time_Ex = cD_01_sample[cD_01_TIME_INDEX] ;
cD_01_device.i = cD_01_sample[cD_01_I_INDEX] ;
cD_01_device.v = cD_01_sample[cD_01_V_INDEX] ;
// ### added for time related dynamics
//static double cD_01_Tau = 0.02 ; // [s] Sampling period
cD_01_Tau = ex_time - cD_01_last_sample_time;
cD_01_last_sample_time = ex_time;
// ### F E A T U R E S E X T R A C T I O N (compute the temperature)
cD_01_device.t = cD_01_extractFeatures( cD_01_device.t, // Previous temperature
cD_01_device.i, // Previous current
cD_01_sample[cD_01_I_INDEX], // Current at this step
cD_01_device.r) ; // Previous resistance
// ### D E G R A D A T I O N M O D E L (compute R_DS_On)
cD_01_device.r = cD_01_degradationModel(cD_01_device.t) ;
// ### N O R M A L I Z E: (x[0] in {0.0, 1.0}) and (x[1] in {0.0, 1.0})
x[0] = cD_01_device.i ;
x[1] = cD_01_device.v ;
cD_01_normalize(dev, x) ;
// // ### P R E D I C T (simple XOR)
// if ( annRun(index, x) != EXIT_SUCCESS ){
//prepare out data payload
cleanData_xx_ann_xx_payload_var.dev = dev;
cleanData_xx_ann_xx_payload_var.step = step;
cleanData_xx_ann_xx_payload_var.ex_time = ex_time;
cleanData_xx_ann_xx_payload_var.device_i = cD_01_device.i;
cleanData_xx_ann_xx_payload_var.device_v = cD_01_device.v;
cleanData_xx_ann_xx_payload_var.device_t = cD_01_device.t;
cleanData_xx_ann_xx_payload_var.device_r = cD_01_device.r;
cleanData_xx_ann_xx_payload_var.x_0 = x[0];
cleanData_xx_ann_xx_payload_var.x_1 = x[1];
cleanData_xx_ann_xx_payload_var.x_2 = x[2];
cleanData_01_ann_01_channel->write(cleanData_xx_ann_xx_payload_var);
HEPSY_P(cleanData_01_id)
}
}
//END
|
#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
|
#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_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
|
#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);
};
|
#include <systemc.h>
#include <systemc-ams.h>
#include <config.hpp>
SCA_TDF_MODULE(Power_bus){
//Rate 1ms
//Input Port
sca_tdf::sca_in <double> core_current;
sca_tdf::sca_in <double> core_voltage;
sca_tdf::sca_in <double> voltage_sensors[NUM_SENSORS];
sca_tdf::sca_in <double> current_sensors[NUM_SENSORS];
#if NUM_SOURCES>0
sca_tdf::sca_in <double> current_sources[NUM_SOURCES];
#endif
#if NUM_BATTERIES>0
sca_tdf::sca_out <double> current_batteries[NUM_BATTERIES];
#endif
SCA_CTOR(Power_bus):
core_current("Current_of_CPU"),
core_voltage("Voltage_of_CPU")
{}
void set_attributes();
void initialize();
void processing();
private:
double total_current = 0;
Power_bus(){}
};
|
/*
* 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
|
/* 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
|
#pragma once
#include "systemc.hpp"
#include "common.hpp"
struct Stimulus_module : sc_core::sc_module
{
sc_core::sc_export<sc_core::sc_fifo_in_if<Data_t>> stim_export { "stim_export" };
sc_core::sc_export<sc_core::sc_signal_in_if<bool>> running_export { "running_export" };
Stimulus_module( sc_core::sc_module_name instance );
void start_of_simulation();
void stimulus_thread();
private:
sc_core::sc_fifo<Data_t> stimulus{ 4 };
sc_core::sc_signal<bool> running;
// Following are here only for tracing purposes
uint16_t test_count{ 0 };
Data_t value{0};
};
|
#include <systemc.h>
#include <systemc-ams.h>
#include <config.hpp>
#include <core.hpp>
#define V_CORE ${vref}
SCA_TDF_MODULE(Core_power)
{
Core* core;
//Data from Functional Instance
sca_tdf::sc_in <double> func_signal;
//Data to Power Bus
sca_tdf::sca_out <double> voltage_state;
sca_tdf::sca_out <double> current_state;
//sca_tdf::sc_out <int> power_to_therm;
SCA_CTOR(Core_power):
func_signal("State_of_Power_From_Functional"),
voltage_state("Voltage_trace_to_Power_Bus"),
current_state("Current_trace_to_Power_Bus")
{}
void set_attributes();
void initialize();
void processing();
Core_power(){}
};
|
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2017 Cadence Design Systems, Inc. All rights reserved worldwide.
//
// The code contained herein is the proprietary and confidential information
// of Cadence or its licensors, and is supplied subject to a previously
// executed license and maintenance agreement between Cadence and customer.
// This code is intended for use with Cadence high-level synthesis tools and
// may not be used with other high-level synthesis tools. Permission is only
// granted to distribute the code as indicated. Cadence grants permission for
// customer to distribute a copy of this code to any partner to aid in designing
// or verifying the customer's intellectual property, as long as such
// distribution includes a restriction of no additional distributions from the
// partner, unless the partner receives permission directly from Cadence.
//
// ALL CODE FURNISHED BY CADENCE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, AND CADENCE SPECIFICALLY DISCLAIMS ANY WARRANTY OF NONINFRINGEMENT,
// FITNESS FOR A PARTICULAR PURPOSE OR MERCHANTABILITY. CADENCE SHALL NOT BE
// LIABLE FOR ANY COSTS OF PROCUREMENT OF SUBSTITUTES, LOSS OF PROFITS,
// INTERRUPTION OF BUSINESS, OR FOR ANY OTHER SPECIAL, CONSEQUENTIAL OR
// INCIDENTAL DAMAGES, HOWEVER CAUSED, WHETHER FOR BREACH OF WARRANTY,
// CONTRACT, TORT, NEGLIGENCE, STRICT LIABILITY OR OTHERWISE.
//
////////////////////////////////////////////////////////////////////////////////
#include <systemc.h> // SystemC definitions
#include "system.h" // Top-level System module header file
static System * m_system = NULL; // The pointer that holds the top-level System module instance.
void esc_elaborate() // This function is required by Stratus to support SystemC-Verilog
{ // cosimulation. It instances the top-level module.
m_system = new System( "system" );
}
void esc_cleanup() // This function is called at the end of simulation by the
{ // Stratus co-simulation hub. It should delete the top-level
delete m_system; // module instance.
}
int sc_main( int argc, char ** argv ) // This function is called by the SystemC kernel for pure SystemC simulations
{
esc_initialize( argc, argv ); // esc_initialize() passes in the cmd-line args. This initializes the Stratus simulation
// environment (such as opening report files for later logging and analysis).
esc_elaborate(); // esc_elaborate() (defined above) creates the top-level module instance. In a SystemC-Verilog
// co-simulation, this is called during cosim initialization rather than from sc_main.
sc_start(); // Starts the simulation. Returns when a module calls esc_stop(), which finishes the simulation.
// esc_cleanup() (defined above) is automatically called before sc_start() returns.
return 0; // Returns the status of the simulation. Required by most C compilers.
}
|
/*
* 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)
{
public:
sc_fifo_in< sc_uint<32> > addr;
sc_fifo_in< sc_uint<24> > rgbv;
SC_CTOR(BMPWriter)
{
SC_THREAD(do_gen);
}
~BMPWriter( )
{
string fn;
fn = "received_image";
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;
}
}
};
|
#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
|
#include <map>
#include <sstream>
#include "systemc.h"
#ifndef SC_TRACE_HPP
#define SC_TRACE_HPP
/** SystemC signal and variable tracer wrapper. */
class sc_tracer; // forward declaration for global singleton
class sc_tracer {
public:
/** Global singleton instance */
static sc_tracer tracer;
/** Initializer specifying output file. */
static void init(const char *out_file, sc_time_unit time_unit) {
if (tracer._enabled) {
std::cout << "Opening trace file " << out_file << std::endl;
tracer._tf = sc_create_vcd_trace_file(out_file);
tracer._tf->set_time_unit(1, time_unit);
}
}
/** Trace a signal. */
template <class T>
static void trace(T& value, sc_module_name module_name, const char *signal_name) {
if (tracer._enabled) {
std::ostringstream ss;
ss << module_name << "." << signal_name;
sc_trace(tracer._tf, value, ss.str().c_str());
}
}
/** Trace a signal. */
template <class T>
static void trace(T& value, const char *module_name, const char *signal_name) {
trace(value, sc_module_name(module_name), signal_name);
}
/** Trace a signal. */
template <class T>
static void trace(T& value, std::string module_name, const char *signal_name) {
trace(value, sc_module_name(module_name.c_str()), signal_name);
}
/** Comment. */
static void comment(std::string comment) {
sc_write_comment(tracer._tf, comment);
}
/** Write the file. */
static void close() {
if (tracer._tf) {
std::cout << "Writing trace file" << std::endl;
sc_close_vcd_trace_file(tracer._tf);
tracer._tf = nullptr;
}
}
/** Disable tracing. */
static void disable() {
tracer._enabled = false;
}
/** Enable tracing. */
static void enable() {
tracer._enabled = true;
}
private:
// enable signal
bool _enabled = true;
// local file handle
sc_trace_file *_tf = nullptr;
};
// trackable class types
enum trackable_class_e {
REDUNDANT_COMMAND,
REDUNDANT_RESPONSE,
TRACKABLE_CLASS_NONE
};
#define NUM_TRACKABLE_CLASSES TRACKABLE_CLASS_NONE
// information about tracked data
struct trackable_data_t {
trackable_class_e data_class;
uint32_t publish_time;
};
/** Class to track latency of data across the NoC. */
class latency_tracker; // forward declaration for global singleton
class latency_tracker {
public:
/** Global singleton instance */
static latency_tracker tracker;
/** Publish a tracker. */
template <class T, class U = uint32_t>
static void publish(trackable_class_e data_class, T* data, U* data2 = nullptr) {
// calculate checksum for key
uint32_t chksum = 0;
uint32_t *ptr = (uint32_t*)data;
for (int i = 0; ptr && i < sizeof(T); i += sizeof(uint32_t), ptr++) {
chksum ^= *ptr;
}
ptr = (uint32_t*)data2;
for (int i = 0; ptr && i < sizeof(U); i += sizeof(uint32_t), ptr++) {
chksum ^= *ptr;
}
// insert into map
trackable_data_t data_struct;
data_struct.data_class = data_class;
data_struct.publish_time = (uint32_t)sc_time_stamp().to_double();
tracker._tracked_data[chksum] = data_struct;
}
/** Capture a tracker. */
template <class T, class U = uint32_t>
static void capture(T* data, U* data2 = nullptr) {
// calculate checksum for key
uint32_t chksum = 0;
uint32_t *ptr = (uint32_t*)data;
for (int i = 0; ptr && i < sizeof(T); i += sizeof(uint32_t), ptr++) {
chksum ^= *ptr;
}
ptr = (uint32_t*)data2;
for (int i = 0; ptr && i < sizeof(U); i += sizeof(uint32_t), ptr++) {
chksum ^= *ptr;
}
// fetch from dictionary
std::map<uint32_t, trackable_data_t>::const_iterator it = tracker._tracked_data.find(chksum);
if (it != tracker._tracked_data.end()) {
// found in map
trackable_data_t entry = it->second;
tracker._durations[entry.data_class] += (uint32_t)sc_time_stamp().to_double() - entry.publish_time;
tracker._counts[entry.data_class]++;
// remove from map
tracker._tracked_data.erase(it);
}
}
/** Print the report. */
static void print_report(std::ostream& out = std::cout) {
for (uint32_t c = (uint32_t)REDUNDANT_COMMAND; c < (uint32_t)TRACKABLE_CLASS_NONE; c++) {
out << "Class " << c << ": total duration " << tracker._durations[c] << " over " << tracker._counts[c] << " packets, average of " << ((double)tracker._durations[c] / (double)tracker._counts[c]) << " ticks per packet." << std::endl;
}
out << tracker._tracked_data.size() << " outstanding packets." << std::endl;
}
private:
// list of tracked values
std::map<uint32_t, trackable_data_t> _tracked_data;
// total durations
uint32_t _durations[NUM_TRACKABLE_CLASSES];
uint32_t _counts[NUM_TRACKABLE_CLASSES];
};
#endif // SC_TRACE_HPP
|
#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
|
/***************************************************************************\
*
*
* ___ ___ ___ ___
* / /\ / /\ / /\ / /\
* / /:/ / /::\ / /::\ / /::\
* / /:/ / /:/\:\ / /:/\:\ / /:/\:\
* / /:/ / /:/~/:/ / /:/~/::\ / /:/~/:/
* / /::\ /__/:/ /:/___ /__/:/ /:/\:\ /__/:/ /:/
* /__/:/\:\ \ \:\/:::::/ \ \:\/:/__\/ \ \:\/:/
* \__\/ \:\ \ \::/~~~~ \ \::/ \ \::/
* \ \:\ \ \:\ \ \:\ \ \:\
* \ \ \ \ \:\ \ \:\ \ \:\
* \__\/ \__\/ \__\/ \__\/
*
*
*
*
* 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
|
/***************************************************************************\
*
*
* ___ ___ ___ ___
* / /\ / /\ / /\ / /\
* / /:/ / /::\ / /::\ / /::\
* / /:/ / /:/\:\ / /:/\:\ / /:/\:\
* / /:/ / /:/~/:/ / /:/~/::\ / /:/~/:/
* / /::\ /__/:/ /:/___ /__/:/ /:/\:\ /__/:/ /:/
* /__/:/\:\ \ \:\/:::::/ \ \:\/:/__\/ \ \:\/:/
* \__\/ \:\ \ \::/~~~~ \ \::/ \ \::/
* \ \:\ \ \:\ \ \:\ \ \:\
* \ \ \ \ \:\ \ \:\ \ \:\
* \__\/ \__\/ \__\/ \__\/
*
*
*
*
* 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
|
#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
|
#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 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
/** @class Objection
@brief UVM-like mechanism to stop simulation when the last objection is removed.
Usage
-----
### Step 1
Instantiate `Objector_module` somewhere (e.g. under the top-most module)
### Step 2
Establish a drain-time using `Objection::set_drain_time(sc_time)`. The
drain-time is how long after all objections are missing to wait before
shutting down the simulation. If an objection is raised during the
drain-time, then the mechanism is reset.
Note that drain-time will start being monitored after the first objection
is raised.
### Step 3
Simply `Objection("name")` in threads at points where activity is starting.
Make sure the objection object has a well-defined life-time. The
construction string provided provides and identifier for the specific
objection.
Note: If verbosity is set to SC_DEBUG, then messages will be produced
as objections are raised and dropped.
Simulation will stop after destruction of the last objection.
Example
-------
```c++
void Stimulus_module::main_thread()
{
Objection stim{ "stimulus" };
...Generate test stimulus data...
}
```
********************************************************************************
*/
#include "systemc.hpp"
#include "report.hpp"
#include <string>
#include <set>
////////////////////////////////////////////////////////////////////////////////
struct Objection
{
Objection( const std::string& name ) ///< Create an objection
: m_name( name )
{
sc_assert( name.size() > 0 );
sc_assert( ready );
objections.insert( m_name );
std::string note{ "Raising objection " };
note += m_name;
INFO( DEBUG, note );
++created;
}
~Objection() ///< Remove an objection
{
auto elt = objections.find( m_name );
sc_assert( elt != objections.end() );
objections.erase( elt );
std::string note{ "Dropping objection " };
note += m_name;
INFO( DEBUG, note );
if( objections.empty() and sc_core::sc_is_running() )
{
INFO( DEBUG, "No objections remain" );
stop_reason = note;
stop_event.notify(sc_core::SC_ZERO_TIME);
wait( sc_core::SC_ZERO_TIME );
}
}
static size_t total() { return created; } ///< Return total times used
static size_t count() { return objections.size(); } ///< Return the outstanding objections
static void set_drain_time( sc_core::sc_time delay ) { Objection::drain_time = delay; }
static sc_core::sc_time get_drain_time() { return Objection::drain_time; }
void set_timeout( sc_core::sc_time delay )
{
timeout = delay;
timeout_event.notify(sc_core::SC_ZERO_TIME);
wait( sc_core::SC_ZERO_TIME );
}
private:
friend struct Objector_module;
std::string m_name;
// Static stuff
static constexpr const char* const MSGID { "/Doulos/Objection" };
inline static sc_core::sc_time drain_time{ sc_core::SC_ZERO_TIME };
inline static size_t created{ 0u };
inline static sc_core::sc_process_handle timer_handle;
inline static std::set<std::string> objections;
inline static sc_core::sc_event stop_event;
inline static std::string stop_reason{ "unknown" };
inline static sc_core::sc_event timeout_event;
inline static sc_core::sc_time timeout{ sc_core::SC_ZERO_TIME };
inline static bool ready{ false };
};
////////////////////////////////////////////////////////////////////////////////
// Module to shutdown SystemC on request
struct Objector_module: sc_core::sc_module
{
Objector_module( sc_core::sc_module_name instance )
: sc_module( instance )
{
SC_HAS_PROCESS( Objector_module );
SC_THREAD( objection_thread );
SC_THREAD( timeout_thread );
if( Objection::get_drain_time() == sc_core::SC_ZERO_TIME ) {
Objection::set_drain_time( sc_core::sc_time( 10, sc_core::SC_NS ));
}
Objection::ready = true;
}
private:
// Shuts down if last objection raised
void objection_thread()
{
auto& MSGID{ Objection::MSGID };
for(;;) {
wait( Objection::stop_event );
// Grab reason while waiting
auto reason = std::exchange( Objection::stop_reason, "unknown"s );
// Allow drainage
DEBUG( "Draining" );
wait( Objection::drain_time );
if( Objection::objections.empty() ) {
std::string note{ "Shutting down " };
note += reason;
INFO( NONE, note );
sc_core::sc_stop();
}
}
}
void timeout_thread()
{
auto& MSGID{ Objection::MSGID };
for(;;) {
wait( Objection::timeout_event );
auto stop_time = sc_core::sc_time_stamp() + Objection::timeout;
sc_core::wait( Objection::timeout, Objection::timeout_event );
if( sc_core::sc_time_stamp() == stop_time ) {
SC_REPORT_WARNING( MSGID, "Timed out - shutting down" );
sc_core::sc_stop();
}
}
}
};
//TAF!
|
#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 ALU12 : public rand_obj {
randv< sc_bv<2> > op ;
randv< sc_uint<12> > a, b ;
ALU12()
: op(this), a(this), b(this)
{
constraint ( (op() != 0x0) || ( 4095 >= a() + b() ) );
constraint ( (op() != 0x1) || ((4095 >= a() - b()) && (b() <= a()) ) );
constraint ( (op() != 0x2) || ( 4095 >= a() * b() ) );
constraint ( (op() != 0x3) || ( b() != 0 ) );
}
friend std::ostream & operator<< (std::ostream & o, ALU12 const & alu)
{
o << alu.op
<< ' ' << alu.a
<< ' ' << alu.b
;
return o;
}
};
int sc_main (int argc, char** argv)
{
boost::timer timer;
ALU12 c;
c.next();
std::cout << "first: " << timer.elapsed() << "\n";
for (int i=0; i<1000; ++i) {
c.next();
}
std::cout << "complete: " << timer.elapsed() << "\n";
return 0;
}
|
/*
* Adder.h
* SystemC_SimpleAdder
*
* Created by Le Gal on 07/05/07.
* Copyright 2007 __MyCompanyName__. All rights reserved.
*
*/
#ifndef _trames_separ_
#define _trames_separ_
#include "systemc.h"
#include <cstdint>
#include "constantes.hpp"
using namespace std;
// #define _DEBUG_SYNCHRO_
SC_MODULE(trames_separ)
{
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_separ)
{
SC_CTHREAD(do_gen, clock.pos());
reset_signal_is(reset,true);
}
private:
void do_gen( )
{
// #ifdef _DEBUG_SYNCHRO_
// uint64_t counter = 0;
// #endif
// float 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
|
/*
* Created on: 21. jun. 2019
* Author: Jonathan Horsted Schougaard
*/
#pragma once
#define SC_INCLUDE_FX
#include <systemc.h>
#include "hwcore/cnn/cnn.h"
#include "hwcore/pipes/pipes.h"
#include "hwcore/hf/helperlib.h"
using namespace hwcore;
SC_MODULE(cpu_sim)
{
sc_fifo_out<pipes::sc_data_stream_t<16*32> > dma_out;
sc_fifo_in<pipes::sc_data_stream_t<16*32> > dma_in;
//sc_out<uint32_t>
};
SC_MODULE(tb_cnn_top)
{
hf::sc_fifo_template<pipes::sc_data_stream_t<16*32> > cpu_sim_2_u1_dma;
cnn::top_cnn<> cnn_u1;
hf::sc_fifo_template<pipes::sc_data_stream_t<16*32> > u1_2_cpu_sim_dma;
};
|
/*
* Adder.h
* SystemC_SimpleAdder
*
* Created by Le Gal on 07/05/07.
* Copyright 2007 __MyCompanyName__. All rights reserved.
*
*/
#include "systemc.h"
SC_MODULE(RAWReader)
{
public:
sc_fifo_out< sc_int<8> > s;
SC_CTOR(RAWReader)
{
SC_THREAD(do_gen);
}
private:
void do_gen( )
{
cout << "(II) RAWReader :: START" << endl;
FILE* f = fopen("/tmp/file.raw", "rb");
if( f == NULL )
{
cout << "(EE) Error opening the input file (/tmp/file.raw)" << endl;
exit( EXIT_FAILURE );
}
while( feof(f) == 0 )
{
int8_t buffer[1024];
uint32_t n = fread(buffer, sizeof(int8_t), 1024, f);
// cout << "(DD) RAWReader (" << n << ") values were read in the file." << endl;
for(uint32_t i = 0; i < n; i += 1)
{
s.write( buffer[i] );
wait(10, SC_NS);
}
}
wait(100, SC_US);
cout << "(II) RAWReader :: STOP" << endl;
sc_stop();
}
};
|
/* 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
|
#include <systemc.h>
#include <systemc-ams.h>
#include <config.hpp>
#include <core.hpp>
#define V_CORE ${vref}
SCA_TDF_MODULE(Core_power)
{
Core* core;
//Data from Functional Instance
sca_tdf::sc_in <double> func_signal;
//Data to Power Bus
sca_tdf::sca_out <double> voltage_state;
sca_tdf::sca_out <double> current_state;
//sca_tdf::sc_out <int> power_to_therm;
SCA_CTOR(Core_power):
func_signal("State_of_Power_From_Functional"),
voltage_state("Voltage_trace_to_Power_Bus"),
current_state("Current_trace_to_Power_Bus")
{}
void set_attributes();
void initialize();
void processing();
Core_power(){}
};
|
#include <map>
#include <sstream>
#include "systemc.h"
#ifndef SC_TRACE_HPP
#define SC_TRACE_HPP
/** SystemC signal and variable tracer wrapper. */
class sc_tracer; // forward declaration for global singleton
class sc_tracer {
public:
/** Global singleton instance */
static sc_tracer tracer;
/** Initializer specifying output file. */
static void init(const char *out_file, sc_time_unit time_unit) {
if (tracer._enabled) {
std::cout << "Opening trace file " << out_file << std::endl;
tracer._tf = sc_create_vcd_trace_file(out_file);
tracer._tf->set_time_unit(1, time_unit);
}
}
/** Trace a signal. */
template <class T>
static void trace(T& value, sc_module_name module_name, const char *signal_name) {
if (tracer._enabled) {
std::ostringstream ss;
ss << module_name << "." << signal_name;
sc_trace(tracer._tf, value, ss.str().c_str());
}
}
/** Trace a signal. */
template <class T>
static void trace(T& value, const char *module_name, const char *signal_name) {
trace(value, sc_module_name(module_name), signal_name);
}
/** Trace a signal. */
template <class T>
static void trace(T& value, std::string module_name, const char *signal_name) {
trace(value, sc_module_name(module_name.c_str()), signal_name);
}
/** Comment. */
static void comment(std::string comment) {
sc_write_comment(tracer._tf, comment);
}
/** Write the file. */
static void close() {
if (tracer._tf) {
std::cout << "Writing trace file" << std::endl;
sc_close_vcd_trace_file(tracer._tf);
tracer._tf = nullptr;
}
}
/** Disable tracing. */
static void disable() {
tracer._enabled = false;
}
/** Enable tracing. */
static void enable() {
tracer._enabled = true;
}
private:
// enable signal
bool _enabled = true;
// local file handle
sc_trace_file *_tf = nullptr;
};
// trackable class types
enum trackable_class_e {
REDUNDANT_COMMAND,
REDUNDANT_RESPONSE,
TRACKABLE_CLASS_NONE
};
#define NUM_TRACKABLE_CLASSES TRACKABLE_CLASS_NONE
// information about tracked data
struct trackable_data_t {
trackable_class_e data_class;
uint32_t publish_time;
};
/** Class to track latency of data across the NoC. */
class latency_tracker; // forward declaration for global singleton
class latency_tracker {
public:
/** Global singleton instance */
static latency_tracker tracker;
/** Publish a tracker. */
template <class T, class U = uint32_t>
static void publish(trackable_class_e data_class, T* data, U* data2 = nullptr) {
// calculate checksum for key
uint32_t chksum = 0;
uint32_t *ptr = (uint32_t*)data;
for (int i = 0; ptr && i < sizeof(T); i += sizeof(uint32_t), ptr++) {
chksum ^= *ptr;
}
ptr = (uint32_t*)data2;
for (int i = 0; ptr && i < sizeof(U); i += sizeof(uint32_t), ptr++) {
chksum ^= *ptr;
}
// insert into map
trackable_data_t data_struct;
data_struct.data_class = data_class;
data_struct.publish_time = (uint32_t)sc_time_stamp().to_double();
tracker._tracked_data[chksum] = data_struct;
}
/** Capture a tracker. */
template <class T, class U = uint32_t>
static void capture(T* data, U* data2 = nullptr) {
// calculate checksum for key
uint32_t chksum = 0;
uint32_t *ptr = (uint32_t*)data;
for (int i = 0; ptr && i < sizeof(T); i += sizeof(uint32_t), ptr++) {
chksum ^= *ptr;
}
ptr = (uint32_t*)data2;
for (int i = 0; ptr && i < sizeof(U); i += sizeof(uint32_t), ptr++) {
chksum ^= *ptr;
}
// fetch from dictionary
std::map<uint32_t, trackable_data_t>::const_iterator it = tracker._tracked_data.find(chksum);
if (it != tracker._tracked_data.end()) {
// found in map
trackable_data_t entry = it->second;
tracker._durations[entry.data_class] += (uint32_t)sc_time_stamp().to_double() - entry.publish_time;
tracker._counts[entry.data_class]++;
// remove from map
tracker._tracked_data.erase(it);
}
}
/** Print the report. */
static void print_report(std::ostream& out = std::cout) {
for (uint32_t c = (uint32_t)REDUNDANT_COMMAND; c < (uint32_t)TRACKABLE_CLASS_NONE; c++) {
out << "Class " << c << ": total duration " << tracker._durations[c] << " over " << tracker._counts[c] << " packets, average of " << ((double)tracker._durations[c] / (double)tracker._counts[c]) << " ticks per packet." << std::endl;
}
out << tracker._tracked_data.size() << " outstanding packets." << std::endl;
}
private:
// list of tracked values
std::map<uint32_t, trackable_data_t> _tracked_data;
// total durations
uint32_t _durations[NUM_TRACKABLE_CLASSES];
uint32_t _counts[NUM_TRACKABLE_CLASSES];
};
#endif // SC_TRACE_HPP
|
#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
|
/*
* Adder.h
* SystemC_SimpleAdder
*
* Created by Le Gal on 07/05/07.
* Copyright 2007 __MyCompanyName__. All rights reserved.
*
*/
#ifndef _Detecteur1_
#define _Detecteur1_
#include "systemc.h"
#include <cstdint>
#include "Doubleur_uint.hpp"
#include "trames_separ1.hpp"
#include "Seuil_calc1.hpp"
// #define _DEBUG_SYNCHRO_
SC_MODULE(Detecteur1)
{
public:
sc_in < bool > clock;
sc_in < bool > reset;
sc_fifo_in < sc_uint<8> > e;
// sc_fifo_in < sc_uint<8> > e2;
sc_fifo_out< sc_uint<8> > s;
// sc_fifo_out< bool > detect1;
SC_CTOR(Detecteur1):
s_calc("s_calc"),
t_sep("t_sep"),
dbl("dbl"),
dbl2scalc("dbl2scalc",1024),
dbl2tsep("dbl2tsep",1024),
detect("detect", 1024)
// detect1("detect1", 4096)
{
dbl.clock(clock);
dbl.reset(reset);
dbl.e(e);
dbl.s1(dbl2scalc);
dbl.s2(dbl2tsep);
s_calc.clock(clock);
s_calc.reset(reset);
s_calc.e(dbl2scalc);
s_calc.detect(detect);
// s_calc.detect1(detect1);
t_sep.clock(clock);
t_sep.reset(reset);
t_sep.e(dbl2tsep);
t_sep.detect(detect);
t_sep.s(s);
}
private:
Seuil_calc1 s_calc;
trames_separ1 t_sep;
DOUBLEUR_U dbl;
sc_fifo< sc_uint<8> > dbl2scalc;
sc_fifo< sc_uint<8> > dbl2tsep;
sc_fifo <bool> detect;
};
#endif
|
/* Copyright 2017 Columbia University, SLD Group */
//
// globals.h - Robert Margelli
// This file several defines and constants: number of registers, data width, opcodes etc.
//
#ifndef GLOBALS_H
#define GLOBALS_H
#include "systemc.h"
// Miscellanous sizes. Most of these can be changed to obtain new architectures.
#define XLEN 32 // Register width. 32 or 64. Currently only 32 is supported.
#define REG_NUM 32 // Number of registers in regfile (x0-x31) // CONST
#define REG_ADDR 5 // Number of reg file address lines // CONST
#define IMEM_SIZE 2048 // Size of instruction memory
#define DMEM_SIZE 2048 // Size of data memory
#define DATA_SIZE 32 // Size of data in DMEM // CONST
#define PC_LEN 32 // Width of PC register
#define ALUOP_SIZE 5 // Size of aluop signal.
#define ALUSRC_SIZE 2 // Size of alusrc signal.
#define BYTE 8 // 8-bits.
#define ZIMM_SIZE 5 // Bit-length of zimm field in CSRRWI, CSRRSI, CSRRCI
#define SHAMT 5 // Number of bits used for the shift value in shift operations.
// Values for CSR and traps
#define LOG2_NUM_CAUSES 3 // Log2 of number of trap causes
#define CSR_NUM 11 // Number of CSR registers (including Performance Counters).
#define CSR_IDX_LEN 4 // Log2 of CSR_NUM // TODO: this should be rewritten into something like log2(CSR_NUM)
#define PRF_CNT_NUM 1 // Number of Performance Counters.
#define CSR_ADDR 12 // CSRs are on a 12-bit addressing space.
#define LOG2_CSR_OP_NUM 2 // Log2 of number of operations on CSR.
#define CSR_OP_WR 1 // CSR write operation.
#define CSR_OP_SET 2 // CSR set operation.
#define CSR_OP_CLR 3 // CSR clear operation.
#define CSR_OP_NULL 0 // Not a CSR operation.
// Instruction fields sizes. All contant.
#define INSN_LEN 32
#define OPCODE_SIZE 5 // Note: in reality opcodes are on 7 bits but bits [1:0] are statically at '1'. This gives us a saving of approximately 300 in 'Total Area' of the fedec stage.
#define FUNCT7_SIZE 7
#define FUNCT3_SIZE 3
#define RS1_SIZE 5
#define RS2_SIZE 5
#define RD_SIZE 5
#define IMM_ITYPE 12 // imm[11:0]
#define IMM_STYPE1 7 // imm[11:5]
#define IMM_STYPE2 5 // imm[4:0]
#define IMM_SBTYPE1 7 // imm[12|10:5]
#define IMM_SBTYPE2 5 // imm[4:1|11]
#define IMM_UTYPE 20 // imm[31:12]
#define IMM_UJTYPE 20 // imm[20|10:1|11|19:12]
/* Supported instructions 45+8=53 :
* add, sll, slt, sltu, xor, srl, or, and, sub, sra,
* addi, slti, sltiu, xori, ori, andi, slli, srli, srai,
* sb, sh, sw, lb, lh, lw, lbu, lhu,
* beq, bne, blt, bge, bltu, bgeu,
* lui, auipc, jalr, jal,
* ebreak, ecall, csrrw, csrrs, csrrc, csrrwi, csrrsi, csrrci,
* mul, mulh, mulhsu, mulhu, div, divu, rem, remu
*
* i.e. all RV32I except {FENCE, FENCE.I} and all RV32M
* NB. ETH/Bologna's RI5CY does not support FENCE and FENCE.I
*/
/* Opcodes as integers. For control word generation switch case. */
#define OPC_ADD 12 // Original value is 51, but we trim the opcode's LSBs which are statically at 2'b11 for all instructions.
#define OPC_SLL OPC_ADD
#define OPC_SLT OPC_ADD
#define OPC_SLTU OPC_ADD
#define OPC_XOR OPC_ADD
#define OPC_SRL OPC_ADD
#define OPC_OR OPC_ADD
#define OPC_AND OPC_ADD
#define OPC_SUB OPC_ADD
#define OPC_SRA OPC_ADD
#define OPC_MUL OPC_ADD
#define OPC_MULH OPC_ADD
#define OPC_MULHSU OPC_ADD
#define OPC_MULHU OPC_ADD
#define OPC_DIV OPC_ADD
#define OPC_DIVU OPC_ADD
#define OPC_REM OPC_ADD
#define OPC_REMU OPC_ADD
#define OPC_ADDI 4 // Original value is 19, but we trim the opcode's LSBs which are statically at 2'b11 for all instructions.
#define OPC_SLTI OPC_ADDI
#define OPC_SLTIU OPC_ADDI
#define OPC_XORI OPC_ADDI
#define OPC_ORI OPC_ADDI
#define OPC_ANDI OPC_ADDI
#define OPC_SLLI OPC_ADDI
#define OPC_SRLI OPC_ADDI
#define OPC_SRAI OPC_ADDI
#define OPC_SB 8 // Original value is 35, but we trim the opcode's LSBs which are statically at 2'b11 for all instructions.
#define OPC_SH OPC_SB
#define OPC_SW OPC_SB
#define OPC_LB 0 // Original value is 3, but we trim the opcode's LSBs which are statically at 2'b11 for all instructions.
#define OPC_LH OPC_LB
#define OPC_LW OPC_LB
#define OPC_LBU OPC_LB
#define OPC_LHU OPC_LB
#define OPC_BEQ 24 // Original value is 99, but we trim the opcode's LSBs which are statically at 2'b11 for all instructions.
#define OPC_BNE OPC_BEQ
#define OPC_BLT OPC_BEQ
#define OPC_BGE OPC_BEQ
#define OPC_BLTU OPC_BEQ
#define OPC_BGEU OPC_BEQ
#define OPC_LUI 13 // Original value is 55, but we trim the opcode's LSBs which are statically at 2'b11 for all instructions.
#define OPC_AUIPC 5 // Original value is 23, but we trim the opcode's LSBs which are statically at 2'b11 for all instructions.
#define OPC_JAL 27 // Original value is 111, but we trim the opcode's LSBs which are statically at 2'b11 for all instructions.
#define OPC_JALR 25 // Original value is 103, but we trim the opcode's LSBs which are statically at 2'b11 for all instructions.
#define OPC_SYSTEM 28 // Original value is 115, but we trim the opcode's LSBs which are statically at 2'b11 for all instructions.
#define OPC_EBREAK OPC_SYSTEM
#define OPC_ECALL OPC_SYSTEM
#define OPC_CSRRW OPC_SYSTEM
#define OPC_CSRRS OPC_SYSTEM
#define OPC_CSRRC OPC_SYSTEM
#define OPC_CSRRWI OPC_SYSTEM
#define OPC_CSRRSI OPC_SYSTEM
#define OPC_CSRRCI OPC_SYSTEM
/* Funct3 as integers. For control word generation switch case. */
#define FUNCT3_ADD 0
#define FUNCT3_SLL 1
#define FUNCT3_SLT 2
#define FUNCT3_SLTU 3
#define FUNCT3_XOR 4
#define FUNCT3_SRL 5
#define FUNCT3_OR 6
#define FUNCT3_AND 7
#define FUNCT3_SUB 0
#define FUNCT3_SRA 5
#define FUNCT3_MUL 0
#define FUNCT3_MULH 1
#define FUNCT3_MULHSU 2
#define FUNCT3_MULHU 3
#define FUNCT3_DIV 4
#define FUNCT3_DIVU 5
#define FUNCT3_REM 6
#define FUNCT3_REMU 7
#define FUNCT3_ADDI 0
#define FUNCT3_SLTI 2
#define FUNCT3_SLTIU 3
#define FUNCT3_XORI 4
#define FUNCT3_ORI 6
#define FUNCT3_ANDI 7
#define FUNCT3_SLLI 1
#define FUNCT3_SRLI 5
#define FUNCT3_SRAI 5
#define FUNCT3_SB 0
#define FUNCT3_SH 1
#define FUNCT3_SW 2
#define FUNCT3_LB 0
#define FUNCT3_LH 1
#define FUNCT3_LW 2
#define FUNCT3_LBU 4
#define FUNCT3_LHU 5
#define FUNCT3_BEQ 0
#define FUNCT3_BNE 1
#define FUNCT3_BLT 4
#define FUNCT3_BGE 5
#define FUNCT3_BLTU 6
#define FUNCT3_BGEU 7
#define FUNCT3_JALR 0
#define FUNCT3_EBREAK 0
#define FUNCT3_ECALL 0
#define FUNCT3_CSRRW 1
#define FUNCT3_CSRRS 2
#define FUNCT3_CSRRC 3
#define FUNCT3_CSRRWI 5
#define FUNCT3_CSRRSI 6
#define FUNCT3_CSRRCI 7
/* Funct7 as integers. For control word generation switch case. */
#define FUNCT7_ADD 0
#define FUNCT7_SLL FUNCT7_ADD
#define FUNCT7_SLT FUNCT7_ADD
#define FUNCT7_SLTU FUNCT7_ADD
#define FUNCT7_XOR FUNCT7_ADD
#define FUNCT7_SRL FUNCT7_ADD
#define FUNCT7_OR FUNCT7_ADD
#define FUNCT7_AND FUNCT7_ADD
#define FUNCT7_SUB 32
#define FUNCT7_SRA FUNCT7_SUB
#define FUNCT7_MUL 1
#define FUNCT7_MULH FUNCT7_MUL
#define FUNCT7_MULHSU FUNCT7_MUL
#define FUNCT7_MULHU FUNCT7_MUL
#define FUNCT7_DIV FUNCT7_MUL
#define FUNCT7_DIVU FUNCT7_MUL
#define FUNCT7_REM FUNCT7_MUL
#define FUNCT7_REMU FUNCT7_MUL
#define FUNCT7_SLLI 0
#define FUNCT7_SRLI FUNCT7_SLLI
#define FUNCT7_SRAI 32
#define FUNCT7_EBREAK 0 // Note: strictly speaking ebreak and ecall don't have a funct7 field, but their [31-20] bits
#define FUNCT7_ECALL 1 // are used to distinguish between them. I call these FUNCT7 for the sake of modularity.
/* ALUOPS */
#define ALUOP_NULL 0
#define ALUOP_ADD 1
#define ALUOP_SLL 2
#define ALUOP_SLT 3
#define ALUOP_SLTU 4
#define ALUOP_XOR 5
#define ALUOP_SRL 6
#define ALUOP_OR 7
#define ALUOP_AND 8
#define ALUOP_SUB 9
#define ALUOP_SRA 10
#define ALUOP_MUL 11
#define ALUOP_MULH 12
#define ALUOP_MULHSU 13
#define ALUOP_MULHU 14
#define ALUOP_DIV 15
#define ALUOP_DIVU 16
#define ALUOP_REM 17
#define ALUOP_REMU 18
// Integer immediate operation's aluops coincide with their r-type counterparts
#define ALUOP_ADDI ALUOP_ADD
#define ALUOP_SLTI ALUOP_SLT
#define ALUOP_SLTIU ALUOP_SLTU
#define ALUOP_XORI ALUOP_XOR
#define ALUOP_ORI ALUOP_OR
#define ALUOP_ANDI ALUOP_AND
#define ALUOP_SLLI 19
#define ALUOP_SRLI 20
#define ALUOP_SRAI 21
#define ALUOP_LUI 22
#define ALUOP_AUIPC 23
#define ALUOP_JAL 24
#define ALUOP_JALR ALUOP_JAL // like JAL, the ALU operation is < rd = pc + 4 >
#define ALUOP_CSRRW 25
#define ALUOP_CSRRS 26
#define ALUOP_CSRRC 27
#define ALUOP_CSRRWI 28
#define ALUOP_CSRRSI 29
#define ALUOP_CSRRCI 30
/* ALU Source discrimination values */
#define ALUSRC_RS2 0
#define ALUSRC_IMM_I 1
#define ALUSRC_IMM_S 2
#define ALUSRC_IMM_U 3
/* Load and store discrimination values to be assigned to the ld or st signals */
#define NO_LOAD 5
#define LB_LOAD 0
#define LH_LOAD 1
#define LW_LOAD 2
#define LBU_LOAD 3
#define LHU_LOAD 4
#define NO_STORE 3
#define SB_STORE 0
#define SH_STORE 1
#define SW_STORE 2
/* Trap causes: see page 35 of RISC-V privileged ISA draft V1.10. */
#define NULL_CAUSE 10 // 10 is actually reserved in the specs but we use it to indicate no cause.
#define EBREAK_CAUSE 3
#define ECALL_CAUSE 11
#define ILL_INSN_CAUSE 2
/* Control Status Registers' addresses */
#define USTATUS_A 0x000
#define MSTATUS_A 0x300
#define MISA_A 0x301
#define MTVECT_A 0x305
#define MEPC_A 0x341
#define MCAUSE_A 0x342
#define MCYCLE_A 0xB00
#define MARCHID_A 0xF12
#define MIMPID_A 0xF13
#define MINSTRET_A 0xF02
#define MHARTID_A 0xF14
#define USTATUS_I 0
#define MSTATUS_I 1
#define MISA_I 2
#define MTVECT_I 3
#define MEPC_I 4
#define MCAUSE_I 5
#define MCYCLE_I 6
#define MARCHID_I 7
#define MIMPID_I 8
#define MINSTRET_I 9
#define MHARTID_I 10
#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 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
|
/*******************************************************************************
* gpio_mf.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design
*******************************************************************************
* Description:
* Implements a SystemC model of a generic multi-function GPIO with
* analog function.
*******************************************************************************
* 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 "gpio_mf.h"
#include "info.h"
/*********************
* Function: set_function()
* inputs: new function
* outputs: none
* returns: none
* globals: none
*
* Sets the function, can be GPIO or ANALOG.
*/
void gpio_mf::set_function(gpio_function_t newfunction) {
/* We ignore unchanged function requests. */
if (newfunction == function) return;
/* We also ignore illegal function requests. */
if (newfunction == GPIOMF_ANALOG) {
PRINTF_WARN("GPIOMF", "%s cannot be set to ANALOG", name())
return;
}
/* To select a function there must be at least the fin or the fout
* available. The fen is optional. Ideal would be to require all three
* but there are some peripherals that need only one of these pins,
* so to make life easier, we require at least a fin or a fout.
*/
if (newfunction >= GPIOMF_FUNCTION &&
(newfunction-1 >= fin.size() && newfunction-1 >= fout.size())) {
PRINTF_WARN("GPIOMF", "%s cannot be set to FUNC%d", name(),
newfunction)
return;
}
/* When we change to the GPIO function, we set the driver high and set
* the function accordingly.
*/
if (newfunction == GPIOMF_GPIO) {
PRINTF_INFO("GPIOMF", "%s set to GPIO mode", name())
function = newfunction;
driveok = true;
/* set_val() handles the driver. */
gpio_base::set_val(pinval);
}
else {
PRINTF_INFO("GPIOMF", "%s set to FUNC%d", name(), newfunction);
function = newfunction;
}
/* And we set any notifications we need. */
updatefunc.notify();
updatereturn.notify();
}
/*********************
* Function: get_function()
* inputs: none
* outputs: none
* returns: current function
* globals: none
*
* Returns the current function.
*/
gpio_function_t gpio_mf::get_function() {
return function;
}
/*********************
* Function: set_val()
* inputs: new value
* outputs: none
* returns: none
* globals: none
*
* Changes the value to set onto the GPIO, if GPIO function is set.
*/
void gpio_mf::set_val(bool newval) {
pinval = newval;
if (function == GPIOMF_GPIO) gpio_base::set_val(newval);
}
/*********************
* Thread: drive_return()
* inputs: none
* outputs: none
* returns: none
* globals: none
*
* Drives the return path from the pin onto the alternate functions.
*/
void gpio_mf::drive_return() {
sc_logic pinsamp;
bool retval;
int func;
/* We begin driving all returns to low. */
for (func = 0; func < fout.size(); func = func + 1) fout[func]->write(false);
/* Now we go into the loop waiting for a return or a change in function. */
for(;;) {
/*
printf("<<%s>>: U:%d pin:%d:%c @%s\n",
name(), updatereturn.triggered(), pin.event(), pin.read().to_char(),
sc_time_stamp().to_string().c_str());
*/
pinsamp = pin.read();
/* If the sampling value is Z or X and we have a function set, we
* then issue a warning. We also do not warn at time 0s or we get some
* dummy initialization warnings.
*/
if (sc_time_stamp() != sc_time(0, SC_NS) &&
(pinsamp == SC_LOGIC_X || pinsamp == SC_LOGIC_Z) &&
function != GPIOMF_ANALOG && function != GPIOMF_GPIO) {
retval = false;
PRINTF_WARN("GPIOMF", "can't return '%c' onto FUNC%d",
pinsamp.to_char(), function)
}
else if (pinsamp == SC_LOGIC_1) retval = true;
else retval = false;
for (func = 0; func < fout.size(); func = func + 1)
if (function == GPIOMF_ANALOG) fout[func]->write(false);
else if (function == GPIOMF_GPIO) fout[func]->write(false);
else if (func != function-1) fout[func]->write(false);
else fout[func]->write(retval);
wait();
}
}
/*********************
* Thread: drive_func()
* inputs: none
* outputs: none
* returns: none
* globals: none
*
* Drives the value from an alternate function onto the pins. This does not
* actually drive the value, it just places it in the correct variables so that
* the drive() thread handles it.
*/
void gpio_mf::drive_func() {
for(;;) {
/* We only use this thread if we have an alternate function selected. */
if (function != GPIOMF_GPIO && function-1 < fin.size()) {
/* We check if the fen is ok. If this function has no fen we default
* it to enabled.
*/
if (function-1 < fen.size() || fen[function-1]->read() == true)
driveok = true;
else driveok = false;
/* Note that we do not set the pin val, just call set_val to handle
* the pin drive.
*/
gpio_base::set_val(fin[function-1]->read());
}
/* We now wait for a change. If the function is no selected or if we
* have an illegal function selected, we have to wait for a change
* in the function selection.
*/
if (function == GPIOMF_GPIO || function-1 >= fin.size())
wait(updatefunc);
/* If we have a valid function selected, we wait for either the
* function or the fen to change. We also have to wait for a
* function change.
*/
else if (fen.size() >= function-1)
wait(updatefunc | fin[function-1]->value_changed_event());
else wait(updatefunc | fin[function-1]->value_changed_event()
| fen[function-1]->value_changed_event());
}
}
|
/*
* 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
|
#pragma once
/** @file report.hpp
@brief Reporting macro extensions
This is a simplified version of David's reporting extensions.
The basic idea is to simplify syntax when reporting on messages more
complex than a basic string. Also, simplifies specification of the
message type (aka message identifier). See instructions for usage.
There are three macros, several requirements, one limitation, and
some instructions below. Read on...
Macros
------
1. REPORT(type,stream) -- trivially improves SC_REPORT_(INFO,WARNING,ERROR,FATAL)
2. INFO(level,stream) -- improves on SC_REPORT_INFO_VERB
3. DEBUG(stream) -- allows sc_object specific debugging
Requirements
------------
1. Assumes SystemC
2. Define MSGID string anytime these macros are used.
3. If using the DEBUG macro, then commandline.hpp must be available
4. To disable the DEBUG macro, define NDEBUG
Limitations
-----------
If your streaming expression (see instructions) contains commas, then
you must surround that element with parentheses due to limitations of
pre-processor macros.
Instructions
------------
### Step 1
Include this at the top of any file where the macros are used.
```c++
#include "report.cpp"
```
### Step 2
Define the message type with a file local variable, MSGID as follows:
In modules, channels, classes or structs:
```c++
inline static constexpr char const * const MSGID
{ "/COMPANY/PROJECT/MODULE" };
```
Or files without a class:
```c++
namespace {
constexpr char const * const MSGID
{ "/COMPANY/PROJECT/MODULE" };
}
```
### Step 3
Insert the macros where you would normally use SC_REPORT_* macros. Here are
some simple examples:
REPORT( WARNING, "Possible problem detected" );
INFO( NONE, "Version " << version );
DEBUG( "Sending packet " << packet );
### Step 4 (for DEBUG macro)
Make sure you have set the verbosity level to SC_DEBUG. You might consider
using the Commandline::has_opt("-debug") to conditionallly set this.
At run-time, add command-line arguments to specify the instances you want to
debug:
% run.x -debug=observer -debug=splitter # debugs only for specified elements
% run.x -debugall # turns on all DEBUG messages
********************************************************************************
*/
#include "systemc.hpp"
#include <string>
#include <iomanip>
#include <sstream>
struct Report {
inline static std::ostringstream mout;
};
// For type: WARNING, ERROR, FATAL
#define REPORT(type,stream) \
do { \
Report::mout << std::dec << stream << std::ends; \
auto str = Report::mout.str(); Report::mout.str(""); \
SC_REPORT_##type( MSGID, str.c_str() ); \
} while (0)
// For level: NONE, LOW, MEDIUM, HIGH, DEBUG
#define INFO(level,stream) \
do { \
if( sc_core::sc_report_handler::get_verbosity_level() \
>= (sc_core::SC_##level) ) { \
Report::mout << std::dec << stream; \
auto now = sc_core::sc_time_stamp(); \
if( now > sc_core::SC_ZERO_TIME \
or sc_core::sc_get_status() >= sc_core::SC_START_OF_SIMULATION ) { \
Report::mout << std::dec << " at " << now; \
} \
Report::mout << std::ends; \
if( (sc_core::SC_##level) > sc_core::SC_DEBUG ) { \
std::string id{"DEBUG("}; \
id+=__FILE__ ; id+=":"; id+=std::to_string(__LINE__)+")"; \
size_t p0=id.find("/"),p1=id.find_last_of("/"); \
if(p1!=std::string::npos) id.erase(p0,p1-p0+1); \
auto str = Report::mout.str(); Report::mout.str(""); \
SC_REPORT_INFO_VERB( id.c_str(), str.c_str(), (sc_core::SC_##level) ); \
} else { \
auto str = Report::mout.str(); Report::mout.str(""); \
SC_REPORT_INFO_VERB( MSGID, str.c_str(), (sc_core::SC_##level) ); \
} \
} \
} while (0)
#ifdef NDEBUG
#define DEBUG()
#else
#include "commandline.hpp"
#define DEBUG(stream) do { \
if( sc_core::sc_report_handler::get_verbosity_level() >= sc_core::SC_DEBUG \
and ( Commandline::has_opt("-debugall") \
or Commandline::has_opt("-debug="s + basename() ) ) ) { \
INFO(DEBUG,stream); \
} \
} while(0)
#endif
// TAF!
|
/*
* Adder.h
* SystemC_SimpleAdder
*
* Created by Le Gal on 07/05/07.
* Copyright 2007 __MyCompanyName__. All rights reserved.
*
*/
#ifndef _DOUBLEUR_
#define _DOUBLEUR_
#include "systemc.h"
#include <cstdint>
SC_MODULE(DOUBLEUR)
{
public:
sc_in < bool > clock;
sc_in < bool > reset;
sc_fifo_in < sc_int<8> > e;
sc_fifo_out< sc_int<8> > s1;
sc_fifo_out< sc_int<8> > s2;
SC_CTOR(DOUBLEUR)
{
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
|
//-----------------------------------------------------
// A 4 bit up-counter with synchronous active high reset
// and with active high enable signal
// Example from www.asic-world.com
//-----------------------------------------------------
#ifndef FIRST_COUNTER_HPP
#define FIRST_COUNTER_HPP
#include "systemc.h"
SC_MODULE(first_counter)
{
// Clock input of the design
sc_in_clk clock;
// Active high, synchronous Reset input
sc_in<bool> reset;
// Active high enable signal for counter
sc_in<bool> enable;
// 4 bit vector output of the counter
sc_out<sc_uint<4> > counter_out;
//------------Local Variables Here---------------------
sc_uint<4> count;
//------------Code Starts Here-------------------------
// Constructor for the counter
// Since this counter is a positive edge trigged one,
// We trigger the below block with respect to positive
// edge of the clock and also when ever reset changes state
SC_CTOR(first_counter);
// Below function implements actual counter logic
void incr_count();
};
#endif // FIRST_COUNTER_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");
|
//****************************************************************************************
// 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 <vector>
#include "RandBase.hpp"
namespace crave {
/**
* constructor, destructor and set operator
*/
#define RANDV_COMMON_INTERFACE(Typename) \
public: \
randv(rand_obj_base* parent = 0) : randv_base<Typename>(parent) {} \
randv(const randv& other) : randv_base<Typename>(other) {} \
randv<Typename>& operator=(const randv<Typename>& i) { \
this->value = i.value; \
return *this; \
} \
randv<Typename>& operator=(Typename i) { \
this->value = i; \
return *this; \
}
/**
* arithmetic operators
*/
#define RANDV_ARITHMETIC_INTERFACE(Typename) \
public: \
randv<Typename>& operator++() { \
++(this->value); \
return *this; \
} \
Typename operator++(int) { \
Typename tmp = this->value; \
++(this->value); \
return tmp; \
} \
randv<Typename>& operator--() { \
--(this->value); \
return *this; \
} \
Typename operator--(int) { \
Typename tmp = this->value; \
--(this->value); \
return tmp; \
} \
randv<Typename>& operator+=(Typename i) { \
this->value += i; \
return *this; \
} \
randv<Typename>& operator-=(Typename i) { \
this->value -= i; \
return *this; \
} \
randv<Typename>& operator*=(Typename i) { \
this->value *= i; \
return *this; \
} \
randv<Typename>& operator/=(Typename i) { \
this->value /= i; \
return *this; \
} \
randv<Typename>& operator%=(Typename i) { \
/*this->value %= i;*/ \
this->value = fmod (this->value, i); \
return *this; \
}
/**
* bitwise operators
*/
#define RANDV_BITWISE_INTERFACE(Typename) \
randv<Typename>& operator&=(Typename i) { \
this->value &= i; \
return *this; \
} \
randv<Typename>& operator|=(Typename i) { \
this->value |= i; \
return *this; \
} \
randv<Typename>& operator^=(Typename i) { \
this->value ^= i; \
return *this; \
} \
randv<Typename>& operator<<=(Typename i) { \
this->value <<= i; \
return *this; \
} \
randv<Typename>& operator>>=(Typename i) { \
this->value >>= i; \
return *this; \
}
/**
* other basic randv functions
*/
#define RANDV_PRIM_INTERFACE(Typename) \
public: \
void gather_values(std::vector<int64_t>* ch) { ch->push_back(static_cast<int64_t>(value)); } \
bool next() { \
static distribution<Typename> dist; \
value = dist.nextValue(); \
return true; \
}
/**
* random boolean variable
*/
template <>
struct randv<bool> : public randv_base<bool> {
RANDV_COMMON_INTERFACE(bool);
RANDV_PRIM_INTERFACE(bool);
// RANDV_BITWISE_INTERFACE(bool);
};
/**
* random integer variables
*/
// for all C/C++ built-in integer types
#define RANDV_INTEGER_TYPE(typename) \
template <> \
struct randv<typename> : public randv_base<typename> { \
RANDV_COMMON_INTERFACE(typename); \
RANDV_PRIM_INTERFACE(typename); \
RANDV_ARITHMETIC_INTERFACE(typename); \
RANDV_BITWISE_INTERFACE(typename); \
};
RANDV_INTEGER_TYPE(int);
RANDV_INTEGER_TYPE(unsigned int);
RANDV_INTEGER_TYPE(char);
RANDV_INTEGER_TYPE(signed char);
RANDV_INTEGER_TYPE(unsigned char);
RANDV_INTEGER_TYPE(short);
RANDV_INTEGER_TYPE(unsigned short);
RANDV_INTEGER_TYPE(long);
RANDV_INTEGER_TYPE(unsigned long);
RANDV_INTEGER_TYPE(long long);
RANDV_INTEGER_TYPE(unsigned long long);
} // namespace crave
/*!
*\ingroup oldAPI
*\deprecated As all old API entities, it is recommended to use the \ref newAPI "new API". The equivalent in the new API is \ref crave::crv_variable
*\struct crave::randv
*\brief A randomizable variable of type T.
*
* <p>This struct 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 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_ENUM </p><p>
* A randv<T> also supports basic binary and arithmetic operations +=,-=,*=,/=,=,|=,&=,%=,<<=,>>=,^=. A very important operator is the operator (). This operator can be used to get a writereference to the randv which is used in the definition of constraints. For details see crave::Constraint</p>
*/
|
#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
|
#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
|
#pragma once
#include "systemc.hpp"
#include <string>
struct Commandline
{
// Return index if a command-line argument beginning with opt exists; otherwise, zero
inline static size_t has_opt( std::string opt )
{
for( int i = 1; i < sc_core::sc_argc(); ++i ) {
std::string arg{ sc_core::sc_argv()[ i ] };
if( arg.find( opt ) == 0 ) return i;
}
return 0;
}
private:
[[maybe_unused]]inline constexpr static char const * const
MSGID{ "/Doulos/Example/Commandline" };
};
|
/*
* Adder.h
* SystemC_SimpleAdder
*
* Created by Le Gal on 07/05/07.
* Copyright 2007 __MyCompanyName__. All rights reserved.
*
*/
#ifndef _trames_separ2_
#define _trames_separ2_
#include "systemc.h"
#include <cstdint>
#include "constantes.hpp"
using namespace std;
// #define _DEBUG_SYNCHRO_
SC_MODULE(trames_separ2)
{
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_separ2)
{
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
|
// ----------------------------------------------------------------------------
// SystemC SCVerify Flow -- sysc_sim_trans.cpp
//
// HLS version: 10.4b/841621 Production Release
// HLS date: Thu Oct 24 17:20:07 PDT 2019
// Flow Packages: HDL_Tcl 8.0a, SCVerify 10.4
//
// Generated by: billyk@cad.eecs.harvard.edu
// Generated date: Fri Apr 17 23:30:03 EDT 2020
//
// ----------------------------------------------------------------------------
//
// -------------------------------------
// sysc_sim_wrapper
// Represents a new SC_MODULE having the same interface as the original model SysTop_rtl
// -------------------------------------
//
#ifndef TO_QUOTED_STRING
#define TO_QUOTED_STRING(x) TO_QUOTED_STRING1(x)
#define TO_QUOTED_STRING1(x) #x
#endif
// Hold time for the SCVerify testbench to account for the gate delay after downstream synthesis in pico second(s)
// Hold time value is obtained from 'top_gate_constraints.cpp', which is generated at the end of RTL synthesis
#ifdef CCS_DUT_GATE
extern double __scv_hold_time;
#else
double __scv_hold_time = 0.0; // default for non-gate simulation is zero
#endif
#ifndef SC_USE_STD_STRING
#define SC_USE_STD_STRING
#endif
#include "../../../../../cmod/lab3/SysTop/SysTop.h"
#include <systemc.h>
#include <mc_scverify.h>
#include <mt19937ar.c>
#include "mc_dut_wrapper.h"
namespace CCS_RTL {
class sysc_sim_wrapper : public sc_module
{
public:
// Interface Ports
sc_core::sc_in<bool > clk;
sc_core::sc_in<bool > rst;
Connections::In<InputSetup::WriteReq, Connections::SYN_PORT > write_req;
Connections::In<ac_int<6, false >, Connections::SYN_PORT > start;
Connections::In<ac_int<8, true >, Connections::SYN_PORT > weight_in_vec[8];
Connections::Out<ac_int<32, true >, Connections::SYN_PORT > accum_out_vec[8];
// Data objects
sc_signal< bool > ccs_rtl_SIG_clk;
sc_signal< sc_logic > ccs_rtl_SIG_rst;
sc_signal< sc_logic > ccs_rtl_SIG_write_req_val;
sc_signal< sc_logic > ccs_rtl_SIG_write_req_rdy;
sc_signal< sc_lv<69> > ccs_rtl_SIG_write_req_msg;
sc_signal< sc_logic > ccs_rtl_SIG_start_val;
sc_signal< sc_logic > ccs_rtl_SIG_start_rdy;
sc_signal< sc_lv<6> > ccs_rtl_SIG_start_msg;
sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_0_val;
sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_1_val;
sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_2_val;
sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_3_val;
sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_4_val;
sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_5_val;
sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_6_val;
sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_7_val;
sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_0_rdy;
sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_1_rdy;
sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_2_rdy;
sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_3_rdy;
sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_4_rdy;
sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_5_rdy;
sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_6_rdy;
sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_7_rdy;
sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_0_msg;
sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_1_msg;
sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_2_msg;
sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_3_msg;
sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_4_msg;
sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_5_msg;
sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_6_msg;
sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_7_msg;
sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_0_val;
sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_1_val;
sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_2_val;
sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_3_val;
sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_4_val;
sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_5_val;
sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_6_val;
sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_7_val;
sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_0_rdy;
sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_1_rdy;
sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_2_rdy;
sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_3_rdy;
sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_4_rdy;
sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_5_rdy;
sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_6_rdy;
sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_7_rdy;
sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_0_msg;
sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_1_msg;
sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_2_msg;
sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_3_msg;
sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_4_msg;
sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_5_msg;
sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_6_msg;
sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_7_msg;
// Named Objects
// Module instance pointers
HDL::ccs_DUT_wrapper ccs_rtl;
// Declare processes (SC_METHOD and SC_THREAD)
void update_proc();
// Constructor
SC_HAS_PROCESS(sysc_sim_wrapper);
sysc_sim_wrapper(
const sc_module_name& nm
)
: ccs_rtl(
"ccs_rtl",
TO_QUOTED_STRING(TOP_HDL_ENTITY)
)
, clk("clk")
, rst("rst")
, write_req("write_req")
, start("start")
, weight_in_vec()
, accum_out_vec()
, ccs_rtl_SIG_clk("ccs_rtl_SIG_clk")
, ccs_rtl_SIG_rst("ccs_rtl_SIG_rst")
, ccs_rtl_SIG_write_req_val("ccs_rtl_SIG_write_req_val")
, ccs_rtl_SIG_write_req_rdy("ccs_rtl_SIG_write_req_rdy")
, ccs_rtl_SIG_write_req_msg("ccs_rtl_SIG_write_req_msg")
, ccs_rtl_SIG_start_val("ccs_rtl_SIG_start_val")
, ccs_rtl_SIG_start_rdy("ccs_rtl_SIG_start_rdy")
, ccs_rtl_SIG_start_msg("ccs_rtl_SIG_start_msg")
, ccs_rtl_SIG_weight_in_vec_0_val("ccs_rtl_SIG_weight_in_vec_0_val")
, ccs_rtl_SIG_weight_in_vec_1_val("ccs_rtl_SIG_weight_in_vec_1_val")
, ccs_rtl_SIG_weight_in_vec_2_val("ccs_rtl_SIG_weight_in_vec_2_val")
, ccs_rtl_SIG_weight_in_vec_3_val("ccs_rtl_SIG_weight_in_vec_3_val")
, ccs_rtl_SIG_weight_in_vec_4_val("ccs_rtl_SIG_weight_in_vec_4_val")
, ccs_rtl_SIG_weight_in_vec_5_val("ccs_rtl_SIG_weight_in_vec_5_val")
, ccs_rtl_SIG_weight_in_vec_6_val("ccs_rtl_SIG_weight_in_vec_6_val")
, ccs_rtl_SIG_weight_in_vec_7_val("ccs_rtl_SIG_weight_in_vec_7_val")
, ccs_rtl_SIG_weight_in_vec_0_rdy("ccs_rtl_SIG_weight_in_vec_0_rdy")
, ccs_rtl_SIG_weight_in_vec_1_rdy("ccs_rtl_SIG_weight_in_vec_1_rdy")
, ccs_rtl_SIG_weight_in_vec_2_rdy("ccs_rtl_SIG_weight_in_vec_2_rdy")
, ccs_rtl_SIG_weight_in_vec_3_rdy("ccs_rtl_SIG_weight_in_vec_3_rdy")
, ccs_rtl_SIG_weight_in_vec_4_rdy("ccs_rtl_SIG_weight_in_vec_4_rdy")
, ccs_rtl_SIG_weight_in_vec_5_rdy("ccs_rtl_SIG_weight_in_vec_5_rdy")
, ccs_rtl_SIG_weight_in_vec_6_rdy("ccs_rtl_SIG_weight_in_vec_6_rdy")
, ccs_rtl_SIG_weight_in_vec_7_rdy("ccs_rtl_SIG_weight_in_vec_7_rdy")
, ccs_rtl_SIG_weight_in_vec_0_msg("ccs_rtl_SIG_weight_in_vec_0_msg")
, ccs_rtl_SIG_weight_in_vec_1_msg("ccs_rtl_SIG_weight_in_vec_1_msg")
, ccs_rtl_SIG_weight_in_vec_2_msg("ccs_rtl_SIG_weight_in_vec_2_msg")
, ccs_rtl_SIG_weight_in_vec_3_msg("ccs_rtl_SIG_weight_in_vec_3_msg")
, ccs_rtl_SIG_weight_in_vec_4_msg("ccs_rtl_SIG_weight_in_vec_4_msg")
, ccs_rtl_SIG_weight_in_vec_5_msg("ccs_rtl_SIG_weight_in_vec_5_msg")
, ccs_rtl_SIG_weight_in_vec_6_msg("ccs_rtl_SIG_weight_in_vec_6_msg")
, ccs_rtl_SIG_weight_in_vec_7_msg("ccs_rtl_SIG_weight_in_vec_7_msg")
, ccs_rtl_SIG_accum_out_vec_0_val("ccs_rtl_SIG_accum_out_vec_0_val")
, ccs_rtl_SIG_accum_out_vec_1_val("ccs_rtl_SIG_accum_out_vec_1_val")
, ccs_rtl_SIG_accum_out_vec_2_val("ccs_rtl_SIG_accum_out_vec_2_val")
, ccs_rtl_SIG_accum_out_vec_3_val("ccs_rtl_SIG_accum_out_vec_3_val")
, ccs_rtl_SIG_accum_out_vec_4_val("ccs_rtl_SIG_accum_out_vec_4_val")
, ccs_rtl_SIG_accum_out_vec_5_val("ccs_rtl_SIG_accum_out_vec_5_val")
, ccs_rtl_SIG_accum_out_vec_6_val("ccs_rtl_SIG_accum_out_vec_6_val")
, ccs_rtl_SIG_accum_out_vec_7_val("ccs_rtl_SIG_accum_out_vec_7_val")
, ccs_rtl_SIG_accum_out_vec_0_rdy("ccs_rtl_SIG_accum_out_vec_0_rdy")
, ccs_rtl_SIG_accum_out_vec_1_rdy("ccs_rtl_SIG_accum_out_vec_1_rdy")
, ccs_rtl_SIG_accum_out_vec_2_rdy("ccs_rtl_SIG_accum_out_vec_2_rdy")
, ccs_rtl_SIG_accum_out_vec_3_rdy("ccs_rtl_SIG_accum_out_vec_3_rdy")
, ccs_rtl_SIG_accum_out_vec_4_rdy("ccs_rtl_SIG_accum_out_vec_4_rdy")
, ccs_rtl_SIG_accum_out_vec_5_rdy("ccs_rtl_SIG_accum_out_vec_5_rdy")
, ccs_rtl_SIG_accum_out_vec_6_rdy("ccs_rtl_SIG_accum_out_vec_6_rdy")
, ccs_rtl_SIG_accum_out_vec_7_rdy("ccs_rtl_SIG_accum_out_vec_7_rdy")
, ccs_rtl_SIG_accum_out_vec_0_msg("ccs_rtl_SIG_accum_out_vec_0_msg")
, ccs_rtl_SIG_accum_out_vec_1_msg("ccs_rtl_SIG_accum_out_vec_1_msg")
, ccs_rtl_SIG_accum_out_vec_2_msg("ccs_rtl_SIG_accum_out_vec_2_msg")
, ccs_rtl_SIG_accum_out_vec_3_msg("ccs_rtl_SIG_accum_out_vec_3_msg")
, ccs_rtl_SIG_accum_out_vec_4_msg("ccs_rtl_SIG_accum_out_vec_4_msg")
, ccs_rtl_SIG_accum_out_vec_5_msg("ccs_rtl_SIG_accum_out_vec_5_msg")
, ccs_rtl_SIG_accum_out_vec_6_msg("ccs_rtl_SIG_accum_out_vec_6_msg")
, ccs_rtl_SIG_accum_out_vec_7_msg("ccs_rtl_SIG_accum_out_vec_7_msg")
{
// Instantiate other modules
ccs_rtl.clk(ccs_rtl_SIG_clk);
ccs_rtl.rst(ccs_rtl_SIG_rst);
ccs_rtl.write_req_val(ccs_rtl_SIG_write_req_val);
ccs_rtl.write_req_rdy(ccs_rtl_SIG_write_req_rdy);
ccs_rtl.write_req_msg(ccs_rtl_SIG_write_req_msg);
ccs_rtl.start_val(ccs_rtl_SIG_start_val);
ccs_rtl.start_rdy(ccs_rtl_SIG_start_rdy);
ccs_rtl.start_msg(ccs_rtl_SIG_start_msg);
ccs_rtl.weight_in_vec_0_val(ccs_rtl_SIG_weight_in_vec_0_val);
ccs_rtl.weight_in_vec_1_val(ccs_rtl_SIG_weight_in_vec_1_val);
ccs_rtl.weight_in_vec_2_val(ccs_rtl_SIG_weight_in_vec_2_val);
ccs_rtl.weight_in_vec_3_val(ccs_rtl_SIG_weight_in_vec_3_val);
ccs_rtl.weight_in_vec_4_val(ccs_rtl_SIG_weight_in_vec_4_val);
ccs_rtl.weight_in_vec_5_val(ccs_rtl_SIG_weight_in_vec_5_val);
ccs_rtl.weight_in_vec_6_val(ccs_rtl_SIG_weight_in_vec_6_val);
ccs_rtl.weight_in_vec_7_val(ccs_rtl_SIG_weight_in_vec_7_val);
ccs_rtl.weight_in_vec_0_rdy(ccs_rtl_SIG_weight_in_vec_0_rdy);
ccs_rtl.weight_in_vec_1_rdy(ccs_rtl_SIG_weight_in_vec_1_rdy);
ccs_rtl.weight_in_vec_2_rdy(ccs_rtl_SIG_weight_in_vec_2_rdy);
ccs_rtl.weight_in_vec_3_rdy(ccs_rtl_SIG_weight_in_vec_3_rdy);
ccs_rtl.weight_in_vec_4_rdy(ccs_rtl_SIG_weight_in_vec_4_rdy);
ccs_rtl.weight_in_vec_5_rdy(ccs_rtl_SIG_weight_in_vec_5_rdy);
ccs_rtl.weight_in_vec_6_rdy(ccs_rtl_SIG_weight_in_vec_6_rdy);
ccs_rtl.weight_in_vec_7_rdy(ccs_rtl_SIG_weight_in_vec_7_rdy);
ccs_rtl.weight_in_vec_0_msg(ccs_rtl_SIG_weight_in_vec_0_msg);
ccs_rtl.weight_in_vec_1_msg(ccs_rtl_SIG_weight_in_vec_1_msg);
ccs_rtl.weight_in_vec_2_msg(ccs_rtl_SIG_weight_in_vec_2_msg);
ccs_rtl.weight_in_vec_3_msg(ccs_rtl_SIG_weight_in_vec_3_msg);
ccs_rtl.weight_in_vec_4_msg(ccs_rtl_SIG_weight_in_vec_4_msg);
ccs_rtl.weight_in_vec_5_msg(ccs_rtl_SIG_weight_in_vec_5_msg);
ccs_rtl.weight_in_vec_6_msg(ccs_rtl_SIG_weight_in_vec_6_msg);
ccs_rtl.weight_in_vec_7_msg(ccs_rtl_SIG_weight_in_vec_7_msg);
ccs_rtl.accum_out_vec_0_val(ccs_rtl_SIG_accum_out_vec_0_val);
ccs_rtl.accum_out_vec_1_val(ccs_rtl_SIG_accum_out_vec_1_val);
ccs_rtl.accum_out_vec_2_val(ccs_rtl_SIG_accum_out_vec_2_val);
ccs_rtl.accum_out_vec_3_val(ccs_rtl_SIG_accum_out_vec_3_val);
ccs_rtl.accum_out_vec_4_val(ccs_rtl_SIG_accum_out_vec_4_val);
ccs_rtl.accum_out_vec_5_val(ccs_rtl_SIG_accum_out_vec_5_val);
ccs_rtl.accum_out_vec_6_val(ccs_rtl_SIG_accum_out_vec_6_val);
ccs_rtl.accum_out_vec_7_val(ccs_rtl_SIG_accum_out_vec_7_val);
ccs_rtl.accum_out_vec_0_rdy(ccs_rtl_SIG_accum_out_vec_0_rdy);
ccs_rtl.accum_out_vec_1_rdy(ccs_rtl_SIG_accum_out_vec_1_rdy);
ccs_rtl.accum_out_vec_2_rdy(ccs_rtl_SIG_accum_out_vec_2_rdy);
ccs_rtl.accum_out_vec_3_rdy(ccs_rtl_SIG_accum_out_vec_3_rdy);
ccs_rtl.accum_out_vec_4_rdy(ccs_rtl_SIG_accum_out_vec_4_rdy);
ccs_rtl.accum_out_vec_5_rdy(ccs_rtl_SIG_accum_out_vec_5_rdy);
ccs_rtl.accum_out_vec_6_rdy(ccs_rtl_SIG_accum_out_vec_6_rdy);
ccs_rtl.accum_out_vec_7_rdy(ccs_rtl_SIG_accum_out_vec_7_rdy);
ccs_rtl.accum_out_vec_0_msg(ccs_rtl_SIG_accum_out_vec_0_msg);
ccs_rtl.accum_out_vec_1_msg(ccs_rtl_SIG_accum_out_vec_1_msg);
ccs_rtl.accum_out_vec_2_msg(ccs_rtl_SIG_accum_out_vec_2_msg);
ccs_rtl.accum_out_vec_3_msg(ccs_rtl_SIG_accum_out_vec_3_msg);
ccs_rtl.accum_out_vec_4_msg(ccs_rtl_SIG_accum_out_vec_4_msg);
ccs_rtl.accum_out_vec_5_msg(ccs_rtl_SIG_accum_out_vec_5_msg);
ccs_rtl.accum_out_vec_6_msg(ccs_rtl_SIG_accum_out_vec_6_msg);
ccs_rtl.accum_out_vec_7_msg(ccs_rtl_SIG_accum_out_vec_7_msg);
// Register processes
SC_METHOD(update_proc);
sensitive << clk << rst << write_req.Connections::InBlocking_Ports_abs<InputSetup::WriteReq >::val << ccs_rtl_SIG_write_req_rdy << write_req.Connections::InBlocking<InputSetup::WriteReq, Connections::SYN_PORT >::msg << start.Connections::InBlocking_Ports_abs<ac_int<6, false > >::val << ccs_rtl_SIG_start_rdy << start.Connections::InBlocking<ac_int<6, false >, Connections::SYN_PORT >::msg << weight_in_vec[0].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[1].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[2].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[3].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[4].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[5].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[6].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[7].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << ccs_rtl_SIG_weight_in_vec_0_rdy << ccs_rtl_SIG_weight_in_vec_1_rdy << ccs_rtl_SIG_weight_in_vec_2_rdy << ccs_rtl_SIG_weight_in_vec_3_rdy << ccs_rtl_SIG_weight_in_vec_4_rdy << ccs_rtl_SIG_weight_in_vec_5_rdy << ccs_rtl_SIG_weight_in_vec_6_rdy << ccs_rtl_SIG_weight_in_vec_7_rdy << weight_in_vec[0].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[1].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[2].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[3].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[4].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[5].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[6].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[7].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << ccs_rtl_SIG_accum_out_vec_0_val << ccs_rtl_SIG_accum_out_vec_1_val << ccs_rtl_SIG_accum_out_vec_2_val << ccs_rtl_SIG_accum_out_vec_3_val << ccs_rtl_SIG_accum_out_vec_4_val << ccs_rtl_SIG_accum_out_vec_5_val << ccs_rtl_SIG_accum_out_vec_6_val << ccs_rtl_SIG_accum_out_vec_7_val << accum_out_vec[0].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[1].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[2].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[3].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[4].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[5].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[6].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[7].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << ccs_rtl_SIG_accum_out_vec_0_msg << ccs_rtl_SIG_accum_out_vec_1_msg << ccs_rtl_SIG_accum_out_vec_2_msg << ccs_rtl_SIG_accum_out_vec_3_msg << ccs_rtl_SIG_accum_out_vec_4_msg << ccs_rtl_SIG_accum_out_vec_5_msg << ccs_rtl_SIG_accum_out_vec_6_msg << ccs_rtl_SIG_accum_out_vec_7_msg;
// Other constructor statements
}
~sysc_sim_wrapper()
{
}
// C++ class functions
};
} // end namespace CCS_RTL
//
// -------------------------------------
// sysc_sim_wrapper
// Represents a new SC_MODULE having the same interface as the original model SysTop_rtl
// -------------------------------------
//
// ---------------------------------------------------------------
// Process: SC_METHOD update_proc
// Static sensitivity: sensitive << clk << rst << write_req.Connections::InBlocking_Ports_abs<InputSetup::WriteReq >::val << ccs_rtl_SIG_write_req_rdy << write_req.Connections::InBlocking<InputSetup::WriteReq, Connections::SYN_PORT >::msg << start.Connections::InBlocking_Ports_abs<ac_int<6, false > >::val << ccs_rtl_SIG_start_rdy << start.Connections::InBlocking<ac_int<6, false >, Connections::SYN_PORT >::msg << weight_in_vec[0].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[1].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[2].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[3].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[4].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[5].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[6].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[7].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << ccs_rtl_SIG_weight_in_vec_0_rdy << ccs_rtl_SIG_weight_in_vec_1_rdy << ccs_rtl_SIG_weight_in_vec_2_rdy << ccs_rtl_SIG_weight_in_vec_3_rdy << ccs
|
_rtl_SIG_weight_in_vec_4_rdy << ccs_rtl_SIG_weight_in_vec_5_rdy << ccs_rtl_SIG_weight_in_vec_6_rdy << ccs_rtl_SIG_weight_in_vec_7_rdy << weight_in_vec[0].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[1].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[2].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[3].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[4].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[5].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[6].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[7].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << ccs_rtl_SIG_accum_out_vec_0_val << ccs_rtl_SIG_accum_out_vec_1_val << ccs_rtl_SIG_accum_out_vec_2_val << ccs_rtl_SIG_accum_out_vec_3_val << ccs_rtl_SIG_accum_out_vec_4_val << ccs_rtl_SIG_accum_out_vec_5_val << ccs_rtl_SIG_accum_out_vec_6_val << ccs_rtl_SIG_accum_out_vec_7_val << accum_out_vec[0].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[1].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[2].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[3].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[4].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[5].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[6].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[7].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << ccs_rtl_SIG_accum_out_vec_0_msg << ccs_rtl_SIG_accum_out_vec_1_msg << ccs_rtl_SIG_accum_out_vec_2_msg << ccs_rtl_SIG_accum_out_vec_3_msg << ccs_rtl_SIG_accum_out_vec_4_msg << ccs_rtl_SIG_accum_out_vec_5_msg << ccs_rtl_SIG_accum_out_vec_6_msg << ccs_rtl_SIG_accum_out_vec_7_msg;
void CCS_RTL::sysc_sim_wrapper::update_proc() {
// none.sc_in field_key=clk:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-685:clk:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-685
sc_logic t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_685; // NPS - LV to hold field
ccs_rtl_SIG_clk.write(clk.read());
// none.sc_in field_key=rst:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-686:rst:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-686
sc_logic t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_686; // NPS - LV to hold field
type_to_vector(rst.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_686); // read orig port and type convert
ccs_rtl_SIG_rst.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_686); // then write to RTL port
// none.sc_in field_key=write_req:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-696:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-725
sc_logic t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_725; // NPS - LV to hold field
type_to_vector(write_req.Connections::InBlocking_Ports_abs<InputSetup::WriteReq >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_725); // read orig port and type convert
ccs_rtl_SIG_write_req_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_725); // then write to RTL port
// none.sc_out field_key=write_req:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-696:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-735
bool d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_735;
vector_to_type(ccs_rtl_SIG_write_req_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_735);
write_req.Connections::InBlocking_Ports_abs<InputSetup::WriteReq >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_735);
// none.sc_in field_key=write_req:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-696:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-745
sc_lv< 69 > t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_745; // NPS - LV to hold field
type_to_vector(write_req.Connections::InBlocking<InputSetup::WriteReq, Connections::SYN_PORT >::msg.read(),69,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_745); // read orig port and type convert
ccs_rtl_SIG_write_req_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_745); // then write to RTL port
// none.sc_in field_key=start:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-755:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-782
sc_logic t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_782; // NPS - LV to hold field
type_to_vector(start.Connections::InBlocking_Ports_abs<ac_int<6, false > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_782); // read orig port and type convert
ccs_rtl_SIG_start_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_782); // then write to RTL port
// none.sc_out field_key=start:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-755:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-792
bool d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_792;
vector_to_type(ccs_rtl_SIG_start_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_792);
start.Connections::InBlocking_Ports_abs<ac_int<6, false > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_792);
// none.sc_in field_key=start:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-755:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-802
sc_lv< 6 > t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_802; // NPS - LV to hold field
type_to_vector(start.Connections::InBlocking<ac_int<6, false >, Connections::SYN_PORT >::msg.read(),6,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_802); // read orig port and type convert
ccs_rtl_SIG_start_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_802); // then write to RTL port
// none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839
sc_logic t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839; // NPS - LV to hold field
type_to_vector(weight_in_vec[0].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert
ccs_rtl_SIG_weight_in_vec_0_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port
// none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839
type_to_vector(weight_in_vec[1].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert
ccs_rtl_SIG_weight_in_vec_1_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port
// none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839
type_to_vector(weight_in_vec[2].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert
ccs_rtl_SIG_weight_in_vec_2_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port
// none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839
type_to_vector(weight_in_vec[3].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert
ccs_rtl_SIG_weight_in_vec_3_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port
// none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839
type_to_vector(weight_in_vec[4].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert
ccs_rtl_SIG_weight_in_vec_4_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port
// none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839
type_to_vector(weight_in_vec[5].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert
ccs_rtl_SIG_weight_in_vec_5_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port
// none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839
type_to_vector(weight_in_vec[6].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert
ccs_rtl_SIG_weight_in_vec_6_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port
// none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839
type_to_vector(weight_in_vec[7].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert
ccs_rtl_SIG_weight_in_vec_7_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port
// none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849
bool d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849;
vector_to_type(ccs_rtl_SIG_weight_in_vec_0_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849);
weight_in_vec[0].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849);
// none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849
vector_to_type(ccs_rtl_SIG_weight_in_vec_1_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849);
weight_in_vec[1].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849);
// none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849
vector_to_type(ccs_rtl_SIG_weight_in_vec_2_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849);
weight_in_vec[2].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849);
// none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849
vector_to_type(ccs_rtl_SIG_weight_in_vec_3_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849);
weight_in_vec[3].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849);
// none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849
vector_to_type(ccs_rtl_SIG_weight_in_vec_4_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849);
weight_in_vec[4].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849);
// none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849
vector_to_type(ccs_rtl_SIG_weight_in_vec_5_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849);
weight_in_vec[5].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849);
// none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849
vector_to_type(ccs_rtl_SIG_weight_in_vec_6_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849);
weight_in_vec[6].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849);
// none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849
vector_to_type(ccs_rtl_SIG_weight_in_vec_7_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849);
weight_in_vec[7].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849);
// none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859
sc_lv< 8 > t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859; // NPS - LV to hold field
type_to_vector(weight_in_vec[0].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert
ccs_rtl_SIG_weight_in_vec_0_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port
// none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859
type_to_vector(weight_in_vec[1].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert
ccs_rtl_SIG_weight_in_vec_1_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port
// none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859
type_to_vector(weight_in_vec[2].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert
ccs_rtl_SIG_weight_in_vec_2_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port
// none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859
type_to_vector(weight_in_vec[3].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert
ccs_rtl_SIG_weight_in_vec_3_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port
// none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859
type_to_vector(weight_in_vec[4].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert
ccs_rtl_SIG_weight_in_vec_4_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port
// none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859
type_to_vector(weight_in_vec[5].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert
ccs_rtl_SIG_weight_in_vec_5_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port
// none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859
type_to_vector(weight_in_vec[6].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert
ccs_rtl_SIG_weight_in_vec_6_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port
// none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859
type_to_vector(weight_in_vec[7].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert
ccs_rtl_SIG_weight_in_vec_7_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port
// none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884
bool d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884;
vector_to_type(ccs_rtl_SIG_accum_out_vec_0_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884);
accum_out_vec[0].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884);
// none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884
vector_to_type(ccs_rtl_SIG_accum_out_vec_1_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884);
accum_out_vec[1].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884);
// none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884
vector_to_type(ccs_rtl_SIG_accum_out_vec_2_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884);
accum_out_vec[2].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884);
// none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884
vector_to_type(ccs_rtl_SIG_accum_out_vec_3_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884);
accum_out_vec[3].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884);
// none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884
vector_to_type(ccs_rtl_SIG_accum_out_vec_4_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884);
accum_out_vec[4].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884);
// none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884
vector_to_type(ccs_rtl_SIG_accum_out_vec_5_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884);
accum_out_vec[5].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884);
// none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884
vector_to_type(ccs_rtl_SIG_accum_out_vec_6_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884);
accum_out_vec[6].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884);
// none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884
vector_to_type(ccs_rtl_SIG_accum_out_vec_7_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884);
accum_out_vec[7].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884);
// none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888
sc_logic t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888; // NPS - LV to hold field
type_to_vector(accum_out_vec[0].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert
ccs_rtl_SIG_accum_out_vec_0_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port
// none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888
type_to_vector(accum_out_vec[1].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert
ccs_rtl_SIG_accum_out_vec_1_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port
// none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888
type_to_vector(accum_out_vec[2].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert
ccs_rtl_SIG_accum_out_vec_2_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port
// none.sc_in fi
|
eld_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888
type_to_vector(accum_out_vec[3].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert
ccs_rtl_SIG_accum_out_vec_3_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port
// none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888
type_to_vector(accum_out_vec[4].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert
ccs_rtl_SIG_accum_out_vec_4_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port
// none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888
type_to_vector(accum_out_vec[5].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert
ccs_rtl_SIG_accum_out_vec_5_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port
// none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888
type_to_vector(accum_out_vec[6].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert
ccs_rtl_SIG_accum_out_vec_6_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port
// none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888
type_to_vector(accum_out_vec[7].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert
ccs_rtl_SIG_accum_out_vec_7_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port
// none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892
sc_dt::sc_lv<32 > d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892;
vector_to_type(ccs_rtl_SIG_accum_out_vec_0_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892);
accum_out_vec[0].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892);
// none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892
vector_to_type(ccs_rtl_SIG_accum_out_vec_1_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892);
accum_out_vec[1].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892);
// none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892
vector_to_type(ccs_rtl_SIG_accum_out_vec_2_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892);
accum_out_vec[2].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892);
// none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892
vector_to_type(ccs_rtl_SIG_accum_out_vec_3_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892);
accum_out_vec[3].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892);
// none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892
vector_to_type(ccs_rtl_SIG_accum_out_vec_4_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892);
accum_out_vec[4].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892);
// none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892
vector_to_type(ccs_rtl_SIG_accum_out_vec_5_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892);
accum_out_vec[5].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892);
// none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892
vector_to_type(ccs_rtl_SIG_accum_out_vec_6_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892);
accum_out_vec[6].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892);
// none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892
vector_to_type(ccs_rtl_SIG_accum_out_vec_7_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892);
accum_out_vec[7].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892);
}
// Include original testbench file(s)
#include "/home/billyk/cs148/hls/lab3/SysTop/../../../cmod/lab3/SysTop/testbench.cpp"
|
/*
* 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__
|
/*
* 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_acc)
{
public:
sc_fifo_in< sc_uint<32> > addr;
sc_fifo_in< sc_uint<24> > rgbv;
SC_CTOR(BMPWriter_fixed_acc)
{
SC_THREAD(do_gen);
}
~BMPWriter_fixed_acc( )
{
string fn;
fn = "received_image_fixed_acc";
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 <systemc.h>
#include <unordered_set>
#include <array>
#include <string>
namespace acs {
typedef int Building;
typedef int Person;
#define NUM_DOORS 6
#define NUM_PERSONS 4
#define NUM_BUILDINGS 4
#define NO_PERSON (-1)
#define DEFAULT_BUILDING 0
#define TIMEOUT_RED 5
#define TIMEOUT_GREEN 20
#define TIME_UNIT SC_SEC
/* Default number of steps in the simulation */
#define NUM_STEPS 20
/* The authentication datatbase */
class Users {
private:
static std::unordered_set<Building> aut[NUM_PERSONS];
static Building sit[NUM_PERSONS];
public:
Users()
{
for (Person p= 0; p< NUM_PERSONS; p++)
{
aut[p]= std::unordered_set<Building>();
sit[p]= DEFAULT_BUILDING;
}
}
static bool admitted(Person p, Building b)
{
return (aut[p].count(b) > 0);
}
static void set_sit(Person p, Building b)
{
sit[p]= b;
}
static Building get_sit(Person b)
{
return sit[b];
}
static void add_aut(Person p, Building b)
{
aut[p].insert(b);
}
};
std::unordered_set<Building> Users::aut[NUM_PERSONS];
Building Users::sit[NUM_PERSONS];
std::string log_time()
{
return "["+ sc_time_stamp().to_string()+ "] ";
}
/* An LED, which can be turned on and off. */
SC_MODULE(LED) {
sc_in<bool> in;
sc_in<bool> in2;
SC_CTOR(LED)
{
SC_METHOD(blink);
sensitive << in;
}
void blink()
{
if (in.read())
cout << log_time() << "LED "<< name() << ": ON\n";
else
cout << log_time() << "LED "<< name() << ": OFF\n";
}
};
/* The gate, implementing the block Door */
SC_MODULE(Gate)
{
sc_in<Person> card;
// Turnstile interface:
sc_in<bool> passed;
sc_out<bool> unlock;
// Two lights for green and red:
sc_out<bool> green;
sc_out<bool> red;
public:
// Better: make it private, include values as constructor args.
Building org;
Building dest;
private:
Person dap= NO_PERSON; // Person currently passing
public:
SC_CTOR(Gate)
{
dap= NO_PERSON;
SC_THREAD(operate);
}
void accept()
{
cout << log_time() << "Person " << dap << " accepted.\n";
green.write(true);
unlock.write(true);
}
void pass_thru()
{
cout << log_time() << "Person " << dap << " has gone to " << dest << "\n";
Users::set_sit(dap, dest);
green.write(false);
unlock.write(false);
dap= NO_PERSON;
}
void off_grn()
{
green.write(false);
unlock.write(false);
dap= NO_PERSON;
}
void refuse()
{
cout << log_time() << "Person " << dap << " refused.\n";
red.write(true);
dap= NO_PERSON;
}
void off_red()
{
red.write(false);
dap= NO_PERSON;
}
void operate()
{
while (true) {
wait(card.value_changed_event());
dap= card.read();
if (Users::admitted(dap, dest))
{
accept();
wait(sc_time(TIMEOUT_GREEN, TIME_UNIT),
passed.posedge_event());
if (passed.read())
pass_thru();
else
off_grn();
}
else
{
refuse();
wait(TIMEOUT_RED, TIME_UNIT);
off_red();
}
}
}
};
bool pick_bool()
{
return rand() % 2 == 0;
}
/* The turnstile has an input to be unlocked, and an output
* indicating wether someone has passed. */
SC_MODULE(turnstile) {
sc_in<bool> unlock;
sc_out<bool> passed;
SC_CTOR(turnstile)
{
SC_THREAD(operate);
// sensitive << unlock;
}
void operate()
{
int t;
bool b;
while (true)
{
wait (unlock.posedge_event());
cout << log_time() << "Turnstile " << name() << " unlocked.\n";
/* Wait random amount of time... */
wait(rand() % (TIMEOUT_GREEN/2)+ TIMEOUT_GREEN/2, TIME_UNIT);
b= pick_bool();
cout << log_time() << "Turnstile " << name () << (b ? ": somebody " : ": nobody ") << "passed.\n";
passed.write(b);
}
}
};
/* A complete door consists of a gate (controller), two LEDs, and a turnstile */
SC_MODULE(Door)
{
sc_out<Person> card;
private:
sc_signal<bool> green_sig;
sc_signal<bool> red_sig;
sc_signal<bool> unlock_sig;
sc_signal<bool> pass_sig;
sc_signal<Person> card_sig;
LED grn;
LED red;
turnstile ts;
Gate gc;
public:
SC_CTOR(Door) : grn("Green"), red("Red"), ts("TS"), gc("GC")
{
gc.red(red_sig);
red.in(red_sig);
gc.green(green_sig);
grn.in(green_sig);
gc.card(card_sig);
card(card_sig);
gc.unlock(unlock_sig);
ts.unlock(unlock_sig);
gc.passed(pass_sig);
ts.passed(pass_sig);
// SC_METHOD(operate);
// sensitive >> card;
}
void setOrgDest(int org, int dest)
{
gc.org= org;
gc.dest= dest;
}
void operate()
{
approach(card.read());
}
void approach(Person p)
{
cout << log_time() << "Person "<< p << " approaching door " << name() << "\n";
card.write(p);
}
};
SC_MODULE(testGen)
{
Door *doors[NUM_DOORS];
int num_steps;
SC_CTOR(testGen)
{
doors[0] = new Door("DoorA");
doors[1] = new Door("DoorB");
doors[2] = new Door("DoorC");
doors[3] = new Door("DoorD");
doors[4] = new Door("DoorE");
doors[5] = new Door("DoorF");
/* Connect doors */
doors[0]->setOrgDest(1, 2);
doors[1]->setOrgDest(2, 1);
doors[2]->setOrgDest(2, 3);
doors[3]->setOrgDest(3, 4);
doors[4]->setOrgDest(4, 3);
doors[5]->setOrgDest(4, 1);
SC_THREAD(driver);
}
void driver()
{
Person p;
Building b;
int c;
for (int i= 0; i< num_steps; i++)
{
cout << log_time() << "#### New simulation step ################\n";
p= rand() % NUM_PERSONS;
c= rand() % NUM_DOORS;
// cout << "Person "<< p<< " approaching door "<< c << "\n";
doors[c]->approach(p);
wait(20, SC_SEC);
cout << log_time() << "Person "<< p<< " now in building "<< Users::get_sit(p) << "\n";
}
}
};
int sc_main(int argc, char* argv[])
{
int steps= NUM_STEPS;
Building permissions[NUM_PERSONS][NUM_BUILDINGS]=
{ {1, 2, 3, 4},
{1, 2},
{2, 3},
{1, 2, 4},
};
if (argc > 1)
{
std::stringstream s;
s << argv[1];
s >> steps;
}
/* Initialize controller */
for (Person p= 0; p< NUM_PERSONS; p++)
for (Building b= 0; b< NUM_BUILDINGS; b++)
{
if (permissions[p][b])
Users::add_aut(p, permissions[p][b]);
}
testGen tg("TestGen");
tg.num_steps= steps;
/* Run the test */
cout << "Starting.\n";
sc_start();
return 0;
}
}
|
/*
Print.cpp - Base class that provides print() and println()
Copyright (c) 2008 David A. Mellis. All right reserved.
This library 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 2.1 of the License, or (at your option) any later version.
This library 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 library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Modified 23 November 2006 by David A. Mellis
Modified December 2014 by Ivan Grokhotkov
Modified May 2015 by Michael C. Miller - ESP31B progmem support
Modified 25 July 2019 by Glenn Ramalho - fixed a small bug
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "Arduino.h"
#include <systemc.h>
#include "info.h"
#include "Print.h"
extern "C" {
#include "time.h"
}
// Public Methods //////////////////////////////////////////////////////////////
/* default implementation: may be overridden */
size_t Print::write(const uint8_t *buffer, size_t size)
{
size_t n = 0;
while(size--) {
n += write(*buffer++);
}
return n;
}
size_t Print::printf(const char *format, ...)
{
char loc_buf[64];
char * temp = loc_buf;
va_list arg;
va_list copy;
va_start(arg, format);
va_copy(copy, arg);
int len = vsnprintf(NULL, 0, format, copy);
va_end(copy);
if (len < 0) {
PRINTF_WARN("PRINTF", "vnprintf returned an error.");
return 0;
}
if((unsigned int)len >= sizeof(loc_buf)){
temp = new char[len+1];
if(temp == NULL) {
return 0;
}
}
len = vsnprintf(temp, len+1, format, arg);
write((uint8_t*)temp, len);
va_end(arg);
if(temp != loc_buf) {
delete[] temp;
}
return len;
}
size_t Print::print(const __FlashStringHelper *ifsh)
{
return print(reinterpret_cast<const char *>(ifsh));
}
size_t Print::print(const String &s)
{
return write(s.c_str(), s.length());
}
size_t Print::print(const char str[])
{
return write(str);
}
size_t Print::print(char c)
{
return write(c);
}
size_t Print::print(unsigned char b, int base)
{
return print((unsigned long) b, base);
}
size_t Print::print(int n, int base)
{
return print((long) n, base);
}
size_t Print::print(unsigned int n, int base)
{
return print((unsigned long) n, base);
}
size_t Print::print(long n, int base)
{
if(base == 0) {
return write(n);
} else if(base == 10) {
if(n < 0) {
int t = print('-');
n = -n;
return printNumber(n, 10) + t;
}
return printNumber(n, 10);
} else {
return printNumber(n, base);
}
}
size_t Print::print(unsigned long n, int base)
{
if(base == 0) {
return write(n);
} else {
return printNumber(n, base);
}
}
size_t Print::print(double n, int digits)
{
return printFloat(n, digits);
}
size_t Print::println(const __FlashStringHelper *ifsh)
{
size_t n = print(ifsh);
n += println();
return n;
}
size_t Print::print(const Printable& x)
{
return x.printTo(*this);
}
size_t Print::print(struct tm * timeinfo, const char * format)
{
const char * f = format;
if(!f){
f = "%c";
}
char buf[64];
size_t written = strftime(buf, 64, f, timeinfo);
print(buf);
return written;
}
size_t Print::println(void)
{
return print("\r\n");
}
size_t Print::println(const String &s)
{
size_t n = print(s);
n += println();
return n;
}
size_t Print::println(const char c[])
{
size_t n = print(c);
n += println();
return n;
}
size_t Print::println(char c)
{
size_t n = print(c);
n += println();
return n;
}
size_t Print::println(unsigned char b, int base)
{
size_t n = print(b, base);
n += println();
return n;
}
size_t Print::println(int num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(unsigned int num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(long num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(unsigned long num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(double num, int digits)
{
size_t n = print(num, digits);
n += println();
return n;
}
size_t Print::println(const Printable& x)
{
size_t n = print(x);
n += println();
return n;
}
size_t Print::println(struct tm * timeinfo, const char * format)
{
size_t n = print(timeinfo, format);
n += println();
return n;
}
// Private Methods /////////////////////////////////////////////////////////////
size_t Print::printNumber(unsigned long n, uint8_t base)
{
char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte.
char *str = &buf[sizeof(buf) - 1];
*str = '\0';
// prevent crash if called with base == 1
if(base < 2) {
base = 10;
}
do {
unsigned long m = n;
n /= base;
char c = m - base * n;
*--str = c < 10 ? c + '0' : c + 'A' - 10;
} while(n);
return write(str);
}
size_t Print::printFloat(double number, uint8_t digits)
{
size_t n = 0;
if(isnan(number)) {
return print("nan");
}
if(isinf(number)) {
return print("inf");
}
if(number > 4294967040.0) {
return print("ovf"); // constant determined empirically
}
if(number < -4294967040.0) {
return print("ovf"); // constant determined empirically
}
// Handle negative numbers
if(number < 0.0) {
n += print('-');
number = -number;
}
// Round correctly so that print(1.999, 2) prints as "2.00"
double rounding = 0.5;
for(uint8_t i = 0; i < digits; ++i) {
rounding /= 10.0;
}
number += rounding;
// Extract the integer part of the number and print it
unsigned long int_part = (unsigned long) number;
double remainder = number - (double) int_part;
n += print(int_part);
// Print the decimal point, but only if there are digits beyond
if(digits > 0) {
n += print(".");
}
// Extract digits from the remainder one at a time
while(digits-- > 0) {
remainder *= 10.0;
int toPrint = int(remainder);
n += print(toPrint);
remainder -= toPrint;
}
return n;
}
|
#include <systemc.h>
#include "full_adder.h"
#include "tb.h"
SC_MODULE( SYSTEM ) {
//Module Declarations
tb *tb0;
full_adder *full_adder0;
//Local signal declarations
sc_signal<bool> sig_inp_a, sig_inp_b,
sig_inp_cin, sig_sum, sig_co;
SC_HAS_PROCESS(SYSTEM);
SYSTEM( sc_module_name nm) : sc_module (nm) {
//Module instance signal connections
tb0 = new tb("tb0");
tb0->inp_a( sig_inp_a );
tb0->inp_b( sig_inp_b );
tb0->inp_cin( sig_inp_cin );
tb0->sum( sig_sum );
tb0->co( sig_co );
full_adder0 = new full_adder("full_adder0");
full_adder0->inp_a( sig_inp_a );
full_adder0->inp_b( sig_inp_b );
full_adder0->inp_cin( sig_inp_cin );
full_adder0->sum( sig_sum );
full_adder0->co( sig_co );
}
//Destructor
~SYSTEM(){
delete tb0;
delete full_adder0;
}
};
SYSTEM *top = NULL;
int sc_main( int argc, char* argv[] ){
// Connect the modules
top = new SYSTEM( "top" );
// Set up the tracing
sc_trace_file* pTraceFile = sc_create_vcd_trace_file("trace_file");
sc_trace(pTraceFile, top->sig_inp_a, "inp_a");
sc_trace(pTraceFile, top->sig_inp_b, "inp_b");
sc_trace(pTraceFile, top->sig_inp_cin, "inp_cin");
sc_trace(pTraceFile, top->sig_sum, "sum");
sc_trace(pTraceFile, top->sig_co, "co");
// Start the simulation
sc_start();
// Close the tracing
sc_close_vcd_trace_file(pTraceFile);
return 0;
}
|
//****************************************************************************************
// 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 ALU24 : public rand_obj {
randv<sc_bv<2> > op;
randv<sc_uint<24> > a, b;
ALU24(rand_obj* parent = 0) : rand_obj(parent), op(this), a(this), b(this) {
constraint((op() != 0x0) || (16777215 >= a() + b()));
constraint((op() != 0x1) || ((16777215 >= a() - b()) && (b() <= a())));
constraint((op() != 0x2) || (16777215 >= a() * b()));
constraint((op() != 0x3) || (b() != 0));
}
friend std::ostream& operator<<(std::ostream& o, ALU24 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;
ALU24 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;
}
|
// Copyright 2019 Glenn Ramalho - RFIDo Design
//
// 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 code was based off the work from Espressif Systems covered by the
// License:
//
// 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 "esp32-hal-log.h"
#include "esp_log.h"
#include <stdarg.h>
#include <stdlib.h>
int log_printf(const char *fmt, ...) {
int size;
char buffer[128];
va_list ap;
va_start(ap, fmt);
size = vsnprintf(buffer, 128, fmt, ap);
va_end(ap);
SC_REPORT_INFO("LOGP", buffer);
return size;
}
int log_v(const char *fmt, ...) {
int size;
char buffer[128];
va_list ap;
va_start(ap, fmt);
size = vsnprintf(buffer, 128, fmt, ap);
va_end(ap);
SC_REPORT_INFO("LOGV", buffer);
return size;
}
int isr_log_v(const char *fmt, ...) {
int size;
char buffer[128];
va_list ap;
va_start(ap, fmt);
size = vsnprintf(buffer, 128, fmt, ap);
va_end(ap);
SC_REPORT_INFO("LOGISRV", buffer);
return size;
}
int log_i(const char *fmt, ...) {
int size;
char buffer[128];
va_list ap;
va_start(ap, fmt);
size = vsnprintf(buffer, 128, fmt, ap);
va_end(ap);
SC_REPORT_INFO("LOG", buffer);
return size;
}
int isr_log_i(const char *fmt, ...) {
int size;
char buffer[128];
va_list ap;
va_start(ap, fmt);
size = vsnprintf(buffer, 128, fmt, ap);
va_end(ap);
SC_REPORT_INFO("LOGISR", buffer);
return size;
}
int log_d(const char *fmt, ...) {
int size;
char buffer[128];
va_list ap;
va_start(ap, fmt);
size = vsnprintf(buffer, 128, fmt, ap);
va_end(ap);
SC_REPORT_INFO("LOGDEBUG", buffer);
return size;
}
int isr_log_d(const char *fmt, ...) {
int size;
char buffer[128];
va_list ap;
va_start(ap, fmt);
size = vsnprintf(buffer, 128, fmt, ap);
va_end(ap);
SC_REPORT_INFO("LOGISRD", buffer);
return size;
}
int log_w(const char *fmt, ...) {
int size;
char buffer[128];
va_list ap;
va_start(ap, fmt);
size = vsnprintf(buffer, 128, fmt, ap);
va_end(ap);
SC_REPORT_WARNING("LOG", buffer);
return size;
}
int isr_log_w(const char *fmt, ...) {
int size;
char buffer[128];
va_list ap;
va_start(ap, fmt);
size = vsnprintf(buffer, 128, fmt, ap);
va_end(ap);
SC_REPORT_WARNING("LOGISR", buffer);
return size;
}
int log_e(const char *fmt, ...) {
int size;
char buffer[128];
va_list ap;
va_start(ap, fmt);
size = vsnprintf(buffer, 128, fmt, ap);
va_end(ap);
SC_REPORT_WARNING("LOGERR", buffer);
return size;
}
int isr_log_e(const char *fmt, ...) {
int size;
char buffer[128];
va_list ap;
va_start(ap, fmt);
size = vsnprintf(buffer, 128, fmt, ap);
va_end(ap);
SC_REPORT_WARNING("LOGISRERR", buffer);
return size;
}
int log_n(const char *fmt, ...) {
int size;
char buffer[128];
va_list ap;
va_start(ap, fmt);
size = vsnprintf(buffer, 128, fmt, ap);
va_end(ap);
SC_REPORT_INFO("LOGNOTE", buffer);
return size;
}
int isr_log_n(const char *fmt, ...) {
int size;
char buffer[128];
va_list ap;
va_start(ap, fmt);
size = vsnprintf(buffer, 128, fmt, ap);
va_end(ap);
SC_REPORT_INFO("LOGISRNOTE", buffer);
return size;
}
esp_log_level_t esp_level;
void esp_log_level_set(const char *tag, esp_log_level_t level) {
esp_level = level;
}
uint32_t esp_log_timestamp() {
double ts = sc_time_stamp().to_seconds();
return (uint32_t)(ts*1000);
}
uint32_t esp_log_early_timestamp() {
double ts = sc_time_stamp().to_seconds();
return (uint32_t)(ts*1000);
}
void esp_log_write(esp_log_level_t level, const char *tag, const char * format,
...) {
if (level <= esp_level) {
int size;
char buffer[128];
va_list ap;
size = strlen(tag);
strncpy(buffer, tag, 16);
if (size > 16) size = 16;
buffer[size] = ':';
va_start(ap, format);
vsnprintf(buffer+size+1, 128 - size - 1, format, ap);
va_end(ap);
switch(level) {
case ESP_LOG_ERROR: SC_REPORT_INFO("LOGERR", buffer); break;
case ESP_LOG_WARN: SC_REPORT_INFO("LOGWARN", buffer); break;
case ESP_LOG_INFO: SC_REPORT_INFO("LOGINFO", buffer); break;
case ESP_LOG_DEBUG: SC_REPORT_INFO("LOGDEBUG", buffer); break;
case ESP_LOG_VERBOSE: SC_REPORT_INFO("LOGVERB", buffer); break;
default : SC_REPORT_INFO("LOGOTHER", buffer); break;
}
}
}
|
/*
* SysTop testbench for Harvard cs148/248 only
*
*/
#include "SysTop.h"
#include <systemc.h>
#include <mc_scverify.h>
#include <nvhls_int.h>
#include <vector>
#define NVHLS_VERIFY_BLOCKS (SysTop)
#include <nvhls_verify.h>
using namespace::std;
#include <testbench/nvhls_rand.h>
// W/I/O dimensions
const static int N = SysArray::N;
const static int M = 3*N;
vector<int> Count(N, 0);
int ERROR = 0;
template<typename T>
vector<vector<T>> GetMat(int rows, int cols) {
vector<vector<T>> mat(rows, vector<T>(cols));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
mat[i][j] = nvhls::get_rand<T::width>();
}
}
return mat;
}
template<typename T>
void PrintMat(vector<vector<T>> mat) {
int rows = (int) mat.size();
int cols = (int) mat[0].size();
for (int i = 0; i < rows; i++) {
cout << "\t";
for (int j = 0; j < cols; j++) {
cout << mat[i][j] << "\t";
}
cout << endl;
}
cout << endl;
}
template<typename T, typename U>
vector<vector<U>> MatMul(vector<vector<T>> mat_A, vector<vector<T>> mat_B) {
// mat_A _N*_M
// mat_B _M*_P
// mat_C _N*_P
int _N = (int) mat_A.size();
int _M = (int) mat_A[0].size();
int _P = (int) mat_B[0].size();
assert(_M == (int) mat_B.size());
vector<vector<U>> mat_C(_N, vector<U>(_P, 0));
for (int i = 0; i < _N; i++) {
for (int j = 0; j < _P; j++) {
mat_C[i][j] = 0;
for (int k = 0; k < _M; k++) {
mat_C[i][j] += mat_A[i][k]*mat_B[k][j];
}
}
}
return mat_C;
}
SC_MODULE (Source) {
Connections::Out<SysPE::InputType> weight_in_vec[N];
Connections::Out<InputSetup::WriteReq> write_req;
Connections::Out<InputSetup::StartType> start;
sc_in <bool> clk;
sc_in <bool> rst;
vector<vector<SysPE::InputType>> W_mat, I_mat;
SC_CTOR(Source) {
SC_THREAD(Run);
sensitive << clk.pos();
async_reset_signal_is(rst, false);
}
void Run() {
for (int i = 0; i < N; i++) {
weight_in_vec[i].Reset();
}
write_req.Reset();
start.Reset();
// Wait for initial reset
wait(100.0, SC_NS);
wait();
// Write Weight to PE, e.g. for 4*4 weight
// (same as transposed)
// w00 w10 w20 w30
// w01 w11 w21 w31
// w02 w12 w22 w32
// w03 w13 w23 w33 <- push this first (col N-1)
cout << sc_time_stamp() << " " << name() << ": Start Loading Weight Matrix" << endl;
for (int j = N-1; j >= 0; j--) {
for (int i = 0; i < N; i++) {
weight_in_vec[i].Push(W_mat[i][j]);
}
}
cout << sc_time_stamp() << " " << name() << ": Finish Loading Weight Matrix" << endl;
wait();
// Store Activation to InputSetup SRAM
// E.g. 4*6 input
// (col)\(row)
// Index\Bank 0 1 2 3
// 0 a00 a10 a20 a30
// 1 a01 a11 a21 a31
// 2 a02 a12 a22 a32
// 3 a03 a13 a23 a33
// 4 a04 a14 a24 a34
// 5 a05 a15 a25 a35
cout << sc_time_stamp() << " " << name() << ": Start Sending Input Matrix" << endl;
InputSetup::WriteReq write_req_tmp;
for (int i = 0; i < M; i++) { // each bank index
write_req_tmp.index = i;
for (int j = 0; j < N; j++) { // each bank
write_req_tmp.data[j] = I_mat[j][i];
}
write_req.Push(write_req_tmp);
}
cout << sc_time_stamp() << " " << name() << ": Finish Sending Input Matrix" << endl;
wait();
cout << sc_time_stamp() << " " << name() << ": Start Computation" << endl;
InputSetup::StartType start_tmp = M;
start.Push(start_tmp);
wait();
}
};
SC_MODULE (Sink) {
Connections::In<SysPE::AccumType> accum_out_vec[N];
sc_in <bool> clk;
sc_in <bool> rst;
vector<vector<SysPE::AccumType>> O_mat;
SC_CTOR(Sink) {
SC_THREAD(Run);
sensitive << clk.pos();
async_reset_signal_is(rst, false);
}
void Run() {
for (int i = 0; i < N; i++) {
accum_out_vec[i].Reset();
}
vector<bool> is_out(N, 0);
while (1) {
vector<SysPE::AccumType> out_vec(N, 0);
for (int i = 0; i < N; i++) {
SysPE::AccumType _out;
is_out[i] = accum_out_vec[i].PopNB(_out);
if (is_out[i]) {
out_vec[i] = _out;
SysPE::AccumType _out_ref = O_mat[i][Count[i]];
if (_out != _out_ref){
ERROR += 1;
cout << "output incorrect" << endl;
}
Count[i] += 1;
}
}
bool is_out_or = 0;
for (int i = 0; i < N; i++) is_out_or |= is_out[i];
if (is_out_or) {
cout << sc_time_stamp() << " " << name() << " accum_out_vec: ";
cout << "\t";
for (int i = 0; i < N; i++) {
if (is_out[i] == 1)
cout << out_vec[i] << "\t";
else
cout << "-\t";
}
cout << endl;
}
wait();
}
}
};
SC_MODULE (testbench) {
sc_clock clk;
sc_signal<bool> rst;
Connections::Combinational<SysPE::InputType> weight_in_vec[N];
Connections::Combinational<SysPE::AccumType> accum_out_vec[N];
Connections::Combinational<InputSetup::WriteReq> write_req;
Connections::Combinational<InputSetup::StartType> start;
NVHLS_DESIGN(SysTop) top;
Source src;
Sink sink;
SC_HAS_PROCESS(testbench);
testbench(sc_module_name name)
: sc_module(name),
clk("clk", 1, SC_NS, 0.5,0,SC_NS,true),
rst("rst"),
top("top"),
src("src"),
sink("sink")
{
top.clk(clk);
top.rst(rst);
src.clk(clk);
src.rst(rst);
sink.clk(clk);
sink.rst(rst);
top.start(start);
src.start(start);
top.write_req(write_req);
src.write_req(write_req);
for (int i=0; i < N; i++) {
top.weight_in_vec[i](weight_in_vec[i]);
top.accum_out_vec[i](accum_out_vec[i]);
src.weight_in_vec[i](weight_in_vec[i]);
sink.accum_out_vec[i](accum_out_vec[i]);
}
SC_THREAD(Run);
}
void Run() {
rst = 1;
wait(10.5, SC_NS);
rst = 0;
cout << "@" << sc_time_stamp() << " Asserting Reset " << endl ;
wait(1, SC_NS);
cout << "@" << sc_time_stamp() << " Deasserting Reset " << endl ;
rst = 1;
wait(1000,SC_NS);
cout << "@" << sc_time_stamp() << " Stop " << endl ;
cout << "Check Output Count" << endl;
for (int i = 0; i < N; i++) {
if (Count[i] != M) {
ERROR += 1;
cout << "Count incorrect" << endl;
}
}
if (ERROR == 0) cout << "Implementation Correct :)" << endl;
else cout << "Implementation Incorrect (:" << endl;
sc_stop();
}
};
int sc_main(int argc, char *argv[])
{
nvhls::set_random_seed();
// Weight N*N
// Input N*M
// Output N*M
vector<vector<SysPE::InputType>> W_mat = GetMat<SysPE::InputType>(N, N);
vector<vector<SysPE::InputType>> I_mat = GetMat<SysPE::InputType>(N, M);
vector<vector<SysPE::AccumType>> O_mat;
O_mat = MatMul<SysPE::InputType, SysPE::AccumType>(W_mat, I_mat);
cout << "Weight Matrix " << endl;
PrintMat(W_mat);
cout << "Input Matrix " << endl;
PrintMat(I_mat);
cout << "Reference Output Matrix " << endl;
PrintMat(O_mat);
testbench my_testbench("my_testbench");
my_testbench.src.W_mat = W_mat;
my_testbench.src.I_mat = I_mat;
my_testbench.sink.O_mat = O_mat;
sc_start();
cout << "CMODEL PASS" << endl;
return 0;
};
|
/*******************************************************************************
* sc_main.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design
*******************************************************************************
* Description:
* The sc_main is the first function always called by the SystemC environment.
* This one takes as arguments a test name and an option:
*
* testname.x [testnumber] [+waveform]
*
* testnumber - test to run, 0 for t0, 1 for t1, etc. Default = 0.
* +waveform - generate VCD file for top level signals.
*
*******************************************************************************
* 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 "HelloServertest.h"
HelloServertest i_helloservertest("i_helloservertest");
int sc_main(int argc, char *argv[]) {
int tn;
bool wv = false;
if (argc > 3) {
SC_REPORT_ERROR("MAIN", "Too many arguments used in call");
return 1;
}
/* If no arguments are given, argc=1, there is no waveform and we run
* test 0.
*/
else if (argc == 1) {
tn = 0;
wv = false;
}
/* If we have at least one argument, we check if it is the waveform command.
* If it is, we set a tag. If we have two arguments, we assume the second
* one is the test number.
*/
else if (strcmp(argv[1], "+waveform")==0) {
wv = true;
/* If two arguments were given (argc=3) we assume the second one is the
* test name. If the testnumber was not given, we run test 0.
*/
if (argc == 3) tn = atoi(argv[2]);
else tn = 0;
}
/* For the remaining cases, we check. If there are two arguments, the first
* one must be the test number and the second one might be the waveform
* option. If we see 2 arguments, we do that. If we do not, then we just
* have a testcase number.
*/
else {
if (argc == 3 && strcmp(argv[2], "+waveform")==0) wv = true;
else wv = false;
tn = atoi(argv[1]);
}
/* We start the wave tracing. */
sc_trace_file *tf = NULL;
if (wv) {
tf = sc_create_vcd_trace_file("waves");
i_helloservertest.trace(tf);
}
/* We need to connect the Arduino pin library to the gpios. */
i_helloservertest.i_esp.pininit();
/* Set the test number */
i_helloservertest.tn = tn;
/* And run the simulation. */
sc_start();
if (wv) sc_close_vcd_trace_file(tf);
exit(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)
*/
#include <gv/gvsoc.hpp>
#include <algorithm>
#include <dlfcn.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <vp/json.hpp>
#include <systemc.h>
#include "main_systemc.hpp"
static gv::Gvsoc *sc_gvsoc;
class my_module : public sc_module, public gv::Gvsoc_user
{
public:
SC_HAS_PROCESS(my_module);
my_module(sc_module_name nm, gv::Gvsoc *gvsoc) : sc_module(nm), gvsoc(gvsoc)
{
SC_THREAD(run);
}
void run()
{
while(1)
{
int64_t time = (int64_t)sc_time_stamp().to_double();
int64_t next_timestamp = gvsoc->step_until(time);
// when we are not executing the engine, it is retained so that no one else
// can execute it while we are leeting the systemv engine executes.
// On the contrary, if someone else is retaining it, we should not let systemv
// update the time.
// If so, just call again the step function so that we release the engine for
// a while.
if (gvsoc->retain_count() == 1)
{
if (next_timestamp == -1)
{
wait(sync_event);
}
else
{
wait(next_timestamp - time, SC_PS, sync_event);
}
}
}
}
void was_updated() override
{
sync_event.notify();
}
void has_ended() override
{
sc_stop();
}
gv::Gvsoc *gvsoc;
sc_event sync_event;
};
int sc_main(int argc, char *argv[])
{
sc_start();
return sc_gvsoc->join();
}
int requires_systemc(const char *config_path)
{
// In case GVSOC was compiled with SystemC, check if we have at least one SystemC component
// and if so, forward the launch to the dedicated SystemC launcher
js::Config *js_config = js::import_config_from_file(config_path);
if (js_config)
{
js::Config *gv_config = js_config->get("target/gvsoc");
if (gv_config)
{
return gv_config->get_child_bool("systemc");
}
}
return 0;
}
int systemc_launcher(const char *config_path)
{
gv::GvsocConf conf = { .config_path=config_path, .api_mode=gv::Api_mode::Api_mode_sync };
gv::Gvsoc *gvsoc = gv::gvsoc_new(&conf);
gvsoc->open();
gvsoc->start();
sc_gvsoc = gvsoc;
my_module module("Gvsoc SystemC wrapper", gvsoc);
gvsoc->bind(&module);
return sc_core::sc_elab_and_sim(0, NULL);
}
|
#include <systemc.h>
#include <and.h>
#include <testbench.h>
int sc_main(int argv, char* argc[]) {
sc_time PERIOD(10,SC_NS);
sc_time DELAY(10,SC_NS);
sc_clock clock("clock",PERIOD,0.5,DELAY,true);
And and1("and1");
testbench tb("tb");
sc_signal<bool> a_sg,b_sg,c_sg;
and1.a(a_sg);
and1.b(b_sg);
and1.c(c_sg);
tb.a(a_sg);
tb.b(b_sg);
tb.c(c_sg);
tb.clk(clock);
sc_start();
return 0;
}
|
/*
* SysAttay testbench, for Harvard cs148/248 only
*/
#include "SysArray.h"
#include <systemc.h>
#include <mc_scverify.h>
#include <nvhls_int.h>
#include <vector>
#define NVHLS_VERIFY_BLOCKS (SysArray)
#include <nvhls_verify.h>
using namespace::std;
#include <testbench/nvhls_rand.h>
// W/I/O dimensions
const static int N = SysArray::N;
const static int M = N*3;
int ERROR = 0;
vector<int> Count(N, 0);
template<typename T>
vector<vector<T>> GetMat(int rows, int cols) {
vector<vector<T>> mat(rows, vector<T>(cols));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
mat[i][j] = nvhls::get_rand<T::width>();
}
}
return mat;
}
template<typename T>
void PrintMat(vector<vector<T>> mat) {
int rows = (int) mat.size();
int cols = (int) mat[0].size();
for (int i = 0; i < rows; i++) {
cout << "\t";
for (int j = 0; j < cols; j++) {
cout << mat[i][j] << "\t";
}
cout << endl;
}
cout << endl;
}
template<typename T, typename U>
vector<vector<U>> MatMul(vector<vector<T>> mat_A, vector<vector<T>> mat_B) {
// mat_A _N*_M
// mat_B _M*_P
// mat_C _N*_P
int _N = (int) mat_A.size();
int _M = (int) mat_A[0].size();
int _P = (int) mat_B[0].size();
assert(_M == (int) mat_B.size());
vector<vector<U>> mat_C(_N, vector<U>(_P, 0));
for (int i = 0; i < _N; i++) {
for (int j = 0; j < _P; j++) {
mat_C[i][j] = 0;
for (int k = 0; k < _M; k++) {
mat_C[i][j] += mat_A[i][k]*mat_B[k][j];
}
}
}
return mat_C;
}
SC_MODULE (Source) {
Connections::Out<SysPE::InputType> act_in_vec[N];
Connections::Out<SysPE::InputType> weight_in_vec[N];
sc_in <bool> clk;
sc_in <bool> rst;
vector<vector<SysPE::InputType>> W_mat, I_mat;
SC_CTOR(Source) {
SC_THREAD(Run);
sensitive << clk.pos();
async_reset_signal_is(rst, false);
}
void Run() {
for (int i = 0; i < N; i++) {
act_in_vec[i].Reset();
weight_in_vec[i].Reset();
}
// Wait for initial reset
wait(100.0, SC_NS);
wait();
// Write Weight to PE, e.g. for 4*4 weight
// w00 w10 w20 w30
// w01 w11 w21 w31
// w02 w12 w22 w32
// w03 w13 w23 w33 <- push this first (col N-1)
cout << sc_time_stamp() << " " << name() << ": Start Loading Weight Matrix" << endl;
for (int j = N-1; j >= 0; j--) {
for (int i = 0; i < N; i++) {
weight_in_vec[i].Push(W_mat[i][j]);
}
}
cout << sc_time_stamp() << " " << name() << ": Finish Loading Weight Matrix" << endl;
wait(N);
cout << sc_time_stamp() << " " << name() << ": Start Sending Input Matrix" << endl;
// Activation most follow Systolic Array Pattern
// e.g. 4*6 Input matrix
// a00
// a01 a10
// a02 a11 a20
// a03 a12 a21 a30
// a04 a13 a22 a31
// a05 a14 a23 a32
// a15 a24 a33
// a25 a34
// a35
vector<int> col(N, 0);
for (int i = 0; i < N-1; i++) {
for (int j = 0; j <= i; j++) {
SysPE::InputType _act = I_mat[j][col[j]];
act_in_vec[j].Push(_act);
col[j] += 1;
}
}
for (int i = N-1; i < M; i++) {
for (int j = 0; j < N; j++) {
SysPE::InputType _act = I_mat[j][col[j]];
act_in_vec[j].Push(_act);
col[j] += 1;
}
}
for (int i = M; i < N+M-1; i++) {
for (int j = i-M+1; j < N; j++) {
SysPE::InputType _act = I_mat[j][col[j]];
act_in_vec[j].Push(_act);
col[j] += 1;
}
}
wait();
}
};
SC_MODULE (Sink) {
Connections::In<SysPE::AccumType> accum_out_vec[N];
sc_in <bool> clk;
sc_in <bool> rst;
vector<vector<SysPE::AccumType>> O_mat;
SC_CTOR(Sink) {
SC_THREAD(Run);
sensitive << clk.pos();
async_reset_signal_is(rst, false);
}
void Run() {
for (int i = 0; i < N; i++) {
accum_out_vec[i].Reset();
}
vector<bool> is_out(N, 0);
while (1) {
vector<SysPE::AccumType> out_vec(N, 0);
for (int i = 0; i < N; i++) {
SysPE::AccumType _out;
is_out[i] = accum_out_vec[i].PopNB(_out);
if (is_out[i]) {
out_vec[i] = _out;
SysPE::AccumType _out_ref = O_mat[i][Count[i]];
if (_out != _out_ref){
ERROR += 1;
cout << "output incorrect" << endl;
}
Count[i] += 1;
}
}
bool is_out_or = 0;
for (int i = 0; i < N; i++) is_out_or |= is_out[i];
if (is_out_or) {
cout << sc_time_stamp() << " " << name() << " accum_out_vec: ";
cout << "\t";
for (int i = 0; i < N; i++) {
if (is_out[i] == 1)
cout << out_vec[i] << "\t";
else
cout << "-\t";
}
cout << endl;
}
wait();
}
}
};
SC_MODULE (testbench) {
sc_clock clk;
sc_signal<bool> rst;
Connections::Combinational<SysPE::InputType> act_in_vec[N];
Connections::Combinational<SysPE::InputType> weight_in_vec[N];
Connections::Combinational<SysPE::AccumType> accum_out_vec[N];
NVHLS_DESIGN(SysArray) sa;
Source src;
Sink sink;
SC_HAS_PROCESS(testbench);
testbench(sc_module_name name)
: sc_module(name),
clk("clk", 1, SC_NS, 0.5,0,SC_NS,true),
rst("rst"),
sa("sa"),
src("src"),
sink("sink")
{
sa.clk(clk);
sa.rst(rst);
src.clk(clk);
src.rst(rst);
sink.clk(clk);
sink.rst(rst);
for (int i=0; i < N; i++) {
sa.act_in_vec[i](act_in_vec[i]);
sa.weight_in_vec[i](weight_in_vec[i]);
sa.accum_out_vec[i](accum_out_vec[i]);
src.act_in_vec[i](act_in_vec[i]);
src.weight_in_vec[i](weight_in_vec[i]);
sink.accum_out_vec[i](accum_out_vec[i]);
}
SC_THREAD(Run);
}
void Run() {
rst = 1;
wait(10.5, SC_NS);
rst = 0;
cout << "@" << sc_time_stamp() << " Asserting Reset " << endl ;
wait(1, SC_NS);
cout << "@" << sc_time_stamp() << " Deasserting Reset " << endl ;
rst = 1;
wait(1000, SC_NS);
cout << "@" << sc_time_stamp() << " Stop " << endl ;
cout << "Check Output Count" << endl;
for (int i = 0; i < N; i++) {
if (Count[i] != M) {
ERROR += 1;
cout << "Count incorrect" << endl;
}
}
if (ERROR == 0) cout << "Implementation Correct :)" << endl;
else cout << "Implementation Incorrect (:" << endl;
sc_stop();
}
};
int sc_main(int argc, char *argv[])
{
nvhls::set_random_seed();
// Weight N*N
// Input N*M
// Output N*M
vector<vector<SysPE::InputType>> W_mat = GetMat<SysPE::InputType>(N, N);
vector<vector<SysPE::InputType>> I_mat = GetMat<SysPE::InputType>(N, M);
vector<vector<SysPE::AccumType>> O_mat;
O_mat = MatMul<SysPE::InputType, SysPE::AccumType>(W_mat, I_mat);
cout << "Weight Matrix " << endl;
PrintMat(W_mat);
cout << "Input Matrix " << endl;
PrintMat(I_mat);
cout << "Reference Output Matrix " << endl;
PrintMat(O_mat);
testbench my_testbench("my_testbench");
my_testbench.src.W_mat = W_mat;
my_testbench.src.I_mat = I_mat;
my_testbench.sink.O_mat = O_mat;
sc_start();
cout << "CMODEL PASS" << endl;
return 0;
};
|
// nand gate
// Luciano Sobral <sobral.luciano@gmail.com>
// this sample should fail
#include <systemc.h>
SC_MODULE(nand_gate)
{
sc_inout<bool> a;
sc_inout<bool> b;
sc_out<bool> c;
void nand_process(void)
{
and_process(); // c = a and b
c = !c.read(); // c = not c
}
void and_process ( void )
{
c = a.read() && b.read();
}
void test_process(void)
{
assert( c.read() == ( a.read() && b.read() ) );
}
SC_CTOR(nand_gate)
{
}
};
int sc_main( int argc, char * argv[] )
{
sc_signal<bool> s1;
sc_signal<bool> s2;
sc_signal<bool> s3;
s1.write(true);
s2.write(false);
s3.write(false);
nand_gate gate("nand_gate");
gate.a(s1);
gate.b(s2);
gate.c(s3);
gate.nand_process();
gate.test_process();
return 0;
}
|
// nand gate
// Luciano Sobral <sobral.luciano@gmail.com>
// this sample should fail
#include <systemc.h>
SC_MODULE(nand_gate)
{
sc_inout<bool> a;
sc_inout<bool> b;
sc_out<bool> c;
void nand_process(void)
{
and_process(); // c = a and b
c = !c.read(); // c = not c
}
void and_process ( void )
{
c = a.read() && b.read();
}
void test_process(void)
{
assert( c.read() == ( a.read() && b.read() ) );
}
SC_CTOR(nand_gate)
{
}
};
int sc_main( int argc, char * argv[] )
{
sc_signal<bool> s1;
sc_signal<bool> s2;
sc_signal<bool> s3;
s1.write(true);
s2.write(false);
s3.write(false);
nand_gate gate("nand_gate");
gate.a(s1);
gate.b(s2);
gate.c(s3);
gate.nand_process();
gate.test_process();
return 0;
}
|
/*
* @ASCK
*/
#include <systemc.h>
SC_MODULE (Mux8) {
sc_in <bool> sel;
sc_in <sc_int<8>> in0;
sc_in <sc_int<8>> in1;
sc_out <sc_int<8>> out;
/*
** module global variables
*/
SC_CTOR (Mux8){
SC_METHOD (process);
sensitive << in0 << in1 << sel;
}
void process () {
if(!sel.read()){
out.write(in0.read());
}
else{
out.write(in1.read());
}
}
};
|
/*****************************************************************************
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.
*****************************************************************************/
/*****************************************************************************
simple_fifo.cpp -- SystemC 2.0 Performance Modeling Example.
This example is derived from the design presented within
"An Introduction to System Level Modeling in SystemC 2.0"
By Stuart Swan, Cadence Design Systems.
Available at www.accellera.org
The system being modeled has a producer block that
sends characters to a consumer block via a fifo.
The fifo will suspend the producer or consumer as
necessary to insure all characters are reliably
delivered.
The consumer block will consume exactly one
character every 100 ns unless it is suspended
waiting for input from the fifo.
The producer block produces between one and
19 characters every 1000 ns unless it is
suspended waiting to write to the fifo.
On average, the producer block produces
one character every 100 ns (unless suspended by
the fifo) since a random linear distribution is
used for the character count.
If the fifo size is sufficiently large, the average
transfer time per character will approach 100 ns
since the producer and consumer will rarely be
blocked. However, as the fifo size decreases,
the average transfer time will increase because
the producer will sometimes be suspended when
it writes (due to a full fifo) and the consumer
will sometimes be suspended when it reads
(due to an empty fifo).
The fifo size can be set via a command line argument
when running this program. By default, the fifo size
is 10. When the design is simulated, one hundred
thousand characters are transferred from the
producer to the consumer and then performance
statistics are displayed.
Using this system level model, determine the size
of the fifo needed to sustain:
A) An average transfer time of 110 ns per character
B) An average transfer time of 105 ns per character
Hint: The answer to (A) is between 10 and 20.
Original Author: Stuart Swan, Cadence Design Systems, 2001-06-18
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
#include <systemc.h>
class write_if : virtual public sc_interface
{
public:
virtual void write(char) = 0;
virtual void reset() = 0;
};
class read_if : virtual public sc_interface
{
public:
virtual void read(char &) = 0;
virtual int num_available() = 0;
};
class fifo : public sc_channel, public write_if, public read_if
{
public:
fifo(sc_module_name name, int size_) : sc_channel(name), size(size_)
{
data = new char[size];
num_elements = first = 0;
num_read = max_used = average = 0;
last_time = SC_ZERO_TIME;
}
~fifo()
{
delete[] data;
cout << endl << "Fifo size is: " << size << endl;
cout << "Average fifo fill depth: " <<
double(average) / num_read << endl;
cout << "Maximum fifo fill depth: " << max_used << endl;
cout << "Average transfer time per character: "
<< last_time / num_read << endl;
cout << "Total characters transferred: " << num_read << endl;
cout << "Total time: " << last_time << endl;
}
void write(char c) {
if (num_elements == size)
wait(read_event);
data[(first + num_elements) % size] = c;
++ num_elements;
write_event.notify();
}
void read(char &c){
last_time = sc_time_stamp();
if (num_elements == 0)
wait(write_event);
compute_stats();
c = data[first];
-- num_elements;
first = (first + 1) % size;
read_event.notify();
}
void reset() { num_elements = first = 0; }
int num_available() { return num_elements;}
private:
char *data;
int num_elements, first;
sc_event write_event, read_event;
int size, num_read, max_used, average;
sc_time last_time;
void compute_stats()
{
average += num_elements;
if (num_elements > max_used)
max_used = num_elements;
++num_read;
}
};
class producer : public sc_module
{
public:
sc_port<write_if> out;
SC_HAS_PROCESS(producer);
producer(sc_module_name name) : sc_module(name)
{
SC_THREAD(main);
}
void main()
{
const char *str =
"Visit www.accellera.org and see what SystemC can do for you today!\n";
const char *p = str;
int total = 100000;
while (true)
{
int i = 1 + int(19.0 * rand() / RAND_MAX); // 1 <= i <= 19
while (--i >= 0)
{
out->write(*p++);
if (!*p) p = str;
-- total;
}
if (total <= 0)
break;
wait(1000, SC_NS);
}
}
};
class consumer : public sc_module
{
public:
sc_port<read_if> in;
SC_HAS_PROCESS(consumer);
consumer(sc_module_name name) : sc_module(name)
{
SC_THREAD(main);
}
void main()
{
char c;
while (true) {
in->read(c);
wait(100, SC_NS);
}
}
};
class top : public sc_module
{
public:
fifo fifo_inst;
producer prod_inst;
consumer cons_inst;
top(sc_module_name name, int size) :
sc_module(name) ,
fifo_inst("Fifo1", size) ,
prod_inst("Producer1") ,
cons_inst("Consumer1")
{
prod_inst.out(fifo_inst);
cons_inst.in(fifo_inst);
}
};
int sc_main (int argc , char *argv[])
{
int size = 10;
if (argc > 1)
size = atoi(argv[1]);
if (size < 1)
size = 1;
if (size > 100000)
size = 100000;
top top1("Top1", size);
sc_start();
return 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.
*****************************************************************************/
/*****************************************************************************
simple_fifo.cpp -- SystemC 2.0 Performance Modeling Example.
This example is derived from the design presented within
"An Introduction to System Level Modeling in SystemC 2.0"
By Stuart Swan, Cadence Design Systems.
Available at www.accellera.org
The system being modeled has a producer block that
sends characters to a consumer block via a fifo.
The fifo will suspend the producer or consumer as
necessary to insure all characters are reliably
delivered.
The consumer block will consume exactly one
character every 100 ns unless it is suspended
waiting for input from the fifo.
The producer block produces between one and
19 characters every 1000 ns unless it is
suspended waiting to write to the fifo.
On average, the producer block produces
one character every 100 ns (unless suspended by
the fifo) since a random linear distribution is
used for the character count.
If the fifo size is sufficiently large, the average
transfer time per character will approach 100 ns
since the producer and consumer will rarely be
blocked. However, as the fifo size decreases,
the average transfer time will increase because
the producer will sometimes be suspended when
it writes (due to a full fifo) and the consumer
will sometimes be suspended when it reads
(due to an empty fifo).
The fifo size can be set via a command line argument
when running this program. By default, the fifo size
is 10. When the design is simulated, one hundred
thousand characters are transferred from the
producer to the consumer and then performance
statistics are displayed.
Using this system level model, determine the size
of the fifo needed to sustain:
A) An average transfer time of 110 ns per character
B) An average transfer time of 105 ns per character
Hint: The answer to (A) is between 10 and 20.
Original Author: Stuart Swan, Cadence Design Systems, 2001-06-18
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
#include <systemc.h>
class write_if : virtual public sc_interface
{
public:
virtual void write(char) = 0;
virtual void reset() = 0;
};
class read_if : virtual public sc_interface
{
public:
virtual void read(char &) = 0;
virtual int num_available() = 0;
};
class fifo : public sc_channel, public write_if, public read_if
{
public:
fifo(sc_module_name name, int size_) : sc_channel(name), size(size_)
{
data = new char[size];
num_elements = first = 0;
num_read = max_used = average = 0;
last_time = SC_ZERO_TIME;
}
~fifo()
{
delete[] data;
cout << endl << "Fifo size is: " << size << endl;
cout << "Average fifo fill depth: " <<
double(average) / num_read << endl;
cout << "Maximum fifo fill depth: " << max_used << endl;
cout << "Average transfer time per character: "
<< last_time / num_read << endl;
cout << "Total characters transferred: " << num_read << endl;
cout << "Total time: " << last_time << endl;
}
void write(char c) {
if (num_elements == size)
wait(read_event);
data[(first + num_elements) % size] = c;
++ num_elements;
write_event.notify();
}
void read(char &c){
last_time = sc_time_stamp();
if (num_elements == 0)
wait(write_event);
compute_stats();
c = data[first];
-- num_elements;
first = (first + 1) % size;
read_event.notify();
}
void reset() { num_elements = first = 0; }
int num_available() { return num_elements;}
private:
char *data;
int num_elements, first;
sc_event write_event, read_event;
int size, num_read, max_used, average;
sc_time last_time;
void compute_stats()
{
average += num_elements;
if (num_elements > max_used)
max_used = num_elements;
++num_read;
}
};
class producer : public sc_module
{
public:
sc_port<write_if> out;
SC_HAS_PROCESS(producer);
producer(sc_module_name name) : sc_module(name)
{
SC_THREAD(main);
}
void main()
{
const char *str =
"Visit www.accellera.org and see what SystemC can do for you today!\n";
const char *p = str;
int total = 100000;
while (true)
{
int i = 1 + int(19.0 * rand() / RAND_MAX); // 1 <= i <= 19
while (--i >= 0)
{
out->write(*p++);
if (!*p) p = str;
-- total;
}
if (total <= 0)
break;
wait(1000, SC_NS);
}
}
};
class consumer : public sc_module
{
public:
sc_port<read_if> in;
SC_HAS_PROCESS(consumer);
consumer(sc_module_name name) : sc_module(name)
{
SC_THREAD(main);
}
void main()
{
char c;
while (true) {
in->read(c);
wait(100, SC_NS);
}
}
};
class top : public sc_module
{
public:
fifo fifo_inst;
producer prod_inst;
consumer cons_inst;
top(sc_module_name name, int size) :
sc_module(name) ,
fifo_inst("Fifo1", size) ,
prod_inst("Producer1") ,
cons_inst("Consumer1")
{
prod_inst.out(fifo_inst);
cons_inst.in(fifo_inst);
}
};
int sc_main (int argc , char *argv[])
{
int size = 10;
if (argc > 1)
size = atoi(argv[1]);
if (size < 1)
size = 1;
if (size > 100000)
size = 100000;
top top1("Top1", size);
sc_start();
return 0;
}
|
/*
* @ASCK
*/
#include <systemc.h>
SC_MODULE (WB) {
sc_in_clk clk;
sc_in <sc_int<8>> prev_alu_result;
sc_in <sc_int<8>> prev_mem_result;
sc_in <bool> prev_WbMux;
sc_in <bool> prev_regWrite;
sc_in <sc_uint<3>> prev_rd;
sc_out <sc_int<8>> next_alu_result;
sc_out <sc_int<8>> next_mem_result;
sc_out <bool> next_WbMux;
sc_out <bool> next_regWrite;
sc_out <sc_uint<3>> next_rd;
/*
** module global variables
*/
SC_CTOR (WB){
SC_THREAD (process);
sensitive << clk.pos();
}
void process () {
while(true){
wait();
if(now_is_call){
wait(micro_acc_ev);
}
next_alu_result.write(prev_alu_result.read());
next_mem_result.write(prev_mem_result.read());
next_WbMux.write(prev_WbMux.read());
next_regWrite.write(prev_regWrite);
next_rd.write(prev_rd.read());
}
}
};
|
/*
* Main.cpp
*
* Created on: 13 Jan 2010
* Author: db434
*/
#include <systemc.h>
#include <stdio.h>
#include "Utility/Arguments.h"
#include "Utility/BlockingInterface.h"
#include "Utility/Debugger.h"
#include "Utility/Instrumentation/IPKCache.h"
#include "Utility/Instrumentation.h"
#include "Utility/Instrumentation/Operations.h"
#include "Utility/Instrumentation/Stalls.h"
#include "Utility/Trace/Callgrind.h"
#include "Utility/StartUp/CodeLoader.h"
#include "Utility/Statistics.h"
using std::vector;
using std::string;
using Instrumentation::Stalls;
void timestep(cycle_count_t cyclesPerStep) {
cycle_count_t cycle = Instrumentation::currentCycle();
LOKI_LOG(1) << "\n======= Cycle " << cycle << " =======" << endl;
sc_start((int)cyclesPerStep, SC_NS);
}
void statusUpdate(std::ostream& os) {
os << "Current cycle number: " << Instrumentation::currentCycle()
<< " [" << Instrumentation::Operations::allOperations() << " operation(s) executed]" << endl;
}
bool checkProgress(cycle_count_t interval) {
static count_t operationCount = 0;
count_t newOperationCount = Instrumentation::Operations::allOperations();
if (newOperationCount == operationCount) {
cerr << "\nNo progress has been made for " << interval << " cycles. Aborting." << endl;
Instrumentation::endExecution();
BlockingInterface::reportProblems(cerr);
RETURN_CODE = EXIT_FAILURE;
return false;
}
operationCount = newOperationCount;
return true;
}
bool checkIdle() {
if (Stalls::cyclesIdle() >= 100) {
statusUpdate(cerr);
cerr << "System has been idle for " << Stalls::cyclesIdle() << " cycles. Aborting." << endl;
Instrumentation::endExecution();
BlockingInterface::reportProblems(cerr);
RETURN_CODE = EXIT_FAILURE;
return true;
}
return false;
}
void timeout() {
cerr << "Simulation timed out after " << Instrumentation::currentCycle() << " cycles." << endl;
Instrumentation::endExecution();
}
void simulate(Chip& chip, const chip_parameters_t& params) {
cycle_count_t smallStep = 1;
cycle_count_t bigStep = 100;
cycle_count_t cyclesPerStep = smallStep;
try {
if (Debugger::usingDebugger) {
Debugger::setChip(&chip, params);
Debugger::waitForInput();
}
else {
cycle_count_t cycle = 0;
while (!sc_core::sc_end_of_simulation_invoked()) {
// if (cycle >= 7000000) {
// cyclesPerStep = 1;
// DEBUG = 1;
// }
// Simulate multiple cycles in a row when possible to reduce the overheads of
// stopping and starting simulation.
if (DEBUG || ((cycle + bigStep) >= TIMEOUT))
cyclesPerStep = smallStep;
else
cyclesPerStep = bigStep;
if ((cycle > 0) && (cycle % 1000000 < cyclesPerStep) && !DEBUG && !Arguments::silent())
statusUpdate(cerr);
timestep(cyclesPerStep);
cycle += cyclesPerStep;
if (cycle % 100000 < cyclesPerStep) {
bool progress = checkProgress(100000);
if (!progress)
break;
}
bool idle = checkIdle();
if (idle)
break;
if (cycle >= TIMEOUT) {
timeout();
break;
}
}
}
}
catch (std::exception& e) {
// If there's no error message, it might mean that not everything is
// connected properly.
cerr << "Execution ended unexpectedly at cycle " << Instrumentation::currentCycle() << ":\n"
<< e.what() << endl;
RETURN_CODE = EXIT_FAILURE;
}
}
// Tasks which happen before the model has been generated.
void initialise(chip_parameters_t& params) {
// Override parameters before instantiating chip model
for (unsigned int i=0; i<Arguments::code().size(); i++)
CodeLoader::loadParameters(Arguments::code()[i], params);
Arguments::updateState(params);
if (DEBUG >= 3)
Parameters::printParameters(params);
// Now that we know how many cores, etc, there are, initialise any
// instrumentation structures.
Encoding::initialise(params);
Instrumentation::initialise(params);
if (ENERGY_TRACE || Arguments::summarise())
Instrumentation::start();
// Switch off some unhelpful SystemC reports.
sc_report_handler::set_actions("/OSCI/SystemC", SC_DO_NOTHING);
}
// Instantiate chip model - changing a parameter after this point has
// undefined behaviour.
Chip& createChipModel(const chip_parameters_t& params) {
Chip* chip = new Chip("chip", params);
return *chip;
}
// Tasks which happen after the chip model has been created, but before
// simulation begins.
void presimulation(Chip& chip, const chip_parameters_t& params) {
// Put arguments for the simulated program into simulated memory.
Arguments::storeArguments(chip);
// Load code to execute, and link it all into one program.
for (unsigned int i=0; i<Arguments::code().size(); i++)
CodeLoader::loadCode(Arguments::code()[i], chip);
CodeLoader::makeExecutable(chip);
if (Arguments::summarise() || ENERGY_TRACE)
Instrumentation::start();
}
// Tasks which happen after simulation finishes.
void postsimulation(Chip& chip, const chip_parameters_t& params) {
Instrumentation::stop();
// Print debug information
if (Arguments::summarise())
Instrumentation::printSummary(params);
if (!Arguments::energyTraceFile().empty()) {
std::ofstream output(Arguments::energyTraceFile().c_str());
Instrumentation::dumpEventCounts(output, params);
output.close();
cout << "Execution statistics written to " << Arguments::energyTraceFile() << endl;
}
else if (Instrumentation::haveEnergyData() && RETURN_CODE == EXIT_SUCCESS) {
// If we have collected some data but haven't been told where to put it,
// dump it all to stdout.
Instrumentation::dumpEventCounts(std::cout, params);
}
if (Arguments::ipkStats()) {
std::ofstream output(Arguments::ipkStatsFile().c_str());
Instrumentation::IPKCache::instructionPacketStats(output);
output.close();
}
Instrumentation::end();
// Stop traces
Callgrind::endTrace();
}
// Entry point of my part of the program.
int sc_main(int argc, char* argv[]) {
Arguments::parse(argc, argv);
if (Arguments::simulate()) {
chip_parameters_t* params = Parameters::defaultParameters();
initialise(*params);
Chip& chip = createChipModel(*params);
presimulation(chip, *params);
simulate(chip, *params);
postsimulation(chip, *params);
delete &chip;
delete params;
return RETURN_CODE;
}
else
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2017 Cadence Design Systems, Inc. All rights reserved worldwide.
//
// The code contained herein is the proprietary and confidential information
// of Cadence or its licensors, and is supplied subject to a previously
// executed license and maintenance agreement between Cadence and customer.
// This code is intended for use with Cadence high-level synthesis tools and
// may not be used with other high-level synthesis tools. Permission is only
// granted to distribute the code as indicated. Cadence grants permission for
// customer to distribute a copy of this code to any partner to aid in designing
// or verifying the customer's intellectual property, as long as such
// distribution includes a restriction of no additional distributions from the
// partner, unless the partner receives permission directly from Cadence.
//
// ALL CODE FURNISHED BY CADENCE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, AND CADENCE SPECIFICALLY DISCLAIMS ANY WARRANTY OF NONINFRINGEMENT,
// FITNESS FOR A PARTICULAR PURPOSE OR MERCHANTABILITY. CADENCE SHALL NOT BE
// LIABLE FOR ANY COSTS OF PROCUREMENT OF SUBSTITUTES, LOSS OF PROFITS,
// INTERRUPTION OF BUSINESS, OR FOR ANY OTHER SPECIAL, CONSEQUENTIAL OR
// INCIDENTAL DAMAGES, HOWEVER CAUSED, WHETHER FOR BREACH OF WARRANTY,
// CONTRACT, TORT, NEGLIGENCE, STRICT LIABILITY OR OTHERWISE.
//
////////////////////////////////////////////////////////////////////////////////
#include <systemc.h> // SystemC definitions
#include "system.h" // Top-level System module header file
static System * m_system = NULL; // The pointer that holds the top-level System module instance.
void esc_elaborate() // This function is required by Stratus to support SystemC-Verilog
{ // cosimulation. It instances the top-level module.
m_system = new System( "system" );
}
void esc_cleanup() // This function is called at the end of simulation by the
{ // Stratus co-simulation hub. It should delete the top-level
delete m_system; // module instance.
}
int sc_main( int argc, char ** argv ) // This function is called by the SystemC kernel for pure SystemC simulations
{
esc_initialize( argc, argv ); // esc_initialize() passes in the cmd-line args. This initializes the Stratus simulation
// environment (such as opening report files for later logging and analysis).
esc_elaborate(); // esc_elaborate() (defined above) creates the top-level module instance. In a SystemC-Verilog
// co-simulation, this is called during cosim initialization rather than from sc_main.
sc_start(); // Starts the simulation. Returns when a module calls esc_stop(), which finishes the simulation.
// esc_cleanup() (defined above) is automatically called before sc_start() returns.
return 0; // Returns the status of the simulation. Required by most C compilers.
}
|
/*****************************************************************************
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.
*****************************************************************************/
/*****************************************************************************
rsa.cpp -- An implementation of the RSA public-key cipher. The
following implementation is based on the one given in Cormen et
al., Inroduction to Algorithms, 1991. I'll refer to this book as
CLR because of its authors. This implementation shows the usage of
arbitrary precision types of SystemC. That is, these types in
SystemC can be used to implement algorithmic examples regarding
arbitrary precision integers. The algorithms used are not the most
efficient ones; however, they are intended for explanatory
purposes, so they are simple and perform their job correctly.
Below, NBITS shows the maximum number of bits in n, the variable
that is a part of both the public and secret keys, P and S,
respectively. NBITS can be made larger at the expense of longer
running time. For example, CLR mentions that the RSA cipher uses
large primes that contain approximately 100 decimal digits. This
means that NBITS should be set to approximately 560.
Some background knowledge: A prime number p > 1 is an integer that
has only two divisiors, 1 and p itself. For example, 2, 3, 5, 7,
and 11 are all primes. If p is not a prime number, it is called a
composite number. If we are given two primes p and q, it is easy
to find their product p * q; however, if we are given a number m
which happens to be the product of two primes p and q that we do
not know, it is very difficult to find p and q if m is very large,
i.e., it is very difficult to factor m. The RSA public-key
cryptosystem is based on this fact. Internally, we use the
Miller-Rabin randomized primality test to deal with primes. More
information can be obtained from pp. 831-836 in CLR, the first
edition.
Original Author: Ali Dasdan, Synopsys, Inc.
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
#include <stdlib.h>
#include <sys/types.h>
#include <time.h>
#include <stdlib.h> // drand48, srand48
#include "systemc.h"
#define DEBUG_SYSTEMC // #undef this to disable assertions.
// NBITS is the number of bits in n of public and secret keys P and
// S. HALF_NBITS is the number of bits in p and q, which are the prime
// factors of n.
#define NBITS 250
#define HALF_NBITS ( NBITS / 2 )
// +2 is for the format specifier '0b' to make the string binary.
#define STR_SIZE ( NBITS + 2 )
#define HALF_STR_SIZE ( HALF_NBITS + 2 )
typedef sc_bigint<NBITS> bigint;
// Return the absolute value of x.
inline
bigint
abs_val( const sc_signed& x )
{
return ( x < 0 ? -x : x );
}
// Initialize the random number generator. If seed == -1, the
// generator will be initialized with the system time. If not, it will
// be initialized with the given seed. This way, an experiment with
// random numbers becomes reproducible.
inline
long
randomize( int seed )
{
long in_seed; // time_t is long.
in_seed = ( seed <= 0 ? static_cast<long>(time( 0 )) : seed );
srand( ( unsigned ) in_seed );
return in_seed;
}
// Flip a coin with probability p.
inline
bool
flip( double p )
{
// rand() produces an integer between 0 and RAND_MAX so
// rand() / RAND_MAX is a number between 0 and 1,
// which is required to compare with p.
return ( rand() < ( int ) ( p * RAND_MAX ) );
}
// Randomly generate a bit string with nbits bits. str has a length
// of nbits + 1. This function is used to generate random messages to
// process.
inline
void
rand_bitstr( char *str, int nbits )
{
assert( nbits >= 4 );
str[ 0 ] = '0';
str[ 1 ] = 'b';
str[ 2 ] = '0'; // Sign for positive numbers.
for ( int i = 3; i < nbits; ++i )
str[ i ] = ( flip( 0.5 ) == true ? '1' : '0' );
str[ nbits ] = '\0';
}
// Generate "111..111" with nbits bits for masking.
// str has a length of nbits + 1.
inline
void
max_bitstr( char *str, int nbits )
{
assert( nbits >= 4 );
str[ 0 ] = '0';
str[ 1 ] = 'b';
str[ 2 ] = '0'; // Sign for positive numbers.
for ( int i = 3; i < nbits; ++i )
str[ i ] = '1';
str[ nbits ] = '\0';
}
// Return a positive remainder.
inline
bigint
ret_pos( const bigint& x, const bigint& n )
{
if ( x < 0 )
return x + n;
return x;
}
// Compute the greatest common divisor ( gcd ) of a and b. This is
// Euclid's algorithm. This algorithm is at least 2,300 years old! The
// non-recursive version of this algorithm is not as elegant.
bigint
gcd( const bigint& a, const bigint& b )
{
if ( b == 0 )
return a;
return gcd( b, a % b );
}
// Compute d, x, and y such that d = gcd( a, b ) = ax + by. x and y can
// be zero or negative. This algorithm is also Euclid's algorithm but
// it is extended to also find x and y. Recall that the existence of x
// and y is guaranteed by Euclid's algorithm.
void
euclid( const bigint& a, const bigint& b, bigint& d, bigint& x, bigint& y )
{
if ( b != 0 ) {
euclid( b, a % b, d, x, y );
bigint tmp = x;
x = y;
y = tmp - ( a / b ) * y;
}
else {
d = a;
x = 1;
y = 0;
}
}
// Return d = a^b % n, where ^ represents exponentiation.
inline
bigint
modular_exp( const bigint& a, const bigint& b, const bigint& n )
{
bigint d = 1;
for ( int i = b.length() - 1; i >= 0; --i )
{
d = ( d * d ) % n;
if ( b[ i ] )
d = ( d * a ) % n;
}
return ret_pos( d, n );
}
// Return the multiplicative inverse of a, modulo n, when a and n are
// relatively prime. Recall that x is a multiplicative inverse of a,
// modulo n, if a * x = 1 ( mod n ).
inline
bigint
inverse( const bigint& a, const bigint& n )
{
bigint d, x, y;
euclid( a, n, d, x, y );
assert( d == 1 );
x %= n;
return ret_pos( x, n );
}
// Find a small odd integer a that is relatively prime to n. I do not
// know an efficient algorithm to do that but the loop below seems to
// work; it usually iterates a few times. Recall that a is relatively
// prime to n if their only common divisor is 1, i.e., gcd( a, n ) ==
// 1.
inline
bigint
find_rel_prime( const bigint& n )
{
bigint a = 3;
while ( true ) {
if ( gcd( a, n ) == 1 )
break;
a += 2;
#ifdef DEBUG_SYSTEMC
assert( a < n );
#endif
}
return a;
}
// Return true if and only if a is a witness to the compositeness of
// n, i.e., a can be used to prove that n is composite.
inline
bool
witness( const bigint& a, const bigint& n )
{
bigint n_minus1 = n - 1;
bigint x;
bigint d = 1;
// Compute d = a^( n-1 ) % n.
for ( int i = n.length() - 1; i >= 0; --i )
{
// Sun's SC5 bug when compiling optimized version
// makes the wrong assignment if abs_val() is inlined
//x = (sc_signed)d<0?-(sc_signed)d:(sc_signed)d;//abs_val( d );
if(d<0)
{
x = -d;
assert(x==-d);
}
else
{
x = d;
assert(x==d);
}
d = ( d * d ) % n;
// x is a nontrivial square root of 1 modulo n ==> n is composite.
if ( ( abs_val( d ) == 1 ) && ( x != 1 ) && ( x != n_minus1 ) )
return true;
if ( n_minus1[ i ] )
d = ( d * a ) % n;
}
// d = a^( n-1 ) % n != 1 ==> n is composite.
if ( abs_val( d ) != 1 )
return true;
return false;
}
// Check to see if n has any small divisors. For small numbers, we do
// not have to run the Miller-Rabin primality test. We define "small"
// to be less than 1023. You can change it if necessary.
inline
bool
div_test( const bigint& n )
{
int limit;
if ( n < 1023 )
limit = n.to_int() - 2;
else
limit = 1023;
for ( int i = 3; i <= limit; i += 2 ) {
if ( n % i == 0 )
return false; // n is composite.
}
return true; // n may be prime.
}
// Return true if n is almost surely prime, return false if n is
// definitely composite. This test, called the Miller-Rabin primality
// test, errs with probaility at most 2^(-s). CLR suggests s = 50 for
// any imaginable application, and s = 3 if we are trying to find
// large primes by applying miller_rabin to randomly chosen large
// integers. Even though we are doing the latter here, we will still
// choose s = 50. The probability of failure is at most
// 0.00000000000000088817, a pretty small number.
inline
bool
miller_rabin( const bigint& n )
{
if ( n <= 2 )
return false;
if ( ! div_test( n ) )
return false;
char str[ STR_SIZE + 1 ];
int s = 50;
for ( int j = 1; j <= s; ++j ) {
// Choose a random number.
rand_bitstr( str, STR_SIZE );
// Set a to the chosen number.
bigint a = str;
// Make sure that a is in [ 1, n - 1 ].
a = ( a % ( n - 1 ) ) + 1;
// Check to see if a is a witness.
if ( witness( a, n ) )
return false; // n is definitely composite.
}
return true; // n is almost surely prime.
}
// Return a randomly generated, large prime number using the
// Miller-Rabin primality test.
inline
bigint
find_prime( const bigint& r )
{
char p_str[ HALF_STR_SIZE + 1 ];
rand_bitstr( p_str, HALF_STR_SIZE );
p_str[ HALF_STR_SIZE - 1 ] = '1'; // Force p to be an odd number.
bigint p = p_str;
#ifdef DEBUG_SYSTEMC
assert( ( p > 0 ) && ( p % 2 == 1 ) );
#endif
// p is randomly determined. Now, we'll look for a prime in the
// vicinity of p. By the prime number theorem, executing the
// following loop approximately ln ( 2^NBITS ) iterations should
// find a prime.
#ifdef DEBUG_SYSTEMC
// A very large counter to check against infinite loops.
sc_bigint<NBITS> niter = 0;
#endif
#if defined(SC_BIGINT_CONFIG_HOLLOW) // Remove when we fix hollow support!!
while ( ! miller_rabin( p ) ) {
p = ( p + 2 ) % r;
#else
size_t increment;
for ( increment = 0; increment < 100000 && !miller_rabin( p ); ++increment ) {
p = ( p + 2 ) % r;
#endif
#ifdef DEBUG_SYSTEMC
assert( ++niter > 0 );
#endif
}
return p;
}
// Encode or cipher the message in msg using the RSA public key P=( e, n ).
inline
bigint
cipher( const bigint& msg, const bigint& e, const bigint& n )
{
return modular_exp( msg, e, n );
}
// Dencode or decipher the message in msg using the RSA secret key S=( d, n ).
inline
bigint
decipher( const bigint& msg, const bigint& d, const bigint& n )
{
return modular_exp( msg, d, n );
}
// The RSA cipher.
inline
void
rsa( int seed )
{
// Generate all 1's in r.
char r_str[ HALF_STR_SIZE + 1 ];
max_bitstr( r_str, HALF_STR_SIZE );
bigint r = r_str;
#ifdef DEBUG_SYSTEMC
assert( r > 0 );
#endif
// Initialize the random number generator.
cout << "\nRandom number generator seed = " << randomize( seed ) << endl;
cout << endl;
// Find two large primes p and q.
bigint p = find_prime( r );
bigint q = find_prime( r );
#ifdef DEBUG_SYSTEMC
assert( ( p > 0 ) && ( q > 0 ) );
#endif
// Compute n and ( p - 1 ) * ( q - 1 ) = m.
bigint n = p * q;
bigint m = ( p - 1 ) * ( q - 1 );
#ifdef DEBUG_SYSTEMC
assert( ( n > 0 ) && ( m > 0 ) );
#endif
// Find a small odd integer e that is relatively prime to m.
bigint e = find_rel_prime( m );
#ifdef DEBUG_SYSTEMC
assert( e > 0 );
#endif
// Find the multiplicative inverse d of e, modulo m.
bigint d = inverse( e, m );
#ifdef DEBUG_SYSTEMC
assert( d > 0 );
#endif
// Output public and secret keys.
cout << "RSA public key P: P=( e, n )" << endl;
cout << "e = " << e << endl;
cout << "n = " << n << endl;
cout << endl;
cout << "RSA secret key S: S=( d, n )" << endl;
cout << "d = " << d << endl;
cout << "n = " << n << endl;
cout << endl;
// Cipher and decipher a randomly generated message msg.
char msg_str[ STR_SIZE + 1 ];
rand_bitstr( msg_str, STR_SIZE );
bigint msg = msg_str;
msg %= n; // Make sure msg is smaller than n. If larger, this part
// will be a block of the input message.
#ifdef DEBUG_SYSTEMC
assert( msg > 0 );
#endif
cout << "Message to be ciphered = " << endl;
cout << msg << endl;
bigint msg2 = cipher( msg, e, n );
cout << "\nCiphered message = " << endl;
cout << msg2 << endl;
msg2 = decipher( msg2, d, n );
cout << "\nDeciphered message = " << endl;
cout << msg2 << endl;
// Make sure that the original message is recovered.
if ( msg == msg2 ) {
cout << "\nNote that the original message == the deciphered message, " << endl;
cout << "showing that this algorithm and implementation work correctly.\n" << endl;
}
else {
// This case is unlikely.
cout << "\nNote that the original message != the deciphered message, " << endl;
cout << "showing that this implementation works incorrectly.\n" << endl;
}
return;
}
int sc_main( int argc, char *argv[] )
{
if ( argc <= 1 )
rsa( -1 );
else
rsa( atoi( argv[ 1 ] ) );
return 0;
}
// End of file
|
/******************************************************************************
* *
* Copyright (C) 2022 MachineWare GmbH *
* All Rights Reserved *
* *
* This is work is licensed under the terms described in the LICENSE file *
* found in the root directory of this source tree. *
* *
******************************************************************************/
#include "vcml/core/thctl.h"
#include "vcml/core/systemc.h"
namespace vcml {
struct thctl {
thread::id sysc_thread;
atomic<thread::id> curr_owner;
mutex sysc_mutex;
atomic<int> nwaiting;
condition_variable_any cvar;
thctl();
~thctl();
bool is_sysc_thread() const;
bool is_in_critical() const;
void notify();
void block();
void enter_critical();
void exit_critical();
void suspend();
void flush();
void set_sysc_thread(thread::id id);
static thctl& instance();
};
thctl::thctl():
sysc_thread(std::this_thread::get_id()),
curr_owner(sysc_thread),
sysc_mutex(),
nwaiting(0),
cvar() {
sysc_mutex.lock();
}
thctl::~thctl() {
sysc_mutex.unlock();
notify();
}
bool thctl::is_sysc_thread() const {
return std::this_thread::get_id() == sysc_thread;
}
bool thctl::is_in_critical() const {
return std::this_thread::get_id() == curr_owner;
}
void thctl::notify() {
cvar.notify_all();
}
void thctl::block() {
VCML_ERROR_ON(is_sysc_thread(), "cannot block SystemC thread");
lock_guard<mutex> l(sysc_mutex);
}
void thctl::enter_critical() {
if (is_sysc_thread())
VCML_ERROR("SystemC thread must not enter critical sections");
if (is_in_critical())
VCML_ERROR("thread already in critical section");
if (!sim_running())
return;
int prev = nwaiting++;
if (!sysc_mutex.try_lock()) {
if (prev == 0)
on_next_update([]() -> void { thctl_suspend(); });
sysc_mutex.lock();
}
curr_owner = std::this_thread::get_id();
}
void thctl::exit_critical() {
if (curr_owner != std::this_thread::get_id())
VCML_ERROR("thread not in critical section");
if (nwaiting <= 0)
VCML_ERROR("no thread in critical section");
if (!sim_running())
return;
curr_owner = thread::id();
sysc_mutex.unlock();
if (--nwaiting == 0)
notify();
}
void thctl::suspend() {
VCML_ERROR_ON(!is_sysc_thread(), "this is not the SystemC thread");
VCML_ERROR_ON(!is_in_critical(), "thread not in critical section");
do {
cvar.wait(sysc_mutex);
} while (nwaiting > 0);
curr_owner = sysc_thread;
}
void thctl::flush() {
if (nwaiting > 0)
suspend();
}
void thctl::set_sysc_thread(thread::id id) {
sysc_thread = id;
}
thctl& thctl::instance() {
static thctl singleton;
return singleton;
}
// need to make sure thctl gets created on the main (aka SystemC) thread
thctl& g_thctl = thctl::instance();
bool thctl_is_sysc_thread() {
return thctl::instance().is_sysc_thread();
}
bool thctl_is_in_critical() {
return thctl::instance().is_in_critical();
}
void thctl_notify() {
thctl::instance().notify();
}
void thctl_block() {
thctl::instance().block();
}
void thctl_enter_critical() {
thctl::instance().enter_critical();
}
void thctl_exit_critical() {
thctl::instance().exit_critical();
}
void thctl_suspend() {
thctl::instance().suspend();
}
void thctl_flush() {
thctl::instance().flush();
}
void thctl_set_sysc_thread(thread::id id) {
thctl::instance().set_sysc_thread(id);
}
} // namespace vcml
|
/*
* 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)
*/
#include <iostream>
#include <sstream>
#include <string>
#include <stdio.h>
#include <vp/vp.hpp>
#include <stdio.h>
#include "string.h"
#include <iostream>
#include <sstream>
#include <string>
#include <dlfcn.h>
#include <algorithm>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <poll.h>
#include <signal.h>
#include <regex>
#include <gv/gvsoc_proxy.hpp>
#include <gv/gvsoc.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/prctl.h>
#include <vp/time/time_scheduler.hpp>
#include <vp/proxy.hpp>
#include <vp/queue.hpp>
#include <vp/signal.hpp>
extern "C" long long int dpi_time_ps();
#ifdef __VP_USE_SYSTEMC
#include <systemc.h>
#endif
#ifdef __VP_USE_SYSTEMV
extern "C" void dpi_raise_event();
#endif
char vp_error[VP_ERROR_SIZE];
static Gv_proxy *proxy = NULL;
void vp::component::get_trace(std::vector<vp::trace *> &traces, std::string path)
{
if (this->get_path() != "" && path.find(this->get_path()) != 0)
{
return;
}
for (vp::component *component: this->get_childs())
{
component->get_trace(traces, path);
}
for (auto x: this->traces.traces)
{
if (x.second->get_full_path().find(path) == 0)
{
traces.push_back(x.second);
}
}
for (auto x: this->traces.trace_events)
{
if (x.second->get_full_path().find(path) == 0)
{
traces.push_back(x.second);
}
}
}
void vp::component::reg_step_pre_start(std::function<void()> callback)
{
this->pre_start_callbacks.push_back(callback);
}
void vp::component::register_build_callback(std::function<void()> callback)
{
this->build_callbacks.push_back(callback);
}
void vp::component::post_post_build()
{
traces.post_post_build();
}
void vp::component::final_bind()
{
for (auto port : this->slave_ports)
{
port.second->final_bind();
}
for (auto port : this->master_ports)
{
port.second->final_bind();
}
for (auto &x : this->childs)
{
x->final_bind();
}
}
void vp::component::set_vp_config(js::config *config)
{
this->vp_config = config;
}
void vp::component::set_gv_conf(struct gv_conf *gv_conf)
{
if (gv_conf)
{
memcpy(&this->gv_conf, gv_conf, sizeof(struct gv_conf));
}
else
{
memset(&this->gv_conf, 0, sizeof(struct gv_conf));
gv_init(&this->gv_conf);
}
}
js::config *vp::component::get_vp_config()
{
if (this->vp_config == NULL)
{
if (this->parent != NULL)
{
this->vp_config = this->parent->get_vp_config();
}
}
vp_assert_always(this->vp_config != NULL, NULL, "No VP config found\n");
return this->vp_config;
}
void vp::component::load_all()
{
for (auto &x : this->childs)
{
x->load_all();
}
this->load();
}
int vp::component::build_new()
{
this->bind_comps();
this->post_post_build_all();
this->pre_start_all();
this->start_all();
this->final_bind();
return 0;
}
void vp::component::post_post_build_all()
{
for (auto &x : this->childs)
{
x->post_post_build_all();
}
this->post_post_build();
}
void vp::component::start_all()
{
for (auto &x : this->childs)
{
x->start_all();
}
this->start();
}
void vp::component::stop_all()
{
for (auto &x : this->childs)
{
x->stop_all();
}
this->stop();
}
void vp::component::flush_all()
{
for (auto &x : this->childs)
{
x->flush_all();
}
this->flush();
}
void vp::component::pre_start_all()
{
for (auto &x : this->childs)
{
x->pre_start_all();
}
this->pre_start();
for (auto x : pre_start_callbacks)
{
x();
}
}
void vp::component_clock::clk_reg(component *_this, component *clock)
{
_this->clock = (clock_engine *)clock;
for (auto &x : _this->childs)
{
x->clk_reg(x, clock);
}
}
void vp::component::reset_all(bool active, bool from_itf)
{
// Small hack to not propagate the reset from top level if the reset has
// already been done through the interface from another component.
// This should be all implemented with interfaces to better control
// the reset propagation.
this->reset_done_from_itf |= from_itf;
if (from_itf || !this->reset_done_from_itf)
{
this->get_trace()->msg("Reset\n");
this->pre_reset();
for (auto reg : this->regs)
{
reg->reset(active);
}
this->block::reset_all(active);
if (active)
{
for (clock_event *event: this->events)
{
this->event_cancel(event);
}
}
for (auto &x : this->childs)
{
x->reset_all(active);
}
}
}
void vp::component_clock::reset_sync(void *__this, bool active)
{
component *_this = (component *)__this;
_this->reset_done_from_itf = true;
_this->reset_all(active, true);
}
void vp::component_clock::pre_build(component *comp)
{
clock_port.set_reg_meth((vp::clk_reg_meth_t *)&component_clock::clk_reg);
comp->new_slave_port("clock", &clock_port);
reset_port.set_sync_meth(&component_clock::reset_sync);
comp->new_slave_port("reset", &reset_port);
comp->traces.new_trace("comp", comp->get_trace(), vp::DEBUG);
comp->traces.new_trace("warning", &comp->warning, vp::WARNING);
}
int64_t vp::time_engine::get_next_event_time()
{
if (this->first_client)
{
return this->first_client->next_event_time;
}
return this->time;
}
bool vp::time_engine::dequeue(time_engine_client *client)
{
if (!client->is_enqueued)
return false;
client->is_enqueued = false;
time_engine_client *current = this->first_client, *prev = NULL;
while (current && current != client)
{
prev = current;
current = current->next;
}
if (prev)
prev->next = client->next;
else
this->first_client = client->next;
return true;
}
bool vp::time_engine::enqueue(time_engine_client *client, int64_t time)
{
vp_assert(time >= 0, NULL, "Time must be positive\n");
int64_t full_time = this->get_time() + time;
#ifdef __VP_USE_SYSTEMC
// Notify to the engine that something has been pushed in case it is done
// by an external systemC component and the engine needs to be waken up
if (started)
sync_event.notify();
#endif
#ifdef __VP_USE_SYSTEMV
dpi_raise_event();
#endif
if (client->is_running())
return false;
if (client->is_enqueued)
{
if (client->next_event_time <= full_time)
return false;
this->dequeue(client);
}
client->is_enqueued = true;
time_engine_client *current = first_client, *prev = NULL;
client->next_event_time = full_time;
while (current && current->next_event_time < client->next_event_time)
{
prev = current;
current = current->next;
}
if (prev)
prev->next = client;
else
first_client = client;
client->next = current;
return true;
}
bool vp::clock_engine::dequeue_from_engine()
{
if (this->is_running() || !this->is_enqueued)
return false;
this->engine->dequeue(this);
return true;
}
void vp::clock_engine::reenqueue_to_engine()
{
this->engine->enqueue(this, this->next_event_time);
}
void vp::clock_engine::apply_frequency(int frequency)
{
if (frequency > 0)
{
bool reenqueue = this->dequeue_from_engine();
int64_t period = this->period;
this->freq = frequency;
this->period = 1e12 / this->freq;
if (reenqueue && period > 0)
{
int64_t cycles = (this->next_event_time - this->get_time()) / period;
this->next_event_time = cycles * this->period;
this->reenqueue_to_engine();
}
else if (period == 0)
{
// Case where the clock engine was clock-gated
// We need to reenqueue the engine in case it has pending events
if (this->has_events())
{
// Compute the time of the next event based on the new frequency
this->next_event_time = (this->get_next_event()->get_cycle() - this->get_cycles()) * this->period;
this->reenqueue_to_engine();
}
}
}
else if (frequency == 0)
{
this->dequeue_from_engine();
this->period = 0;
}
}
void vp::clock_engine::update()
{
if (this->period == 0)
return;
int64_t diff = this->get_time() - this->stop_time;
#ifdef __VP_USE_SYSTEMC
if ((int64_t)sc_time_stamp().to_double() > this->get_time())
diff = (int64_t)sc_time_stamp().to_double() - this->stop_time;
engine->update((int64_t)sc_time_stamp().to_double());
#endif
if (diff > 0)
{
int64_t cycles = (diff + this->period - 1) / this->period;
this->stop_time += cycles * this->period;
this->cycles += cycles;
}
}
vp::clock_event *vp::clock_engine::enqueue_other(vp::clock_event *event, int64_t cycle)
{
// Slow case where the engine is not running or we must enqueue out of the
// circular buffer.
// First check if we have to enqueue it to the global time engine in case we
// were not running.
// Check if we can enqueue to the fast circular queue in case were not
// running.
bool can_enqueue_to_cycle = false;
if (!this->is_running())
{
//this->current_cycle = (this->get_cycles() + 1) & CLOCK_EVENT_QUEUE_MASK;
//can_enqueue_to_cycle = this->current_cycle + cycle - 1 < CLOCK_EVENT_QUEUE_SIZE;
}
if (can_enqueue_to_cycle)
{
//this->current_cycle = (this->get_cycles() + cycle) & CLOCK_EVENT_QUEUE_MASK;
this->enqueue_to_cycle(event, cycle - 1);
if (this->period != 0)
enqueue_to_engine(period);
}
else
{
this->must_flush_delayed_queue = true;
if (this->period != 0)
{
enqueue_to_engine(cycle * period);
}
vp::clock_event *current = delayed_queue, *prev = NULL;
int64_t full_cycle = cycle + get_cycles();
while (current && current->cycle < full_cycle)
{
prev = current;
current = current->next;
}
if (prev)
prev->next = event;
else
delayed_queue = event;
event->next = current;
event->cycle = full_cycle;
}
return event;
}
vp::clock_event *vp::clock_engine::get_next_event()
{
// There is no quick way of getting the next event.
// We have to first check if there is an event in the circular buffer
// and if not in the delayed queue
if (this->nb_enqueued_to_cycle)
{
for (int i = 0; i < CLOCK_EVENT_QUEUE_SIZE; i++)
{
int cycle = (current_cycle + i) & CLOCK_EVENT_QUEUE_MASK;
vp::clock_event *event = event_queue[cycle];
if (event)
{
return event;
}
}
vp_assert(false, 0, "Didn't find any event in circular buffer while it is not empty\n");
}
return this->delayed_queue;
}
void vp::clock_engine::cancel(vp::clock_event *event)
{
if (!event->is_enqueued())
return;
// There is no way to know if the event is enqueued into the circular buffer
// or in the delayed queue so first go through the delayed queue and if it is
// not found, look in the circular buffer
// First the delayed queue
vp::clock_event *current = delayed_queue, *prev = NULL;
while (current)
{
if (current == event)
{
if (prev)
prev->next = event->next;
else
delayed_queue = event->next;
goto end;
}
prev = current;
current = current->next;
}
// Then in the circular buffer
for (int i = 0; i < CLOCK_EVENT_QUEUE_SIZE; i++)
{
vp::clock_event *current = event_queue[i], *prev = NULL;
while (current)
{
if (current == event)
{
if (prev)
prev->next = event->next;
else
event_queue[i] = event->next;
this->nb_enqueued_to_cycle--;
goto end;
}
prev = current;
current = current->next;
}
}
vp_assert(0, NULL, "Didn't find event in any queue while canceling event\n");
end:
event->enqueued = false;
if (!this->has_events())
this->dequeue_from_engine();
}
void vp::clock_engine::flush_delayed_queue()
{
clock_event *event = delayed_queue;
this->must_flush_delayed_queue = false;
while (event)
{
if (nb_enqueued_to_cycle == 0)
cycles = event->cycle;
uint64_t cycle_diff = event->cycle - get_cycles();
if (cycle_diff >= CLOCK_EVENT_QUEUE_SIZE)
break;
clock_event *next = event->next;
enqueue_to_cycle(event, cycle_diff);
event = next;
delayed_queue = event;
}
}
int64_t vp::clock_engine::exec()
{
vp_assert(this->has_events(), NULL, "Executing clock engine while it has no event\n");
vp_assert(this->get_next_event(), NULL, "Executing clock engine while it has no next event\n");
this->cycles_trace.event_real(this->cycles);
// The clock engine has a circular buffer of events to be executed.
// Events longer than the buffer as put temporarly in a queue.
// Everytime we start again at the beginning of the buffer, we need
// to check if events must be enqueued from the queue to the buffer
// in case they fit the window.
if (unlikely(this->must_flush_delayed_queue))
{
this->flush_delayed_queue();
}
vp_assert(this->get_next_event(), NULL, "Executing clock engine while it has no next event\n");
// Now take all events available at the current cycle and execute them all without returning
// to the main engine to execute them faster.
clock_event *current = event_queue[current_cycle];
while (likely(current != NULL))
{
event_queue[current_cycle] = current->next;
current->enqueued = false;
nb_enqueued_to_cycle--;
current->meth(current->_this, current);
current = event_queue[current_cycle];
}
// Now we need to tell the time engine when is the next event.
// The most likely is that there is an event in the circular buffer,
// in which case we just return the clock period, as we will go through
// each element of the circular buffer, even if the next event is further in
// the buffer.
if (likely(nb_enqueued_to_cycle))
{
cycles++;
current_cycle = (current_cycle + 1) & CLOCK_EVENT_QUEUE_MASK;
if (unlikely(current_cycle == 0))
this->must_flush_delayed_queue = true;
return period;
}
else
{
// Otherwise if there is an event in the delayed queue, return the time
// to this event.
// In both cases, force the delayed queue flush so that the next event to be
// executed is moved to the circular buffer.
this->must_flush_delayed_queue = true;
// Also remember the current time in order to resynchronize the clock engine
// in case we enqueue and event from another engine.
this->stop_time = this->get_time();
if (delayed_queue)
{
return (delayed_queue->cycle - get_cycles()) * period;
}
else
{
// In case there is no more event to execute, returns -1 to tell the time
// engine we are done.
return -1;
}
}
}
vp::clock_event::clock_event(component_clock *comp, clock_event_meth_t *meth)
: comp(comp), _this((void *)static_cast<vp::component *>((vp::component_clock *)(comp))), meth(meth), enqueued(false)
{
comp->add_clock_event(this);
}
void vp::component_clock::add_clock_event(clock_event *event)
{
this->events.push_back(event);
}
vp::time_engine *vp::component::get_time_engine()
{
if (this->time_engine_ptr == NULL)
{
this->time_engine_ptr = (vp::time_engine*)this->get_service("time");
}
return this->time_engine_ptr;
}
vp::master_port::master_port(vp::component *owner)
: vp::port(owner)
{
}
void vp::component::new_master_port(std::string name, vp::master_port *port)
{
this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New master port (name: %s, port: %p)\n", name.c_str(), port);
port->set_owner(this);
port->set_context(this);
port->set_name(name);
this->add_master_port(name, port);
}
void vp::component::new_master_port(void *comp, std::string name, vp::master_port *port)
{
this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New master port (name: %s, port: %p)\n", name.c_str(), port);
port->set_owner(this);
port->set_context(comp);
port->set_name(name);
this->add_master_port(name, port);
}
void vp::component::add_slave_port(std::string name, vp::slave_port *port)
{
vp_assert_always(port != NULL, this->get_trace(), "Adding NULL port\n");
//vp_assert_always(this->slave_ports[name] == NULL, this->get_trace(), "Adding already existing port\n");
this->slave_ports[name] = port;
}
void vp::component::add_master_port(std::string name, vp::master_port *port)
{
vp_assert_always(port != NULL, this->get_trace(), "Adding NULL port\n");
//vp_assert_always(this->master_ports[name] == NULL, this->get_trace(), "Adding already existing port\n");
this->master_ports[name] = port;
}
void vp::component::new_slave_port(std::string name, vp::slave_port *port)
{
this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New slave port (name: %s, port: %p)\n", name.c_str(), port);
port->set_owner(this);
port->set_context(this);
port->set_name(name);
this->add_slave_port(name, port);
}
void vp::component::new_slave_port(void *comp, std::string name, vp::slave_port *port)
{
this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New slave port (name: %s, port: %p)\n", name.c_str(), port);
port->set_owner(this);
port->set_context(comp);
port->set_name(name);
this->add_slave_port(name, port);
}
void vp::component::add_service(std::string name, void *service)
{
if (this->parent)
this->parent->add_service(name, service);
else if (all_services[name] == NULL)
all_services[name] = service;
}
void vp::component::new_service(std::string name, void *service)
{
this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New service (name: %s, service: %p)\n", name.c_str(), service);
if (this->parent)
this->parent->add_service(name, service);
all_services[name] = service;
}
void *vp::component::get_service(string name)
{
if (all_services[name])
return all_services[name];
if (this->parent)
return this->parent->get_service(name);
return NULL;
}
std::vector<std::string> split_name(const std:
|
:string &s, char delimiter)
{
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(s);
while (std::getline(tokenStream, token, delimiter))
{
tokens.push_back(token);
}
return tokens;
}
vp::config *vp::config::create_config(jsmntok_t *tokens, int *_size)
{
jsmntok_t *current = tokens;
config *config = NULL;
switch (current->type)
{
case JSMN_PRIMITIVE:
if (strcmp(current->str, "True") == 0 || strcmp(current->str, "False") == 0 || strcmp(current->str, "true") == 0 || strcmp(current->str, "false") == 0)
{
config = new config_bool(current);
}
else
{
config = new config_number(current);
}
current++;
break;
case JSMN_OBJECT:
{
int size;
config = new config_object(current, &size);
current += size;
break;
}
case JSMN_ARRAY:
{
int size;
config = new config_array(current, &size);
current += size;
break;
}
case JSMN_STRING:
config = new config_string(current);
current++;
break;
case JSMN_UNDEFINED:
break;
}
if (_size)
{
*_size = current - tokens;
}
return config;
}
vp::config *vp::config_string::get_from_list(std::vector<std::string> name_list)
{
if (name_list.size() == 0)
return this;
return NULL;
}
vp::config *vp::config_number::get_from_list(std::vector<std::string> name_list)
{
if (name_list.size() == 0)
return this;
return NULL;
}
vp::config *vp::config_bool::get_from_list(std::vector<std::string> name_list)
{
if (name_list.size() == 0)
return this;
return NULL;
}
vp::config *vp::config_array::get_from_list(std::vector<std::string> name_list)
{
if (name_list.size() == 0)
return this;
return NULL;
}
vp::config *vp::config_object::get_from_list(std::vector<std::string> name_list)
{
if (name_list.size() == 0)
return this;
vp::config *result = NULL;
std::string name;
int name_pos = 0;
for (auto &x : name_list)
{
if (x != "*" && x != "**")
{
name = x;
break;
}
name_pos++;
}
for (auto &x : childs)
{
if (name == x.first)
{
result = x.second->get_from_list(std::vector<std::string>(name_list.begin() + name_pos + 1, name_list.begin() + name_list.size()));
if (name_pos == 0 || result != NULL)
return result;
}
else if (name_list[0] == "*")
{
result = x.second->get_from_list(std::vector<std::string>(name_list.begin() + 1, name_list.begin() + name_list.size()));
if (result != NULL)
return result;
}
else if (name_list[0] == "**")
{
result = x.second->get_from_list(name_list);
if (result != NULL)
return result;
}
}
return result;
}
vp::config *vp::config_object::get(std::string name)
{
return get_from_list(split_name(name, '/'));
}
vp::config_string::config_string(jsmntok_t *tokens)
{
value = tokens->str;
}
vp::config_number::config_number(jsmntok_t *tokens)
{
value = atof(tokens->str);
}
vp::config_bool::config_bool(jsmntok_t *tokens)
{
value = strcmp(tokens->str, "True") == 0 || strcmp(tokens->str, "true") == 0;
}
vp::config_array::config_array(jsmntok_t *tokens, int *_size)
{
jsmntok_t *current = tokens;
jsmntok_t *top = current++;
for (int i = 0; i < top->size; i++)
{
int child_size;
elems.push_back(create_config(current, &child_size));
current += child_size;
}
if (_size)
{
*_size = current - tokens;
}
}
vp::config_object::config_object(jsmntok_t *tokens, int *_size)
{
jsmntok_t *current = tokens;
jsmntok_t *t = current++;
for (int i = 0; i < t->size; i++)
{
jsmntok_t *child_name = current++;
int child_size;
config *child_config = create_config(current, &child_size);
current += child_size;
if (child_config != NULL)
{
childs[child_name->str] = child_config;
}
}
if (_size)
{
*_size = current - tokens;
}
}
vp::config *vp::component::import_config(const char *config_string)
{
if (config_string == NULL)
return NULL;
jsmn_parser parser;
jsmn_init(&parser);
int nb_tokens = jsmn_parse(&parser, config_string, strlen(config_string), NULL, 0);
jsmntok_t tokens[nb_tokens];
jsmn_init(&parser);
nb_tokens = jsmn_parse(&parser, config_string, strlen(config_string), tokens, nb_tokens);
char *str = strdup(config_string);
for (int i = 0; i < nb_tokens; i++)
{
jsmntok_t *tok = &tokens[i];
tok->str = &str[tok->start];
str[tok->end] = 0;
}
return new vp::config_object(tokens);
}
void vp::component::conf(string name, string path, vp::component *parent)
{
this->name = name;
this->parent = parent;
this->path = path;
if (parent != NULL)
{
parent->add_child(name, this);
}
}
void vp::component::add_child(std::string name, vp::component *child)
{
this->childs.push_back(child);
this->childs_dict[name] = child;
}
vp::component *vp::component::get_component(std::vector<std::string> path_list)
{
if (path_list.size() == 0)
{
return this;
}
std::string name = "";
unsigned int name_pos= 0;
for (auto x: path_list)
{
if (x != "*" && x != "**")
{
name = x;
break;
}
name_pos += 1;
}
for (auto x:this->childs)
{
vp::component *comp;
if (name == x->get_name())
{
comp = x->get_component({ path_list.begin() + name_pos + 1, path_list.end() });
}
else if (path_list[0] == "**")
{
comp = x->get_component(path_list);
}
else if (path_list[0] == "*")
{
comp = x->get_component({ path_list.begin() + 1, path_list.end() });
}
if (comp)
{
return comp;
}
}
return NULL;
}
void vp::component::elab()
{
for (auto &x : this->childs)
{
x->elab();
}
}
void vp::component::new_reg_any(std::string name, vp::reg *reg, int bits, uint8_t *reset_val)
{
reg->init(this, name, bits, NULL, reset_val);
this->regs.push_back(reg);
}
void vp::component::new_reg(std::string name, vp::reg_1 *reg, uint8_t reset_val, bool reset)
{
this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New register (name: %s, width: %d, reset_val: 0x%x, reset: %d)\n",
name.c_str(), 1, reset_val, reset
);
reg->init(this, name, reset ? (uint8_t *)&reset_val : NULL);
this->regs.push_back(reg);
}
void vp::component::new_reg(std::string name, vp::reg_8 *reg, uint8_t reset_val, bool reset)
{
this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New register (name: %s, width: %d, reset_val: 0x%x, reset: %d)\n",
name.c_str(), 8, reset_val, reset
);
reg->init(this, name, reset ? (uint8_t *)&reset_val : NULL);
this->regs.push_back(reg);
}
void vp::component::new_reg(std::string name, vp::reg_16 *reg, uint16_t reset_val, bool reset)
{
this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New register (name: %s, width: %d, reset_val: 0x%x, reset: %d)\n",
name.c_str(), 16, reset_val, reset
);
reg->init(this, name, reset ? (uint8_t *)&reset_val : NULL);
this->regs.push_back(reg);
}
void vp::component::new_reg(std::string name, vp::reg_32 *reg, uint32_t reset_val, bool reset)
{
this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New register (name: %s, width: %d, reset_val: 0x%x, reset: %d)\n",
name.c_str(), 32, reset_val, reset
);
reg->init(this, name, reset ? (uint8_t *)&reset_val : NULL);
this->regs.push_back(reg);
}
void vp::component::new_reg(std::string name, vp::reg_64 *reg, uint64_t reset_val, bool reset)
{
this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New register (name: %s, width: %d, reset_val: 0x%x, reset: %d)\n",
name.c_str(), 64, reset_val, reset
);
reg->init(this, name, reset ? (uint8_t *)&reset_val : NULL);
this->regs.push_back(reg);
}
bool vp::reg::access_callback(uint64_t reg_offset, int size, uint8_t *value, bool is_write)
{
if (this->callback != NULL)
this->callback(reg_offset, size, value, is_write);
return this->callback != NULL;
}
void vp::reg::init(vp::component *top, std::string name, int bits, uint8_t *value, uint8_t *reset_value)
{
this->top = top;
this->nb_bytes = (bits + 7) / 8;
this->bits = bits;
if (reset_value)
this->reset_value_bytes = new uint8_t[this->nb_bytes];
else
this->reset_value_bytes = NULL;
if (value)
this->value_bytes = value;
else
this->value_bytes = new uint8_t[this->nb_bytes];
this->name = name;
if (reset_value)
memcpy((void *)this->reset_value_bytes, (void *)reset_value, this->nb_bytes);
top->traces.new_trace(name + "/trace", &this->trace, vp::TRACE);
top->traces.new_trace_event(name, &this->reg_event, bits);
}
void vp::reg::reset(bool active)
{
if (active)
{
this->trace.msg("Resetting register\n");
if (this->reset_value_bytes)
{
memcpy((void *)this->value_bytes, (void *)this->reset_value_bytes, this->nb_bytes);
}
else
{
memset((void *)this->value_bytes, 0, this->nb_bytes);
}
if (this->reg_event.get_event_active())
{
this->reg_event.event((uint8_t *)this->value_bytes);
}
}
}
void vp::reg_1::init(vp::component *top, std::string name, uint8_t *reset_val)
{
reg::init(top, name, 1, (uint8_t *)&this->value, reset_val);
}
void vp::reg_8::init(vp::component *top, std::string name, uint8_t *reset_val)
{
reg::init(top, name, 8, (uint8_t *)&this->value, reset_val);
}
void vp::reg_16::init(vp::component *top, std::string name, uint8_t *reset_val)
{
reg::init(top, name, 16, (uint8_t *)&this->value, reset_val);
}
void vp::reg_32::init(vp::component *top, std::string name, uint8_t *reset_val)
{
reg::init(top, name, 32, (uint8_t *)&this->value, reset_val);
}
void vp::reg_64::init(vp::component *top, std::string name, uint8_t *reset_val)
{
reg::init(top, name, 64, (uint8_t *)&this->value, reset_val);
}
void vp::reg_1::build(vp::component *top, std::string name)
{
top->new_reg(name, this, this->reset_val, this->do_reset);
}
void vp::reg_8::build(vp::component *top, std::string name)
{
top->new_reg(name, this, this->reset_val, this->do_reset);
}
void vp::reg_16::build(vp::component *top, std::string name)
{
top->new_reg(name, this, this->reset_val, this->do_reset);
}
void vp::reg_32::build(vp::component *top, std::string name)
{
top->new_reg(name, this, this->reset_val, this->do_reset);
}
void vp::reg_32::write(int reg_offset, int size, uint8_t *value)
{
uint8_t *dest = this->value_bytes+reg_offset;
uint8_t *src = value;
uint8_t *mask = ((uint8_t *)&this->write_mask) + reg_offset;
for (int i=0; i<size; i++)
{
dest[i] = (dest[i] & ~mask[i]) | (src[i] & mask[i]);
}
this->dump_after_write();
if (this->reg_event.get_event_active())
{
this->reg_event.event((uint8_t *)this->value_bytes);
}
}
void vp::reg_64::build(vp::component *top, std::string name)
{
top->new_reg(name, this, this->reset_val, this->do_reset);
}
void vp::master_port::final_bind()
{
if (this->is_bound)
{
this->finalize();
}
}
void vp::slave_port::final_bind()
{
if (this->is_bound)
this->finalize();
}
extern "C" char *vp_get_error()
{
return vp_error;
}
extern "C" void vp_port_bind_to(void *_master, void *_slave, const char *config_str)
{
vp::master_port *master = (vp::master_port *)_master;
vp::slave_port *slave = (vp::slave_port *)_slave;
vp::config *config = NULL;
if (config_str != NULL)
{
config = master->get_comp()->import_config(config_str);
}
master->bind_to(slave, config);
slave->bind_to(master, config);
}
void vp::component::throw_error(std::string error)
{
throw std::invalid_argument("[\033[31m" + this->get_path() + "\033[0m] " + error);
}
void vp::component::build_instance(std::string name, vp::component *parent)
{
std::string comp_path = parent->get_path() != "" ? parent->get_path() + "/" + name : name == "" ? "" : "/" + name;
this->conf(name, comp_path, parent);
this->pre_pre_build();
this->pre_build();
this->build();
this->power.build();
for (auto x : build_callbacks)
{
x();
}
}
vp::component *vp::component::new_component(std::string name, js::config *config, std::string module_name)
{
if (module_name == "")
{
module_name = config->get_child_str("vp_component");
if (module_name == "")
{
module_name = "utils.composite_impl";
}
}
if (this->get_vp_config()->get_child_bool("sv-mode"))
{
module_name = "sv." + module_name;
}
else if (this->get_vp_config()->get_child_bool("debug-mode"))
{
module_name = "debug." + module_name;
}
this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New component (name: %s, module: %s)\n", name.c_str(), module_name.c_str());
std::replace(module_name.begin(), module_name.end(), '.', '/');
std::string path = std::string(getenv("GVSOC_PATH")) + "/" + module_name + ".so";
void *module = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL | RTLD_DEEPBIND);
if (module == NULL)
{
this->throw_error("ERROR, Failed to open periph model (module: " + module_name + ", error: " + std::string(dlerror()) + ")");
}
vp::component *(*constructor)(js::config *) = (vp::component * (*)(js::config *)) dlsym(module, "vp_constructor");
if (constructor == NULL)
{
this->throw_error("ERROR, couldn't find vp_constructor in loaded module (module: " + module_name + ")");
}
vp::component *instance = constructor(config);
instance->build_instance(name, this);
return instance;
}
vp::component::component(js::config *config)
: block(NULL), traces(*this), power(*this), reset_done_from_itf(false)
{
this->comp_js_config = config;
//this->conf(path, parent);
}
void vp::component::create_ports()
{
js::config *config = this->get_js_config();
js::config *ports = config->get("vp_ports");
if (ports == NULL)
{
ports = config->get("ports");
}
if (ports != NULL)
{
this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating ports\n");
for (auto x : ports->get_elems())
{
std::string port_name = x->get_str();
this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating port (name: %s)\n", port_name.c_str());
if (this->get_master_port(port_name) == NULL && this->get_slave_port(port_name) == NULL)
this->add_master_port(port_name, new vp::virtual_port(this));
}
}
}
void vp::component::create_bindings()
{
js::config *config = this->get_js_config();
js::config *bindings = config->get("vp_bindings");
if (bindings == NULL)
{
bindings = config->get("bindings");
}
if (bindings != NULL)
{
this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating bindings\n");
for (auto x : bindings->get_elems())
{
std::string master_binding = x->get_elem(0)->get_str();
std::string slave_binding = x->get_elem(1)->get_str();
int pos = master_binding.find_first_of("->");
std::string master_comp_name = master_binding.substr(0, pos);
std::string master_port_name = master_binding.substr(pos + 2);
pos = slave_binding.find_first_of("->");
std::string slave_comp_name = slave_binding.substr(0, pos);
std::string slave_port_name = slave_binding.substr(pos + 2);
this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating binding (%s:%s -> %s:%s)\n",
master_comp_name.c_str(), master_port_name.c_str(),
slave_comp_name.c_str(), slave_port_name.c_str()
);
vp::component *master_comp = master_comp_name == "self" ? this : this->get_childs_dict()[master_comp_name];
vp::component *slave_comp = slave_comp_name == "self" ? this : this->get_childs_dict()[slave_comp_name];
vp_assert_always(master_comp != NULL, this->get_trace(), "Binding from invalid master\n");
vp_assert_always(slave_comp != NULL, this->get_trace(), "Binding from invalid slave\n");
vp::port *master_port = master_comp->get_master_port(master_port_name);
vp::port *slave_port = slave_comp->get_slave_port(slave_port_name);
vp_assert_always(master_port != NULL, this->get_trace(), "Binding from invalid master port\n");
vp_assert_always(slave_port != NULL, this->get_trace(), "Binding from invalid slave port\n");
master_port->bind_to_virtual(slave_port);
}
}
}
std::vector<vp::slave_port *> vp::slave_port::get_final_ports()
{
return { this };
}
std::vector<vp::slave_port *> vp::master_port::get_final_ports()
{
std::vector<vp::slave_port *> result;
for (auto x : this->slave_ports)
{
std::vector<vp::slave_port *> slave_ports = x->get_final_ports();
result.insert(result.end(), slave_ports.begin(), slave_ports.end());
}
return result;
}
void vp::master_port::bind_to_slaves()
{
for (auto x : this->slave_ports)
{
for (auto y : x->get_final_ports())
{
this->get_owner()->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating final binding (%s:%s -> %s:%s)\n",
this->get_owner()->get_path().c_str(), this->get_name().c_str(),
y->get_owner()->get_path().c_str(), y->get_name().c_str()
);
this->bind_to(y, NULL);
y->bind_to(this, NULL);
}
}
}
void vp::component::bind_comps()
{
this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating final bindings\n");
for (auto x : this->get_childs())
{
x->bind_comps();
}
for (auto x : this->master_ports)
{
if (!x.second->is_virtual())
{
x.second->bind_to_slaves();
}
}
}
void *vp::component::external_bind(std::string comp_name, std::string itf_name, void *handle)
{
for (auto &x : this->childs)
{
void *result = x->external_bind(comp_name, itf_name, handle);
if (result != NULL)
return result;
}
return NULL;
}
void vp::master_port::bind_to_virtual(vp::port *port)
{
vp_assert_always(port != NULL, this->get_comp()->get_trace(), "Trying to bind master port to NULL\n");
this->slave_ports.push_back(port);
}
void vp::component::create_comps()
{
js::config *config = this->get_js_config();
js::config *comps = config->get("vp_comps");
if (comps == NULL)
{
comps = config->get("components");
}
if (comps != NULL)
{
this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating components\n");
for (auto x : comps->get_elems())
{
std::string comp_name = x->get_str();
js::config *comp_config = config->get(comp_name);
std::string vp_component = comp_config->get_child_str("vp_component");
if (vp_component == "")
vp_component = "utils.composite_impl";
this->new_component(comp_name, comp_config, vp_component);
}
}
}
void vp::component::dump_traces_recursive(FILE *file)
{
this->dump_traces(file);
for
|
(auto& x: this->get_childs())
{
x->dump_traces_recursive(file);
}
}
vp::component *vp::__gv_create(std::string config_path, struct gv_conf *gv_conf)
{
setenv("PULP_CONFIG_FILE", config_path.c_str(), 1);
js::config *js_config = js::import_config_from_file(config_path);
if (js_config == NULL)
{
fprintf(stderr, "Invalid configuration.");
return NULL;
}
js::config *gv_config = js_config->get("**/gvsoc");
std::string module_name = "vp.trace_domain_impl";
if (gv_config->get_child_bool("sv-mode"))
{
module_name = "sv." + module_name;
}
else if (gv_config->get_child_bool("debug-mode"))
{
module_name = "debug." + module_name;
}
std::replace(module_name.begin(), module_name.end(), '.', '/');
std::string path = std::string(getenv("GVSOC_PATH")) + "/" + module_name + ".so";
void *module = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL | RTLD_DEEPBIND);
if (module == NULL)
{
throw std::invalid_argument("ERROR, Failed to open periph model (module: " + module_name + ", error: " + std::string(dlerror()) + ")");
}
vp::component *(*constructor)(js::config *) = (vp::component * (*)(js::config *)) dlsym(module, "vp_constructor");
if (constructor == NULL)
{
throw std::invalid_argument("ERROR, couldn't find vp_constructor in loaded module (module: " + module_name + ")");
}
vp::component *instance = constructor(js_config);
vp::top *top = new vp::top();
top->top_instance = instance;
top->power_engine = new vp::power::engine(instance);
instance->set_vp_config(gv_config);
instance->set_gv_conf(gv_conf);
return (vp::component *)top;
}
extern "C" void *gv_create(const char *config_path, struct gv_conf *gv_conf)
{
return (void *)vp::__gv_create(config_path, gv_conf);
}
extern "C" void gv_destroy(void *arg)
{
}
extern "C" void gv_start(void *arg)
{
vp::top *top = (vp::top *)arg;
vp::component *instance = (vp::component *)top->top_instance;
instance->pre_pre_build();
instance->pre_build();
instance->build();
instance->build_new();
if (instance->gv_conf.open_proxy || instance->get_vp_config()->get_child_bool("proxy/enabled"))
{
int in_port = instance->gv_conf.open_proxy ? 0 : instance->get_vp_config()->get_child_int("proxy/port");
int out_port;
proxy = new Gv_proxy(instance, instance->gv_conf.req_pipe, instance->gv_conf.reply_pipe);
if (proxy->open(in_port, &out_port))
{
instance->throw_error("Failed to start proxy");
}
if (instance->gv_conf.proxy_socket)
{
*instance->gv_conf.proxy_socket = out_port;
}
}
}
extern "C" void gv_reset(void *arg, bool active)
{
vp::top *top = (vp::top *)arg;
vp::component *instance = (vp::component *)top->top_instance;
instance->reset_all(active);
}
extern "C" void gv_step(void *arg, int64_t timestamp)
{
vp::top *top = (vp::top *)arg;
vp::component *instance = (vp::component *)top->top_instance;
instance->step(timestamp);
}
extern "C" int64_t gv_time(void *arg)
{
vp::top *top = (vp::top *)arg;
vp::component *instance = (vp::component *)top->top_instance;
return instance->get_time_engine()->get_next_event_time();
}
extern "C" void *gv_open(const char *config_path, bool open_proxy, int *proxy_socket, int req_pipe, int reply_pipe)
{
struct gv_conf gv_conf;
gv_conf.open_proxy = open_proxy;
gv_conf.proxy_socket = proxy_socket;
gv_conf.req_pipe = req_pipe;
gv_conf.reply_pipe = reply_pipe;
void *instance = gv_create(config_path, &gv_conf);
if (instance == NULL)
return NULL;
gv_start(instance);
return instance;
}
Gvsoc_proxy::Gvsoc_proxy(std::string config_path)
: config_path(config_path)
{
}
void Gvsoc_proxy::proxy_loop()
{
FILE *sock = fdopen(this->reply_pipe[0], "r");
while(1)
{
char line[1024];
if (!fgets(line, 1024, sock))
return ;
std::string s = std::string(line);
std::regex regex{R"([\s]+)"};
std::sregex_token_iterator it{s.begin(), s.end(), regex, -1};
std::vector<std::string> words{it, {}};
if (words.size() > 0)
{
if (words[0] == "stopped")
{
int64_t timestamp = std::atoll(words[1].c_str());
printf("GOT STOP AT %ld\n", timestamp);
this->mutex.lock();
this->stopped_timestamp = timestamp;
this->running = false;
this->cond.notify_all();
this->mutex.unlock();
}
else if (words[0] == "running")
{
int64_t timestamp = std::atoll(words[1].c_str());
printf("GOT RUN AT %ld\n", timestamp);
this->mutex.lock();
this->running = true;
this->cond.notify_all();
this->mutex.unlock();
}
else if (words[0] == "req=")
{
}
else
{
printf("Ignoring invalid command: %s\n", words[0].c_str());
}
}
}
}
int Gvsoc_proxy::open()
{
pid_t ppid_before_fork = getpid();
if (pipe(this->req_pipe) == -1)
return -1;
if (pipe(this->reply_pipe) == -1)
return -1;
pid_t child_id = fork();
if(child_id == -1)
{
return -1;
}
else if (child_id == 0)
{
int r = prctl(PR_SET_PDEATHSIG, SIGTERM);
if (r == -1) { perror(0); exit(1); }
// test in case the original parent exited just
// before the prctl() call
if (getppid() != ppid_before_fork) exit(1);
void *instance = gv_open(this->config_path.c_str(), true, NULL, this->req_pipe[0], this->reply_pipe[1]);
int retval = gv_run(instance);
gv_stop(instance, retval);
return retval;
}
else
{
this->running = false;
this->loop_thread = new std::thread(&Gvsoc_proxy::proxy_loop, this);
}
return 0;
}
void Gvsoc_proxy::run()
{
dprintf(this->req_pipe[1], "cmd=run\n");
}
int64_t Gvsoc_proxy::pause()
{
int64_t result;
dprintf(this->req_pipe[1], "cmd=stop\n");
std::unique_lock<std::mutex> lock(this->mutex);
while (this->running)
{
this->cond.wait(lock);
}
result = this->stopped_timestamp;
lock.unlock();
return result;
}
void Gvsoc_proxy::close()
{
dprintf(this->req_pipe[1], "cmd=quit\n");
}
void Gvsoc_proxy::add_event_regex(std::string regex)
{
dprintf(this->req_pipe[1], "cmd=event add %s\n", regex.c_str());
}
void Gvsoc_proxy::remove_event_regex(std::string regex)
{
dprintf(this->req_pipe[1], "cmd=event remove %s\n", regex.c_str());
}
void Gvsoc_proxy::add_trace_regex(std::string regex)
{
dprintf(this->req_pipe[1], "cmd=trace add %s\n", regex.c_str());
}
void Gvsoc_proxy::remove_trace_regex(std::string regex)
{
dprintf(this->req_pipe[1], "cmd=trace remove %s\n", regex.c_str());
}
vp::time_scheduler::time_scheduler(js::config *config)
: time_engine_client(config), first_event(NULL)
{
}
int64_t vp::time_scheduler::exec()
{
vp::time_event *current = this->first_event;
while (current && current->time == this->get_time())
{
this->first_event = current->next;
current->meth(current->_this, current);
current = this->first_event;
}
if (this->first_event == NULL)
{
return -1;
}
else
{
return this->first_event->time - this->get_time();
}
}
vp::time_event::time_event(time_scheduler *comp, time_event_meth_t *meth)
: comp(comp), _this((void *)static_cast<vp::component *>((vp::time_scheduler *)(comp))), meth(meth), enqueued(false)
{
}
vp::time_event *vp::time_scheduler::enqueue(time_event *event, int64_t time)
{
vp::time_event *current = this->first_event, *prev = NULL;
int64_t full_time = time + this->get_time();
while (current && current->time < full_time)
{
prev = current;
current = current->next;
}
if (prev)
prev->next = event;
else
this->first_event = event;
event->next = current;
event->time = full_time;
this->enqueue_to_engine(time);
return event;
}
extern "C" int gv_run(void *arg)
{
vp::top *top = (vp::top *)arg;
vp::component *instance = (vp::component *)top->top_instance;
if (!proxy)
{
instance->run();
}
return instance->join();
}
extern "C" void gv_init(struct gv_conf *gv_conf)
{
gv_conf->open_proxy = 0;
if (gv_conf->proxy_socket)
{
*gv_conf->proxy_socket = -1;
}
gv_conf->req_pipe = 0;
gv_conf->reply_pipe = 0;
}
extern "C" void gv_stop(void *arg, int retval)
{
vp::top *top = (vp::top *)arg;
vp::component *instance = (vp::component *)top->top_instance;
if (proxy)
{
proxy->stop(retval);
}
instance->stop_all();
delete top->power_engine;
}
#ifdef __VP_USE_SYSTEMC
static void *(*sc_entry)(void *);
static void *sc_entry_arg;
void set_sc_main_entry(void *(*entry)(void *), void *arg)
{
sc_entry = entry;
sc_entry_arg = arg;
}
int sc_main(int argc, char *argv[])
{
sc_entry(sc_entry_arg);
return 0;
}
#endif
void vp::fatal(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
if (vfprintf(stderr, fmt, ap) < 0) {}
va_end(ap);
abort();
}
extern "C" void *gv_chip_pad_bind(void *handle, char *name, int ext_handle)
{
vp::top *top = (vp::top *)handle;
vp::component *instance = (vp::component *)top->top_instance;
return instance->external_bind(name, "", (void *)(long)ext_handle);
}
|
/*
* @ASCK
*/
#include <systemc.h>
SC_MODULE (IF) {
sc_in_clk clk;
sc_in <sc_uint<20>> prev_data;
sc_out <sc_uint<20>> next_data;
/*
** module global variables
*/
SC_CTOR (IF){
SC_THREAD (process);
sensitive << clk.pos();
}
void process () {
while(true){
wait();
if(now_is_call){
cout<<"\t\t\t\t*******************" << endl;
wait(micro_acc_ev);
}
next_data.write(prev_data.read());
}
}
};
|
// BEGIN engine.cpp ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// $Copyright: (c)2003-2006 Eklectically, Inc. $
// $License: May be used under the same terms as SystemC library. $
#include <systemc.h>
#include <iomanip>
//--------------------------------------------------------------------//
// This SystemC code is designed to illustrate the operation of the //
// SystemC simulation kernel with added instrumentation. In order to //
// output messages that indicate operation, instrumentation has been //
// added to the basic code: //
// //
// 1. A special "Did_update" channel is present to monitor when //
// update state occurs. It sets a flag used by other routines. //
// //
// 2. Two special dumping methods were added to the main module, //
// Eval() and Changes(). In addition, several "prev_" prefixed //
// variables hold the "old" values of variables. This allows //
// Eval() and Changes() to print differences on-the-fly. Eval() //
// is strategically located anywhere we expect evaluations begin. //
// Changes() monitors variable changes that may have occurred just //
// prior to its call. Changes() is setup to occur anywhere //
// evaluation of a thread may be suspended or exit. //
// //
// 3. A monitor SC_METHOD, mon(), was added to observe the clock. //
//--------------------------------------------------------------------//
struct Did_update : public sc_prim_channel {
// This is special primitive channel to notify entry by the simulator
// into the update state. In other words, end of a delta-cycle.
unsigned int *counter;
bool updated;
void watch(unsigned int * count) {
counter = count;
request_update();
}
void clear(void) { updated = false; }
void update(void) {
(*counter)++;
updated = true;
cout << "T" << std::setfill('_') << std::setw(2) << *counter
//<< std::setfill('~') << std::setw(60) << std::left
<< ":---- UPDT" << std::endl;
}
};//endstruct
SC_MODULE(M) {
sc_in<bool> ckp;
sc_out<int> s1p;
sc_signal<int> s2;
sc_event e1, e2;
void P1_meth(void);
void P3_thrd(void);
void P2_thrd(void);
SC_CTOR(M):count(0),temp(9)
,prev_time(99),prev_ck(true),prev_s1(99),prev_s2(99),prev_temp(99)
{
cout << "T-5:---- Elaborating (CTOR Registering P3_thrd)" << std::endl;
SC_THREAD(P3_thrd);
cout << "T-4:---- Elaborating (CTOR Registering P2_thrd)" << std::endl;
SC_THREAD(P2_thrd);
sensitive << ckp.pos();
cout << "T-3:---- Elaborating (CTOR Registering P1_meth)" << std::endl;
SC_METHOD(P1_meth);
dont_initialize();
sensitive << s2;
SC_METHOD(mon);
sensitive << ckp;
dont_initialize();
}//end SC_CTOR
void mon(void){Eval("ck",1);}// Monitor the clock
unsigned int count;
private:
int temp;
// Special variables and routines to monitor execution follow
Did_update me;
double prev_time;
int prev_temp, prev_s1, prev_s2;
bool prev_ck;
void Eval(const char* message,int type=0){ // Used to trace simulation
if (me.updated) {
Changes();
me.clear();
}//endif
me.watch(&count);
count++;
cout << "T" << std::setfill('_') << std::setw(2) << count;
cout << std::setfill(' ');
if (prev_time == sc_time_stamp()/sc_time(1,SC_NS)) {
cout << ": ";
} else {
cout << ":" << std::setw(2) << int(sc_time_stamp()/sc_time(1,SC_NS)) << "ns";
}//endif
switch (type) {
case 1: cout << " MNTR "; break;
default: cout << " EVAL "; break;
}//endswitch
if (ckp->read() == prev_ck) cout << " ";
else cout << " ck=" << ckp->read();
if (s1p->read() == prev_s1) cout << " ";
else cout << " s1=" << s1p->read();
if (s2.read() == prev_s2) cout << " ";
else cout << " s2=" << s2.read();
if (temp == prev_temp) cout << " ";
else cout << " temp=" << temp;
cout << ": " << message
<< std::endl;
prev_time = sc_time_stamp()/sc_time(1,SC_NS);
prev_ck = ckp->read();
prev_s1 = s1p->read();
prev_s2 = s2.read();
prev_temp = temp;
}//end Eval()
void Changes(void) { // Display variable changes if any
if (ckp->read() != prev_ck || s1p->read() != prev_s1 || s2.read() != prev_s2 || temp != prev_temp) {
cout << " [ ] ";
if (ckp->read() == prev_ck) cout << " ";
else cout << " ck=" << ckp->read();
if (s1p->read() == prev_s1) cout << " ";
else cout << " s1=" << s1p->read();
if (s2.read() == prev_s2) cout << " ";
else cout << " s2=" << s2.read();
if (temp == prev_temp) cout << " ";
else cout << " temp=" << temp;
cout << std::endl;
prev_ck = ckp->read();
prev_s1 = s1p->read();
prev_s2 = s2.read();
prev_temp = temp;
}//endif
}//end Changes()
};//end SC_MODULE
void M::P1_meth(void) {
Eval("P1_meth");
temp = s2.read();
s1p->write(temp+1);
e2.notify(2,SC_NS);
Changes();
}
void M::P2_thrd(void) {
Eval("P2_thrd.A");
A: s2.write(5);
e1.notify();//immediate
Changes();
wait(); Eval("P2_thrd.B");
B: for (int i=7;i<9;i++){
s2.write(i);
Changes();
wait(1,SC_NS); Eval("P2_thrd.C");
C: e1.notify(SC_ZERO_TIME);//delta cycle
Changes();
wait(); Eval("P2_thrd.B");//static sensitive
}//endfor
Eval("P2_thrd.EXITED");
}
void M::P3_thrd(void) {
Eval("P3_thrd.D");
D: while(true) {
Changes();
wait(e1|e2); Eval("P3_thrd.E");
E: cout << "NOTE " << sc_time_stamp()
<< std::endl;
}//endwhile
}
// The purpose of sc_main() is to start up the simulation. This is
// where the design is constructed during the "elaboration phase",
// before simulation starts.
int sc_main(int argc __attribute__((unused)),char *argv[] __attribute__((unused))) {
cout << "T-6:---- MAIN Elaborating (constructing/binding)" << std::endl;
sc_clock ck("ck",sc_time(6,SC_NS),0.5,sc_time(3,SC_NS));
sc_signal<int> s1;
M m("m");
cout << "T-2:---- MAIN Elaboration (Connecting ck)" << std::endl;
m.ckp(ck);
cout << "T-1:---- MAIN Elaborating (Connecting s1)" << std::endl;
m.s1p(s1);
cout << "T_0:---- MAIN Elaboration finished" << std::endl;
cout << "T_0:---- MAIN Starting simulation" << std::endl;
// Elaboration complete!
// Begin simulation...
sc_start(30,SC_NS); // Simulate for 30 nano-seconds
// Simulation complete!
cout << "T" << ++m.count << ":"
<< int(sc_time_stamp()/sc_time(1,SC_NS)) << "ns"
<< " MAIN Simulation stopped" << std::endl;
return 0;
}//end sc_main()
// END engine.cpp ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
/*******************************************************************************
* tpencoder.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design
*******************************************************************************
* Description:
* This is a testbench module to emulate a rotary quad encoder with a button.
* This encoder encodes the button by forcing pin B high.
*******************************************************************************
* 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 "tpencoder.h"
void tpencoder::press(bool pb) {
if (pb) {
pinA.write(GN_LOGIC_1);
buttonpressed = true;
}
else {
pinA.write(GN_LOGIC_Z);
buttonpressed = false;
}
}
void tpencoder::turnleft(int pulses, bool pressbutton) {
/* We start by raising the button, if requested. */
if (pressbutton) press(true);
/* If the last was a left turn, we need to do the direction change glitch.
* Note that if the button is pressed, we only toggle pin B. */
if (!lastwasright) {
wait(speed, SC_MS);
pinB.write(GN_LOGIC_1);
wait(speed, SC_MS);
pinB.write(GN_LOGIC_Z);
}
/* And we apply the pulses, again, watching for the button. */
wait(phase, SC_MS);
while(pulses > 0) {
wait(speed-phase, SC_MS);
if (!buttonpressed) pinA.write(GN_LOGIC_1);
wait(phase, SC_MS);
pinB.write(GN_LOGIC_1);
wait(speed-phase, SC_MS);
if (!buttonpressed) pinA.write(GN_LOGIC_Z);
if (edges == 2) wait(phase, SC_MS);
pinB.write(GN_LOGIC_Z);
if (edges != 2) wait(phase, SC_MS);
pulses = pulses - 1;
}
/* If the customer requested us to press the button with a turn, we release
* it now.
*/
if (pressbutton) {
wait(speed, SC_MS);
press(false);
}
/* And we tag that the last was a right turn as when we shift to the left
* we can have some odd behaviour.
*/
lastwasright = true;
}
void tpencoder::turnright(int pulses, bool pressbutton) {
/* We start by raising the button, if requested. */
if (pressbutton) press(true);
/* If the last was a right turn, we need to do the direction change glitch.
* Note that if the button is pressed, we only toggle pin A. */
if (lastwasright) {
wait(speed, SC_MS);
if (!buttonpressed) pinA.write(GN_LOGIC_1);
wait(speed, SC_MS);
pinB.write(GN_LOGIC_1);
wait(speed, SC_MS);
pinB.write(GN_LOGIC_Z);
wait(speed, SC_MS);
if (!buttonpressed) pinA.write(GN_LOGIC_Z);
}
/* And we apply the pulses, again, watching for the button. */
wait(phase, SC_MS);
while(pulses > 0) {
wait(speed-phase, SC_MS);
pinB.write(GN_LOGIC_1);
wait(phase, SC_MS);
if (!buttonpressed) pinA.write(GN_LOGIC_1);
wait(speed-phase, SC_MS);
pinB.write(GN_LOGIC_Z);
if (edges == 2) wait(phase, SC_MS);
if (!buttonpressed) pinA.write(GN_LOGIC_Z);
if (edges != 2) wait(phase, SC_MS);
pulses = pulses - 1;
}
/* If the customer requested us to press the button with a turn, we release
* it now.
*/
if (pressbutton) {
wait(speed, SC_MS);
press(false);
}
/* And we tag that the last was a left turn, so we can do the left turn to
* right turn glitch.
*/
lastwasright = false;
}
void tpencoder::start_of_simulation() {
pinA.write(GN_LOGIC_Z);
pinB.write(GN_LOGIC_Z);
}
void tpencoder::trace(sc_trace_file *tf) {
sc_trace(tf, buttonpressed, buttonpressed.name());
sc_trace(tf, pinA, pinA.name());
sc_trace(tf, pinB, pinB.name());
}
|
// #include <QApplication>
#include "mainwindow.h"
#include "qapplication.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QSplitter>
#include <QPushButton>
#include <systemc.h>
#include <pthread.h>
#include <QList>
#include <iostream>
#include "scqt_worker.h"
// -------------- From "How do I create a pause/wait function using Qt?" -----
// -------------- https://stackoverflow.com/questions/3752742/how-do-i-create-a-pause-wait-function-using-qt -----
// -------------- answered Mar 24, 2017 at 15:18 by dvntehn00bz -----------------
#include <QEventLoop>
#include <QTimer>
inline void delay(int millisecondsWait)
{
QEventLoop loop;
QTimer t;
t.connect(&t, &QTimer::timeout, &loop, &QEventLoop::quit);
t.start(millisecondsWait);
loop.exec();
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, m_scqtThread(nullptr)
, m_scqtWorker(nullptr)
, ui(new Ui::MainWindow)
{
connect(this, &MainWindow::Message, this, &MainWindow::onMessage);
// setupUi();
ui->setupUi(this);
setupSim();
SVGs = new SVG_Viewer(NULL);
SVGs->getScene()->addItem (SVGs->getTxt());
ui->graphicsView->setScene(SVGs->getScene());
ui->graphicsView->show();
QObject::connect(ui->verticalSlider, SIGNAL( valueChanged(int) ), SVGs, SLOT(on_verticalSlider_valueChanged(int)));
}
MainWindow::~MainWindow()
{
}
/* SVG rendering is updated in this function (each time the "clock" button is pressed).
* A first mode where lists are initialized: case where 'logMessage.contains("Report received: 0 s")
* This involves a search for correspondences between systemC components and SVG file elements.
*
* Another mode where rendering is updated according to the string generated by systemC: case where logMessage.contains("Report received")
* SVG element list values are updated according to the values (after the '=' sign) contained in the strDom string array
*/
void MainWindow::onMessage(QString const &msg_origin, QString const &msg_level, QString const &msg)
{
QString logMessage(msg_level);
// QStringList strDom;
// QList<QDomElement> listElem;
QDomElement elem;
logMessage.append(" msg (").append(msg_origin).append(") :: ").append(msg);
// logConsole->append(logMessage);
ui->textBrowser->append(logMessage);
if(logMessage.contains("Report received: 0 s"))
{
ui->textBrowser->append("Report received time 0 : findDomelements related to SVG file and value processing");
*(SVGs->getStrDom()) = logMessage.split(", "); /* Loading hierarchy elements (string) */
// *(SVGs->getPrior_value()) = *(SVGs->getStrDom());
/* Visual console of hierarchy elements (character string) */
for(int i = 0 ; i< (SVGs->getStrDom())->length() ; i++)
{
ui->textBrowser->append((SVGs->getStrDom())->at(i));
}
SVGs->getStrDom()->removeFirst(); // Deleting the first element corresponding to a systemC message
/* DOM loading based on string array elements */
ui->textBrowser->append("");
ui->textBrowser->append("Find elements!");
for(int i = 0 ; i<(SVGs->getStrDom())->length() ; i++)
{
elem = findDomElement("svg30:layer1:STROKES:"+ ((SVGs->getStrDom())->at(i).split("=").at(0)), *(SVGs->getDom()));
if(!(elem).isNull())
{
SVGs->getPrior_value()->append((SVGs->getStrDom())->at(i));
SVGs->getIndex_elem()->append(i);
SVGs->getListElem()->append(elem); // Add element only when non-zero
}
}
/* Visual for all SVG elements found */
std::cout<<std::endl;
std::cout<<"Display found elements and its index value!"<<std::endl;
for(int i = 0 ; i<SVGs->getListElem()->length() ; i++)
{
// ui->textBrowser->append(SVGs->getListElem()->at(i).attribute("id"));
// ui->textBrowser->append((SVGs->getIndex_elem()->at(i)));
std::cout<<"el:"<<SVGs->getListElem()->at(i).attribute("id").toStdString()<<" ; index:"<<(SVGs->getIndex_elem()->at(i))<<std::endl;
}
}
else if(logMessage.contains("Report received"))
{
*(SVGs->getStrDom()) = logMessage.split(", "); /* Loading hierarchy elements (string) */
SVGs->getStrDom()->removeFirst(); // Deleting the first element corresponding to a systemC message
ui->textBrowser->append("Report received time > 0 : only value processing");
// setTextDomElementSim((QDomElement*)&(SVGs->getListElem()->at(12)), (SVGs->getStrDom())->at(12).split("=").at(1));
/* Updating values */
for(int i=0 ; i<SVGs->getIndex_elem()->length() ; i++)
{
// std::cout<<"12:"<<SVGs->getListElem()->at(i).attribute("id").toStdString()<<std::endl;
setTextDomElementSim((SVGs->getListElem()->at(i)), (SVGs->getStrDom())->at(SVGs->getIndex_elem()->at(i)).split("=").at(1));
}
/* Scans all elements of the strDom, listElem and prior_value lists to detect a change in value, thus changing the color of the thread (red). */
for(int i=0 ; i<SVGs->getIndex_elem()->length() ; i++)
{
if((SVGs->getPrior_value()->at(i)) != ((SVGs->getStrDom())->at(SVGs->getIndex_elem()->at(i))))
{
std::cout<<"12:"<<(SVGs->getPrior_value()->at(i)).toStdString()<<std::endl;
setColorDomElement((SVGs->getListElem()->at(i)), "ff0000");
}
}
/* Update priority_value */
for(int i=0 ; i<SVGs->getIndex_elem()->length() ; i++)
{
std::cout<<"actual:"<<((SVGs->getStrDom())->at(SVGs->getIndex_elem()->at(i))).toStdString()<<" ; prior:"<<(SVGs->getPrior_value()->at(i)).toStdString()<<std::endl;
(SVGs->getPrior_value())->replace(i, (SVGs->getStrDom())->at(SVGs->getIndex_elem()->at(i)));
}
SVGs->refresh();
}
}
//void MainWindow::onResetClicked(bool checked)
//{
// (void)checked;
// _sendMessage("DEBUG", "Reset clicked");
//}
void MainWindow::on_pushButton_clicked(bool checked)
{
(void)checked;
_sendMessage("DEBUG", "Reset clicked");
}
//void MainWindow::onClockClicked(bool checked)
//{
// (void)checked;
// _sendMessage("DEBUG", "Clock clicked");
// if (m_scqtWorker != nullptr) {
// emit setNewState(SC_ST_COMMAND_RUN);
// emit requestReport();
// }
//}
void MainWindow::on_pushButton_3_clicked(bool checked)
{
(void)checked;
_sendMessage("DEBUG", "Clock clicked");
if (m_scqtWorker != nullptr) {
emit setNewState(SC_ST_COMMAND_RUN);
emit requestReport();
}
}
void MainWindow::on_pushButton_2_clicked(bool checked)
{
(void)checked;
_sendMessage("DEBUG", "Exit clicked, terminating program");
if (m_scqtWorker != nullptr) {
emit setNewState(SC_ST_COMMAND_EXIT);
}
delay(1000);
QApplication::quit();
}
void MainWindow::newHierarchy(QStringList hier)
{
QString debugMsg("Hierarchy received:");
for (qsizetype i=0; i<hier.size(); i++) {
if (i == 0) {
debugMsg.append(" ");
} else {
debugMsg.append(", ");
}
debugMsg.append(hier.at(i));
}
_sendMessage("DEBUG", debugMsg);
}
void MainWindow::newReport(QStringList rep)
{
QString debugMsg("Report received:");
for (qsizetype i=0; i<rep.size(); i++) {
if (i == 0) {
debugMsg.append(" ");
} else {
debugMsg.append(", ");
}
debugMsg.append(rep.at(i));
}
_sendMessage("DEBUG", debugMsg);
}
void MainWindow::_sendMessage(QString const &msg_level, QString const &msg)
{
emit Message("GUI", msg_level, msg);
// emit Message("DEBUG", msg_level, msg_upper);
}
void MainWindow::setupUi()
{
QGridLayout *gridLayout = new QGridLayout;
QPushButton *btnReset;
QPushButton *btnClock;
QPushButton *btnExit;
QWidget *cWidget = new QWidget();
setCentralWidget(cWidget);
centralWidget()->setLayout(gridLayout);
btnReset = new QPushButton("Reset");
connect(btnReset, &QPushButton::clicked, this, &MainWindow::on_pushButton_clicked);
btnClock = new QPushButton("Clock");
connect(btnClock, &QPushButton::clicked, this, &MainWindow::on_pushButton_3_clicked);
btnExit = new QPushButton("Exit");
connect(btnExit, &QPushButton::clicked, this, &MainWindow::on_pushButton_2_clicked);
// logConsole = new QTextBrowser();
// Layout grid
// First row: <Reset> ...splitter... <Clock>
// Second row: < logConsole >
// Third row: <Exit>
gridLayout->addWidget(btnReset, 0, 0);
gridLayout->addWidget(new QSplitter(Qt::Horizontal), 0, 1);
gridLayout->addWidget(btnClock, 0, 2);
// gridLayout->addWidget(logConsole, 2, 0, 1, 3); // Span the three columns
gridLayout->addWidget(btnExit, 3, 0);
setWindowTitle("SystemC Test");
}
void MainWindow::setupSim()
{
m_scqtThread = new QThread;
m_scqtWorker = new scQtWorker;
m_scqtWorker->moveToThread(m_scqtThread);
// Prepare config parameters
m_ConfigParams.rst_act_level = false; // Reset: low-level active
m_ConfigParams.rst_act_microsteps = 20; // Reset active for 25 usteps (2.5 clock periods)
m_ConfigParams.clk_act_edge = false; // Clock: falling-edge sensitive
m_ConfigParams.ena_act_level = true; // Enable: high-level active
m_ConfigParams.clk_period = sc_time(10, SC_NS); // CLock period: 10 ns
m_ConfigParams.clk_semiperiod_microsteps = 4;
m_ConfigParams.microstep = m_ConfigParams.clk_period/m_ConfigParams.clk_semiperiod_microsteps;
m_scqtWorker->setConfigParameters(m_ConfigParams);
connect(m_scqtThread, &QThread::started, m_scqtWorker, &scQtWorker::doStart);
connect(m_scqtWorker, &scQtWorker::Message, this, &MainWindow::onMessage);
connect(this, &MainWindow::setNewState, m_scqtWorker, &scQtWorker::setNewState);
connect(this, &MainWindow::requestHierarchy, m_scqtWorker, &scQtWorker::getHierarchy);
connect(this, &MainWindow::requestReport, m_scqtWorker, &scQtWorker::getReport);
connect(this, &MainWindow::setTraceList, m_scqtWorker, &scQtWorker::setTraceList);
connect(m_scqtWorker, &scQtWorker::signalHierarchy, this, &MainWindow::newHierarchy);
connect(m_scqtWorker, &scQtWorker::signalReport, this, &MainWindow::newReport);
m_scqtThread->start();
emit setNewState(SC_ST_COMMAND_RUN);
emit requestHierarchy();
}
void MainWindow::Refresh()
{
ui->graphicsView->update();
}
void MainWindow::on_checkBox_clicked(bool checked)
{
std::cout<<"clicked"<<std::endl;
if(checked)
{
for(int i=0 ; i<SVGs->getIndex_elem()->length() ; i++)
{
// showDomElementSim(SVGs->getListElem()->at(i));
setStyleAttrDomElementSim(SVGs->getListElem()->at(i), "display:inline");
}
}
else
{
for(int i=0 ; i<SVGs->getIndex_elem()->length() ; i++)
{
// hideDomElementSim(SVGs->getListElem()->at(i));
setStyleAttrDomElementSim(SVGs->getListElem()->at(i), "display:none");
}
}
SVGs->refresh();
}
/*
* Not used for this simulation
*/
void MainWindow::on_actionExit_triggered()
{
}
/* Function called when user clicks on 'file' > 'Open Source
*
*/
void MainWindow::on_actionOpen_source_triggered()
{
/* The files displayed in the dialog box are only those whose extension is set in the 2nd parameter (txt and asm). */
QString link = WinSelectFile.getOpenFileName(this, tr("Select Source file)"), "C:/", tr("Assembler Files (*.asm *.txt)"));
std::cout<<link.toStdString()<<std::endl;
QFile asmf(link);
asmf.open(QIODevice::ReadOnly);
/* The contents of the file go into this Widget */
ui->TextEditor->setPlainText(asmf.readAll());
}
|
/*
Problem 3 Design
*/
#include<systemc.h>
SC_MODULE(communicationInterface) {
sc_in<sc_uint<12> > inData;
sc_in<bool> clock , reset , clear;
sc_out<sc_uint<4> > payloadOut;
sc_out<sc_uint<8> > countOut , errorOut;
void validateData();
SC_CTOR(communicationInterface) {
SC_METHOD(validateData);
sensitive<<clock.pos();
}
};
void communicationInterface::validateData() {
cout<<"@ "<<sc_time_stamp()<<"----------Start validateData---------"<<endl;
if(reset.read() == false || clear.read() == true) {
payloadOut.write(0);
countOut.write(0);
errorOut.write(0);
return;
}
sc_uint<4> header = inData.read().range(11 , 8) , payload = inData.read().range(7 , 4);
sc_uint<1> parity = inData.read().range(0 , 0);
sc_uint<2> parityCheck = 0;
if(header == 1) {
payloadOut.write(payload);
countOut.write(countOut.read() + 1);
}
while(payload) {
parityCheck++;
payload &= payload - 1;
}
errorOut.write(errorOut.read() + (parityCheck%2 && parity ? 1 : 0));
}
|
#include "systemc.h"
#include "cache_pr.h"
void cache::address_handler(){
int align;
int _address;
_address = address.read();
align = (_address & 0x00000003);
if(align != 0){
std::cout << "Endereco desalinhado. Vai dar ruim." << std::endl;
}
else{
address_offset = ((_address >> 2) & 0x0000000F);
address_index = ((_address >> 6) & 0x000000FF);
address_tag = ((_address >> 14) & 0x0003FFFF);
}
}
void cache::get_data(){
address_handler();
if(address_offset < 0 || address_offset > 15 || address_tag < 0 || address_tag > 262143 || address_index < 0 || address_index > 255 ){
std::cout << "Endereco fora dos limites da memoria" << std::endl;
}
else{
if(address_tag == cached_tag[index]){
data.write(cached_data[index][offset]);
hit.write(true);
}
else{
data.write(0x0);
hit.write(false);
//call_mem(address);
//cash_writer(address, data);
}
}
}
|
#include <systemc.h>
#include <string>
using namespace sc_core;
using namespace std;
SC_MODULE(IDE) {
// Declare inputs and outputs if needed
};
SC_MODULE(PCIx) {
// Declare inputs and outputs if needed
};
SC_MODULE(ESATA) {
public:
sc_in<bool> clk;
sc_out<std::string> path;
void write(const std::string& path) {
// Write logic goes here
}
void read_permissions() {
// Read permissions logic goes here
}
void thread_process() {
wait();
write(/* Your path */);
read_permissions();
}
};
SC_MODULE(ETH) {
public:
sc_in<bool> clk;
sc_in<unsigned char*> ethData;
sc_out<std::string> encryptionKey;
void thread_process() {
wait();
// Replace this line with your actual Ethernet signal transmission logic
sendEthernetSignal(ethData, encryptionKey);
}
};
SC_MODULE(bootmsgs) : sc_module("bootmsgs") {
QUIETELSECLASS(bootmsgs, "bootmsgs");
SC_HAS_PROCESS(bootmsgs);
bootmsgs(sc_module_name name) : sc_module(name) {
IDE ide("ide");
PCIx pci("/PCI@0xC0000471e/PCIe_X2_1.0");
ESATA esata("esata");
ETH eth("eth");
sensitive << clk.pos();
idesign(ide, pci, esata);
idesign(pci, esata);
idesign(esata, eth);
clk.register_close(_clock());
printf("0x%x, %p\n", 0xED4401EU + static_cast<unsigned int>(System::getVersion()), &System::driverManagementApplication);
printf("0x%x, %p\n", 0xFF18103U, &System::driverManagementApplication);
printf("0x%x, %p\n", 0xA1835CBU, &System::bootManager);
printf("0x%x, %p\n", 0xC000014U, &System::IPXE);
printf("0x%x, %p\n", 0x2FFF27BU, &System::bootOptions);
printf("0x%x, %p\n", 0xC51813AU, &System::sysinfo, postinfo, biosinfo, disks);
printf("0x%x, %p\n", 0x10183EDU, "Unix network time error !!");
printf("0x%x, %p\n", 0xFE018E4U, "Unix network time sync failure !!", &System::kernelversion, pkgmanagerversion, jreversion, javaversion, jdkversion, debuggerversion, *all);
eth.write("AgoyoaFY6TTAOY887sTSFTakujmhGAKH.ksgLHSlauhsfoFAYKGCgcVJHVulfugCgcJGCHGKcgh/.,,/.><M$?@N$M@#n4/23n$<M$N#2/.,me.,M?><>,mS/aMS:las;amS:?<Y!@Pu#H!:kb3?!@mne !@?#>m");
};
int main(int argc, char **argv) {
sc_init(argc, argv);
bootmsgs bootMsgs("bootmsgs");
sc_start(100, SC_NS);
return sc_finish();
}
|
/*
* Created on: 21. jun. 2019
* Author: Jonathan Horsted Schougaard
*/
#ifdef HW_COSIM
//#define __GMP_WITHIN_CONFIGURE
#endif
#define DEBUG_SYSTEMC
#define SC_INCLUDE_FX
#include <systemc.h>
#include "hwcore/tb/cnn/tb_CNN.hpp"
unsigned errors = 0;
const char simulation_name[] = "tb_CNN";
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_CNN tb_01("tb_CNN");
cout << "INFO: Simulating "<< simulation_name << endl;
sc_start(1000,SC_US);
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;
}
|
#include "systemc.h"
#if 0
#include "first_counter.cpp"
#else
#include "counter_vhdl.cpp"
#endif
int sc_main (int argc, char* argv[]) {
sc_signal<bool> clock;
sc_signal<bool> reset;
sc_signal<bool> enable;
sc_signal<sc_uint<4> > counter_out;
int i = 0;
// Connect the DUT
first_counter counter("COUNTER");
counter.clock(clock);
counter.reset(reset);
counter.enable(enable);
counter.counter_out(counter_out);
sc_start(1, SC_NS);
// Open VCD file
sc_trace_file *wf = sc_create_vcd_trace_file("counter");
// Dump the desired signals
sc_trace(wf, clock, "clock");
sc_trace(wf, reset, "reset");
sc_trace(wf, enable, "enable");
sc_trace(wf, counter_out, "count");
// Initialize all variables
reset = 0; // initial value of reset
enable = 0; // initial value of enable
for (i=0;i<5;i++) {
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
}
reset = 1; // Assert the reset
cout << "@" << sc_time_stamp() <<" Asserting reset\n" << endl;
for (i=0;i<10;i++) {
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
}
reset = 0; // De-assert the reset
cout << "@" << sc_time_stamp() <<" De-Asserting reset\n" << endl;
for (i=0;i<5;i++) {
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
}
cout << "count=" << counter_out << endl;
cout << "@" << sc_time_stamp() <<" Asserting Enable\n" << endl;
enable = 1; // Assert enable
for (i=0;i<20;i++) {
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
}
cout << "count=" << counter_out << endl;
cout << "@" << sc_time_stamp() <<" De-Asserting Enable\n" << endl;
enable = 0; // De-assert enable
cout << "@" << sc_time_stamp() <<" Terminating simulation\n" << endl;
sc_close_vcd_trace_file(wf);
return 0;// Terminate simulation
}
|
#include <systemc.h>
#include "Vmmu.h"
class mmu_tb_t : public sc_module
{
public:
Vmmu* dut;
sc_in<bool> clk_tb;
sc_signal<bool> resetb_tb;
sc_signal<bool> dm_we_tb;
sc_signal<uint32_t> im_addr_tb, dm_addr_tb, dm_di_tb;
sc_signal<uint32_t> dm_be_tb;
sc_signal<bool> is_signed_tb;
sc_signal<uint32_t> im_addr_out_tb;
sc_signal<uint32_t> im_data_tb, io_data_read_tb;
sc_signal<uint32_t> io_data_write_tb, dm_do_tb;
sc_signal<uint32_t> im_do_tb;
sc_signal<uint32_t> io_addr_tb;
sc_signal<bool> io_en_tb, io_we_tb;
uint32_t instruction_memory[1024];
uint32_t io_memory[64];
SC_CTOR(mmu_tb_t)
: clk_tb("clk_tb")
, resetb_tb("resetb_tb")
, dm_we_tb("dm_we_tb")
, im_addr_tb("im_addr_tb"), dm_addr_tb("dm_addr_tb"), dm_di_tb("dm_di_tb")
, dm_be_tb("dm_be_tb"), is_signed_tb("is_signed_tb")
, im_addr_out_tb("im_addr_out_tb")
, im_data_tb("im_data_tb"), io_data_read_tb("io_data_read_tb")
, io_data_write_tb("io_data_write_tb"), dm_do_tb("dm_do_tb")
, im_do_tb("im_do_tb"), io_addr_tb("io_addr_tb")
, io_en_tb("io_en_tb"), io_we_tb("io_we_tb")
{
init_memory();
SC_THREAD(im_thread);
sensitive << im_addr_out_tb;
SC_THREAD(io_thread);
sensitive << io_addr_tb;
SC_CTHREAD(test_thread, clk_tb.pos());
dut = new Vmmu("dut");
dut->clk(clk_tb);
dut->resetb(resetb_tb);
dut->dm_we(dm_we_tb);
dut->im_addr(im_addr_tb);
dut->im_do(im_do_tb);
dut->dm_addr(dm_addr_tb);
dut->dm_di(dm_di_tb);
dut->dm_do(dm_do_tb);
dut->dm_be(dm_be_tb);
dut->is_signed(is_signed_tb);
dut->im_addr_out(im_addr_out_tb);
dut->im_data(im_data_tb);
dut->io_addr(io_addr_tb);
dut->io_en(io_en_tb);
dut->io_we(io_we_tb);
dut->io_data_read(io_data_read_tb);
dut->io_data_write(io_data_write_tb);
}
~mmu_tb_t()
{
delete dut;
}
void reset()
{
resetb_tb.write(false);
wait();
resetb_tb.write(true);
wait();
}
void init_memory()
{
for (int i=0; i<1024; ++i) {
instruction_memory[i] = 1023 - i;
}
for (int i=0; i<64; ++i) {
io_memory[i] = 1024 + i;
}
}
void im_thread(void);
void io_thread(void);
void test_thread(void);
/** Testing Byte read/write.*/
void test1(void);
/** Testing Halfword read/write.*/
void test2(void);
/** Testing Word read/write.*/
void test3(void);
/** Testing Instruction Memory read.*/
void test4(void);
/** Testing IO read/write.*/
void test5(void);
};
void mmu_tb_t::im_thread()
{
while(true) {
uint32_t addrw32 = im_addr_out_tb.read();
uint32_t addrw9 = addrw32 % 1024;
im_data_tb.write(instruction_memory[addrw9]);
wait();
}
}
void mmu_tb_t::io_thread()
{
while(true) {
uint32_t addrw32 = io_addr_tb.read();
uint32_t addrw6 = (addrw32 >> 2) % 64;
io_data_read_tb.write(io_memory[addrw6]);
wait();
}
}
void mmu_tb_t::test_thread()
{
reset();
test1();
test2();
test3();
test4();
test5();
sc_stop();
}
void mmu_tb_t::test1()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 1: Byte R/W " << std::endl
<< "(TT) 1. Writes 0, 1, ... to *(0x10000000), ... consecutively in unsigned bytes" << std::endl
<< "(TT) 2. Then reads from the same addresses. Values should be same" << std::endl
<< "(TT) 3. Ignore the first dm_do(prev) which is invalid" << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
// Reset
is_signed_tb.write(false);
dm_we_tb.write(false);
reset();
dm_we_tb.write(true);
// 1. Write all bytes within each word
for(unsigned int i=0; i<8; ++i) {
dm_addr_tb.write(0x10000000 + 4*i);
dm_di_tb.write(4*i + 0);
dm_be_tb.write(0b0001);
wait();
dm_di_tb.write(4*i + 1);
dm_be_tb.write(0b0010);
wait();
dm_di_tb.write(4*i + 2);
dm_be_tb.write(0b0100);
wait();
dm_di_tb.write(4*i + 3);
dm_be_tb.write(0b1000);
wait();
}
// Stop writing
dm_we_tb.write(false);
// 2. Read bytes
for (unsigned int i=0; i<8; ++i) {
dm_addr_tb.write(0x10000000 + 4*i);
dm_be_tb.write(0b0001);
wait();
printf("(TT) dm_addr = 0x%x, dm_be = %x, dm_do(prev) = %d\n",
dm_addr_tb.read(), dm_be_tb.read(), dm_do_tb.read());
dm_be_tb.write(0b0010);
wait();
printf("(TT) dm_addr = 0x%x, dm_be = %x, dm_do(prev) = %d\n",
dm_addr_tb.read(), dm_be_tb.read(), dm_do_tb.read());
dm_be_tb.write(0b0100);
wait();
printf("(TT) dm_addr = 0x%x, dm_be = %x, dm_do(prev) = %d\n",
dm_addr_tb.read(), dm_be_tb.read(), dm_do_tb.read());
dm_be_tb.write(0b1000);
wait();
printf("(TT) dm_addr = 0x%x, dm_be = %x, dm_do(prev) = %d\n",
dm_addr_tb.read(), dm_be_tb.read(), dm_do_tb.read());
}
}
void mmu_tb_t::test2()
{
printf("(TT) --------------------------------------------------\n");
printf("(TT) Test 2: Half Word R/W \n");
printf("(TT) 1. Writes 0, 1, ... to *(0x10000000), ... consecutively in unsigned half words\n");
printf("(TT) 2. Then reads from the same addresses. Values should be same\n");
printf("(TT) 3. Ignore the first dm_do(prev) which is invalid\n");
printf("(TT) --------------------------------------------------\n");
// Reset
dm_we_tb.write(false);
is_signed_tb.write(false);
reset();
// 1. Write halfwords
dm_we_tb.write(true);
for (uint32_t i=0; i<8; ++i) {
dm_addr_tb.write(0x10000000 + 4*i);
dm_di_tb.write(2*i + 0);
dm_be_tb.write(0b0011);
wait();
dm_di_tb.write(2*i + 1);
dm_be_tb.write(0b1100);
wait();
}
dm_we_tb.write(false);
// 2. Read halfwords
for (uint32_t i=0; i<8; ++i) {
dm_addr_tb.write(0x10000000 + 4*i);
dm_be_tb.write(0b0011);
wait();
printf("(TT) dm_addr = 0x%x, dm_be = %x, dm_do(prev) = %d\n",
dm_addr_tb.read(), dm_be_tb.read(), dm_do_tb.read());
dm_be_tb.write(0b1100);
wait();
printf("(TT) dm_addr = 0x%x, dm_be = %x, dm_do(prev) = %d\n",
dm_addr_tb.read(), dm_be_tb.read(), dm_do_tb.read());
}
}
void mmu_tb_t::test3()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 3: Word R/W " << std::endl
<< "(TT) 1. Writes 0, 1, ... to *(0x10000000), ... consecutively in unsigned words" << std::endl
<< "(TT) 2. Then reads from the same addresses. Values should be same" << std::endl
<< "(TT) 3. Ignore the first dm_do(prev) which is invalid" << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
// Reset
dm_we_tb.write(false);
is_signed_tb.write(false);
reset();
// 1. Write halfwords
dm_we_tb.write(true);
for (uint32_t i=0; i<8; ++i) {
dm_addr_tb.write(0x10000000 + 4*i);
dm_di_tb.write(i);
dm_be_tb.write(0b1111);
wait();
}
dm_we_tb.write(false);
// 2. Read halfwords
for (uint32_t i=0; i<8; ++i) {
dm_addr_tb.write(0x10000000 + 4*i);
dm_be_tb.write(0b1111);
wait();
printf("(TT) dm_addr = 0x%x, dm_be = %x, dm_do(prev) = %d\n",
dm_addr_tb.read(), dm_be_tb.read(), dm_do_tb.read());
}
}
void mmu_tb_t::test4()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 4: Read Instruction Memory " << std::endl
<< "(TT) 1. Reads words from 0x0000000, 0x0000004, ..." << std::endl
<< "(TT) 2. Read has one cycle delay. Should read 1023, 1022, ..." << std::endl
<< "(TT) 3. Ignore the first read which is invalid" << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
dm_we_tb.write(false);
is_signed_tb.write(false);
reset();
for (uint32_t i=0; i<8; ++i) {
im_addr_tb.write(i*4);
wait();
printf("(TT) im_addr = 0x%x, im_do(prev) = %d\n",
im_addr_tb.read(), im_do_tb.read());
}
}
void mmu_tb_t::test5()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 5: IO R/W " << std::endl
<< "(TT) 1. Writes 0, 1, ... to 0x80000000, ... consecutively in unsigned words" << std::endl
<< "(TT) 2. The IO port should output the written values with one cycle delay" << std::endl
<< "(TT) 3. Then IO port is read" << std::endl
<< "(TT) 4. IO port should read 1024, 1025, ..." << std::endl
<< "(TT) 5. Ignore the first dm_do(prev) which is invalid" << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
dm_we_tb.write(false);
is_signed_tb.write(false);
reset();
// 1. Write IO
dm_we_tb.write(true);
for (uint32_t i=0; i<8; ++i) {
dm_addr_tb.write(0x80000000 + 4*i);
dm_di_tb.write(i);
dm_be_tb.write(0b1111);
wait();
printf("(TT) io_we = %x, io_addr = 0x%x, io_data_write = 0x%x\n",
io_we_tb.read(), io_addr_tb.read(), io_data_write_tb.read());
}
dm_we_tb.write(false);
// 2. Read IO
for (uint32_t i=0; i<8; ++i) {
dm_addr_tb.write(0x80000000 + 4*i);
dm_be_tb.write(0b1111);
wait();
printf("(TT) dm_addr = 0x%x, dm_be = %x, dm_do(prev) = %d\n",
dm_addr_tb.read(), dm_be_tb.read(), dm_do_tb.read());
}
}
////////////////////////
int sc_main(int argc, char** argv)
{
Verilated::commandArgs(argc, argv);
auto tb = new mmu_tb_t("tb");
sc_clock sysclk("sysclk", 10, SC_NS);
tb->clk_tb(sysclk);
sc_start();
delete tb;
exit(0);
}
|
/**
* Author: Anubhav Tomar
*
* Robot Navigation Testbench
**/
#include<systemc.h>
#include<SERVER.h>
#include<ROBOT.h>
#include<ENVIRONMENT.h>
// template < >
class _robotNavigation : public sc_module {
public:
/*Signals for Module Interconnections*/
// FIFO
sc_fifo<int> _serverToRobot1 , _envToRobot1 , _robot1ToServer , _robotToEnv1;
sc_fifo<int> _serverToRobot2 , _envToRobot2 , _robot2ToServer , _robotToEnv2;
sc_fifo<int> _serverToRobot3 , _envToRobot3 , _robot3ToServer , _robotToEnv3;
sc_fifo<int> _serverToRobot4 , _envToRobot4 , _robot4ToServer , _robotToEnv4;
// Server
sc_signal<bool> _enableServerToRobot1 , _enableServerToRobot2 , _enableServerToRobot3 , _enableServerToRobot4;
// Robot
sc_signal<bool> _enableFromServer , _enableFromEnv;
// Environment
sc_signal<bool> _clock , _enableEnvToRobot1 , _enableEnvToRobot2 , _enableEnvToRobot3 , _enableEnvToRobot4;
/*Module Instantiation*/
_serverBlock* _s;
_environmentBlock* _e;
_robotBlock* _r1;
_robotBlock* _r2;
_robotBlock* _r3;
_robotBlock* _r4;
SC_HAS_PROCESS(_robotNavigation);
_robotNavigation(sc_module_name name) : sc_module(name) {
/**
* Module Instances Created
**/
_s = new _serverBlock ("_server_");
_e = new _environmentBlock ("_environment_");
_r1 = new _robotBlock ("_robot1_" , 1);
_r2 = new _robotBlock ("_robot2_" , 2);
_r3 = new _robotBlock ("_robot3_" , 3);
_r4 = new _robotBlock ("_robot4_" , 4);
/**
* Server -> Robots
**/
_s->_serverToRobot1(_serverToRobot1);
_r1->_serverToRobot(_serverToRobot1);
_s->_serverToRobot2(_serverToRobot2);
_r2->_serverToRobot(_serverToRobot2);
_s->_serverToRobot3(_serverToRobot3);
_r3->_serverToRobot(_serverToRobot3);
_s->_serverToRobot4(_serverToRobot4);
_r4->_serverToRobot(_serverToRobot4);
_s->_enableServerToRobot1(_enableServerToRobot1);
_r1->_enableFromServer(_enableServerToRobot1);
_s->_enableServerToRobot2(_enableServerToRobot2);
_r2->_enableFromServer(_enableServerToRobot2);
_s->_enableServerToRobot3(_enableServerToRobot3);
_r3->_enableFromServer(_enableServerToRobot3);
_s->_enableServerToRobot4(_enableServerToRobot4);
_r4->_enableFromServer(_enableServerToRobot4);
/**
* Robot -> Server
**/
_r1->_robotToServer(_robot1ToServer);
_s->_robot1ToServer(_robot1ToServer);
_r2->_robotToServer(_robot2ToServer);
_s->_robot2ToServer(_robot2ToServer);
_r3->_robotToServer(_robot3ToServer);
_s->_robot3ToServer(_robot3ToServer);
_r4->_robotToServer(_robot4ToServer);
_s->_robot4ToServer(_robot4ToServer);
/**
* Environment -> Robots
**/
_e->_envToRobot1(_envToRobot1);
_r1->_envToRobot(_envToRobot1);
_e->_envToRobot2(_envToRobot2);
_r2->_envToRobot(_envToRobot2);
_e->_envToRobot3(_envToRobot3);
_r3->_envToRobot(_envToRobot3);
_e->_envToRobot4(_envToRobot4);
_r4->_envToRobot(_envToRobot4);
_e->_enableEnvToRobot1(_enableEnvToRobot1);
_r1->_enableFromEnv(_enableEnvToRobot1);
_e->_enableEnvToRobot2(_enableEnvToRobot2);
_r2->_enableFromEnv(_enableEnvToRobot2);
_e->_enableEnvToRobot3(_enableEnvToRobot3);
_r3->_enableFromEnv(_enableEnvToRobot3);
_e->_enableEnvToRobot4(_enableEnvToRobot4);
_r4->_enableFromEnv(_enableEnvToRobot4);
/**
* Robots -> Environment
**/
_r1->_robotToEnv(_robotToEnv1);
_e->_robot1ToEnv(_robotToEnv1);
_r2->_robotToEnv(_robotToEnv2);
_e->_robot2ToEnv(_robotToEnv2);
_r3->_robotToEnv(_robotToEnv3);
_e->_robot3ToEnv(_robotToEnv3);
_r4->_robotToEnv(_robotToEnv4);
_e->_robot4ToEnv(_robotToEnv4);
/**
* Clock -> Environment & Server
**/
_e->_clock(_clock);
_s->_clock(_clock);
SC_THREAD(clockSignal);
sc_fifo<int> _serverToRobot1 (50) , _envToRobot1 (50) , _robotToServer1 (50) , _robotToEnv1 (50);
sc_fifo<int> _serverToRobot2 (50) , _envToRobot2 (50) , _robotToServer2 (50) , _robotToEnv2 (50);
sc_fifo<int> _serverToRobot3 (50) , _envToRobot3 (50) , _robotToServer3 (50) , _robotToEnv3 (50);
sc_fifo<int> _serverToRobot4 (50) , _envToRobot4 (50) , _robotToServer4 (50) , _robotToEnv4 (50);
};
void clockSignal() {
while (true){
wait(0.5 , SC_MS);
_clock = false;
wait(0.5 , SC_MS);
_clock = true;
}
};
};
int sc_main(int argc , char* argv[]) {
cout<<"@ "<<sc_time_stamp()<<"----------Start---------"<<endl<<endl<<endl;
_robotNavigation _robotNav("_robotNavigation_");
cout<<"@ "<<sc_time_stamp()<<"----------Start Simulation---------"<<endl<<endl<<endl;
sc_start(10000 , SC_MS);
cout<<"@ "<<sc_time_stamp()<<"----------End Simulation---------"<<endl<<endl<<endl;
return 0;
}
|
/*
** This file is part of gSysC.
**
** gSysC is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** gSysC 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 General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with gSysC with the file ``LICENSE''; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/****************************************************************************
Author: Christian J. Eibl
last modified: 2005-09-29
****************************************************************************
Content:
This file provides a simple script for automatically adjusting
an existing (and working!) systemc design to an usable gSysC
design. This means, the system.h include is replaced by gsysc.h and
the signals and ports get automatically registered to the gSysC classes.
***************************************************************************/
#include<iostream>
#include<fstream>
#include<cstring>
#include<string>
#include<vector>
#include <cstdio>
using namespace std;
//##########################################################################
//## Structure declarations for storing scan results ##
//##########################################################################
struct port_data {
char* variableName;
bool isPointer;
bool isArray;
char* arraySize;
char* name;
port_data(const char* varName="", bool isP=false, const char* n="") {
variableName=(char*) malloc(strlen(varName)+1);
strcpy(variableName,varName);
variableName[strlen(varName)]='\0';
isPointer=isP;
isArray=false;
name=(char*) malloc(strlen(n)+1);
strcpy(name,n);
name[strlen(n)]='\0';
}
void setArraySize(const char* size) {
arraySize=(char*) malloc(strlen(size)+1);
strcpy(arraySize,size);
arraySize[strlen(size)]='\0';
}
void setVariableName(const char* name) {
variableName=(char*) malloc(strlen(name)+1);
strcpy(variableName,name);
variableName[strlen(name)]='\0';
}
};
struct signal_data {
char* variableName;
bool isPointer;
bool isArray;
char* arraySize;
vector<string> portList;
char* name;
signal_data(const char* varName="", bool isP=false, const char* n="") {
arraySize=0;
setVariableName(varName);
portList.clear();
isArray=false;
isPointer=isP;
name=(char*) malloc(strlen(n)+1);
strcpy(name,n);
name[strlen(n)]='\0';
}
void setArraySize(const char* size) {
arraySize=(char*) malloc(strlen(size)+1);
if(arraySize==NULL) cerr << "ERROR: Could not allocate memory for array size delimiter '" << size << "'!" << endl;
strcpy(arraySize,size);
arraySize[strlen(size)]='\0';
}
void setVariableName(const char* name) {
variableName=(char*) malloc(strlen(name)+1);
if(variableName==NULL) cerr << "ERROR: Could not allocate memory for signal variable name '" << name << "'!" << endl;
strcpy(variableName,name);
variableName[strlen(name)]='\0';
}
};
struct module_data {
char* name;
bool isMain;
vector<port_data*> ports_vec;
vector<signal_data*> signals_vec;
module_data(const char* n=0) {
ports_vec.clear();
signals_vec.clear();
isMain=false;
if(n!=NULL) this->setName(n);
else name=0;
}
void setName(const char* n) {
name=(char*) malloc(strlen(n)+1);
strcpy(name,n);
name[strlen(n)]='\0';
}
};
struct module_decl {
char* variableName;
char* givenName;
module_data* moduleType;
bool isPointer;
bool isArray;
char* arraySize;
module_decl(const char* name=0) {
if(name!=0) this->setVariableName(name);
else variableName=0;
givenName=0;
moduleType=0;
isPointer=false;
isArray=false;
arraySize=0;
}
void setVariableName(const char* n) {
variableName=(char*) malloc(strlen(n)+1);
strcpy(variableName,n);
variableName[strlen(n)]='\0';
}
void setRealName(const char* n) {
givenName=(char*) malloc(strlen(n)+1);
strcpy(givenName,n);
givenName[strlen(n)]='\0';
}
void setArraySize(const char* n) {
arraySize=(char*) malloc(strlen(n)+1);
strcpy(arraySize,n);
arraySize[strlen(n)]='\0';
}
};
struct file_data {
char* fileName;
char* includeFile;
bool headerIncluded;
bool incFileIncluded;
int systemcIncludeLine;
int CTORfirstLine;
vector<module_decl> modules_vec;
module_data* module;
file_data(const char* file) {
this->setFileName(file);
systemcIncludeLine=-1;
CTORfirstLine=-1;
module=0;
headerIncluded=false;
incFileIncluded=false;
}
void setModule(module_data* mod) {
module=mod;
}
void setFileName(const char* name) {
fileName=(char*) malloc(strlen(name)+1);
strcpy(fileName,name);
fileName[strlen(name)]='\0';
}
void setIncludeFile(const char* name) {
includeFile=(char*) malloc(strlen(name)+1);
strcpy(includeFile,name);
includeFile[strlen(name)]='\0';
}
};
//##########################################################################
//## Global variable declarations ##
//##########################################################################
vector<port_data*> ports_vec;
vector<signal_data*> signals_vec;
vector<file_data*> files_vec;
file_data* tmp_file;
module_data* emptyModule;
char* filename;
string include_file;
bool starComment;
string zeile,workLine;
string varName;
string givenName;
int pos,pos1;
int lineNum;
bool isP; // Pointer declaration
char ch; /////////////////// Input for pause (debugging purposes)
//##########################################################################
//## Implementations ##
//##########################################################################
int main(int argc, char* argv[])
{
if (argc == 1) {
cout << "No file parameter found! \nThis program needs all files that have to be considered for further processing to be put into the parameter list:\n\t" << argv[0] << " file1 file2 file3 ...\n" << endl;
exit(1);
}
else {
files_vec.clear();
cout << "##### Scanning Files..." << endl;
for(int parameter=1; parameter<argc; parameter++) {
cout << "\t" << argv[parameter] << endl;
filename=argv[parameter];
include_file=filename;
include_file=include_file+".gsysc";
// Working with the files
ifstream* fp;
fp->open(filename,ios::in);
lineNum=0;
ports_vec.clear();
signals_vec.clear();
starComment=false;
if(fp!=nullptr) {
tmp_file=new file_data(filename);
tmp_file->setIncludeFile(include_file.c_str());
while (getline(*fp,zeile)) {
lineNum++;
if(starComment==true && (pos=zeile.find("*/"))>=0) {
zeile=zeile.erase(0,pos);
starComment=false;
}
if(starComment) { continue; } // abort loop if the whole line is part of a comment
if((pos=zeile.find("//")) >= 0) { zeile=zeile.erase(pos); }
while((pos=zeile.find("/*")) >= 0) {
starComment=true;
if((pos1=zeile.find("*/",pos)) >= 0) {
zeile=zeile.erase(pos,pos1-pos+2);
starComment=false;
}
else {
zeile=zeile.erase(pos);
}
}
if((pos=zeile.find_first_not_of(" ")) > 0) { zeile = zeile.erase(0,pos); }
if((pos=zeile.find(".gsysc")) > 0 && (pos1=zeile.find("#include")) >=0) {
tmp_file->incFileIncluded=true;
}
if((pos=zeile.find("gsysc.h")) > 0 && (pos1=zeile.find("#include")) >=0) {
tmp_file->headerIncluded=true;
}
if((pos=zeile.find("systemc.h")) > 0 && (pos1=zeile.find("#include")) >=0) {
tmp_file->systemcIncludeLine=lineNum;
}
if((pos=zeile.find("SC_MODULE")) >= 0) {
varName=zeile.substr(0,zeile.find(")"));
varName=varName.erase(0,varName.find("(")+1);
module_data* tmp_module=new module_data(varName.c_str());
tmp_file->setModule(tmp_module);
}
if((pos=zeile.find("sc_main")) >= 0) {
varName="Main File";
module_data* main_module=new module_data(varName.c_str());
tmp_file->setModule(main_module);
tmp_file->module->isMain=true;
// cout << "DEBUG: Main File found; bool=" << tmp_file->module->isMain << endl;
}
if( (pos=zeile.find("SC_CTOR"))>=0 || ( tmp_file->module!=0 && tmp_file->module->name!=0 && (pos1=zeile.find((string) (tmp_file->module->name)))==zeile.find_first_not_of(" ") && pos1>=0) )
{
/* if((pos1=zeile.find(";",pos)) >= 0) {
varName=zeile.substr(0,pos1);
}
else { varName=zeile; }
varName=varName.erase(0,pos);
*/
if((pos=zeile.find("{"))>0 && !(((pos1=zeile.find("}",pos))>0))) {
tmp_file->CTORfirstLine=lineNum+1;
}
else {
while (getline(*fp,zeile)) {
lineNum++;
if ((pos=zeile.find("{"))>=0) break;
}
tmp_file->CTORfirstLine=lineNum+1;
} // CAVE: the CTOR is supposed to consist of brackets in different
// lines, i.e., the CTOR is not empty!
}
while((pos=zeile.find(";")) >= 0) { // while another command can be found in this line
workLine=zeile.substr(0,zeile.find(";"))+",";
zeile=zeile.erase(0,zeile.find(";")+1);
if((pos=workLine.find("sc_int"))>=0) {
continue;
}
// cout << "DEBUG: Workline 1: " << workLine << endl;
if((pos=workLine.find("sc_in"))>=0 || (pos=workLine.find("gsys_in"))>=0 ||
(pos=workLine.find("sc_out"))>=0 || (pos=workLine.find("gsys_out"))>=0 ) {
if(tmp_file->CTORfirstLine<lineNum+1) { tmp_file->CTORfirstLine=lineNum+1; }
workLine=workLine.erase(0,workLine.find("_"));
if((pos1=workLine.find(">"))>=0) { workLine=workLine.erase(0,pos1+1); }
while((pos=workLine.find(","))>=0) {
varName=workLine.substr(0,pos);
workLine=workLine.erase(0,pos+1);
if((pos=varName.find("*")) >=0) { isP=true; } else { isP=false; } // declared as pointer?
if(varName[0]=='_') {
if((pos1=varName.find(" "))>=0) { varName=varName.erase(0,pos1); }
}
if((pos1=varName.find_first_not_of(" >*"))>=0) {
varName=varName.erase(0,pos1);
}
if((pos=varName.find("("))>0) {
givenName=varName.substr(pos+2);
givenName=givenName.erase(givenName.size() -2);
varName=varName.erase(pos);
}
else { givenName=""; }
port_data *tmp_port;
if((pos=varName.find("["))>=0) {
tmp_port = new port_data((varName.substr(0,pos)).c_str(),isP,givenName.c_str());
}
else {
tmp_port = new port_data(varName.c_str(),isP,givenName.c_str());
}
if(tmp_port!=NULL) {
ports_vec.push_back(tmp_port);
if((pos=varName.find("["))>=0 && (pos1=varName.find("]"))>=0) {
tmp_port->isArray=true;
tmp_port->setArraySize( ((varName.erase(pos1)).erase(0,pos+1)).c_str() );
}
}
else { cerr << "Port " << varName << " could not be added to the list of ports!" << endl; }
tmp_port=0;
}
continue;
}
// cout << "DEBUG: Workline 2: " << workLine << endl;
if((pos=workLine.find("sc_signal"))>=0 || (pos=workLine.find("gsys_signal"))>=0) {
// cout << "DEBUG: Condition TRUE" << endl;
if(tmp_file->CTORfirstLine<lineNum+1) { tmp_file->CTORfirstLine=lineNum+1; }
workLine=workLine.erase(0,workLine.find("_"));
if((pos1=workLine.find(">"))>=0) { workLine=workLine.erase(0,pos1+1); }
// cout << "DEBUG: Workline 3: " << workLine << endl;
while((pos=workLine.find(","))>=0) {
varName=workLine.substr(0,pos);
workLine=workLine.erase(0,pos+1);
// cout << "DEBUG: varName 1: " << varName << endl;
// cout << "DEBUG: Workline 4: " << workLine << endl;
if((pos=varName.find("*")) >=0) { isP=true; } else { isP=false; } // declared as pointer?
if(varName[0]=='_') {
if((pos1=varName.find(" "))>=0) { varName=varName.erase(0,pos1); }
}
// cout << "DEBUG: varName 2: " << varName << endl;
if((pos1=varName.find_first_not_of(" >*"))>=0) { varName=varName.erase(0,pos1); }
// cout << "DEBUG: varName 3: " << varName << endl;
if((pos=varName.find("("))>0) {
givenName=varName.substr(pos+2);
givenName=givenName.erase(givenName.size() -2);
varName=varName.erase(pos);
}
else { givenName=""; }
// cout << "DEBUG: varName 4: " << varName << endl;
// cout << "DEBUG: givenName: " << givenName << endl;
signal_data *tmp_signal;
if((pos=varName.find("["))>=0) {
tmp_signal = new signal_data((varName.substr(0,pos)).c_str(),isP,givenName.c_str());
}
else {
tmp_signal = new signal_data(varName.c_str(),isP,givenName.c_str());
}
if(tmp_signal!=NULL) {
if((pos=varName.find("["))>=0 && (pos1=varName.find("]"))>=0) {
tmp_signal->isArray=true;
tmp_signal->setArraySize( ((varName.erase(varName.find("]"))).erase(0,pos+1)).c_str() );
}
// cout << "DEBUG: signals_vec Size (vorher): " << signals_vec.size() << endl;
signals_vec.push_back(tmp_signal);
// cout << "DEBUG: signals_vec Size (nachher): " << signals_vec.size() << endl;
//////DEBUG
// if(tmp_signal!=0) {
// cout << endl << "DEBUG: tmp_signal = " << tmp_signal << endl;
// if(tmp_signal->variableName!=0) cout << "Name: " << (void*) tmp_signal->variableName << " - " << tmp_signal->variableName << endl; //DEBUG
// if(tmp_signal->name!=0) cout << "GivenName: " << tmp_signal->name << endl;
// cout << "Array? " << tmp_signal->isArray << endl;
// if(tmp_signal->arraySize!=0) cout << "ArraySize: " << (void*) tmp_signal->arraySize << " - " << tmp_signal->arraySize << endl;
// cout << "Pointer? " << tmp_signal->isPointer << endl << endl;
// }
// else
// cout << "DEBUG: tmp_signal ist NULL !!!!" << endl;
}
else { cerr << "Signal " << varName << " could not be added to the list of signals!" << endl; }
tmp_signal=0;
}
continue;
}
// else cout << "DEBUG: Condition FALSE" << endl;
if((pos=workLine.find("sc_start"))>=0) {
if(tmp_file->CTORfirstLine<lineNum) { tmp_file->CTORfirstLine=lineNum; }
}
}
}
if(tmp_file!=NULL && tmp_file->module!=NULL) tmp_file->module->ports_vec=ports_vec;
if(tmp_file!=NULL && tmp_file->module!=NULL) {
// cout << "DEBUG: Schreibe signals_vec; size=" << signals_vec.size() << endl;
tmp_file->module->signals_vec=signals_vec;
// cout << "DEBUG: Anschlie�end size in tmp_file: " << tmp_file->module->signals_vec.size() << endl;
}
// else cout << "DEBUG: Fehler: tmp_file ist NULL? " << (void*) tmp_file << " ... oder tmp_file->module? " << (void*) tmp_file->module << endl;
if(tmp_file->module==NULL) {
// cout << "DEBUG: Kein Modul zur Datei zugewiesen." << endl;
emptyModule=new module_data();
tmp_file->setModule(emptyModule); // prevent NULL pointers
// cout << "DEBUG: emptyModule: " << (void*) emptyModule << endl;
emptyModule=0;
}
files_vec.push_back(tmp_file);
tmp_file=0;
(*fp).close();
}
else {
cout << "ERROR: File could not be opened!" << endl;
}
}
// second run on input files
cout << endl;
cout << "##### Scanning for declarations in files... " << endl;
for(int parameter=0; parameter < files_vec.size(); parameter++) {
filename=(files_vec[parameter])->fileName;
if((files_vec[parameter])->module!=NULL) {
signals_vec=(files_vec[parameter])->module->signals_vec;
ports_vec=(files_vec[parameter])->module->ports_vec;
}
fstream* fpin;
fstream* fpout;
fpin->open(filename,ios::in);
fpout->open((string(filename)+".tmp").c_str(),ios::out);
lineNum=-1;
if(fpin!=nullptr && fpout!=nullptr) {
cout << "\t" << filename << endl;
if((files_vec[parameter])->systemcIncludeLine==1 && !(files_vec[parameter])->headerIncluded) {
*fpout << "#include <gsysc.h>" << endl;
getline(*fpin,zeile);
lineNum++;
}
while(getline(*fpin,zeile)) {
lineNum++;
if((files_vec[parameter])->systemcIncludeLine>0 && !(files_vec[parameter])->headerIncluded) {
if(lineNum+1 == (files_vec[parameter])->systemcIncludeLine) { // Replace '#include "systemc.h"' with gsysc.h
*fpout << "#include <gsysc.h>" << endl;
getline(*fpin,zeile);
lineNum++;
}
}
if(!(files_vec[parameter])->incFileIncluded && (files_vec[parameter])->CTORfirstLine>0) {
if(lineNum+1 == (files_vec[parameter])->CTORfirstLine) {
*fpout << " #include \"" << (files_vec[parameter])->includeFile << "\"" << endl;
}
}
*fpout << zeile << endl;
// Remove comments
if(starComment && (pos=zeile.find("*/"))>=0) {
zeile=zeile.erase(0,pos);
starComment=false;
}
if(starComment) { continue; } // abort loop if the whole line is part of a comment
if((pos=zeile.find("//")) >= 0) { zeile=zeile.erase(pos); }
while((pos=zeile.find("/*")) >= 0) {
starComment=true;
if((pos1=zeile.find("*/",pos)) >= 0) {
zeile=zeile.erase(pos,pos1-pos+2);
starComment=false;
}
else {
zeile=zeile.erase(pos);
}
}
if((pos=zeile.find_first_not_of(" ")) > 0) { zeile = zeile.erase(0,pos); }
// search for declarations
while((pos=zeile.find(";"))>=0) {
workLine=zeile.substr(0,pos);
zeile=zeile.erase(0,pos+1);
// search for signals connected to some ports
if(!((pos=workLine.find(","))>=0)) {
for(int i=0; i<signals_vec.size(); i++) {
if((pos1=workLine.find("("))>=0 && (pos1=(workLine.substr(workLine.find("("))).find((signals_vec[i])->variableName)) >= 0) {
if((pos1=workLine.find("("))>=0) { workLine = workLine.substr(0,pos1); }
if((pos1=workLine.find("=")) >= 0) { continue; }
((signals_vec[i])->portList).push_back(workLine);
continue;
}
}
}
string variableType;
module_data* typeModule=0;
|
workLine=workLine.erase(0,workLine.find_first_not_of(" "));
variableType=workLine.substr(0,workLine.find_first_of("* "));
workLine=workLine.erase(0,workLine.find(" ")+1);
//cout << "--- WorkLine 1: " << workLine << endl;
for(int i=0; i<files_vec.size(); i++) {
if(i==parameter) { continue; }
if((files_vec[i])->module!=NULL && (files_vec[i])->module->name!=NULL) {
if(variableType.compare((files_vec[i])->module->name)==0) {
typeModule=(files_vec[i])->module;
// ensure loop termination:
workLine=workLine+",";
while((pos=workLine.find(","))>=0) {
//cout << "--- WorkLine 2: " << workLine << endl;
varName=workLine.substr(0,pos);
//cout << "--- varName 1: " << varName << endl;
workLine=workLine.erase(0,pos+1);
//cout << "--- WorkLine 3: " << workLine << endl;
if((pos=varName.find_first_not_of(" "))>0) varName=varName.erase(0,pos);
module_decl tempModule;
if((pos1=varName.find("=")) >= 0) { continue; }
if((pos1=varName.find("*"))>=0) {
varName=varName.erase(0,varName.find("*")+1);
tempModule.isPointer=true;
if((pos=varName.find_first_not_of(" "))>0) varName=varName.erase(0,pos);
}
//cout << "--- varName 2: " << varName << endl;
while(varName.at(varName.size()-1)==' ') varName=varName.erase(varName.size()-1,1);
if((pos1=varName.find("["))>=0) {
tempModule.isArray=true;
tempModule.setArraySize( ((varName.substr(0,varName.find("]"))).substr(varName.find("[")+1)).c_str() );
varName=varName.erase(varName.find("["));
}
//cout << "--- varName 3: " << varName << endl;
if((pos1=varName.find("("))>=0) {
givenName=(varName.substr(0,varName.find(")")-1)).substr(pos1+2);
varName=varName.erase(pos1);
tempModule.setRealName(givenName.c_str());
}
//cout << "--- varName 4: " << varName << endl;
tempModule.moduleType=typeModule;
tempModule.setVariableName(varName.c_str());
((files_vec[parameter])->modules_vec).push_back(tempModule);
continue;
} //while
} //if module found
} //if no SEGFAULT
} //for (all files)
}
}
fpin->close();
fpout->close();
remove(filename);
rename((string(filename)+".tmp").c_str(),filename);
}
else {
cerr << "ERROR: '" << filename << "' (or temporary file '" << filename << ".tmp') could not be opened, although it was possible in a former step!\nSkip this file..." << endl;
}
}
// create includable files
cout << "\n##### Creating includable files ..." << endl;
vector<module_decl> modules_vec;
string port_string,port_module,port_port;
for (int parameter=0; parameter < files_vec.size(); parameter++) {
if((files_vec[parameter])->module!=NULL) {
// cout << "DEBUG: Modul-Adresse: " << (files_vec[parameter])->module << endl;
signals_vec=(files_vec[parameter])->module->signals_vec;
ports_vec=(files_vec[parameter])->module->ports_vec;
modules_vec=(files_vec[parameter])->modules_vec;
}
else cout << "ERROR: The module of the currently processed file is NULL." << endl;
cout << "\t" << (files_vec[parameter])->includeFile << " (ports: " << ports_vec.size() << "; signals: " << signals_vec.size() << "; modules: " << modules_vec.size() << ")" << endl;
fstream* incfp;
incfp->open((files_vec[parameter])->includeFile,ios::out);
if(incfp != nullptr) {
string incFileString=(files_vec[parameter])->includeFile;
while ((pos=incFileString.find(".")) > 0) {
incFileString[pos]='_';
}
*incfp << "#ifndef " << incFileString << endl;
*incfp << "#define " << incFileString << endl;
if(ports_vec.size() > 0 || signals_vec.size() || modules_vec.size() > 0) {
for(int i=0; i<ports_vec.size(); i++) {
if((ports_vec[i])->isArray) {
if(strlen((ports_vec[i])->variableName)>0) { *incfp << "for(int GSYSwrapper=0; GSYSwrapper < " << (ports_vec[i])->arraySize << "; GSYSwrapper++) {" << endl; }
}
if(strlen((ports_vec[i])->variableName)==0) {
cout << "\tERROR: This port has no variable name. Skip further processing." << endl;
continue;
}
*incfp << "REG_PORT((";
if(!(ports_vec[i])->isPointer) { *incfp << "&"; }
*incfp << (ports_vec[i])->variableName << ")";
if((ports_vec[i])->isArray) { *incfp << " + GSYSwrapper"; }
*incfp << ",this,0)" << endl;
*incfp << "RENAME_PORT((";
if(!(ports_vec[i])->isPointer) { *incfp << "&"; }
*incfp << (ports_vec[i])->variableName << ")";
if((ports_vec[i])->isArray) {
*incfp << " + GSYSwrapper,\"";
}
else {
*incfp << ",\"";
}
if(strlen((ports_vec[i])->name) > 0) {
*incfp << (ports_vec[i])->name;
}
else {
*incfp << (ports_vec[i])->variableName;
}
*incfp << "\")" << endl;
if((ports_vec[i])->isArray) {
*incfp << "}" << endl;
}
}
for(int i=0; i<modules_vec.size(); i++) {
if((modules_vec[i]).isArray) {
*incfp << "for(int GSYSwrapper=0; GSYSwrapper<" << (modules_vec[i]).arraySize << "; GSYSwrapper++) {" << endl;
}
*incfp << "REG_MODULE(" << (modules_vec[i]).variableName;
if((modules_vec[i]).isArray) { *incfp << "[GSYSwrapper]"; }
*incfp << ",\"";
if(modules_vec[i].givenName!=0) *incfp << modules_vec[i].givenName;
else *incfp << (modules_vec[i]).moduleType->name;
if((files_vec[parameter])->module->isMain) *incfp << "\",0)" << endl;
else *incfp << "\",this)" << endl;
if((modules_vec[i]).isArray) {
*incfp << "}" << endl;
}
}
for(int i=0; i<signals_vec.size(); i++) {
if((signals_vec[i])->isArray) {
if(strlen((signals_vec[i])->variableName)>0) { *incfp << "for(int GSYSwrapper; GSYSwrapper < " << (signals_vec[i])->arraySize << "; GSYSwrapper++) {" << endl; }
}
if(strlen((signals_vec[i])->variableName)==0) {
cout << "\tERROR: This signal has no variable name. Skip further processing." << endl;
continue;
}
for(int o=0; o<((signals_vec[i])->portList).size(); o++) {
*incfp << "REG_PORT(";
port_string=((signals_vec[i])->portList)[o];
if((pos=port_string.find("."))>=0 || (pos1=port_string.find("->"))>=0) {
if(pos>=0) port_module=port_string.substr(0,pos);
else port_module=port_string.substr(0,pos1);
if((pos1=port_module.find("->"))>=0) { // assume level differences of at most 1 between module and port
port_module=port_module.substr(0,pos);
}
port_port=port_string.substr(port_module.size());
if((pos1=port_port.rfind("."))>=0) port_port=port_port.erase(0,pos1+1);
if((pos1=port_port.rfind("->"))>=0) port_port=port_port.erase(0,pos1+2);
while((pos1=port_module.find(" "))>=0) port_module=port_module.erase(pos1,1);
while((pos1=port_port.find(" "))>=0) port_port=port_port.erase(pos1,1);
for(int u=0; u<(files_vec[parameter])->modules_vec.size(); u++) {
if(port_module.compare((((files_vec[parameter])->modules_vec)[u]).variableName)==0) {
vector<port_data*> tempports = ((files_vec[parameter])->modules_vec)[u].moduleType->ports_vec;
for(int a=0; a<tempports.size(); a++) {
if(port_port.compare(tempports[a]->variableName)==0) {
if(!tempports[a]->isPointer) { *incfp << "&"; }
}
}
}
}
}
*incfp << "(";
*incfp << ((signals_vec[i])->portList)[o] << ")";
if((signals_vec[i])->isArray) {
*incfp << " + GSYSwrapper";
}
varName=((signals_vec[i])->portList)[o];
if((pos=varName.find("->"))>=0) varName=varName.erase(pos);
if((pos=varName.find("."))>=0) varName=varName.erase(pos);
*incfp << "," << varName << ",";
if(!(signals_vec[i])->isPointer) { *incfp << "&"; }
*incfp << (signals_vec[i])->variableName << ")" << endl;
}
*incfp << "RENAME_SIGNAL((";
if(!(signals_vec[i])->isPointer) { *incfp << "&"; }
*incfp << (signals_vec[i])->variableName << ")";
if((signals_vec[i])->isArray) {
*incfp << " + GSYSwrapper,\"";
}
else {
*incfp << ",\"";
}
if(strlen((signals_vec[i])->name) > 0) {
*incfp << (signals_vec[i])->name;
}
else {
*incfp << (signals_vec[i])->variableName;
}
*incfp << "\")" << endl;
if((signals_vec[i])->isArray) {
*incfp << "}" << endl;
}
}
}
else {
cout << "\t\tWARNING: Nothing to include for this file." << endl;
}
*incfp << "#endif" << endl;
incfp->close();
}
else {
cout << "ERROR: Could not create this file!" << endl;
}
}
}
}
|
/*
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;
}
|
#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 ALU12 : public rand_obj {
randv< sc_bv<2> > op ;
randv< sc_uint<12> > a, b ;
ALU12()
: op(this), a(this), b(this)
{
constraint ( (op() != 0x0) || ( 4095 >= a() + b() ) );
constraint ( (op() != 0x1) || ((4095 >= a() - b()) && (b() <= a()) ) );
constraint ( (op() != 0x2) || ( 4095 >= a() * b() ) );
constraint ( (op() != 0x3) || ( b() != 0 ) );
}
friend std::ostream & operator<< (std::ostream & o, ALU12 const & alu)
{
o << alu.op
<< ' ' << alu.a
<< ' ' << alu.b
;
return o;
}
};
int sc_main (int argc, char** argv)
{
boost::timer timer;
ALU12 c;
c.next();
std::cout << "first: " << timer.elapsed() << "\n";
for (int i=0; i<1000; ++i) {
c.next();
}
std::cout << "complete: " << timer.elapsed() << "\n";
return 0;
}
|
//--------Thread function definitions-----------------------------
//-----You must modify this file as indicated by TODO comments----
//must include to use the systemc library
#include "systemc.h"
#include "CPU.h"
#include "Block.h"
#include "ReadBmp_aux.h"
#include <string.h>
void CPU::Read_thread(){
cout << sc_time_stamp() << ": Thread Read BMP is initialized\n";
//initial part before the loop
ReadBmpHeader();
ImageWidth = BmpInfoHeader[1];
ImageHeight = BmpInfoHeader[2];
InitGlobals();
NumberMDU = MDUWide * MDUHigh;
//local
Block block;
for(int iter = 0; iter < 180; iter++)
{
ReadBmpBlock(iter);
memcpy(block.data, bmpinput, sizeof(block.data));
cout << sc_time_stamp() << ": Thread Read BMP attempting to send frame" << iter << " to DCT\n";
// TODO: Insert appropriate channel call here
Read2DCT->write(block);
cout << sc_time_stamp() << ": Thread Read BMP has sent frame" << iter << " to DCT\n";
}
wait();
}
void CPU::DCT_thread(){
//local
Block block;
int in_block[64], out_block[64];
cout << sc_time_stamp() << ": Thread DCT is initialized\n";
for(int iter = 0; iter < 180; iter++)
{
cout << sc_time_stamp() << ": Thread DCT is attempting to receive frame" << iter << " from Read BMP\n";
// TODO: Insert appropriate channel call here
Read2DCT->read(block);
cout << sc_time_stamp() << ": Thread DCT has received frame" << iter << " from Read BMP\n";
memcpy(in_block, block.data, sizeof(in_block));
chendct(in_block,out_block);
memcpy(block.data, out_block, sizeof(block.data));
cout << sc_time_stamp() << ": Thread DCT is attempting to send frame" << iter << " to Quantize\n";
// TODO: Insert appropriate channel call here
DCT2Quant->write(block);
cout << sc_time_stamp() << ": Thread DCT has sent frame" << iter << " to Quantize\n";
}
wait();
}
void CPU::Quant_thread(){
Block block;
int in_block[64], out_block[64];
cout << sc_time_stamp() << ": Thread Quantize is initialized\n";
for(int iter = 0; iter < 180; iter++)
{
cout << sc_time_stamp() << ": Thread Quantize is attempting to receive frame" << iter << " from DCT\n";
// TODO: Insert appropriate channel call here
DCT2Quant->read(block);
cout << sc_time_stamp() << ": Thread Quantize has received frame" << iter << " from DCT\n";
// TODO: Copy over block received from channel into local in_block
memcpy(in_block, block.data, sizeof(in_block));
quantize(in_block,out_block);
// TODO: Copy over out_block to block for sending over the channel below
memcpy(block.data, out_block, sizeof(block.data));
cout << sc_time_stamp() << ": Thread Quantize is attempting to send frame" << iter << " to ZigZag\n";
// TODO: Insert appropriate channel call here
Quant2Zigzag->write(block);
cout << sc_time_stamp() << ": Thread Quantize has sent frame" << iter << " to ZigZag\n";
}
wait();
}
void CPU::Zigzag_thread(){
Block block;
int in_block[64], out_block[64];
cout << sc_time_stamp() << ": Thread ZigZag is initialized\n";
for(int iter = 0; iter < 180; iter++)
{
cout << sc_time_stamp() << ": Thread ZigZag is attempting to receive frame" << iter << " from Quantize\n";
// TODO: Insert appropriate channel call here
Quant2Zigzag->read(block);
cout << sc_time_stamp() << ": Thread ZigZag has received frame" << iter << " from Quantize\n";
// TODO: Copy over block received from channel into local in_block
memcpy(in_block, block.data, sizeof(in_block));
zigzag(in_block,out_block);
// TODO: Copy over out_block to block for sending over the channel below
memcpy(block.data, out_block, sizeof(block.data));
cout << sc_time_stamp() << ": Thread ZigZag is attempting to send frame" << iter << " to Huffman\n";
// TODO: Insert appropriate channel call here
Zigzag2Huff->write(block);
cout << sc_time_stamp() << ": Thread ZigZag has sent frame" << iter << " to Huffman\n";
}
wait();
}
void CPU::Huff_thread(){
Block block;
int in_block[64];
cout << sc_time_stamp() << ": Thread Huffman is initialized\n";
for(int iter = 0; iter < 180; iter++)
{
cout << sc_time_stamp() << ": Thread Huffman is attempting to receive frame" << iter << " from ZigZag\n";
// TODO: Insert appropriate channel call here
Zigzag2Huff->read(block);
cout << sc_time_stamp() << ": Thread Huffman has received frame" << iter << " from ZigZag\n";
// TODO: Copy over block received from channel into local in_block
memcpy(in_block, block.data, sizeof(in_block));
huffencode(in_block);
}
cout << sc_time_stamp() << ": Thread Huffman is writing encoded JPEG to file\n";
FileWrite();
cout << sc_time_stamp() << ": JPEG encoding completed\n";
wait();
}
//----------------End of thread function definitions--------------
|
#include <systemc.h>
#include <sstream>
#include <iomanip>
//#include "rom_1024x32_t.hpp"
#include "Vcpu_top.h"
#include "Vcpu_top_cpu_top.h"
#include "Vcpu_top_core_top.h"
#include "Vcpu_top_core_top.h"
#include "Vcpu_top_core.h"
#include "Vcpu_top_regfile.h"
#include "Vcpu_top_bram_dpstrobe.h"
#include "disasm.h"
//////////////////////////////////////////////////
class cpu_top_tb_t : public sc_module
{
public:
Vcpu_top* dut;
uint32_t* ROM;
uint32_t* FD_PC;
uint32_t* FD_inst;
//rom_1024x32_t* instruction_rom;
sc_in<bool> clk_tb;
sc_signal<bool> resetb_tb;
sc_signal<uint32_t> gpio0_tb;
SC_CTOR(cpu_top_tb_t)
: clk_tb("clk_tb")
, resetb_tb("resetb_tb")
, gpio0_tb("gpio0_tb")
{
SC_CTHREAD(test_thread, clk_tb.pos());
dut = new Vcpu_top("dut");
dut->clk(clk_tb);
dut->resetb(resetb_tb);
dut->gpio0(gpio0_tb);
ROM = dut->cpu_top->RAM0->ram;
FD_PC = &(dut->cpu_top->CT0->CPU0->FD_PC);
FD_inst = &(dut->cpu_top->CT0->CPU0->im_do);
// FD_disasm_opcode =
// (char*)dut->cpu_top->CT0->CPU0->inst_dec->disasm_opcode;
}
~cpu_top_tb_t()
{
delete dut;
}
std::string reverse(char* s) {
std::string str(s);
std::reverse(str.begin(), str.end());
return str;
}
void reset()
{
resetb_tb.write(false);
wait();
resetb_tb.write(true);
wait();
}
bool load_program(const std::string& path)
{
//instruction_rom->load_binary(path);
for (int i=0; i<512; ++i) {
ROM[i] = 0;
}
ifstream f(path, std::ios::binary);
if (f.is_open()) {
f.seekg(0, f.end);
int size = f.tellg();
if (size == 0 || size > 2048) {
return false;
}
if (size % 4 != 0) {
return false;
}
f.seekg(0, f.beg);
auto buf = new char[size];
f.read(buf, size);
// std::vector<unsigned char> buf
// (std::istreambuf_iterator<char>(f), {});
auto words = (uint32_t*) buf;
for (int i=0; i<size/4; ++i) {
ROM[i] = words[i];
//std::cerr << "(LOAD) " << std::setfill('0') << std::setw(8) << std::hex << words[i] << std::endl;
}
f.close();
delete[] buf;
//update.write(!update.read());
return true;
}
else {
return false;
}
}
bool report_failure(uint32_t failure_vec, uint32_t prev_PC)
{
if (*FD_PC == failure_vec || disasm(*FD_inst) == "ILLEGAL ") {
std::cout << "(TT) Test failed! prevPC = 0x"
<< std::hex << prev_PC << std::endl;
return true;
}
return false;
}
void view_snapshot_pc()
{
std::cout << "(TT) Opcode=" << disasm(*FD_inst)
<< std::hex
<< ", FD_PC=0x"
<< *FD_PC
//<< ", inst: " << std::hex << std::setfill('0') << std::setw(8) << dut->cpu_top->CT0->CPU0->im_do
//<< ", dm_be: " << std::hex << (unsigned int) dut->cpu_top->CT0->CPU0->dm_be
<< std::endl;
}
void view_snapshot_hex()
{
std::cout << "(TT) Opcode=" << disasm(*FD_inst)
<< ", FD_PC=0x"
<< std::hex
<< *FD_PC
<< ", x1 = 0x" << std::hex
<< dut->cpu_top->CT0->CPU0->RF->data[1]
//<< ", inst: " << std::hex << std::setfill('0') << std::setw(8) << dut->cpu_top->CT0->CPU0->im_do
//<< ", ram_addr: " << std::hex << std::setfill('0') << std::setw(8) << dut->cpu_top->RAM0->addrb
//<< ", ram_wdata: " << std::hex << std::setfill('0') << std::setw(8) << dut->cpu_top->RAM0->dinb
//<< ", dm_do: " << std::hex << std::setfill('0') << std::setw(8) << dut->cpu_top->CT0->CPU0->dm_do
//<< ", dm_be: " << std::hex << (unsigned int) dut->cpu_top->CT0->CPU0->dm_be
<< std::endl;
}
void view_snapshot_int()
{
std::cout << "(TT) Opcode=" << disasm(*FD_inst)
<< ", FD_PC=0x"
<< std::hex
<< *FD_PC
<< ", x1 = "
<< std::dec
<< static_cast<int32_t>(dut->cpu_top->CT0->CPU0->RF->data[1])
//<< ", inst: " << std::hex << std::setfill('0') << std::setw(8) << dut->cpu_top->CT0->CPU0->im_do
//<< ", dm_be: " << std::hex << (unsigned int) dut->cpu_top->CT0->CPU0->dm_be
<< std::endl;
}
void test_thread(void);
void test0(void);
void test1(void);
void test2(void);
void test3(void);
void test4(void);
void test5(void);
void test6(void);
void test7(void);
void test8(void);
void test9(void);
void test10(void);
void test11(void);
void test12(void);
void test13(void);
void test14(void);
void test15(void);
};
void cpu_top_tb_t::test0()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 0: NOP and J Test " << std::endl
<< "(TT) 1. Waveform must be inspected" << std::endl
<< "(TT) 2. Before reset, PC is at 0xFFFFFFFC." << std::endl
<< "(TT) 3. Reset PC is 0x0, which then jumps to 0xC." << std::endl
<< "(TT) 4. Then, increments at steps of 0x4." << std::endl
<< "(TT) 5. Then, jumps to 0xC after 0x20." << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
if (!load_program("tb_out/00-nop.bin")) {
std::cerr << "Program loading failed!" << std::endl;
}
else {
reset();
for (int i=0; i<12; ++i) {
view_snapshot_pc();
wait();
}
}
}
void cpu_top_tb_t::test1()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 1: OP-IMM Test " << std::endl
<< "(TT) 1. Waveform must be inspected" << std::endl
<< "(TT) 2. OP-IMM's start at PC=10, depositing x1 in XB stage" << std::endl
<< "(TT) 3. x1=1,2,3,4,5,6,1,2,1,0,1,-1,-1" << std::endl
<< "(TT) 4. Loops to 0x0C at 0x40" << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
if (!load_program("tb_out/01-opimm.bin")) {
std::cerr << "Program loading failed!" << std::endl;
}
else {
reset();
for (int i=0; i<20; ++i) {
view_snapshot_int();
wait();
}
}
}
void cpu_top_tb_t::test2()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 2: OP Test " << std::endl
<< "(TT) 1. Waveform must be inspected" << std::endl
<< "(TT) 2. OP's start at PC=14." << std::endl
<< "(TT) 3. x1=4,3,1,0,1,0,1,2,4,2,-2,-1,1,0,1" << std::endl
<< "(TT) 4. Loops to 0x0C at 50" << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
if (!load_program("tb_out/02-op.bin")) {
std::cerr << "Program loading failed!" << std::endl;
}
else {
reset();
for (int i=0; i<24; ++i) {
view_snapshot_int();
wait();
}
}
}
void cpu_top_tb_t::test3()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 3: Branch Test " << std::endl
<< "(TT) 1. Waveform must be inspected" << std::endl
<< "(TT) 2. Each type of branch instruction executes twice" << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
if (!load_program("tb_out/03-br.bin")) {
std::cerr << "Program loading failed!" << std::endl;
}
else {
reset();
for (int i=0; i<48; ++i) {
view_snapshot_pc();
wait();
}
}
}
void cpu_top_tb_t::test4()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 4: LUI/AUIPC Test " << std::endl
<< "(TT) 1. Waveform must be inspected" << std::endl
<< "(TT) 2. First, x1 will be loaded with 0xDEADBEEF" << std::endl
<< "(TT) 3. Then, x1 will be loaded with PC=0x14" << std::endl
<< "(TT) 4. Loops at 0x18" << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
if (!load_program("tb_out/04-lui.bin")) {
std::cerr << "Program loading failed!" << std::endl;
}
else {
reset();
for (int i=0; i<16; ++i) {
view_snapshot_hex();
wait();
}
}
}
void cpu_top_tb_t::test5()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 5: JAL/JALR Test " << std::endl
<< "(TT) 1. Waveform must be inspected" << std::endl
<< "(TT) 2. PC=00,0C,18,10,1C,14,0C,18,10,1C,..." << std::endl
<< "(TT) 3. x1=XX,XX,XX,10,10,14,20,20,10,10,..." << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
if (!load_program("tb_out/05-jalr.bin")) {
std::cerr << "Program loading failed!" << std::endl;
}
else {
reset();
for (int i=0; i<16; ++i) {
view_snapshot_hex();
wait();
}
}
}
void cpu_top_tb_t::test6()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 6: CSRR Test " << std::endl
<< "(TT) 1. On failure, a message is displayed" << std::endl
<< "(TT) 2. Failure vector is PC=0x10" << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
if (!load_program("tb_out/06-csrr.bin")) {
std::cerr << "Program loading failed!" << std::endl;
}
else {
reset();
uint32_t prev_PC = 0;
for (int i=0; i<96; ++i) {
if (report_failure(0x10, prev_PC)) break;
prev_PC = *FD_PC;
wait();
}
}
}
void cpu_top_tb_t::test7()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 7: CSRWI Test " << std::endl
<< "(TT) 1. On failure, a message is displayed" << std::endl
<< "(TT) 2. Failure vector is PC=0x10" << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
if (!load_program("tb_out/07-csrwi.bin")) {
std::cerr << "Program loading failed!" << std::endl;
}
else {
reset();
uint32_t prev_PC = 0;
for (int i=0; i<96; ++i) {
//view_snapshot_int();
if (report_failure(0x10, prev_PC)) break;
prev_PC = *FD_PC;
wait();
}
}
}
void cpu_top_tb_t::test8()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 8: CSRW Test " << std::endl
<< "(TT) 1. On failure, a message is displayed" << std::endl
<< "(TT) 2. Failure vector is PC=0x10" << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
if (!load_program("tb_out/08-csrw.bin")) {
std::cerr << "Program loading failed!" << std::endl;
}
else {
reset();
uint32_t prev_PC = 0;
for (int i=0; i<96; ++i) {
if (report_failure(0x10, prev_PC)) break;
prev_PC = *FD_PC;
wait();
}
}
}
void cpu_top_tb_t::test9()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 9: CSRSI Test " << std::endl
<< "(TT) 1. On failure, a message is displayed" << std::endl
<< "(TT) 2. Failure vector is PC=0x10" << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
if (!load_program("tb_out/09-csrsi.bin")) {
std::cerr << "Program loading failed!" << std::endl;
}
else {
reset();
uint32_t prev_PC = 0;
for (int i=0; i<96; ++i) {
if (report_failure(0x10, prev_PC)) break;
prev_PC = *FD_PC;
wait();
}
}
}
void cpu_top_tb_t::test10()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 10: CSRS Test " << std::endl
<< "(TT) 1. On failure, a message is displayed" << std::endl
<< "(TT) 2. Failure vector is PC=0x10" << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
if (!load_program("tb_out/10-csrs.bin")) {
std::cerr << "Program loading failed!" << std::endl;
}
else {
reset();
uint32_t prev_PC = 0;
for (int i=0; i<96; ++i) {
if (report_failure(0x10, prev_PC)) break;
prev_PC = *FD_PC;
wait();
}
}
}
void cpu_top_tb_t::test11()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 11: CSRCI Test " << std::endl
<< "(TT) 1. On failure, a message is displayed" << std::endl
<< "(TT) 2. Failure vector is PC=0x10" << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
if (!load_program("tb_out/11-csrci.bin")) {
std::cerr << "Program loading failed!" << std::endl;
}
else {
reset();
uint32_t prev_PC = 0;
for (int i=0; i<96; ++i) {
if (report_failure(0x10, prev_PC)) break;
prev_PC = *FD_PC;
wait();
}
}
}
void cpu_top_tb_t::test12()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 12: CSRC Test " << std::endl
<< "(TT) 1. On failure, a message is displayed" << std::endl
<< "(TT) 2. Failure vector is PC=0x10" << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
if (!load_program("tb_out/12-csrc.bin")) {
std::cerr << "Program loading failed!" << std::endl;
}
else {
reset();
uint32_t prev_PC = 0;
for (int i=0; i<96; ++i) {
//view_snapshot_hex();
if (report_failure(0x10, prev_PC)) break;
prev_PC = *FD_PC;
wait();
}
}
}
void cpu_top_tb_t::test13()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 13: CSR Atomic Test " << std::endl
<< "(TT) 1. On failure, a message is displayed" << std::endl
<< "(TT) 2. Failure vector is PC=0x10" << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
if (!load_program("tb_out/13-csr.bin")) {
std::cerr << "Program loading failed!" << std::endl;
}
else {
reset();
uint32_t prev_PC = 0;
for (int i=0; i<48; ++i) {
//view_snapshot_int();
if (report_failure(0x10, prev_PC)) break;
prev_PC = *FD_PC;
wait();
}
}
}
void cpu_top_tb_t::test14()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 14: Memory " << std::endl
<< "(TT) 1. On failure, a message is displayed" << std::endl
<< "(TT) 2. Failure vector is PC=0x10" << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
if (!load_program("tb_out/14-mem.bin")) {
std::cerr << "Program loading failed!" << std::endl;
}
else {
reset();
uint32_t prev_PC = 0;
for (int i=0; i<160; ++i) {
//view_snapshot_hex();
if (report_failure(0x10, prev_PC)) break;
prev_PC = *FD_PC;
wait();
}
}
}
void cpu_top_tb_t::test15()
{
std::cout
<< "(TT) --------------------------------------------------" << std::endl
<< "(TT) Test 15: Exception" << std::endl
<< "(TT) 1. On failure, a message is displayed" << std::endl
<< "(TT) 2. Failure vector is PC=0x10" << std::endl
<< "(TT) --------------------------------------------------" << std::endl;
if (!load_program("tb_out/15-exception.bin")) {
std::cerr << "Program loading failed!" << std::endl;
}
else {
reset();
uint32_t prev_PC = 0;
for (int i=0; i<384; ++i) {
// view_snapshot_hex();
if (report_failure(0x0C, prev_PC)) break;
prev_PC = *FD_PC;
wait();
}
}
}
void cpu_top_tb_t::test_thread()
{
reset();
test0();
test1();
test2();
test3();
test4();
test5();
test6();
test7();
test8();
test9();
test10();
test11();
test12();
test13();
test14();
test15();
sc_stop();
}
////////////////////////
int sc_main(int argc, char** argv)
{
Verilated::commandArgs(argc, argv);
auto tb = new cpu_top_tb_t("tb");
sc_clock sysclk("sysclk", 10, SC_NS);
tb->clk_tb(sysclk);
sc_start();
delete tb;
exit(0);
}
|
#include "systemc.h"
#include "system.h"
#include "noc_if.h"
#include "noc_router.h"
#include "sc_trace.hpp"
noc_router::noc_router(sc_module_name name, uint32_t x, uint32_t y)
: sc_module(name), _x(x), _y(y)
{
SC_THREAD(main);
}
void noc_router::setup_ctrl() {
for (int i = 0; i < NOC_N_RDIR; ++i) {
_rdir_ctrls[i] = noc_router_rctrl(i, _x, _y, rports[i]->is_dummy_if());
}
for (int i = 0; i < NOC_N_WDIR; ++i) {
_wdir_ctrls[i] = noc_router_wctrl(i, _x, _y, false);
}
}
void noc_router::read_port(noc_dir_e dir, noc_data_t& data, noc_link_ctrl_t& link_ctrl) {
_wdir_ctrls[(uint32_t)(dir)].read_output(data, link_ctrl);
}
void noc_router::main() {
// port directions to read from
noc_dir_e if_port_dirs[NOC_N_RDIR];
if_port_dirs[NOC_DIR_X_PLUS] = NOC_DIR_X_MINUS; // read x- port from x+ router
if_port_dirs[NOC_DIR_X_MINUS] = NOC_DIR_X_PLUS; // read x+ port from x- router
if_port_dirs[NOC_DIR_Y_PLUS] = NOC_DIR_Y_MINUS; // read y- port from y+ router
if_port_dirs[NOC_DIR_Y_MINUS] = NOC_DIR_Y_PLUS; // read y+ port from y- router
#if NOC_MODE == NOC_MODE_BASE
if_port_dirs[NOC_DIR_TILE] = NOC_DIR_TILE; // read tile port
#elif NOC_MODE == NOC_MODE_RELIABLE
if_port_dirs[NOC_DIR_TILE0] = NOC_DIR_TILE0; // read tile port
if_port_dirs[NOC_DIR_TILE1] = NOC_DIR_TILE1; // read tile port
if_port_dirs[NOC_DIR_TILE2] = NOC_DIR_TILE2; // read tile port
#endif
// data to parse
noc_data_t data;
noc_link_ctrl_t link_ctrl;
// counters
int i, j;
uint32_t x, y, rel;
// status bits
bool out_port_taken[NOC_N_WDIR];
while (true) {
// write to input FIFOs
for (i = 0; i < NOC_N_RDIR; ++i) {
rports[i]->read_port(if_port_dirs[i], data, link_ctrl);
if (link_ctrl.ctrl) {
//LOGF("Packet at rtr %d %d on port %d: %016lx @ %08x", _x, _y, i, data, NOC_RECOVER_RAW_ADDR(link_ctrl.dst));
if (!_rdir_ctrls[i].write_input(data, link_ctrl)) {
// send backpressure
}
}
}
// allow other routers to grab input data
YIELD();
// clear status bits
for (j = 0; j < NOC_N_WDIR; ++j) {
out_port_taken[j] = !_wdir_ctrls[j].can_write_output();
}
// find access requests for each port
for (i = NOC_N_RDIR-1; i >= 0; --i) {
for (j = 0; j < NOC_N_WDIR; ++j) {
// if current port not taken and packet requested
if (!out_port_taken[j] && _rdir_ctrls[i].read_input((noc_dir_e)j, data, link_ctrl)) {
// write to output FIFO
_wdir_ctrls[j].write_output(data, link_ctrl);
out_port_taken[j] = true;
break;
}
}
}
POSEDGE_NoC();
}
}
|
//#define DEBUG //for tracing all internal prints, following are module tracing
//#define DEBUG_BATTERY
//#define DEBUG_OS
//#define DEBUG_SCREEN
//#define DEBUG_POWERBUTTON
#include "systemc.h"
#include "interface.h"
#include "user.h"
#include "phone.h"
int sc_main(int argc, char* argv[])
{
// generating the sc_signal
sc_fifo<Activity> act_fifo;
sc_fifo<CmdPrompt> cmdprompt_fifo;
sc_fifo<Notification> noti_fifo;
sc_signal<bool> pt_sig("pt_sig");
sc_signal<bool> ps_sig("ps_sig");
sc_signal<bool> pow_sig("pow_sig");
sc_signal<Display, SC_MANY_WRITERS> disp_sig("disp_sig"); //use SC_MANY_WRITERS to avoid check
sc_signal<Screen, SC_MANY_WRITERS> scr_sig("scr_sig");
sc_signal<int> batt_sig("batt_sig");
//add any internal signals here
//internal signals are inside the phone and SHOULD NOT be placed here!
// generating the modules
User user1("User1");
// add smartphone modules here
Phone phone("Phone");
// connecting moduleports
user1.activity(act_fifo);
user1.cmdprompt(cmdprompt_fifo);
user1.notification(noti_fifo);
user1.pt_pressed(pt_sig);
user1.ps_plugged(ps_sig);
user1.powered_on(pow_sig);
user1.display(disp_sig);
user1.screen(scr_sig);
user1.battery_level(batt_sig);
//phone port
phone.activity(act_fifo);
phone.cmdprompt(cmdprompt_fifo);
phone.notification(noti_fifo);
phone.pt_pressed(pt_sig);
phone.ps_plugged(ps_sig);
phone.powered_on(pow_sig);
phone.display(disp_sig);
phone.screen(scr_sig);
phone.battery_level(batt_sig);
sc_start(9000,SC_SEC);
return 0;
}
|
/*
* SysPE testbench for Harvard cs148/248 only
*/
#include "SysPE.h"
#include <systemc.h>
#include <mc_scverify.h>
#include <nvhls_int.h>
#include <vector>
#define NVHLS_VERIFY_BLOCKS (SysPE)
#include <nvhls_verify.h>
using namespace::std;
#include <testbench/nvhls_rand.h>
SC_MODULE (Source) {
Connections::Out<SysPE::InputType> act_in;
Connections::Out<SysPE::InputType> weight_in;
Connections::Out<SysPE::AccumType> accum_in;
Connections::In<SysPE::AccumType> accum_out;
Connections::In<SysPE::InputType> act_out;
Connections::In<SysPE::InputType> weight_out;
sc_in <bool> clk;
sc_in <bool> rst;
bool start_src;
vector<SysPE::InputType> act_list{0, -1, 3, -7, 15, -31, 63, -127};
vector<SysPE::AccumType> accum_list{0, -10, 30, -70, 150, -310, 630, -1270};
SysPE::InputType weight_data = 10;
SysPE::AccumType accum_init = 0;
SysPE::InputType act_out_src;
SysPE::AccumType accum_out_src;
SC_CTOR(Source) {
SC_THREAD(run);
sensitive << clk.pos();
async_reset_signal_is(rst, false);
SC_THREAD(pop_result);
sensitive << clk.pos();
async_reset_signal_is(rst, false);
}
void run() {
SysPE::InputType _act;
SysPE::AccumType _acc;
act_in.Reset();
weight_in.Reset();
accum_in.Reset();
// Wait for initial reset
wait(20.0, SC_NS);
wait();
// Write wait to PE
weight_in.Push(weight_data);
wait();
for (int i=0; i< (int) act_list.size(); i++) {
_act = act_list[i];
_acc = accum_list[i];
act_in.Push(_act);
accum_in.Push(_acc);
wait();
} // for
wait(5);
}// void run()
void pop_result() {
weight_out.Reset();
wait();
unsigned int i = 0, j = 0;
bool correct = 1;
while (1) {
SysPE::InputType tmp;
if (weight_out.PopNB(tmp)) {
cout << sc_time_stamp() << ": Received Output Weight:" << " \t " << tmp << endl;
}
if (act_out.PopNB(act_out_src)) {
cout << sc_time_stamp() << ": Received Output Activation:" << " \t " << act_out_src << "\t| Reference \t" << act_list[i] << endl;
correct &= (act_list[i] == act_out_src);
i++;
}
if (accum_out.PopNB(accum_out_src)) {
int acc_ref = accum_list[j] + act_list[j]*weight_data;
cout << sc_time_stamp() << ": Received Accumulated Output:" << "\t " << accum_out_src << "\t| Reference \t" << acc_ref << endl;
correct &= (acc_ref == accum_out_src);
j++;
}
wait();
if (i == act_list.size() && j == act_list.size()) break;
}// while
if (correct == 1) cout << "Implementation Correct :)" << endl;
else cout << "Implementation Incorrect (:" << endl;
}// void pop_result()
};
SC_MODULE (testbench) {
sc_clock clk;
sc_signal<bool> rst;
Connections::Combinational<SysPE::InputType> act_in;
Connections::Combinational<SysPE::InputType> act_out;
Connections::Combinational<SysPE::InputType> weight_in;
Connections::Combinational<SysPE::InputType> weight_out;
Connections::Combinational<SysPE::AccumType> accum_in;
Connections::Combinational<SysPE::AccumType> accum_out;
NVHLS_DESIGN(SysPE) PE;
Source src;
SC_HAS_PROCESS(testbench);
testbench(sc_module_name name)
: sc_module(name),
clk("clk", 1, SC_NS, 0.5,0,SC_NS,true),
rst("rst"),
PE("PE"),
src("src")
{
PE.clk(clk);
PE.rst(rst);
PE.act_in(act_in);
PE.act_out(act_out);
PE.weight_in(weight_in);
PE.weight_out(weight_out);
PE.accum_in(accum_in);
PE.accum_out(accum_out);
src.clk(clk);
src.rst(rst);
src.act_in(act_in);
src.act_out(act_out);
src.weight_in(weight_in);
src.weight_out(weight_out);
src.accum_in(accum_in);
src.accum_out(accum_out);
SC_THREAD(run);
}
void run() {
rst = 1;
wait(10.5, SC_NS);
rst = 0;
cout << "@" << sc_time_stamp() << " Asserting Reset " << endl ;
wait(1, SC_NS);
cout << "@" << sc_time_stamp() << " Deasserting Reset " << endl ;
rst = 1;
wait(10000,SC_NS);
cout << "@" << sc_time_stamp() << " Stop " << endl ;
sc_stop();
}
};
int sc_main(int argc, char *argv[])
{
nvhls::set_random_seed();
testbench my_testbench("my_testbench");
sc_start();
//cout << "CMODEL PASS" << endl;
return 0;
};
|
//--------Thread function definitions-----------------------------
//-----You must modify this file as indicated by TODO comments----
//must include to use the systemc library
#include "systemc.h"
#include "JPEG.h"
#include "Block.h"
#include "ReadBmp_aux.h"
void Read_Module::Read_thread(){
cout << sc_time_stamp() << ": Thread Read BMP is initialized\n";
//initial part before the loop
ReadBmpHeader();
ImageWidth = BmpInfoHeader[1];
ImageHeight = BmpInfoHeader[2];
InitGlobals();
NumberMDU = MDUWide * MDUHigh;
//local
Block block;
for(int iter = 0; iter < 180; iter++)
{
// TODO: consume time for this iteration = 1119 micro-seconds
sc_time TimeForIteration(1119, SC_US);
wait(TimeForIteration);
ReadBmpBlock(iter);
for(int i = 0; i < 64; i++){
block.data[i] = bmpinput[i];
}
cout << sc_time_stamp() << ": Thread Read BMP attempting to send frame" << iter << " to DCT\n";
// TODO: Insert appropriate port call here
outport.write(block);
cout << sc_time_stamp() << ": Thread Read BMP has sent frame" << iter << " to DCT\n";
}
wait();
}
void DCT_Module::DCT_thread(){
//local
Block block;
int in_block[64], out_block[64];
cout << sc_time_stamp() << ": Thread DCT is initialized\n";
for(int iter = 0; iter < 180; iter++)
{
cout << sc_time_stamp() << ": Thread DCT is attempting to receive frame" << iter << " from Read BMP\n";
// TODO: Insert appropriate port call here
inport.read(block);
cout << sc_time_stamp() << ": Thread DCT has received frame" << iter << " from Read BMP\n";
// TODO: consume time for this iteration = 4321 micro-seconds
sc_time TimeForIteration(4321, SC_US);
wait(TimeForIteration);
memcpy(in_block, block.data, sizeof(in_block));
chendct(in_block,out_block);
memcpy(block.data, out_block, sizeof(block.data));
cout << sc_time_stamp() << ": Thread DCT is attempting to send frame" << iter << " to Quantize\n";
// TODO: Insert appropriate port call here
outport.write(block);
cout << sc_time_stamp() << ": Thread DCT has sent frame" << iter << " to Quantize\n";
}
wait();
}
void Quant_Module::Quant_thread(){
Block block;
int in_block[64], out_block[64];
cout << sc_time_stamp() << ": Thread Quantize is initialized\n";
for(int iter = 0; iter < 180; iter++)
{
cout << sc_time_stamp() << ": Thread Quantize is attempting to receive frame" << iter << " from DCT\n";
// TODO: Insert appropriate port call here
inport.read(block);
cout << sc_time_stamp() << ": Thread Quantize has received frame" << iter << " from DCT\n";
// TODO: consume time for this iteration = 5711 micro-seconds
sc_time TimeForIteration(5711, SC_US);
wait(TimeForIteration);
// TODO: Copy over block received from channel into local in_block
memcpy(in_block, block.data, sizeof(in_block));
quantize(in_block,out_block);
// TODO: Copy over out_block to block for sending over the channel below
memcpy(block.data, out_block, sizeof(block.data));
cout << sc_time_stamp() << ": Thread Quantize is attempting to send frame" << iter << " to ZigZag\n";
// TODO: Insert appropriate port call here
outport.write(block);
cout << sc_time_stamp() << ": Thread Quantize has sent frame" << iter << " to ZigZag\n";
}
wait();
}
void Zigzag_Module::Zigzag_thread(){
Block block;
int in_block[64], out_block[64];
cout << sc_time_stamp() << ": Thread ZigZag is initialized\n";
for(int iter = 0; iter < 180; iter++)
{
cout << sc_time_stamp() << ": Thread ZigZag is attempting to receive frame" << iter << " from Quantize\n";
// TODO: Insert appropriate port call here
inport.read(block);
cout << sc_time_stamp() << ": Thread ZigZag has received frame" << iter << " from Quantize\n";
// TODO: consume time for this iteration = 587 micro-seconds
sc_time TimeForIteration(587, SC_US);
wait(TimeForIteration);
// TODO: Copy over block received from channel into local in_block
memcpy(in_block, block.data, sizeof(in_block));
zigzag(in_block,out_block);
// TODO: Copy over out_block to block for sending over the channel below
memcpy(block.data, out_block, sizeof(block.data));
cout << sc_time_stamp() << ": Thread ZigZag is attempting to send frame" << iter << " to Huffman\n";
// TODO: Insert appropriate port call here
outport.write(block);
cout << sc_time_stamp() << ": Thread ZigZag has sent frame" << iter << " to Huffman\n";
}
wait();
}
void Huff_Module::Huff_thread(){
Block block;
int in_block[64];
cout << sc_time_stamp() << ": Thread Huffman is initialized\n";
for(int iter = 0; iter < 180; iter++)
{
cout << sc_time_stamp() << ": Thread Huffman is attempting to receive frame" << iter << " from ZigZag\n";
// TODO: Insert appropriate port call here
inport.read(block);
cout << sc_time_stamp() << ": Thread Huffman has received frame" << iter << " from ZigZag\n";
// TODO: consume time for this iteration = 10162 micro-seconds
sc_time TimeForIteration(10162, SC_US);
wait(TimeForIteration);
// TODO: Copy over block received from channel into local in_block
memcpy(in_block, block.data, sizeof(in_block));
huffencode(in_block);
}
cout << sc_time_stamp() << ": Thread Huffman is writing encoded JPEG to file\n";
FileWrite();
cout << sc_time_stamp() << ": JPEG encoding completed\n";
wait();
}
//----------------End of thread function definitions--------------
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.