text
stringlengths
41
20k
//-----Function definitions for classes os, os_taski and os_sem--- //-----You must modify this file as indicated by TODO comments---- //-----You should reuse code from Programming Assignment 3-------- //-----as indicated by the REUSE comments------------------------- //-----Note that new code must be written for os_sem methods------ //-----The time_wait method in OS must be rewritten--------------- //-----to account for preemption---------------------------------- #include "systemc.h" #include "os.h" using namespace std; // implementation of os_task methods //placeholder constructor since we have a pool os_task::os_task() { } os_task::~os_task(){ } void os_task::instantiate(sc_core::sc_process_handle handle, const char *name, unsigned int priority){ static unsigned int count = 0; task_name = name; // All tasks are initially ready when created task_state = READY; task_id = count; task_priority = priority; task_handle = handle; activation_flag = rd_suspended_flag = wr_suspended_flag = false; count++; } const char *os_task::get_name(){ return task_name.data(); } enum state os_task::get_state(){ return task_state; } unsigned int os_task::get_id(){ return task_id; } unsigned int os_task::get_priority(){ return task_priority; } sc_core::sc_process_handle os_task::get_handle(){ return task_handle; } void os_task::activate(){ // REUSE: set the activation flag and notify the event // TODO: set the activation flag and notify the event activation_flag = true; activation_event.notify(); task_state = RUNNING; return; } void os_task::wait_for_activation(){ // REUSE: If the activation flag is not set, // REUSE: wait for it to be set if (activation_flag == false) { wait(activation_event); } // REUSE: reset the activation flag activation_flag = false; // REUSE: update the task state //task_state = SUSPENDED; return; } //os class method implementation os::os(){ // empty constructor } os::~os(){ } // dynamic task creation function // this function is called by the main SC thread in the top module // it may also be called by tasks to dynamically create children os_task *os::task_create( const char* name, unsigned int priority, sc_core::sc_process_handle h) { // get a task object from the pool static int count = 0; os_task *t = &(task_pool[count++]); // REUSE: instantiate the user task in the OS model t->instantiate(h, name, priority); // REUSE: add the task to the ALL_TASKS list ALL_TASKS.push_back(t); //newly created task is in the ready state // REUSE: add it to READY vector list READY_TASKS.push_back(t); // return the task pointer return t; } // task initialization function // this function is called by the SystemC thread // for the task, at the very beginning void os::task_init(){ // REUSE: find this task's pointer "t" os_task *t = NULL; // REUSE: wait for the task to be scheduled by the OS // TODO: find this task's pointer "t" static int count = 0; t = &(task_pool[count++]); // TODO: wait for the task to be scheduled by the OS t->wait_for_activation(); cout << sc_time_stamp() << ": Task " << t->get_name() << " is initialized" << endl; return; } // task termination function // this function is called by the running task // to terminate itself void os::task_terminate(){ // REUSE: update the state of the task os_task *t = CURRENT; t->task_state = TERMINATED; // REUSE: do a rescheduling on remaining tasks schedule(); // REUSE: wait till end of simulation if no tasks remain bool all_terminated = true; for (int i = 0; i < ALL_TASKS.size(); i++) { os_task *temp_t = ALL_TASKS[i]; if (temp_t->get_state() != TERMINATED) { all_terminated = false; break; } } if (all_terminated) { wait(); } } // this function displays the states of // all the tasks in the order of their creation // It is called by the OS schedule method // whenever a rescheduling takes place void os::status(){ cout << endl << sc_time_stamp() << ":" << endl; for (int i = 0; i < ALL_TASKS.size(); i++){ os_task *t = ALL_TASKS[i]; cout << t->get_name() << ": "; if (t->get_state() == RUNNING) cout << "RUNNING" << endl; else if (t->get_state() == READY) cout << "READY" << endl; else if (t->get_state() == SUSPENDED) cout << "SUSPENDED" << endl; else if (t->get_state() == TERMINATED) cout << "TERMINATED" << endl; } } void os::time_wait(sc_time t) { // TODO: use simultaneous wait on time and preemption event // TODO: if preemption event arrives before all the time // TODO: has been consumed, go to ready state, wait for activation // TODO: then consume the remainder time // TODO: repeat until all of "t" has been consumed os_task *temp_task = CURRENT; sc_time start_time = sc_time_stamp(), elapsed_time = SC_ZERO_TIME; do { sc_time remainder_time = t - elapsed_time; wait(remainder_time, preemption); sc_time delta = sc_time_stamp() - start_time; elapsed_time = elapsed_time + delta; if(elapsed_time < t) { temp_task->wait_for_activation(); } } while(elapsed_time < t); return; } // end time_wait ERROR os::schedule() { // REUSE: If there are no tasks or all tasks have terminated // REUSE: Pring the status and return code E_NO_TASKS if (READY_TASKS.empty()) { status(); return E_NO_TASKS; } bool all_terminated = true; for (int i = 0; i < ALL_TASKS.size(); i++) { os_task *t = ALL_TASKS[i]; if (t->get_state() != TERMINATED) { all_terminated = false; break; } } if (all_terminated) { status(); return E_NO_TASKS; } // REUSE: If all tasks are suspended, just display // REUSE: the states and return code E_OK bool not_all_suspended = false; for (int i = 0; i < ALL_TASKS.size(); i++) { os_task *t = ALL_TASKS[i]; if (t->get_state() != SUSPENDED) { not_all_suspended = true; break; } } // otherwise, we have some scheduling to do! // REUSE: find the highest priority ready task // REUSE: remove the highest priority task from the ready list // REUSE: and activate it! if (not_all_suspended) { // TODO: remove the highest priority task from the ready list // TODO: and activate it! unsigned int task_index = 0; unsigned int priority = READY_TASKS[0]->get_priority(); for (int i = 1; i < READY_TASKS.size(); i++) { os_task *t = READY_TASKS[i]; if (t->get_priority() > priority) { task_index = i; priority = t->get_priority(); } } CURRENT = READY_TASKS[task_index]; READY_TASKS.erase(READY_TASKS.begin() + task_index); CURRENT->activate(); } // print out the status of all the tasks status(); return E_OK; } // end schedule void os::run() { // all the initial tasks have been created // kickstart the scheduler cout << "Initializing Scheduler..." <<endl; schedule(); } // os_sem method implementation //------------------------------------------------------------- int os_sem::wait() { int retval; class os_task *temp_t = OS->CURRENT; // TODO: if the semaphore value is 0 // TODO: the accessing task must be blocked if (get_value() == 0) { // TODO: block the caller temp_t->task_state = SUSPENDED; OS->CURRENT = NULL; cout << sc_time_stamp() <<": Task "<< temp_t->get_name() << " blocked on semaphore " << sc_semaphore::name() << "\n"; // TODO: set the blocked_task pointer blocked_task = temp_t; // TODO: find the next active task and run it OS->schedule(); blocked_task->wait_for_activation(); } // proceed by running the base class method retval = sc_semaphore::wait(); return retval; } // end os_sem wait method int os_sem::post() { int retval; class os_task *temp_task = blocked_task; // increment the semaphore value // by calling the base class method retval = sc_semaphore::post(); // TODO: if there is a blocked task, it should be unblocked if (blocked_task) { // TODO: if all tasks are suspended // TODO: run the scheduler here // TODO: after waking up the blocked task bool all_suspended = true; for (int i = 0; i < OS->ALL_TASKS.size(); i++) { os_task *t = OS->ALL_TASKS[i]; if (t->get_state() != SUSPENDED && t->get_state() != TERMINATED) { all_suspended = false; break; } } blocked_task->task_state = READY; OS->READY_TASKS.push_back(blocked_task); blocked_task = 0; if(all_suspended) { OS->schedule(); } else if(OS->CURRENT->get_priority() < temp_task->get_priority() ) { // TODO: if there is a running task with lower priority // TODO: than the newly unblocked task, // TODO: the running task should be preempted OS->CURRENT->task_state = READY; OS->READY_TASKS.push_back(OS->CURRENT); OS->preemption.notify(); // TODO: the message below should be printed only in the case of preemption cout << sc_time_stamp() <<": Task "<< OS->CURRENT->get_name() << " preempted by task " << temp_task->get_name() << "\n"; OS->CURRENT = NULL; OS->schedule(); temp_task->wait_for_activation(); } } return retval; } // end os_sem post method
//--------Thread function definitions----------------------------- //-----You must modify this file as indicated by TODO comments---- //must include to use the systemc library #include "systemc.h" #include "sysc/kernel/sc_dynamic_processes.h" #include "CPU.h" #include "Block.h" #include "ReadBmp_aux.h" // The main thread that will spawn JPEG tasks void CPU::top() { // define the SystemC process handles sc_core::sc_process_handle Read_h, DCT_h, Quant_h, Zigzag_h, Huff_h; // spawn the SystemC threads Read_h = sc_spawn(sc_bind(&CPU::Read_thread, this)); DCT_h = sc_spawn(sc_bind(&CPU::DCT_thread, this)); Quant_h = sc_spawn(sc_bind(&CPU::Quant_thread, this)); Zigzag_h = sc_spawn(sc_bind(&CPU::Zigzag_thread, this)); Huff_h = sc_spawn(sc_bind(&CPU::Huff_thread, this)); // TODO: create the tasks in the OS context OS->task_create("Read"/*sc_gen_unique_name("Read")*/, READ_PRIORITY,Read_h); OS->task_create("DCT"/*sc_gen_unique_name("DCT")*/, DCT_PRIORITY, DCT_h); OS->task_create("Quantize"/*sc_gen_unique_name("Quantize")*/, QUANTIZE_PRIORITY, Quant_h); OS->task_create("Zigzag"/*sc_gen_unique_name("Zigzag")*/, ZIGZAG_PRIORITY, Zigzag_h); OS->task_create("Huffman"/*sc_gen_unique_name("Huffman")*/, HUFFMAN_PRIORITY, Huff_h); // tasks have been created // now kickstart the OS OS->run(); return; } //end top method void CPU::Read_thread() { // TODO: initialize the task in the OS context OS->task_init(); //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++) { // consume time for this iteration = 1119 micro-seconds OS->time_wait(1119, SC_US); ReadBmpBlock(iter); for (int i = 0; i < 64; i++) { block.data[i] = bmpinput[i]; } Read2DCT->write(block); } // TODO: terminate the task in the OS context OS->task_terminate(); } void CPU::DCT_thread() { //local Block block; int in_block[64], out_block[64]; // TODO: initialize the task in the OS context OS->task_init(); for (int iter = 0; iter < 180; iter++) { Read2DCT->read(block); // consume time for this iteration = 4321 micro-seconds OS->time_wait(4321, SC_US); for (int i = 0; i < 64; i++) { in_block[i] = block.data[i]; } chendct(in_block, out_block); for (int i = 0; i < 64; i++) { block.data[i] = out_block[i]; } DCT2Quant->write(block); } // TODO: terminate the task in the OS context OS->task_terminate(); } void CPU::Quant_thread() { Block block; int in_block[64], out_block[64]; // TODO: initialize the task in the OS context OS->task_init(); for (int iter = 0; iter < 180; iter++) { DCT2Quant->read(block); // consume time for this iteration = 5711 micro-seconds OS->time_wait(5711, SC_US); for (int i = 0; i < 64; i++) { in_block[i] = block.data[i]; } quantize(in_block, out_block); for (int i = 0; i < 64; i++) { block.data[i] = out_block[i]; } Quant2Zigzag->write(block); } // TODO: terminate the task in the OS context OS->task_terminate(); } void CPU::Zigzag_thread() { Block block; int in_block[64], out_block[64]; // TODO: initialize the task in the OS context OS->task_init(); for (int iter = 0; iter < 180; iter++) { Quant2Zigzag->read(block); // consume time for this iteration = 587 micro-seconds OS->time_wait(587, SC_US); for (int i = 0; i < 64; i++) { in_block[i] = block.data[i]; } zigzag(in_block, out_block); for (int i = 0; i < 64; i++) { block.data[i] = out_block[i]; } Zigzag2Huff->write(block); } // TODO: terminate the task in the OS context OS->task_terminate(); } void CPU::Huff_thread() { Block block; int in_block[64]; // TODO: initialize the task in the OS context OS->task_init(); for (int iter = 0; iter < 180; iter++) { Zigzag2Huff->read(block); // consume time for this iteration = 10162 micro-seconds OS->time_wait(10162, SC_US); for (int i = 0; i < 64; i++) { in_block[i] = block.data[i]; } 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"; // TODO: terminate the task in the OS context OS->task_terminate(); }
/* 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; }
/** * Murac Auxilliary Architecture integration framework * Author: Brandon Hamilton <[email protected]> */ #include <systemc.h> #include <dlfcn.h> #include <fcntl.h> #include <sys/mman.h> #include "muracAA.hpp" typedef int (*murac_init_func)(BusInterface*); typedef int (*murac_exec_func)(unsigned long int); using std::cout; using std::endl; using std::dec; using std::hex; SC_HAS_PROCESS( muracAA ); muracAAInterupt::muracAAInterupt(const char *name, muracAA *aa): m_aa(aa), m_name(name) { } void muracAAInterupt::write(const int &value) { if (value == 1) { m_aa->onBrArch(value); } } /** * Constructor */ muracAA::muracAA( sc_core::sc_module_name name) : sc_module( name ), brarch("brarch", this) { } int muracAA::loadLibrary(const char *library) { cout << "Loading murac library: " << library << endl; void* handle = dlopen(library, RTLD_NOW | RTLD_GLOBAL); if (!handle) { cout << dlerror() << endl; return -1; } dlerror(); cout << "Initializing murac library: " << library << endl; murac_init_func m_init = (murac_init_func) dlsym(handle, "murac_init"); int result = m_init(this); return result; } int muracAA::invokePluginSimulation(const char* path, unsigned long int ptr) { char *error; void* handle = dlopen(path, RTLD_LAZY | RTLD_GLOBAL); if (!handle) { cout << dlerror() << endl; return -1; } dlerror(); murac_exec_func m_exec = (murac_exec_func) dlsym(handle, "murac_execute"); if ((error = dlerror()) != NULL) { fprintf(stderr, "%s\n", error); return -1; } int result = -1; sc_process_handle h = sc_spawn(&result, sc_bind(m_exec, ptr) ); wait(h.terminated_event()); //dlclose(handle); return result; } /** * Handle the BrArch interrupt from the PA */ void muracAA::onBrArch(const int &value) { cout << "@" << sc_time_stamp() << " onBrArch" << endl; int ret = -1; int fd; unsigned long int pc = 0; unsigned int instruction_size = 0; unsigned long int ptr = 0; unsigned char* fmap; char *tmp_file_name = strdup("/tmp/murac_AA_XXXXXX"); if (busRead(MURAC_PC_ADDRESS, (unsigned char*) &pc, 4) < 0) { cout << "@" << sc_time_stamp() << " Memory read error !" << endl; goto trigger_return_interrupt; } cout << "@" << sc_time_stamp() << " PC: 0x" << hex << pc << endl; if (busRead(MURAC_PC_ADDRESS + 4, (unsigned char*) &instruction_size, 4) < 0) { cout << "@" << sc_time_stamp() << " Memory read error !" << endl; goto trigger_return_interrupt; } cout << "@" << sc_time_stamp() << " Instruction size: " << dec << instruction_size << endl; if (busRead(MURAC_PC_ADDRESS + 8, (unsigned char*) &ptr, 4) < 0) { cout << "@" << sc_time_stamp() << " Memory read error !" << endl; goto trigger_return_interrupt; } cout << "@" << sc_time_stamp() << " Ptr : " << hex << ptr << dec << endl; cout << "@" << sc_time_stamp() << " Reading embedded AA simulation file " << endl; fd = mkostemp (tmp_file_name, O_RDWR | O_CREAT | O_TRUNC); if (fd == -1) { cout << "Error: Cannot open temporary file for writing." << endl; goto trigger_return_interrupt; } ret = lseek(fd, instruction_size-1, SEEK_SET); if (ret == -1) { close(fd); cout << "Error: Cannot call lseek() on temporary file." << endl; goto trigger_return_interrupt; } ret = ::write(fd, "", 1); if (ret != 1) { close(fd); cout << "Error: Error writing last byte of the temporary file." << endl; goto trigger_return_interrupt; } fmap = (unsigned char*) mmap(0, instruction_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (fmap == MAP_FAILED) { close(fd); cout << "Error: Error mmapping the temporary file." << endl; goto trigger_return_interrupt; } // Write the file if (busRead(pc, fmap, instruction_size) < 0) { cout << "@" << sc_time_stamp() << " Memory read error !" << endl; munmap(fmap, instruction_size); close(fd); goto trigger_return_interrupt; } if (munmap(fmap, instruction_size) == -1) { close(fd); cout << "Error: Error un-mmapping the temporary file." << endl; goto trigger_return_interrupt; } close(fd); cout << "@" << sc_time_stamp() << " Running murac AA simulation " << endl; ret = invokePluginSimulation(tmp_file_name, ptr); cout << "@" << sc_time_stamp() << " Simulation result = " << ret << endl; remove(tmp_file_name); trigger_return_interrupt: free(tmp_file_name); cout << "@" << sc_time_stamp() << " Returning to PA " << endl; // Trigger interrupt for return to PA intRetArch.write(1); intRetArch.write(0); } /** * Read from the bus */ int muracAA::busRead (unsigned long int addr, unsigned char rdata[], int dataLen) { bus_payload.set_read (); bus_payload.set_address ((sc_dt::uint64) addr); bus_payload.set_byte_enable_length ((const unsigned int) dataLen); bus_payload.set_byte_enable_ptr (0); bus_payload.set_data_length ((const unsigned int) dataLen); bus_payload.set_data_ptr ((unsigned char *) rdata); busTransfer(bus_payload); return bus_payload.is_response_ok () ? 0 : -1; } /** * Write to the bus */ int muracAA::busWrite (unsigned long int addr, unsigned char wdata[], int dataLen) { bus_payload.set_write (); bus_payload.set_address ((sc_dt::uint64) addr); bus_payload.set_byte_enable_length ((const unsigned int) dataLen); bus_payload.set_byte_enable_ptr (0); bus_payload.set_data_length ((const unsigned int) dataLen); bus_payload.set_data_ptr ((unsigned char *) wdata); busTransfer(bus_payload); return bus_payload.is_response_ok () ? 0 : -1; } /** * Initiate bus transfer */ void muracAA::busTransfer( tlm::tlm_generic_payload &trans ) { sc_core::sc_time dummyDelay = sc_core::SC_ZERO_TIME; aa_bus->b_transport( trans, dummyDelay ); } int muracAA::read(unsigned long int addr, unsigned char*data, unsigned int len) { return busRead(addr, data, len); } int muracAA::write(unsigned long int addr, unsigned char*data, unsigned int len) { return busWrite(addr, data, len); }
#include <systemc.h> #include "HammingRegister.h" #include "testbench.h" #include "SYSTEM.h" SYSTEMH *sysh=NULL; int sc_main(int argc, char *argv[]) { cout << " The Simulation Started"<< endl; sysh=new SYSTEMH("sysh"); sc_start(); //start the simulation cout <<" The Simulation Ended "<<endl; return 0; }
/* * 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; };
//-----Function definitions for classes os, os_taski and os_sem--- //-----You must modify this file as indicated by TODO comments---- //-----You should reuse code from Programming Assignment 3-------- //-----as indicated by the REUSE comments------------------------- //-----Note that new code must be written for os_sem methods------ //-----The time_wait method in OS must be rewritten--------------- //-----to account for preemption---------------------------------- #include "systemc.h" #include "os.h" using namespace std; // implementation of os_task methods //placeholder constructor since we have a pool os_task::os_task() { } os_task::~os_task(){ } void os_task::instantiate(sc_core::sc_process_handle handle, const char *name, unsigned int priority){ static unsigned int count = 0; task_name = name; // All tasks are initially ready when created task_state = READY; task_id = count; task_priority = priority; task_handle = handle; activation_flag = rd_suspended_flag = wr_suspended_flag = false; count++; } const char *os_task::get_name(){ return task_name.data(); } enum state os_task::get_state(){ return task_state; } unsigned int os_task::get_id(){ return task_id; } unsigned int os_task::get_priority(){ return task_priority; } sc_core::sc_process_handle os_task::get_handle(){ return task_handle; } void os_task::activate(){ // REUSE: set the activation flag and notify the event // TODO: set the activation flag and notify the event activation_flag = true; activation_event.notify(); task_state = RUNNING; return; } void os_task::wait_for_activation(){ // REUSE: If the activation flag is not set, // REUSE: wait for it to be set if (activation_flag == false) { wait(activation_event); } // REUSE: reset the activation flag activation_flag = false; // REUSE: update the task state //task_state = SUSPENDED; return; } //os class method implementation os::os(){ // empty constructor } os::~os(){ } // dynamic task creation function // this function is called by the main SC thread in the top module // it may also be called by tasks to dynamically create children os_task *os::task_create( const char* name, unsigned int priority, sc_core::sc_process_handle h) { // get a task object from the pool static int count = 0; os_task *t = &(task_pool[count++]); // REUSE: instantiate the user task in the OS model t->instantiate(h, name, priority); // REUSE: add the task to the ALL_TASKS list ALL_TASKS.push_back(t); //newly created task is in the ready state // REUSE: add it to READY vector list READY_TASKS.push_back(t); // return the task pointer return t; } // task initialization function // this function is called by the SystemC thread // for the task, at the very beginning void os::task_init(){ // REUSE: find this task's pointer "t" os_task *t = NULL; // REUSE: wait for the task to be scheduled by the OS // TODO: find this task's pointer "t" static int count = 0; t = &(task_pool[count++]); // TODO: wait for the task to be scheduled by the OS t->wait_for_activation(); cout << sc_time_stamp() << ": Task " << t->get_name() << " is initialized" << endl; return; } // task termination function // this function is called by the running task // to terminate itself void os::task_terminate(){ // REUSE: update the state of the task os_task *t = CURRENT; t->task_state = TERMINATED; // REUSE: do a rescheduling on remaining tasks schedule(); // REUSE: wait till end of simulation if no tasks remain bool all_terminated = true; for (int i = 0; i < ALL_TASKS.size(); i++) { os_task *temp_t = ALL_TASKS[i]; if (temp_t->get_state() != TERMINATED) { all_terminated = false; break; } } if (all_terminated) { wait(); } } // this function displays the states of // all the tasks in the order of their creation // It is called by the OS schedule method // whenever a rescheduling takes place void os::status(){ cout << endl << sc_time_stamp() << ":" << endl; for (int i = 0; i < ALL_TASKS.size(); i++){ os_task *t = ALL_TASKS[i]; cout << t->get_name() << ": "; if (t->get_state() == RUNNING) cout << "RUNNING" << endl; else if (t->get_state() == READY) cout << "READY" << endl; else if (t->get_state() == SUSPENDED) cout << "SUSPENDED" << endl; else if (t->get_state() == TERMINATED) cout << "TERMINATED" << endl; } } void os::time_wait(sc_time t) { // TODO: use simultaneous wait on time and preemption event // TODO: if preemption event arrives before all the time // TODO: has been consumed, go to ready state, wait for activation // TODO: then consume the remainder time // TODO: repeat until all of "t" has been consumed os_task *temp_task = CURRENT; sc_time start_time = sc_time_stamp(), elapsed_time = SC_ZERO_TIME; do { sc_time remainder_time = t - elapsed_time; wait(remainder_time, preemption); sc_time delta = sc_time_stamp() - start_time; elapsed_time = elapsed_time + delta; if(elapsed_time < t) { temp_task->wait_for_activation(); } } while(elapsed_time < t); return; } // end time_wait ERROR os::schedule() { // REUSE: If there are no tasks or all tasks have terminated // REUSE: Pring the status and return code E_NO_TASKS if (READY_TASKS.empty()) { status(); return E_NO_TASKS; } bool all_terminated = true; for (int i = 0; i < ALL_TASKS.size(); i++) { os_task *t = ALL_TASKS[i]; if (t->get_state() != TERMINATED) { all_terminated = false; break; } } if (all_terminated) { status(); return E_NO_TASKS; } // REUSE: If all tasks are suspended, just display // REUSE: the states and return code E_OK bool not_all_suspended = false; for (int i = 0; i < ALL_TASKS.size(); i++) { os_task *t = ALL_TASKS[i]; if (t->get_state() != SUSPENDED) { not_all_suspended = true; break; } } // otherwise, we have some scheduling to do! // REUSE: find the highest priority ready task // REUSE: remove the highest priority task from the ready list // REUSE: and activate it! if (not_all_suspended) { // TODO: remove the highest priority task from the ready list // TODO: and activate it! unsigned int task_index = 0; unsigned int priority = READY_TASKS[0]->get_priority(); for (int i = 1; i < READY_TASKS.size(); i++) { os_task *t = READY_TASKS[i]; if (t->get_priority() > priority) { task_index = i; priority = t->get_priority(); } } CURRENT = READY_TASKS[task_index]; READY_TASKS.erase(READY_TASKS.begin() + task_index); CURRENT->activate(); } // print out the status of all the tasks status(); return E_OK; } // end schedule void os::run() { // all the initial tasks have been created // kickstart the scheduler cout << "Initializing Scheduler..." <<endl; schedule(); } // os_sem method implementation //------------------------------------------------------------- int os_sem::wait() { int retval; class os_task *temp_t = OS->CURRENT; // TODO: if the semaphore value is 0 // TODO: the accessing task must be blocked if (get_value() == 0) { // TODO: block the caller temp_t->task_state = SUSPENDED; OS->CURRENT = NULL; cout << sc_time_stamp() <<": Task "<< temp_t->get_name() << " blocked on semaphore " << sc_semaphore::name() << "\n"; // TODO: set the blocked_task pointer blocked_task = temp_t; // TODO: find the next active task and run it OS->schedule(); blocked_task->wait_for_activation(); } // proceed by running the base class method retval = sc_semaphore::wait(); return retval; } // end os_sem wait method int os_sem::post() { int retval; class os_task *temp_task = blocked_task; // increment the semaphore value // by calling the base class method retval = sc_semaphore::post(); // TODO: if there is a blocked task, it should be unblocked if (blocked_task) { // TODO: if all tasks are suspended // TODO: run the scheduler here // TODO: after waking up the blocked task bool all_suspended = OS->READY_TASKS.empty(); for (int i = 0; i < OS->ALL_TASKS.size(); i++) { os_task *t = OS->ALL_TASKS[i]; if (t->get_state() == RUNNING) { all_suspended = false; break; } } blocked_task->task_state = READY; OS->READY_TASKS.push_back(blocked_task); blocked_task = 0; if(all_suspended) { OS->schedule(); } else if(OS->CURRENT->get_priority() < temp_task->get_priority() ) { // TODO: if there is a running task with lower priority // TODO: than the newly unblocked task, // TODO: the running task should be preempted OS->CURRENT->task_state = READY; OS->READY_TASKS.push_back(OS->CURRENT); OS->preemption.notify(); // TODO: the message below should be printed only in the case of preemption cout << sc_time_stamp() <<": Task "<< OS->CURRENT->get_name() << " preempted by task " << temp_task->get_name() << "\n"; OS->CURRENT = NULL; OS->schedule(); temp_task->wait_for_activation(); } } return retval; } // end os_sem post method
#include <systemc.h> #include "SYSTEM.h"
#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; /** * ALU: * complete enumerated there are: * ADD 0x0: 136 * SUB 0x1: 136 * MUL 0x2: 76 * DIV 0x3: 240 * valid assignments. */ struct ALU4 : public rand_obj { randv< sc_bv<2> > op ; randv< sc_uint<4> > a, b ; ALU4() : op(this), a(this), b(this) { constraint ( (op() != (unsigned char)0x0) || ( (unsigned char)15 >= a() + b() ) ); constraint ( (op() != (unsigned char)0x1) || (((unsigned char)15 >= a() - b()) && (b() <= a()) ) ); constraint ( (op() != (unsigned char)0x2) || ( (unsigned char)15 >= a() * b() ) ); constraint ( (op() != (unsigned char)0x3) || ( b() != (unsigned char)0 ) ); } friend std::ostream & operator<< (std::ostream & o, ALU4 const & alu) { o << alu.op << ' ' << alu.a << ' ' << alu.b ; return o; } }; int sc_main (int argc, char** argv) { boost::timer timer; ALU4 c; std::cout << "first: " << timer.elapsed() << "\n"; for (int i=0; i<1000; ++i) { c.next(); //std::cout << i << ": " << c << std::endl; } std::cout << "complete: " << timer.elapsed() << "\n"; return 0; }
/** * Author: Anubhav Tomar * * Gaze Behavior Monitoring System Testbench **/ #include<systemc.h> #include<SERVER.h> #include<MOBILE.h> // template < > class _gazeMonitor : public sc_module { public: /*Signals for Module Interconnections*/ sc_signal<bool> _clock; sc_signal<sc_uint<1> > _inM1_1 , _inM2_1 , _inM1_2 , _inM2_2; sc_signal<int> _inRoi_1 , _inStart_1 , _inEnd_1 , _inRoi_2 , _inStart_2 , _inEnd_2; // Outputs sc_signal<sc_uint<1> > _outS1 , _outS2_1 , _outS2_2; /*Module Instantiation*/ _serverBlock* _s; _mobileBlock* _m1; _mobileBlock* _m2; SC_HAS_PROCESS(_gazeMonitor); _gazeMonitor(sc_module_name name) : sc_module(name) { /** * Module Instances Created **/ _s = new _serverBlock ("_server_"); _m1 = new _mobileBlock ("_mobile1_"); _m2 = new _mobileBlock ("_mobile2_"); /** * Server -> Mobile **/ _s->_outS1(_outS1); _m1->_inS1(_outS1); _m2->_inS1(_outS1); _s->_outS2_1(_outS2_1); _m1->_inS2(_outS2_1); _s->_outS2_2(_outS2_2); _m2->_inS2(_outS2_2); /** * Mobile -> Server **/ _m1->_outM1(_inM1_1); _s->_inM1_1(_inM1_1); _m1->_outM2(_inM2_1); _s->_inM2_1(_inM2_1); _m1->_outRoi(_inRoi_1); _s->_inRoi_1(_inRoi_1); _m1->_outStart(_inStart_1); _s->_inStart_1(_inStart_1); _m1->_outEnd(_inEnd_1); _s->_inEnd_1(_inEnd_1); _m2->_outM1(_inM1_2); _s->_inM1_2(_inM1_2); _m2->_outM2(_inM2_2); _s->_inM2_2(_inM2_2); _m2->_outRoi(_inRoi_2); _s->_inRoi_2(_inRoi_2); _m2->_outStart(_inStart_2); _s->_inStart_2(_inStart_2); _m2->_outEnd(_inEnd_2); _s->_inEnd_2(_inEnd_2); /** * Clock -> Environment & Server **/ _s->_clock(_clock); _m1->_clock(_clock); _m2->_clock(_clock); SC_THREAD(clockSignal); _outS1.write(0b0); }; 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; _gazeMonitor _gaze("_gazeMonitor_"); 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; }
/* * @ASCK */ #include <systemc.h> SC_MODULE (ALU) { sc_in <sc_int<8>> in1; // A sc_in <sc_int<8>> in2; // B sc_in <bool> c; // Carry Out // in this project, this signal is always 1 // ALUOP // has 5 bits by merging: opselect (4bits) and first LSB bit of opcode (1bit) sc_in <sc_uint<5>> aluop; sc_in <sc_uint<3>> sa; // Shift Amount sc_out <sc_int<8>> out; // Output /* ** module global variables */ // SC_CTOR (ALU){ SC_METHOD (process); sensitive << in1 << in2 << aluop; } void process () { sc_int<8> a = in1.read(); sc_int<8> b = in2.read(); bool cin = c.read(); sc_uint<5> op = aluop.read(); sc_uint<3> sh = sa.read(); switch (op){ case 0b00000 : out.write(a); break; case 0b00001 : out.write(++a); break; case 0b00010 : out.write(a+b); break; case 0b00011 : out.write(a+b+cin); break; case 0b00100 : out.write(a-b); break; case 0b00101 : out.write(a-b-cin); break; case 0b00110 : out.write(--a); break; case 0b00111 : out.write(b); break; case 0b01000 : case 0b01001 : out.write(a&b); break; case 0b01010 : case 0b01011 : out.write(a|b); break; case 0b01100 : case 0b01101 : out.write(a^b); break; case 0b01110 : case 0b01111 : out.write(~a); break; case 0b10000 : case 0b10001 : case 0b10010 : case 0b10011 : case 0b10100 : case 0b10101 : case 0b10110 : case 0b10111 : out.write(a>>sh); break; default: out.write(a<<sh); break; } } };
/***************************************************************************** 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. *****************************************************************************/ /***************************************************************************** fir.cpp -- Original Author: Rocco Jonack, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation: Teodor Vasilache and Dragos Dospinescu, AMIQ Consulting s.r.l. ([email protected]) Date: 2018-Feb-20 Description of Modification: Added sampling of the covergroup created in the "fir.h" file. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include <systemc.h> #include "fir.h" void fir::entry() { sc_int<8> sample_tmp; sc_int<17> pro; sc_int<19> acc; sc_int<8> shift[16]; // reset watching /* this would be an unrolled loop */ for (int i=0; i<=15; i++) shift[i] = 0; result.write(0); output_data_ready.write(false); wait(); // main functionality while(1) { output_data_ready.write(false); do { wait(); } while ( !(input_valid == true) ); sample_tmp = sample.read(); acc = sample_tmp*coefs[0]; for(int i=14; i>=0; i--) { /* this would be an unrolled loop */ pro = shift[i]*coefs[i+1]; acc += pro; }; for(int i=14; i>=0; i--) { /* this would be an unrolled loop */ shift[i+1] = shift[i]; }; shift[0] = sample_tmp; // sample the shift value shift_cg.sample(shift[0]); // write output values result.write((int)acc); output_data_ready.write(true); wait(); }; }
/***************************************************************************** main.cpp -- The testbench *****************************************************************************/ #include <systemc.h> #include "NoximMain.h" #include "NoximNoC.h" #include "NoximGlobalStats.h" #include "NoximCmdLineParser.h" #include <time.h> using namespace std; // need to be globally visible to allow "-volume" simulation stop unsigned int drained_volume; //--------------------------------------------------------------------------- // Initialize global configuration parameters (can be overridden with command-line arguments) int NoximGlobalParams::verbose_mode = DEFAULT_VERBOSE_MODE; int NoximGlobalParams::trace_mode = DEFAULT_TRACE_MODE; char NoximGlobalParams::trace_filename[128] = DEFAULT_TRACE_FILENAME; int NoximGlobalParams::mesh_dim_x = DEFAULT_MESH_DIM_X; int NoximGlobalParams::mesh_dim_y = DEFAULT_MESH_DIM_Y; int NoximGlobalParams::mesh_dim_z = DEFAULT_MESH_DIM_Z; int NoximGlobalParams::topology = DEFAULT_TOPOLOGY; int NoximGlobalParams::buffer_depth = DEFAULT_BUFFER_DEPTH; int NoximGlobalParams::min_packet_size = DEFAULT_MIN_PACKET_SIZE; int NoximGlobalParams::max_packet_size = DEFAULT_MAX_PACKET_SIZE; int NoximGlobalParams::routing_algorithm = DEFAULT_ROUTING_ALGORITHM; int NoximGlobalParams::number_virtual_channel = DEFAULT_NUMBER_VIRTUAL_CHANNEL; char NoximGlobalParams::routing_table_filename[128] = DEFAULT_ROUTING_TABLE_FILENAME; int NoximGlobalParams::selection_strategy = DEFAULT_SELECTION_STRATEGY; float NoximGlobalParams::packet_injection_rate = DEFAULT_PACKET_INJECTION_RATE; float NoximGlobalParams::probability_of_retransmission = DEFAULT_PROBABILITY_OF_RETRANSMISSION; int NoximGlobalParams::traffic_distribution = DEFAULT_TRAFFIC_DISTRIBUTION; char NoximGlobalParams::traffic_table_filename[128] = DEFAULT_TRAFFIC_TABLE_FILENAME; int NoximGlobalParams::simulation_time = DEFAULT_SIMULATION_TIME; int NoximGlobalParams::stats_warm_up_time = DEFAULT_STATS_WARM_UP_TIME; int NoximGlobalParams::partitions = DEFAULT_PARTITIONS; int NoximGlobalParams::rnd_generator_seed = time(NULL); bool NoximGlobalParams::detailed = DEFAULT_DETAILED; float NoximGlobalParams::dyad_threshold = DEFAULT_DYAD_THRESHOLD; char NoximGlobalParams::elevator_nodes_filename[256] = DEFAULT_ELEVATOR_NODES_FILENAME; char NoximGlobalParams::traffic_fname[128] = DEFAULT_TRAFFIC_FNAME; bool NoximGlobalParams::rnd_traffic = DEFAULT_RND_TRAFFIC; unsigned int NoximGlobalParams::data_encoding = DEFAULT_DENC; unsigned int NoximGlobalParams::max_volume_to_be_drained = DEFAULT_MAX_VOLUME_TO_BE_DRAINED; unsigned int NoximGlobalParams::flit_size_bits = DEFAULT_FLIT_SIZE_BITS; unsigned int NoximGlobalParams::rnd_traffic_size = DEFAULT_RND_TRAFFIC_SIZE; float NoximGlobalParams::bit_error_rate = DEFAULT_BIT_ERROR_RATE; float NoximGlobalParams::link_vdd = DEFAULT_LINK_VDD; unsigned int NoximGlobalParams::error_coding = DEFAULT_ERROR_CODING; vector<pair<int,double> > NoximGlobalParams::hotspots; //--------------------------------------------------------------------------- int sc_main(int arg_num, char* arg_vet[]) { // TEMP drained_volume = 0; // Handle command-line arguments cout << endl << "\t\tNoxim - the NoC Simulator" << endl; cout << "\t\t(C) University of Catania" << endl << endl; parseCmdLine(arg_num, arg_vet); // Signals sc_clock clock("clock", 1, SC_NS); sc_signal<bool> reset; // NoC instance NoximNoC* n = new NoximNoC("NoC"); n->clock(clock); n->reset(reset); // Trace signals sc_trace_file* tf = NULL; if(NoximGlobalParams::trace_mode) { tf = sc_create_vcd_trace_file(NoximGlobalParams::trace_filename); sc_trace(tf, reset, "reset"); sc_trace(tf, clock, "clock"); for(int i=0; i<NoximGlobalParams::mesh_dim_x; i++) { for(int j=0; j<NoximGlobalParams::mesh_dim_y; j++) { char label[30]; sprintf(label, "req_to_east(%02d)(%02d)", i, j); sc_trace(tf, n->req_to_east[i][j], label); sprintf(label, "req_to_west(%02d)(%02d)", i, j); sc_trace(tf, n->req_to_west[i][j], label); sprintf(label, "req_to_south(%02d)(%02d)", i, j); sc_trace(tf, n->req_to_south[i][j], label); sprintf(label, "req_to_north(%02d)(%02d)", i, j); sc_trace(tf, n->req_to_north[i][j], label); sprintf(label, "ack_to_east(%02d)(%02d)", i, j); sc_trace(tf, n->ack_to_east[i][j], label); sprintf(label, "ack_to_west(%02d)(%02d)", i, j); sc_trace(tf, n->ack_to_west[i][j], label); sprintf(label, "ack_to_south(%02d)(%02d)", i, j); sc_trace(tf, n->ack_to_south[i][j], label); sprintf(label, "ack_to_north(%02d)(%02d)", i, j); sc_trace(tf, n->ack_to_north[i][j], label); } } } // Reset the chip and run the simulation reset.write(1); cout << "Reset..."; srand(NoximGlobalParams::rnd_generator_seed); // time(NULL)); sc_start(DEFAULT_RESET_TIME, SC_NS); reset.write(0); cout << " done! Now running for " << NoximGlobalParams::simulation_time << " cycles..." << endl; sc_start(NoximGlobalParams::simulation_time, SC_NS); // Close the simulation if(NoximGlobalParams::trace_mode) sc_close_vcd_trace_file(tf); cout << "Noxim simulation completed." << endl; cout << " ( " << sc_time_stamp().to_double()/1000 << " cycles executed)" << endl << endl; // Show statistics NoximGlobalStats gs(n); gs.showStats(std::cout, NoximGlobalParams::detailed); if ((NoximGlobalParams::max_volume_to_be_drained>0) && (sc_time_stamp().to_double()/1000 >= NoximGlobalParams::simulation_time)) { cout << "\nWARNING! the number of kbytes specified with -volume option"<<endl; cout << "has not been reached. ( " << drained_volume/8/1024 << " KB instead of " << NoximGlobalParams::max_volume_to_be_drained << " KB)" <<endl; cout << "You might want to try an higher value of simulation cycles" << endl; cout << "using -sim option." << endl; } return 0; }
#include "systemc.h" #include "rfsm.h" void notify_ev(sc_out<bool> &s, const char* name) { s.write(1); #ifdef SYSTEMC_TRACE_EVENTS cout << "rsfm.cpp: notify_ev(" << name << ") @ t=" << sc_time_stamp() << " (delta=" << sc_delta_count() << ")" << endl; #endif wait(SYSTEMC_EVENT_DURATION,SYSTEMC_EVENT_DURATION_UNIT); s.write(0); }
/******************************************************************************* * ledcmod.cpp -- Copyright 2020 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Implements a SystemC module for the ESP32 PWM LEDC module. ******************************************************************************* * 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. ******************************************************************************* */ #define SC_INCLUDE_DYNAMIC_PROCESSES #include <systemc.h> #include "ledcmod.h" #include "setfield.h" #include "soc/ledc_struct.h" #include "soc/ledc_reg.h" #include "clockpacer.h" #include "info.h" #define LEDC_OVF_TIMER_INTR 0 #define LEDC_DUTYEND_TIMER_INTR 8 void ledcmod::updateth() { int ch; int tim; sc_time base_period; while(true) { wait(); for(ch = 0; ch < (LEDC_CHANNELS/2); ch = ch + 1) { conf0[ch].write(LEDC.channel_group[0].channel[ch].conf0.val); conf1[ch].write(LEDC.channel_group[0].channel[ch].conf1.val); hpoint[ch].write(LEDC.channel_group[0].channel[ch].hpoint.val); duty[ch].write(LEDC.channel_group[0].channel[ch].duty.val); conf0[ch+LEDC_CHANNELS/2].write( LEDC.channel_group[1].channel[ch].conf0.val); conf1[ch+LEDC_CHANNELS/2].write( LEDC.channel_group[1].channel[ch].conf1.val); hpoint[ch+LEDC_CHANNELS/2].write( LEDC.channel_group[1].channel[ch].hpoint.val); duty[ch+LEDC_CHANNELS/2].write( LEDC.channel_group[1].channel[ch].duty.val); } /* we do not actually build the timers, so we need to do some * precalculations for the channels. */ for(tim = 0; tim < (LEDC_TIMERS/2); tim = tim + 1) { /* HSTIMER */ timer_conf[tim].write(LEDC.timer_group[0].timer[tim].conf.val); if (LEDC.timer_group[0].timer[tim].conf.tick_sel == 0) base_period = clockpacer.get_ref_period(); else base_period = clockpacer.get_apb_period(); /* TODO -- do the decimal part */ timerinc[tim].write( sc_time(base_period * (LEDC.timer_group[0].timer[tim].conf.clock_divider>>8))); /* LSTIMER */ timer_conf[tim+LEDC_TIMERS/2].write( LEDC.timer_group[1].timer[tim].conf.val); if (LEDC.timer_group[1].timer[tim].conf.tick_sel == 0) base_period = clockpacer.get_ref_period(); else base_period = clockpacer.get_rtc8m_period(); /* TODO -- do the decimal part */ /* TODO -- do the pause */ if (LEDC.timer_group[1].timer[tim].conf.low_speed_update) { timerinc[tim+LEDC_TIMERS/2].write(sc_time(base_period * (LEDC.timer_group[1].timer[tim].conf.clock_divider>>8))); } } /* int_ena we simply copy. */ int_ena.write(LEDC.int_ena.val); /* If we got a clear command, we trigger the event for the returnth to * handle it. */ if (LEDC.int_clr.val != 0x0) int_clr_ev.notify(); } } void ledcmod::returnth() { int un; /* We wait for one of the responses to get triggered, and then we copy the * R/O register back to the struct. */ while (true) { wait( timer_cnt[0].value_changed_event()| timer_cnt[1].value_changed_event() | timer_cnt[2].value_changed_event()| timer_cnt[3].value_changed_event() | timer_cnt[4].value_changed_event()| timer_cnt[5].value_changed_event() | timer_cnt[6].value_changed_event()| timer_cnt[7].value_changed_event() | duty_r[0].value_changed_event()| duty_r[1].value_changed_event() | duty_r[2].value_changed_event()| duty_r[3].value_changed_event() | duty_r[4].value_changed_event()| duty_r[5].value_changed_event() | duty_r[6].value_changed_event()| duty_r[7].value_changed_event() | duty_r[8].value_changed_event()| duty_r[9].value_changed_event() | duty_r[10].value_changed_event()| duty_r[11].value_changed_event() | duty_r[12].value_changed_event()| duty_r[13].value_changed_event() | duty_r[14].value_changed_event()| duty_r[15].value_changed_event() | int_clr_ev | int_ev[0] | int_ev[1] | int_ev[2] | int_ev[3] | int_ev[4] | int_ev[5] | int_ev[6] | int_ev[7] | int_ev[8] | int_ev[9] | int_ev[10]| int_ev[11]| int_ev[12]| int_ev[13]| int_ev[14]| int_ev[15]| int_ev[16]| int_ev[17]| int_ev[18]| int_ev[19]| int_ev[20]| int_ev[21]| int_ev[22]| int_ev[23]); for (un = 0; un < LEDC_CHANNELS; un = un + 1) { LEDC.int_raw.val = 0x0; /* If we hit the maximum dither times, we have an interrupt and * clear the duty_start. */ if (int_ev[un+LEDC_DUTYEND_TIMER_INTR].triggered()) { LEDC.int_raw.val = LEDC.int_raw.val | (1<<un); if (un < LEDC_CHANNELS/2) LEDC.channel_group[0].channel[un].conf1.duty_start = false; else LEDC.channel_group[1].channel[un-8].conf1.duty_start = false; } /* We copy the duty values */ if (un < LEDC_CHANNELS/2) LEDC.channel_group[0].channel[un].duty_rd.duty_read = duty_r[un].read(); else LEDC.channel_group[1].channel[un-8].duty_rd.duty_read = duty_r[un-8].read(); } /* We also copy over the timer values and interrupts. */ for(un = 0; un < (LEDC_TIMERS/2); un = un + 1) { if (int_ev[un+LEDC_OVF_TIMER_INTR].triggered()) LEDC.int_raw.val = LEDC.int_raw.val | (1<<un); LEDC.timer_group[0].timer[un].value.timer_cnt = timer_cnt[un].read(); if (int_ev[un+LEDC_OVF_TIMER_INTR+LEDC_TIMERS/2].triggered()) LEDC.int_raw.val = LEDC.int_raw.val | (1<<un+LEDC_TIMERS/2); LEDC.timer_group[1].timer[un].value.timer_cnt = timer_cnt[un].read(); } /* If we have a clear event we take it too. */ if (int_clr_ev.triggered()) { LEDC.int_raw.val = LEDC.int_raw.val & ~LEDC.int_clr.val; LEDC.int_clr.val = 0; } /* We update the raw. */ LEDC.int_st.val = LEDC.int_raw.val & int_ena.read(); /* We also drive the interrupt line */ intr_o.write(LEDC.int_st.val != 0); } } void ledcmod::update() { update_ev.notify(); clockpacer.wait_next_apb_clk(); } void ledcmod::initstruct() { memset(&LEDC, 0, sizeof(ledc_dev_t)); /* The reset bits begin all on. */ LEDC.timer_group[0].timer[0].conf.rst = 1; LEDC.timer_group[0].timer[1].conf.rst = 1; LEDC.timer_group[0].timer[2].conf.rst = 1; LEDC.timer_group[0].timer[3].conf.rst = 1; LEDC.timer_group[1].timer[0].conf.rst = 1; LEDC.timer_group[1].timer[1].conf.rst = 1; LEDC.timer_group[1].timer[2].conf.rst = 1; LEDC.timer_group[1].timer[3].conf.rst = 1; } void ledcmod::start_of_simulation() { /* We spawn a thread for each channel and timer. */ int un; for(un = 0; un < LEDC_CHANNELS; un = un + 1) { conf0[un].write(0); conf1[un].write(0); hpoint[un].write(0); duty[un].write(0); } for(un = 0; un < sig_out_hs_o.size(); un = un + 1) { sc_spawn(sc_bind(&ledcmod::channel, this, un)); sig_out_hs_o[un]->write(false); } for(un = LEDC_CHANNELS/2; un < sig_out_ls_o.size(); un = un + 1) { sc_spawn(sc_bind(&ledcmod::channel, this, un)); sig_out_ls_o[un-LEDC_CHANNELS/2]->write(false); } for(un = 0; un < LEDC_TIMERS; un = un + 1) { sc_spawn(sc_bind(&ledcmod::timer, this, un)); /* The RST bit starts off high, the other bits all start off low. */ timer_conf[un].write(LEDC_HSTIMER0_RST_M); timer_cnt[un].write(0); timer_lim[un].write(0); timerinc[un].write(sc_time(0, SC_NS)); } int_ena.write(0); } void ledcmod::calc_points(int un, bool start_dither) { int lp; int lpoint_frac; bool duty_start; int duty_num; int duty_cycle; bool duty_inc; int duty_scale; /* We first take the values into local registers to not have to keep * placing these lines in the middle of the code. */ if (un < LEDC_CHANNELS/2) { duty_start = (RDFIELD(conf1[un],LEDC_DUTY_START_HSCH0_M,LEDC_DUTY_START_HSCH0_S)>0); duty_num = RDFIELD(conf1[un],LEDC_DUTY_NUM_HSCH0_M,LEDC_DUTY_NUM_HSCH0_S); duty_cycle = RDFIELD(conf1[un],LEDC_DUTY_CYCLE_HSCH0_M,LEDC_DUTY_CYCLE_HSCH0_S); duty_inc = (RDFIELD(conf1[un],LEDC_DUTY_CYCLE_HSCH0_M,LEDC_DUTY_INC_HSCH0_S)>0); duty_scale = RDFIELD(conf1[un],LEDC_DUTY_CYCLE_HSCH0_M,LEDC_DUTY_SCALE_HSCH0_S); } else { duty_start = (RDFIELD(conf1[un],LEDC_DUTY_START_LSCH0_M,LEDC_DUTY_START_LSCH0_S)>0); duty_num = RDFIELD(conf1[un],LEDC_DUTY_NUM_LSCH0_M,LEDC_DUTY_NUM_LSCH0_S); duty_cycle = RDFIELD(conf1[un],LEDC_DUTY_CYCLE_LSCH0_M,LEDC_DUTY_CYCLE_LSCH0_S); duty_inc = (RDFIELD(conf1[un],LEDC_DUTY_CYCLE_LSCH0_M,LEDC_DUTY_INC_LSCH0_S)>0); duty_scale = RDFIELD(conf1[un],LEDC_DUTY_CYCLE_LSCH0_M,LEDC_DUTY_SCALE_LSCH0_S); } /* We get the lpoint and frac. */ lp = (duty[un].read() >> 4); lpoint_frac = duty[un].read() & 0x0f; /* We adjust the lpoint according to the fraction */ if (lpoint_frac > thiscyc[un]) lp = lp + 1; /* And we adjust the lpoint according to the dither. */ if (duty_start) { if (start_dither) { /* If this is the first time, dithcycles will be zero. We then * start by loading the settings of the dither and go on. */ dithtimes[un] = duty_num; dithcycles[un] = duty_cycle; } else { /* Other times we count the cycles and process it. */ dithcycles[un] = dithcycles[un] - 1; /* If we hit the target, we are done. */ if (dithcycles == 0 && duty_inc) { lp = lp + duty_scale; dithcycles[un] = duty_cycle; dithtimes[un] = dithtimes[un] - 1; } else if (dithcycles[un] == 0) { lp = lp - duty_scale; dithcycles[un] = duty_cycle; dithtimes[un] = dithtimes[un] - 1; } int_ev[un+LEDC_DUTYEND_TIMER_INTR].notify(); } } /* We put the lp value in the read/only register. */ duty_r[un].write(lp & LEDC_DUTY_HSCH0); thislp[un] = lp & LEDC_DUTY_HSCH0; } void ledcmod::channel(int ch) { bool outen; bool recheckpoints; /* Sel begins with -1 and it then is switched to the correct value. */ int sel = -1; while(1) { /* If there is no selected timer, all we do is wait for a configuration * change. If there is a timer specified, we wait for a timer trigger * or a configuration change. */ if (sel < 0) wait(conf0[ch].value_changed_event()); else wait(conf0[ch].value_changed_event() | conf1[ch].value_changed_event() | hpoint[ch].value_changed_event() | duty[ch].value_changed_event() | timer_cnt[sel].value_changed_event()); /* We go ahead and grab the output enable as we use it quite often. */ if (ch < LEDC_CHANNELS/2) { outen = RDFIELD(conf0[ch], LEDC_SIG_OUT_EN_HSCH0_M, LEDC_SIG_OUT_EN_HSCH0_S); sel= RDFIELD(conf0[ch], LEDC_TIMER_SEL_HSCH0_M, LEDC_TIMER_SEL_HSCH0_S); } else { outen = RDFIELD(conf0[ch], LEDC_SIG_OUT_EN_LSCH0_M, LEDC_SIG_OUT_EN_LSCH0_S); sel= RDFIELD(conf0[ch], LEDC_TIMER_SEL_LSCH0_M, LEDC_TIMER_SEL_LSCH0_S) + LEDC_TIMERS/2; } /* First we process changes in the PWM. These can affect the rest. */ /* If we got a trigger on the output and the channel is stopped, we * update the value. * The timer we ignore as the timer mux is done outside the channel. */ if (conf0[ch].event() && !outen) { if (ch < LEDC_CHANNELS/2) sig_out_hs_o[ch]->write( RDFIELD(conf0[ch], LEDC_IDLE_LV_HSCH0_M, LEDC_IDLE_LV_HSCH0_S)); else sig_out_ls_o[ch-LEDC_CHANNELS/2]->write( RDFIELD(conf0[ch], LEDC_IDLE_LV_LSCH0_M, LEDC_IDLE_LV_LSCH0_S)); } /* If we see a change in the hpoint or the duty we need to recalculate * the lpoint. We also need to do this when the timer is switched or when * we start a new cycle. */ if (duty[ch].event() || conf0[ch].event()) { calc_points(ch, true); /* We restart the cycle calculation. */ thiscyc[ch] = 0; /* And we will need to recheck the hpoint and lpoint. */ recheckpoints = true; } /* Anytime the cycle restarts (timer returns to zero) we need to * increment the cycle counter and adjust the jitter, if any. */ else if (timer_cnt[sel].read() == 0) { /* We start adjusting the cycle number for the dither. */ thiscyc[ch] = thiscyc[ch] + 1; if (thiscyc[ch] == LEDC_CYCLES) thiscyc[ch] = 0; /* We also calculate the lpoint. */ calc_points(ch, false); /* And we will need to recheck the hpoint and lpoint. */ recheckpoints = true; } else recheckpoints = false; /* If it was a timer tick, we need to see if it affects us. */ if (outen && (timer_cnt[sel].event() || recheckpoints)) { /* And we check where we are in the flow. */ bool nv; if (timer_cnt[sel].read() >= thislp[ch] + hpoint[ch].read()) nv = false; else if (timer_cnt[sel].read() >= hpoint[ch]) nv = true; else nv = false; if (ch < LEDC_CHANNELS/2) sig_out_hs_o[ch]->write(nv); else sig_out_ls_o[ch-LEDC_CHANNELS/2]->write(nv); } } } void ledcmod::timer(int tim) { bool rst; bool pause; bool wasstoped = true; while(1) { /* We wait for a timer tick or a change to the configuration register. */ wait(timer_ev[tim] | timer_conf[tim].value_changed_event() | timerinc[tim].value_changed_event()); /* We get the parameters first. */ if (tim < LEDC_TIMERS/2) { rst = RDFIELD(timer_conf[tim], LEDC_HSTIMER0_RST_M, LEDC_HSTIMER0_RST_S)>0; pause = RDFIELD(timer_conf[tim], LEDC_HSTIMER0_PAUSE_M, LEDC_HSTIMER0_PAUSE_S)>0; } else { rst = RDFIELD(timer_conf[tim], LEDC_LSTIMER0_RST_M, LEDC_LSTIMER0_RST_S)>0; pause = RDFIELD(timer_conf[tim], LEDC_LSTIMER0_PAUSE_M, LEDC_LSTIMER0_PAUSE_S)>0; } /* If we are in reset, we clear any future time events and wait. The next * event should be then a configuration change. */ if (rst) { timer_cnt[tim].write(0); timer_ev[tim].cancel(); wasstoped = true; } /* If we are paused, we just cancel any future events, but we do not * touch the counter value. */ else if (pause) { timer_ev[tim].cancel(); wasstoped = true; } /* If the timer increment is zero, we do the same. */ else if (timerinc[tim].read() == sc_time(0, SC_NS)) { timer_ev[tim].cancel(); } /* If we are comming out of reset or pause, we need to get the counter * going. */ else if (wasstoped) { timer_ev[tim].notify(timerinc[tim]); wasstoped = false; } /* We only count on timer event triggers. Configuration events should * not change the timer value. */ else if (timer_ev[tim].triggered()) { /* We calculate the next value, whichever it is. */ if (timer_cnt[tim].read() < timer_lim[tim].read() - 1) timer_cnt[tim].write(timer_cnt[tim].read() + 1); else { /* We hit the end we write a zero and raise the interrupt. */ timer_cnt[tim].write(0); int_ev[tim+LEDC_OVF_TIMER_INTR].notify(); } /* And we sleep until the next event. */ timer_ev[tim].notify(timerinc[tim]); } } } void ledcmod::trace(sc_trace_file *tf) { int un; std::string sigb = name(); std::string sign; for(un = 0; un < LEDC_CHANNELS; un = un + 1) { sign = sigb + std::string(".conf0_") + std::to_string(un); sc_trace(tf, conf0[un], sign.c_str()); } for(un = 0; un < LEDC_CHANNELS; un = un + 1) { sign = sigb + std::string(".conf1_") + std::to_string(un); sc_trace(tf, conf1[un], sign.c_str()); } for(un = 0; un < LEDC_CHANNELS; un = un + 1) { sign = sigb + std::string(".hpoint_") + std::to_string(un); sc_trace(tf, hpoint[un], sign.c_str()); } for(un = 0; un < LEDC_CHANNELS; un = un + 1) { sign = sigb + std::string(".duty_") + std::to_string(un); sc_trace(tf, duty[un], sign.c_str()); } for(un = 0; un < LEDC_CHANNELS; un = un + 1) { sign = sigb + std::string(".duty_r") + std::to_string(un); sc_trace(tf, duty_r[un], sign.c_str()); } for(un = 0; un < LEDC_TIMERS; un = un + 1) { sign = sigb + std::string(".timer_conf_") + std::to_string(un); sc_trace(tf, timer_conf[un], sign.c_str()); } for(un = 0; un < LEDC_TIMERS; un = un + 1) { sign = sigb + std::string(".timer_cnt_") + std::to_string(un); sc_trace(tf, timer_cnt[un], sign.c_str()); } for(un = 0; un < LEDC_TIMERS; un = un + 1) { sign = sigb + std::string(".timer_lim_") + std::to_string(un); sc_trace(tf, timer_lim[un], sign.c_str()); } }
/***************************************************************************** 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. *****************************************************************************/ /***************************************************************************** numgen.cpp -- The implementation for the numgen module. Original Author: Amit Rao, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc.h" #include "numgen.h" // definition of the `generate' method void numgen::generate() { static double a = 134.56; static double b = 98.24; a -= 1.5; b -= 2.8; out1.write(a); out2.write(b); } // end of `generate' method
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_vector_module_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { vector_module vector_module("VECTOR_MODULE"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_in[SIZE_I_IN]; sc_signal<int> data_out; vector_module.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { vector_module.data_in[i](data_in[i]); } vector_module.data_out(data_out); for (int i = 0; i < SIZE_I_IN; i++) { data_in[i] = i; } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": data_out = " << data_out.read() << endl; return 0; }
/* * @ASCK */ #include <systemc.h> SC_MODULE (ID) { sc_in_clk clk; sc_in <sc_int<8>> prev_A; sc_in <sc_int<8>> prev_B; sc_in <sc_int<13>> prev_Imm; sc_in <sc_uint<3>> prev_Sa; sc_in <sc_uint<5>> prev_AluOp; sc_in <bool> prev_r; sc_in <bool> prev_w; sc_in <bool> prev_AluMux; sc_in <bool> prev_WbMux; sc_in <bool> prev_call; sc_in <bool> prev_regWrite; sc_in <sc_uint<3>> prev_rd; sc_out <sc_int<8>> next_A; sc_out <sc_int<8>> next_B; sc_out <sc_int<13>> next_Imm; sc_out <sc_uint<3>> next_Sa; sc_out <sc_uint<5>> next_AluOp; sc_out <bool> next_r; sc_out <bool> next_w; sc_out <bool> next_AluMux; sc_out <bool> next_WbMux; sc_out <bool> next_call; sc_out <bool> next_regWrite; sc_out <sc_uint<3>> next_rd; /* ** module global variables */ SC_CTOR (ID){ SC_THREAD (process); sensitive << clk.pos(); } void process () { while(true){ wait(); if(now_is_call){ wait(micro_acc_ev); } next_A.write(prev_A.read()); next_B.write(prev_B.read()); next_Imm.write(prev_Imm.read()); next_Sa.write(prev_Sa.read()); next_AluOp.write(prev_AluOp.read()); next_AluMux.write(prev_AluMux.read()); next_r.write(prev_r.read()); next_w.write(prev_w.read()); next_WbMux.write(prev_WbMux.read()); next_call.write(prev_call.read()); next_regWrite.write(prev_regWrite); next_rd.write(prev_rd.read()); } } };
/******************************************************************************* * task.cpp -- Copyright 2019 Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This file reimplements the freertos tasks to get them to compile under the * ESPMOD SystemC model. The tasks were rewrittent to spawn SC dynamic * threads. ******************************************************************************* * 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 file was based off the work covered by the license below: * FreeRTOS V8.2.0 - Copyright (C) 2015 Real Time Engineers Ltd. * All rights reserved * * FreeRTOS is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License (version 2) as published by the * Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception. * * FreeRTOS 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. Full license text is available on the following * link: http://www.freertos.org/a00114.html */ #define SC_INCLUDE_DYNAMIC_PROCESSES #include <systemc.h> #include "FreeRTOS.h" #include "task.h" void vTaskDelay( const TickType_t xTicksToDelay ) { /* We set the portTICK_RATE_MS to 1, so the value should be the * number in lilliseconds. Perhaps we should change this later. */ wait(xTicksToDelay, SC_MS); } BaseType_t xTaskCreatePinnedToCore( TaskFunction_t pvTaskCode, const char * const pcName, const uint32_t usStackDepth, void * const pvParameters, UBaseType_t uxPriority, TaskHandle_t * const pvCreatedTask, const BaseType_t xCoreID) { sc_spawn(sc_bind(pvTaskCode, pvParameters)); return pdTRUE; } void vTaskDelete( TaskHandle_t xTaskToDelete ) { }
#include <systemc.h> class sc_clockx : sc_module, sc_interface { public: sc_event edge; sc_event change; bool val; bool _val; int delta; private: int period; SC_HAS_PROCESS(sc_clockx); void run(void) { int tmp = period/2; edge.notify(SC_ZERO_TIME); change.notify(SC_ZERO_TIME); while(true) { wait(tmp, SC_NS); edge.notify(SC_ZERO_TIME); change.notify(SC_ZERO_TIME); val = !val; } } public: sc_clockx(sc_module_name name, int periodparam): sc_module(name) { SC_THREAD(run); period = periodparam; val = true; _val = true; } bool read() { return val; } void write(bool newval) { _val = newval; if (!(_val == val)) request_update(); } void update() { if (!(_val == val)) { val = _val; change.notify(SC_ZERO_TIME); delta = sc_delta_count(); } } };
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_inputs_vector_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
// //------------------------------------------------------------// // Copyright 2009-2012 Mentor Graphics Corporation // // All Rights Reserved Worldwid // // // // 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 "tlm.h" #include <vector> #include <iomanip> #include <uvmc.h> using std::vector; using namespace sc_core; using namespace tlm; //------------------------------------------------------------------------------ // Title: UVMC Converter Example - SC In-Transaction // // This example's packet class defines ~do_pack~ and ~do_unpack~ methods that // are compatible with the default converter in SC. The default converter merely // delegates conversion to these two methods in the transaction class. // // (see UVMC_Converters_SC_InTrans.png) // // This approach is not very common in practice, as it couples your transaction // types to the UVMC library. // // Instead of defining member functions of the transaction type to do conversion, // you should instead implement a template specialization of uvmc_convert<T>. // This leaves conversion knowledge outside your transaction proper, and allows // you to define different conversion algorithms without requiring inheritance. // This example demonstrates use of a transaction class that defines the // conversion functionality in compliant ~do_pack~ and ~do_unpack~ methods. // Thus, an custom converter specialization will not be needed--the default // converter, which delegates to ~do_pack~ and ~do_unpack~ methods in the // transaction, is sufficient. // // Because most SC transactions do not implement the pack and unpack member // functions required by the default converter, a template specialization // definition is normally required. // // The default converter, uvmc_converter<T>, or any template specialization // of that converter for a given packet type, e.g. uvmc_converter<packet>, // is implicitly chosen by the C+ compiler. This means you will seldom need to // explicitly specify the converter type when connecting via <uvmc_connect>. // //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Group: User Library // // This section defines a transaction class and generic consumer model. The // transaction implements the ~do_pack~ and ~do_unpack~ methods required by the // default converter. // // Packing and unpacking involves streaming the contents of your transaction // fields into and out of the ~packer~ object provided as an argument to ~do_pack~ // and ~do_unpack~. The packer needs to have defined ~operator<<~ for each type // of field you stream. See <UVMC Type Support> for a list of supported // transaction field types. //------------------------------------------------------------------------------ // (begin inline source) namespace user_lib { using namespace uvmc; class packet_base { public: enum cmd_t { WRITE=0, READ, NOOP }; cmd_t cmd; unsigned int addr; vector<unsigned char> data; virtual void do_pack(uvmc_packer &packer) const { packer << cmd << addr << data; } virtual void do_unpack(uvmc_packer &packer) { packer >> cmd >> addr >> data; } }; class packet : public packet_base { public: unsigned int extra_int; virtual void do_pack(uvmc_packer &packer) const { packet_base::do_pack(packer); packer << extra_int; } virtual void do_unpack(uvmc_packer &packer) { packet_base::do_unpack(packer); packer >> extra_int; } }; // a generic target with a TLM1 put export #include "consumer.cpp" } // (end inline source) //------------------------------------------------------------------------------ // Group: Conversion code // // We do not need to define an external conversion class because it conversion // is built into the transaction proper. The default converter will delegate to // our transaction's ~do_pack~ and ~do_unpack~ methods. // // We do, however, define ~operator<< (ostream&)~ for our transaction type using // <UVMC_PRINT> macros. With this, we can print the transaction contents to any // output stream. // // For example // //| packet p; //| ...initialize p... //| cout << p; // // This produces output similar to // //| '{cmd:2 addr:1fa34f22 data:'{4a, 27, de, a2, 6b, 62, 8d, 1d, 6} } // // You can invoke the macros in any namepace in which the uvmc namespace // was imported and the macros #included. // //------------------------------------------------------------------------------ // (begin inline source) using namespace user_lib; UVMC_PRINT_3(packet_base,cmd,addr,data) UVMC_PRINT_EXT_1(packet,packet_base,extra_int) // (end inline source) //------------------------------------------------------------------------------ // Group: Testbench code // // This section defines our testbench environment. In the top-level module, we // instantiate the generic consumer model. We also register the consumer's ~in~ // export to have a UVMC connection with a lookup string, ~stimulus~. The // SV-side will register its producer's ~out~ port with the same lookup string. // UVMC will match these two strings to complete the cross-language connection, // i.e. the SV producer's ~out~ port will be bound to the SC consumer's // ~in~ export. //------------------------------------------------------------------------------ // (begin inline source) class sc_env : public sc_module { public: consumer<packet> cons; sc_env(sc_module_name nm) : cons("cons") { uvmc_connect(cons.in,"stimulus"); uvmc_connect(cons.ap,"checker"); } }; // Define sc_main, the vendor-independent means of starting a // SystemC simulation. int sc_main(int argc, char* argv[]) { sc_env env("env"); sc_start(); return 0; } // (end inline source)
#include <memory> #include <systemc.h> #include "sc_top.h" int sc_main(int argc, char* argv[]) { if (false && argc && argv) {} Verilated::debug(0); Verilated::randReset(2); Verilated::commandArgs(argc, argv); ios::sync_with_stdio(); const std::unique_ptr<sc_top> u_sc_top{new sc_top("sc_top")}; sc_start(); cout << "done, time = " << sc_time_stamp() << endl; return 0; } #ifdef VL_USER_STOP void vl_stop(const char *filename, int linenum, const char *hier) VL_MT_UNSAFE { sc_stop(); cout << "call vl_stop" << endl; } #endif
/******************************************************************************* * panic.cpp -- Copyright 2019 Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This file replaces the run time error functions from the ESP32 with * equivalents that will kill the model and print a message on the screen. ******************************************************************************* * 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 file was based off the work covered by the license below: * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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 "info.h" #include <stdlib.h> #include <esp_system.h> #include <freertos/FreeRTOS.h> #include <freertos/task.h> /* Note: The linker script will put everything in this file in IRAM/DRAM, so it also works with flash cache disabled. */ void __attribute__((weak)) vApplicationStackOverflowHook( TaskHandle_t xTask, signed char *pcTaskName ) { printf("***ERROR*** A stack overflow in task "); printf((char *)pcTaskName); printf(" has been detected.\r\n"); espm_abort(); } /* These two weak stubs for esp_reset_reason_{get,set}_hint are used when * the application does not call esp_reset_reason() function, and * reset_reason.c is not linked into the output file. */ void __attribute__((weak)) esp_reset_reason_set_hint(esp_reset_reason_t hint) { } esp_reset_reason_t __attribute__((weak)) esp_reset_reason_get_hint(void) { return ESP_RST_UNKNOWN; } static inline void invoke_abort() { SC_REPORT_FATAL("PANIC", "Abort Called"); } /* Renamed to espm_abort to not conflict with the system abort(). */ void espm_abort() { printf("abort() was called\n"); /* Calling code might have set other reset reason hint (such as Task WDT), * don't overwrite that. */ if (esp_reset_reason_get_hint() == ESP_RST_UNKNOWN) { esp_reset_reason_set_hint(ESP_RST_PANIC); } invoke_abort(); } /* This disables all the watchdogs for when we call the gdbstub. */ static void esp_panic_dig_reset() { SC_REPORT_FATAL("PANIC", "Panic Dig Reset"); } void esp_set_breakpoint_if_jtag(void *fn) { PRINTF_INFO("PANIC", "Set breakpoint %p", fn); } esp_err_t esp_set_watchpoint(int no, void *adr, int size, int flags) { if (no < 0 || no > 1) { return ESP_ERR_INVALID_ARG; } if (flags & (~0xC0000000)) { return ESP_ERR_INVALID_ARG; } PRINTF_INFO("PANIC", "Setting watchpoint %d addr=%p size=%d flags=%x", no, adr, size, flags); return ESP_OK; } void esp_clear_watchpoint(int no) { PRINTF_INFO("PANIC", "Clearing watchpoint %d", no); } static void esp_error_check_failed_print(const char *msg, esp_err_t rc, const char *file, int line, const char *function, const char *expression) { printf("%s failed: esp_err_t 0x%x", msg, rc); } void _esp_error_check_failed_without_abort(esp_err_t rc, const char *file, int line, const char *function, const char *expression) { esp_error_check_failed_print("ESP_ERROR_CHECK_WITHOUT_ABORT", rc, file, line, function, expression); } void _esp_error_check_failed(esp_err_t rc, const char *file, int line, const char *function, const char *expression) { esp_error_check_failed_print("ESP_ERROR_CHECK", rc, file, line, function, expression); invoke_abort(); }
/******************************************************************************* * uart.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Model for a UART. ******************************************************************************* * 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 "uart.h" #include "info.h" void uart::intake() { int cnt; unsigned char msg; unsigned char pos; bool incomming; /* First we wait for the signal to rise. */ while (rx.read() != true) wait(); /* Sometimes we have a glitch at powerup. If a dead time is defined, we * use it. */ if (deadtime != sc_time(0, SC_NS)) wait(deadtime); /* Now we can listen for a packet. */ while(true) { /* We wait for the RX to go low. */ wait(); if (rx.read() != false) continue; /* If we are in autodetect mode, we will keep looking for a rise. */ if (autodetect) { sc_time start = sc_time_stamp(); wait(sc_time(2, SC_MS), rx.value_changed_event()); sc_time delta = start - sc_time_stamp(); if (delta >= sc_time(2, SC_MS)) { PRINTF_WARN("UART", "%s: autodetect timed out", name()); set_baud(300); } else if (delta >= sc_time(3, SC_MS)) set_baud(300); else if (delta >= sc_time(1, SC_MS)) set_baud(600); else if (delta >= sc_time(800, SC_US)) set_baud(1200); else if (delta >= sc_time(400, SC_US)) set_baud(2400); else if (delta >= sc_time(200, SC_US)) set_baud(4800); else if (delta >= sc_time(100, SC_US)) set_baud(9600); else if (delta >= sc_time(50, SC_US)) set_baud(19200); else if (delta >= sc_time(20, SC_US)) set_baud(38400); else if (delta >= sc_time(15, SC_US)) set_baud(57600); else if (delta >= sc_time(12, SC_US)) set_baud(74880); else if (delta >= sc_time(7, SC_US)) set_baud(115200); else if (delta >= sc_time(4, SC_US)) set_baud(230400); else if (delta >= sc_time(3, SC_US)) set_baud(256000); else if (delta >= sc_time(2, SC_US)) set_baud(460800); else if (delta >= sc_time(900, SC_NS)) set_baud(921600); else if (delta >= sc_time(400, SC_NS)) set_baud(1843200); else if (delta >= sc_time(200, SC_NS)) set_baud(3686400); else { PRINTF_WARN("UART", "rate too fast on UART %s", name()); set_baud(3686400); } /* We wait now for the packet to end, assuming 2 stop bits and some * extra time. */ wait(baudperiod * 10); /* And we clear the flag. */ autodetect = false; continue; } /* We jump halfway into the start pulse. */ wait(baudperiod/2); /* And we advance to the next bit. */ wait(baudperiod); /* And we take one bit at a time and merge them together. */ msg = 0; for(cnt = 0, pos = 1; cnt < 8; cnt = cnt + 1, pos = pos << 1) { incomming = rx.read(); if (debug) { PRINTF_INFO("UART", "[%s/%d]: received lvl %c", name(), cnt, (incomming)?'h':'l'); } if (incomming == true) msg = msg | pos; wait(baudperiod); } /* And we send the char. If the buffer is filled, we discard it and * warn the user. If it is free, then we take it. This is needed as * the sender has no way to know if the buffer has space or not. */ if (from.num_free() == 0) { PRINTF_WARN("UART", "Buffer overflow on UART %s", name()); } else { from.write(msg); if (debug && isprint(msg)) { PRINTF_INFO("UART", "[%s] received-'%c'/%02x\n", name(), msg, msg); } else if (debug) { PRINTF_INFO("UART", "[%s] received-%02x\n", name(), msg); } } } } void uart::outtake() { int cnt; unsigned char msg; unsigned char pos; tx.write(true); while(true) { /* We block until we receive something to send. */ msg = to.read(); if (debug && isprint(msg)) { PRINTF_INFO("UART","[%s] sending-'%c'/%02x", name(), msg, msg); } else if (debug) { PRINTF_INFO("UART","[%s] sending-%02x", name(), msg); } /* Then we send the packet asynchronously. */ tx.write(false); wait(baudperiod); for(cnt = 0, pos = 1; cnt < 8; cnt = cnt + 1, pos = pos << 1) { if(debug) { PRINTF_INFO("UART", "[%s/%d]: sent '%c'", name(), cnt, ((pos & msg)>0)?'h':'l'); } if ((pos & msg)>0) tx.write(true); else tx.write(false); wait(baudperiod); } /* And we send the stop bit. */ tx.write(true); if (stopbits < 2) wait(baudperiod); else if (stopbits == 2) wait(baudperiod + baudperiod / 2); else wait(baudperiod * 2); } } void uart::set_baud(unsigned int rate) { baudrate = rate; baudperiod = sc_time(8680, SC_NS) * (115200 / rate); } int uart::getautorate() { /* If autodetect is still true, it is not done, we return 0. */ if (autodetect) { return 0; } /* if it is false, we return the rate. */ else { return get_baud(); } }
#ifndef PACKET_GENERATOR_TLM_CPP #define PACKET_GENERATOR_TLM_CPP #include <systemc.h> using namespace sc_core; using namespace sc_dt; using namespace std; #include <tlm.h> #include <tlm_utils/simple_initiator_socket.h> #include <tlm_utils/simple_target_socket.h> #include <tlm_utils/peq_with_cb_and_phase.h> #include "packetGenerator_tlm.hpp" #include "common_func.hpp" #include "address_map.hpp" void packetGenerator_tlm::do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address){ dbgimgtarmodprint(use_prints, "Calling do_when_read_transaction"); if ((address >= IMG_OUTPUT_STATUS_ADDRESS_LO) && (address < IMG_OUTPUT_STATUS_ADDRESS_HI)) { if (packetGenerator::tmp_data_out_valid == true) { *data = 1; } else { *data = 0; } } } void packetGenerator_tlm::do_when_write_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address) { dbgimgtarmodprint(use_prints, "Calling do_when_write_transaction"); if ((address >= IMG_OUTPUT_ADDRESS_LO) && (address < IMG_OUTPUT_SIZE_ADDRESS_LO)) { memcpy(tmp_data + address - IMG_OUTPUT_ADDRESS_LO, data, data_length); } else if ((address >= IMG_OUTPUT_SIZE_ADDRESS_LO) && (address < IMG_OUTPUT_DONE_ADDRESS_LO)) { unsigned char *data_length_ptr = (unsigned char *)&tmp_data_length; memcpy(data_length_ptr + address - IMG_OUTPUT_SIZE_ADDRESS_LO, data, data_length); dbgimgtarmodprint(use_prints, "Current data_length %0d", tmp_data_length); } else if ((address >= IMG_OUTPUT_DONE_ADDRESS_LO) && (address < IMG_OUTPUT_STATUS_ADDRESS_LO) && (*data == 1)) { if (tmp_data_length == 0) { *(tmp_data) = 0; tmp_data_length = 1; } dbgimgtarmodprint(use_prints, "Preparing to send %0d bytes", tmp_data_length); fill_data(tmp_data, (int)tmp_data_length); tmp_data_length = 0; } } #endif // PACKET_GENERATOR_TLM_CPP
#include <systemc.h> #include "Memory.h" using namespace std; void Memory::execute() { // Initialize memory to some predefined contents. for (int i=0; i<MEM_SIZE; i++) _data[i] = i + 0xff000; port_Stall = true; for (;;) { wait(); int addr = port_Addr % MEM_SIZE; if (port_Read) { // Read word from memory. int data = _data[addr]; port_RData = data; port_Stall = false; // Always ready. #if defined(PRINT_WHILE_RUN) cout << sc_time_stamp() << "\tMemory: Done read request. Addr = " << showbase << hex << addr << ", Data = " << showbase << hex << data << endl; #endif // Hold data until read cleared. do { wait(); } while (port_Read); port_RData = 0; } else if (port_Write) { // Write a word to memory. int data = port_WData; //int be = port_BE; port_Stall = true; #if defined(PRINT_WHILE_RUN) cout << sc_time_stamp() << "\tMemory: Started write request. Addr = " << showbase << hex << addr << ", Data = " << showbase << hex << data << endl; #endif wait(10); port_Stall = false; _data[addr] = data; // TODO: byte enable #if defined(PRINT_WHILE_RUN) cout << sc_time_stamp() << "\tMemory: Finished write request. Addr = " << showbase << hex << addr << endl; #endif // Wait until write cleared. do { wait(); } while (port_Write); } } }
// //------------------------------------------------------------// // Copyright 2009-2012 Mentor Graphics Corporation // // All Rights Reserved Worldwid // // // // 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 PACKET_H #define PACKET_H #include <vector> using std::vector; #include <systemc.h> #include <tlm.h> using namespace sc_core; class packet { public: short cmd; int addr; vector<char> data; }; //------------------------------------------------------------------------------ // Begin UVMC-specific code #include "uvmc.h" using namespace uvmc; UVMC_UTILS_3 (packet,cmd,addr,data) #endif // PACKET_H
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_addressing_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; 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_bus_main.cpp : sc_main Original Author: Ric Hilderink, Synopsys, Inc., 2001-10-11 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc.h" #include "simple_bus_test.h" int sc_main(int, char **) { simple_bus_test top("top"); sc_start(10000, SC_NS); return 0; }
#ifndef IMG_TARGET_CPP #define IMG_TARGET_CPP #include <systemc.h> using namespace sc_core; using namespace sc_dt; using namespace std; #include <tlm.h> #include <tlm_utils/simple_initiator_socket.h> #include <tlm_utils/simple_target_socket.h> #include <tlm_utils/peq_with_cb_and_phase.h> //For an internal response phase DECLARE_EXTENDED_PHASE(internal_processing_ph); // Initiator module generating generic payload transactions struct img_target: sc_module { // TLM2.0 Socket tlm_utils::simple_target_socket<img_target> socket; //Internal fields unsigned char* data_ptr; unsigned int data_length; unsigned int address; //Pointer to transaction in progress tlm::tlm_generic_payload* response_transaction; //Payload event queue with callback and phase tlm_utils::peq_with_cb_and_phase<img_target> m_peq; //Delay sc_time response_delay = sc_time(10, SC_NS); sc_time receive_delay = sc_time(10,SC_NS); //Constructor SC_CTOR(img_target) : socket("socket"), response_transaction(0), m_peq(this, &img_target::peq_cb) // Construct and name socket { // Register callbacks for incoming interface method calls socket.register_nb_transport_fw(this, &img_target::nb_transport_fw); } tlm::tlm_sync_enum nb_transport_fw(tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_time& delay) { if (trans.get_byte_enable_ptr() != 0) { trans.set_response_status(tlm::TLM_BYTE_ENABLE_ERROR_RESPONSE); return tlm::TLM_COMPLETED; } if (trans.get_streaming_width() < trans.get_data_length()) { trans.set_response_status(tlm::TLM_BURST_ERROR_RESPONSE); return tlm::TLM_COMPLETED; } // Queue the transaction m_peq.notify(trans, phase, delay); return tlm::TLM_ACCEPTED; } //Payload and Queue Callback void peq_cb(tlm::tlm_generic_payload& trans, const tlm::tlm_phase& phase) { tlm::tlm_sync_enum status; sc_time delay; switch (phase) { //Case 1: Target is receiving the first transaction of communication -> BEGIN_REQ case tlm::BEGIN_REQ: { cout << name() << " BEGIN_REQ RECEIVED" << " TRANS ID " << 0 << " at time " << sc_time_stamp() << endl; //Check for errors here // Increment the transaction reference count trans.acquire(); //Queue a response tlm::tlm_phase int_phase = internal_processing_ph; m_peq.notify(trans, int_phase, response_delay); break; } case tlm::END_RESP: case tlm::END_REQ: case tlm::BEGIN_RESP:{ SC_REPORT_FATAL("TLM-2", "Illegal transaction phase received by target"); break; } default: { if (phase == internal_processing_ph){ cout << "INTERNAL PHASE: PROCESSING TRANSACTION" << endl; process_transaction(trans); } break; } } } //Resposne function void send_response(tlm::tlm_generic_payload& trans) { tlm::tlm_sync_enum status; tlm::tlm_phase response_phase; response_phase = tlm::BEGIN_RESP; status = socket->nb_transport_bw(trans, response_phase, response_delay); //Check Initiator response switch(status) { case tlm::TLM_ACCEPTED: { cout << name() << " TLM_ACCEPTED RECEIVED" << " TRANS ID " << 0 << " at time " << sc_time_stamp() << endl; // Target only care about acknowledge of the succesful response trans.release(); break; } //Not implementing Updated and Completed Status default: { printf("%s:\t [ERROR] Invalid status received at target", name()); break; } } } virtual void do_when_read_transaction(unsigned char*& data){ } virtual void do_when_write_transaction(unsigned char*&data){ } //Thread to call nb_transport on the backward path -> here the module process data and responds to initiator void process_transaction(tlm::tlm_generic_payload& trans) { //Status and Phase tlm::tlm_sync_enum status; tlm::tlm_phase phase; cout << name() << " Processing transaction: " << 0 << endl; //get variables from transaction tlm::tlm_command cmd = trans.get_command(); sc_dt::uint64 addr = trans.get_address(); unsigned char* data_ptr = trans.get_data_ptr(); unsigned int len = trans.get_data_length(); unsigned char* byte_en = trans.get_byte_enable_ptr(); unsigned int width = trans.get_streaming_width(); //Process transaction switch(cmd) { case tlm::TLM_READ_COMMAND: { unsigned char* response_data_ptr; this->do_when_read_transaction(response_data_ptr); //Add read according to length //-----------DEBUG----------- printf("[DEBUG] Reading: "); for (int i = 0; i < len/sizeof(int); ++i){ printf("%02x", *(reinterpret_cast<int*>(response_data_ptr)+i)); } printf("\n"); //-----------DEBUG----------- trans.set_data_ptr(response_data_ptr); break; } case tlm::TLM_WRITE_COMMAND: { this->do_when_write_transaction(data_ptr); //-----------DEBUG----------- printf("[DEBUG] Writing: "); for (int i = 0; i < len/sizeof(int); ++i){ printf("%02x", *(reinterpret_cast<int*>(data_ptr)+i)); } printf("\n"); //-----------DEBUG----------- break; } default: { cout << " ERROR " << "Command " << cmd << "is NOT valid" << endl; } } //Send response cout << name() << " BEGIN_RESP SENT" << " TRANS ID " << 0 << " at time " << sc_time_stamp() << endl; send_response(trans); } }; #endif
/***************************************************************************** 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. *****************************************************************************/ /***************************************************************************** in_class_initialization.cpp : Showcase for in-class initialization macros Original Author: Roman I. Popov, Intel *****************************************************************************/ #include <systemc.h> #ifdef USE_PIMPL_ADDER #include "adder_int_5_pimpl.h" #else #include "adder.h" #endif const int TEST_SIZE = 10; template <typename T, int N_INPUTS> struct adder_tester : sc_module { sc_in<bool> SC_NAMED(clock); sc_in<bool> SC_NAMED(reset); sc_in<T> SC_NAMED(res); sc_vector<sc_out<T>> SC_NAMED(din, N_INPUTS); SC_CTOR(adder_tester){} private: // In-class initialization of SC_CTHREAD, second parameter is clock edge, // third parameter is arbitrary initialization code SC_CTHREAD_IMP(adder_tester_cthread, clock.pos(), { async_reset_signal_is(reset, true); } ) { wait(); for (int ii = 0; ii < TEST_SIZE; ++ii) { T ref_res = 0; for (int jj = 0; jj < N_INPUTS; ++jj) { T input = ii + jj; ref_res += input; din[jj] = input; } wait(); cout << "RES: " << res << " REFERENCE: " << ref_res << "\n"; sc_assert(res == ref_res); } sc_stop(); } }; template <typename T, int N_INPUTS> struct testbench : sc_module { sc_clock SC_NAMED(clock, 10, SC_NS); sc_signal<bool> SC_NAMED(reset); sc_signal<T> SC_NAMED(res); sc_vector<sc_signal<T>> SC_NAMED(din, N_INPUTS); SC_CTOR(testbench) {} private: // SC_NAMED_WITH_INIT allows to specify arbitrary initialization code after member declaration // for example you can bind module ports here adder_tester<T, N_INPUTS> SC_NAMED_WITH_INIT(tester_inst) { tester_inst.clock(clock); tester_inst.reset(reset); tester_inst.res(res); tester_inst.din(din); } #ifdef USE_PIMPL_ADDER adder_int_5_pimpl SC_NAMED_WITH_INIT(adder_inst) #else adder<T, N_INPUTS> SC_NAMED_WITH_INIT(adder_inst) #endif { adder_inst.res(res); adder_inst.din(din); } SC_THREAD_IMP(reset_thread, sensitive << clock.posedge_event();) { reset = 1; wait(); reset = 0; } }; int sc_main(int argc, char **argv) { testbench<int, 5> SC_NAMED(tb_inst); sc_start(); 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--------------
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************************/ /** * @file main.cpp * @brief This implementation assigns preset values to a list of cci-parameters * (without any knowledge of them being present in the model) and then * instantiates the 'parameter_owner' and 'parameter_configurator' modules * @author P V S Phaneendra, CircuitSutra Technologies <[email protected]> * @date 21st July, 2011 (Thursday) */ #include <cci_configuration> #include <systemc.h> #include <string> #include <cci_configuration> #include "ex18_cci_configFile_Tool.h" #include "ex18_parameter_owner.h" #include "ex18_parameter_configurator.h" /** * @fn int sc_main(int sc_argc, char* sc_argv[]) * @brief Here, a reference of the global broker is taken with the help of * the originator information and then preset values are assigned to * a list of cci-parameters. * @param sc_argc The number of input arguments * @param sc_argv The list of input arguments * @return An integer denoting the return status of execution. */ int sc_main(int sc_argc, char* sc_argv[]) { cci::cci_register_broker(new cci_utils::broker("My Global Broker")); cci::ex18_cci_configFile_Tool configTool("ConfigTool"); configTool.config("Configuration_File.txt"); #if 0 // In case, if user doesn't want to use the reading from configuration file // approach, here is an alternative that assigns preset values to the // cci-parameters // Get reference/handle of the default global broker cci::cci_broker_handle myMainBrokerIF = cci::cci_get_broker(); SC_REPORT_INFO("sc_main", "[MAIN] : Set preset value to 'integer type" " parameter'"); myMainBrokerIF.set_preset_cci_value("param_owner.int_param", cci::cci_value(10)); SC_REPORT_INFO("sc_main", "[MAIN] : Set preset value to 'float type" " parameter'"); myMainBrokerIF.set_preset_cci_value("param_owner.float_param", cci::cci_value(11.11)); SC_REPORT_INFO("sc_main", "[MAIN] : Set preset value to 'string type" " parameter'"); myMainBrokerIF.set_preset_cci_value("param_owner.string_param", cci::cci_value::from_json("Used_parameter")); SC_REPORT_INFO("sc_main", "[MAIN] : Set preset value to 'double type" " parameter'"); myMainBrokerIF.set_preset_cci_value("param_owner.double_param", cci::cci_value(100.123456789)); #endif // Instatiation of 'parameter_owner' and 'parameter_configurator' modules ex18_parameter_owner param_owner("param_owner"); ex18_parameter_configurator param_cfgr("param_cfgr"); // BEOE, EOE and simulation phases advance from here SC_REPORT_INFO("sc_main", "Begin Simulation."); sc_core::sc_start(10.0, sc_core::SC_NS); SC_REPORT_INFO("sc_main", "End Simulation."); return EXIT_SUCCESS; } // sc_main
/** #define meta ... prInt32f("%s\n", meta); **/ /* All rights reserved to Alireza Poshtkohi (c) 1999-2023. Email: [email protected] Website: http://www.poshtkohi.info */ #include <systemc.h> #include <iostream> #include "des.h" #include "tb.h" #include <vector> #include <iostream> using namespace std; #include <general.h> #include <StaticFunctions/StaticFunctions.h> #include <System/BasicTypes/BasicTypes.h> #include <System/Object/Object.h> #include <System/String/String.h> #include <System/DateTime/DateTime.h> #include <Parvicursor/Profiler/ResourceProfiler.h> #include <System.IO/IOException/IOException.h> using namespace System; using namespace System::IO; using namespace Parvicursor::Profiler; //--------------------------------------- extern long long int numberOfActivatedProcesss; std::vector<sc_uint<64> > __patterns__; sc_uint<64> __input_key__ = "17855376605625100923"; //--------------------------------------- void BuildInputs() { ifstream *reader = new ifstream("patterns.txt", ios::in); if(!reader->is_open()) { //std::cout << "Could not open the file patterns.txt" << std::endl; //abort(); throw IOException("Could not open the file patterns.txt"); } std::string line; sc_uint<64> read; while(getline(*reader, line)) { *reader >> read; __patterns__.push_back(read); } reader->close(); delete reader; //cout << __inputs__.size() << endl; } //--------------------------------------- //sc_clock *clk; class Core { sc_signal<bool > reset; sc_signal<bool > rt_load; sc_signal<bool > rt_decrypt; sc_signal<sc_uint<64> > rt_data_i; sc_signal<sc_uint<64> > rt_key; sc_signal<sc_uint<64> > rt_data_o; sc_signal<bool > rt_ready; sc_clock *clk; des *de1; tb *tb1; public: Core() { sc_time period(2, SC_NS); double duty_cycle = 0.5; sc_time start_time(0, SC_NS); bool posedge_first = true; clk = new sc_clock("", period, duty_cycle, start_time, posedge_first); de1 = new des("des"); tb1 = new tb("tb"); de1->clk(*clk); de1->reset(reset); de1->load_i(rt_load); de1->decrypt_i(rt_decrypt); de1->data_i(rt_data_i); de1->key_i(rt_key); de1->data_o(rt_data_o); de1->ready_o(rt_ready); tb1->clk(*clk); tb1->rt_des_data_i(rt_data_o); tb1->rt_des_ready_i(rt_ready); tb1->rt_load_o(rt_load); tb1->rt_des_data_o(rt_data_i); tb1->rt_des_key_o(rt_key); tb1->rt_decrypt_o(rt_decrypt); tb1->rt_reset(reset); } }; void Model() { new Core(); } //--------------------------------------- int sc_main(int argc, char *argv[]) { BuildInputs(); //for(Int32 i = 0 ; i < 10 ; i++) // std::cout << __patterns__[i].to_string(SC_BIN) << std::endl; //return 0; struct timeval start; // has tv_sec and tv_usec elements. xParvicursor_gettimeofday(&start, null); int numOfCores = 1; // 1200 int simUntil = 100; // 100000 // sc_set_time_resolution... should be called before starting the simulation. sc_set_time_resolution(1, SC_NS); /*sc_time period(2, SC_NS); double duty_cycle = 0.5; sc_time start_time(0, SC_NS); bool posedge_first = true; clk = new sc_clock("", period, duty_cycle, start_time, posedge_first);*/ for(register UInt32 i = 0 ; i < numOfCores ; i++) Model(); sc_start(simUntil, SC_NS); struct timeval stop; // has tv_sec and tv_usec elements. xParvicursor_gettimeofday(&stop, null); double _d1, _d2; _d1 = (double)start.tv_sec + 1e-6*((double)start.tv_usec); _d2 = (double)stop.tv_sec + 1e-6*((double)stop.tv_usec); // return result in seconds double totalSimulationTime = _d2 - _d1; std::cout << "Simulation completed in " << totalSimulationTime << " secs." << std::endl; std::cout << "sc_delta_count(): " << sc_delta_count() << std::endl; // returns the absolute number of delta cycles that have occurred during simulation, std::cout << "Total events change_stamp(): " << sc_get_curr_simcontext()->change_stamp() << std::endl; std::cout << "Timed events: " << sc_get_curr_simcontext()->change_stamp() - sc_delta_count() << std::endl; std::cout << "\nnumberOfActivatedProcesses: " << numberOfActivatedProcesss << std::endl; std::cout << "\n---------------- Runtime Statistics ----------------\n\n"; usage u; ResourceProfiler::GetResourceUsage(&u); ResourceProfiler::PrintResourceUsage(&u); return 0; } //---------------------------------------
// ************************************************************************************** // User-defined memory manager, which maintains a pool of transactions // From TLM Duolos tutorials // ************************************************************************************** #ifndef TRANSACTION_MEMORY_MANAGER_CPP #define TRANSACTION_MEMORY_MANAGER_CPP #include <systemc.h> using namespace sc_core; using namespace sc_dt; using namespace std; #include <tlm.h> #include <tlm_utils/simple_initiator_socket.h> #include <tlm_utils/simple_target_socket.h> #include <tlm_utils/peq_with_cb_and_phase.h> class mm: public tlm::tlm_mm_interface { typedef tlm::tlm_generic_payload gp_t; public: mm() : free_list(0), empties(0) #ifdef DEBUG , count(0) #endif // DEBUG {} gp_t* allocate() { #ifdef DEBUG cout << "----------------------------- Called allocate(), #trans = " << ++count << endl; #endif // DEBUG gp_t* ptr; if (free_list) { ptr = free_list->trans; empties = free_list; free_list = free_list->next; } else { ptr = new gp_t(this); } return ptr; } void free(gp_t* trans) { #ifdef DEBUG cout << "----------------------------- Called free(), #trans = " << --count << endl; #endif // DEBUG if (!empties) { empties = new access; empties->next = free_list; empties->prev = 0; if (free_list) free_list->prev = empties; } free_list = empties; free_list->trans = trans; empties = free_list->prev; } private: struct access { gp_t* trans; access* next; access* prev; }; access* free_list; access* empties; #ifdef DEBUG int count; #endif // DEBUG }; #endif // TRANSACTION_MEMORY_MANAGER_CPP
/* * 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 "hwcore/tb/cnn/tb_pe.hpp" #include <systemc.h> unsigned errors = 0; const char simulation_name[] = "tb_pe"; 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"); return 0; tb_pe<sizeof(int) * 8, sizeof(int) * 4, 1> tb_01("tb_pe"); cout << "INFO: Simulating " << simulation_name << endl; sc_time time_out(1000, SC_US); sc_start(time_out); return errors ? 1 : 0; cout << "INFO: end time is: " << sc_time_stamp().to_string() << ", and max time is: " << time_out.to_string() << std::endl << std::flush; sc_assert(sc_time_stamp() != time_out); cout << "INFO: Post-processing " << simulation_name << endl; cout << "INFO: Simulation " << simulation_name << " " << (errors ? "FAILED" : "PASSED") << " with " << errors << " errors" << std::endl << std::flush; #ifdef __RTL_SIMULATION__ cout << "HW cosim done" << endl; #endif return errors ? 1 : 0; } // test2
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_output_v_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
//----------------------------------------------------- #include "systemc.h" SC_MODULE (ram) { sc_inout<sc_uint<32> > data; sc_in<sc_uint<32> > address; //-----------Internal variables------------------- sc_uint <32> mem[1024]; sc_event rd_t, wr_t; // Constructor for memory //SC_CTOR(ram) { SC_HAS_PROCESS(ram); ram(sc_module_name ram) { SC_THREAD(wr); SC_THREAD(rd); } // End of Constructor //------------Code Starts Here------------------------- void write() { wr_t.notify(2, SC_NS); } void read() { rd_t.notify(2, SC_NS); } void wr() { while(true) { wait(wr_t); mem [address.read()] = data.read(); } } void rd() { while(true) { wait(rd_t); data = mem [address.read()]; } } }; // End of Module memory
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_matrix_deviation_function_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/****************************************************** * This is the main file for the mips1 ArchC model * * This file is automatically generated by ArchC * * WITHOUT WARRANTY OF ANY KIND, either express * * or implied. * * For more information on ArchC, please visit: * * http://www.archc.org * * * * The ArchC Team * * Computer Systems Laboratory (LSC) * * IC-UNICAMP * * http://www.lsc.ic.unicamp.br * ******************************************************/ // Rodolfo editou aqui // const char *project_name="mips"; const char *project_file="mips1.ac"; const char *archc_version="2.0beta1"; const char *archc_options="-abi -dy "; #include <systemc.h> #include <stdlib.h> #include "mips.H" #include "memory.h" #include "peripheral.h" #include "bus.h" int sc_main(int ac, char *av[]) { int ac2 = ac; char** av2 = (char **) malloc((ac+1) * sizeof (*av2)); for(int i = 0; i < ac; ++i) { size_t length = strlen(av[i])+1; av2[i] = (char *) malloc(length); memcpy(av2[i], av[i], length); } av2[ac] = NULL; //! ISA simulator mips mips_proc1("mips1"); mips mips_proc2("mips2"); //! Bus ac_tlm_bus bus("bus"); // Memory ac_tlm_mem mem("mem"); // Peripheral ac_tlm_peripheral peripheral("peripheral"); #ifdef AC_DEBUG ac_trace("mips1_proc1.trace"); #endif mips_proc1.DM(bus.target_export); mips_proc2.DM(bus.target_export); bus.MEM_port(mem.target_export); bus.PERIPHERAL_port(peripheral.target_export); mips_proc1.init(ac, av); mips_proc1.set_prog_args(); cerr << endl; mips_proc2.init(ac2, av2); mips_proc2.set_prog_args(); cerr << endl; sc_start(); mips_proc1.PrintStat(); mips_proc2.PrintStat(); cerr << endl; #ifdef AC_STATS mips1_proc1.ac_sim_stats.time = sc_simulation_time(); mips1_proc1.ac_sim_stats.print(); #endif #ifdef AC_DEBUG ac_close_trace(); #endif return mips_proc1.ac_exit_status; }
#include <systemc.h> //here we create a module called hello_world SC_MODULE(hello_world) { private int meaning_of_life; // easter egg //SC_CTOR -- systemC constructor SC_CTOR(hello_world) { meaning_of_life=42; } void say_hello() { cout << "Hello Systemc-2.3.1!\n"; } void open_magic_box() { cout << meaning_of_life << endl; } }; int sc_main(int argc, char* argv[]) { hello_world hello("HELLO"); hello.say_hello(); hello.open_magic_box(); return(0); }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_input_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
#include <systemc.h> #include "Producer.h" #include "Consumer.h" int sc_main(int argc, char* argv[]) { // generating the sc_signal sc_signal<int> data_sig; // generating the modules Producer prod1("Producer1"); Consumer cons1("Consumer1"); // connecting modules via signals prod1.data(data_sig); cons1.data(data_sig); // Run the simulation till sc_stop is encountered sc_start(); return 0; }
/** * Author: Anubhav Tomar * * Controller Definition **/ #include<systemc.h> template <class _addrSize , class _dataSize> class _controllerBlock : public sc_module { public: // Inputs sc_in<bool> _clock; sc_in<sc_uint<16> > _instructionIn; sc_in<_dataSize> _operand1In; sc_in<_dataSize> _operand2In; sc_in<_dataSize> _dmDataIn; sc_in<_dataSize> _aluResultIn; // Outputs to PM sc_out<sc_uint<16> > _PCOut; sc_out<bool> _pmRead; // Outputs to DM sc_out<_addrSize> _dmAddrOut; sc_out<bool> _dmRead; sc_out<bool> _dmWrite; sc_out<_dataSize> _dmDataOut; // Outputs to RF sc_out<_addrSize> _rfAddr1Out; sc_out<_addrSize> _rfAddr2Out; sc_out<_dataSize> _rfDataOut; sc_out<bool> _rfRead; sc_out<bool> _rfWrite; sc_out<sc_uint<1> > _isImmData; // Outputs to ALU sc_out<bool> _aluEnable; sc_out<sc_uint<4> > _aluControlSig; sc_out<sc_uint<4> > _condControlSig; sc_out<sc_uint<1> > _isImmControlSig; sc_out<_dataSize> _operand1Out; sc_out<_dataSize> _operand2Out; enum states {S0 , S1 , S2 , S3 , S4 , S5 , S6}; sc_signal<states> _currentState; SC_HAS_PROCESS(_controllerBlock); _controllerBlock(sc_module_name name) : sc_module(name) { PC = 0x0000; _currentState.write(S0); SC_THREAD(_runFSM); sensitive<<_clock; }; private: std::vector<sc_uint<49> > _instructionControlSigQ; sc_uint<16> _IR; sc_uint<16> PC; void _runFSM () { while(true) { wait(); if(_clock.read() == 1) { cout<<"@ "<<sc_time_stamp()<<"------Start _runFSMRising--------"<<endl<<endl<<endl; switch(_currentState.read()) { case S0 : _currentState.write(S1); _runFetch(); break; case S2 : _currentState.write(S3); _runRFRead(); _runFetch(); break; case S3 : _currentState.write(S4); _runExecution(); _runDecode(); break; case S4 : _currentState.write(S5); _runMemAccess(); break; default: break; } cout<<"@ "<<sc_time_stamp()<<"------End _runFSMRising--------"<<endl<<endl<<endl; } else { cout<<"@ "<<sc_time_stamp()<<"------Start _runFSMFalling--------"<<endl<<endl<<endl; switch(_currentState.read()) { case S1 : _currentState.write(S2); _runDecode(); break; case S5 : _currentState.write(S6); _runRFWriteBack(); _currentState.write(S0); break; default: break; } cout<<"@ "<<sc_time_stamp()<<"------End _runFSMFalling--------"<<endl<<endl<<endl; } } } void _runFetch () { cout<<"@ "<<sc_time_stamp()<<"------Start _runFetch from PM--------"<<endl<<endl<<endl; if(_currentState.read() != S0 && _IR == 0) { // NOP return; } _PCOut.write(PC); _pmRead.write(1); wait(10 , SC_PS); _IR = _instructionIn.read(); wait(10 , SC_PS); _pmRead.write(0); if(_IR == 0) { // NOP return; } PC += 1; cout<<"/**===================================CONTROLLER LOG===================================**/"<<endl; cout<<" Stage : Instruction Fetch"<<endl; cout<<" Instruction : "<<_IR<<endl; cout<<" Current PC Value : "<<PC<<endl; cout<<"/**===================================CONTROLLER LOG===================================**/"<<endl<<endl<<endl; cout<<"@ "<<sc_time_stamp()<<"------End _runFetch from PM--------"<<endl<<endl<<endl; } sc_uint<49> _prepareInstructionControlSig (sc_uint<4> _aluControlSig , sc_uint<1> _isImmData , sc_uint<4> _rDestCond , sc_uint<4> _opCodeExtImmH , sc_uint<4> _rSrcImmL) { cout<<"@ "<<sc_time_stamp()<<"------Start _prepareInstructionControlSig--------"<<endl; sc_uint<49> _instructionControlSig; _instructionControlSig.range(16 , 13) = _aluControlSig; // _aluControlSig _instructionControlSig.range(12 , 12) = _isImmData; // _isImmData _instructionControlSig.range(11 , 8) = _rDestCond; // _condControlSig _instructionControlSig.range(7 , 4) = _opCodeExtImmH; // Rdest/ImmHi _instructionControlSig.range(3 , 0) = _rSrcImmL; // Rsrc/ImmLo cout<<" _aluControlSig : "<<_aluControlSig<<endl; cout<<" _isImmData : "<<_isImmData<<endl; cout<<" _rDestCond : "<<_rDestCond<<endl; cout<<" _opCodeExtImmH : "<<_opCodeExtImmH<<endl; cout<<" _rSrcImmL : "<<_rSrcImmL<<endl; cout<<"@ "<<sc_time_stamp()<<"------End _prepareInstructionControlSig--------"<<endl; return _instructionControlSig; } void _runDecode () { cout<<"@ "<<sc_time_stamp()<<"------Start _runDecode--------"<<endl<<endl<<endl; if(_IR == 0) { // NOP cout<<"/**===================================CONTROLLER LOG===================================**/"<<endl; cout<<" Stage : Instruction Decode"<<endl; cout<<" Instruction Opcode : NOP"<<endl; cout<<"/**===================================CONTROLLER LOG===================================**/"<<endl<<endl<<endl; return; } sc_uint<4> _opcode = _IR.range(15 , 12); sc_uint<4> _rDestCond = _IR.range(11 , 8); sc_uint<4> _opCodeExtImmH = _IR.range(7 , 4); sc_uint<4> _rSrcImmL = _IR.range(3 , 0); sc_uint<49> _instructionControlSig; cout<<"/**===================================CONTROLLER LOG===================================**/"<<endl; cout<<" Stage : Instruction Decode"<<endl; cout<<" Instruction Opcode : "<<_IR<<endl; switch(_opcode) { case 0b0000 : // ADD , SUB , CMP , AND , OR , XOR , MOV switch(_opCodeExtImmH) { case 0b0101 : // ADD cout<<" Instruction : ADD"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b0000 , 0 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b1001 : // SUB cout<<" Instruction : SUB"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b0001 , 0 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b1011 : // CMP cout<<" Instruction : CMP"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b0010 , 0 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b0001 : // AND cout<<" Instruction : AND"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b0011 , 0 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b0010 : // OR cout<<" Instruction : OR"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b0100 , 0 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b0011 : // XOR cout<<" Instruction : XOR"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b0101 , 0 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b1101 : // MOV cout<<" Instruction : MOV"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b0110 , 0 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; } break; case 0b0101 : // ADDI cout<<" Instruction : ADDI"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b0000 , 1 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b1001 : // SUBI cout<<" Instruction : SUBI"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b0001 , 1 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b1011 : // CMPI cout<<" Instruction : CMPI"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b0010 , 1 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b0001 : // ANDI cout<<" Instruction : ANDI"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b0011 , 1 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b0010 : // ORI cout<<" Instruction : ORI"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b0100 , 1 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b0011 : // XORI cout<<" Instruction : XORI"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b0101 , 1 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b1101 : // MOVI cout<<" Instruction : MOVI"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b0110 , 1 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b1000 : // LSH , LSHI , ASH , ASHI switch(_opCodeExtImmH) { case 0b0100 : // LSH cout<<" Instruction : LSH"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b0111 , 0 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b0000 : // LSHI cout<<" Instruction : LSHI"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b0111 , 1 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b0110 : // ASH cout<<" Instruction : ASH"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b1000 , 0 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b0001 : // ASHI cout<<" Instruction : ASHI"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b1000 , 1 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; } break; case 0b1111 : // LUI cout<<" Instruction : LUI"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b1001 , 1 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b0100 : // LOAD , STOR , Jcond , JAL switch(_opCodeExtImmH) { case 0b0000 : // LOAD cout<<" Instruction : LOAD"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b1001 , 0 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b0100 : // STOR cout<<" Instruction : STOR"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b1010 , 0 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b1100 : // Jcond cout<<" Instruction : Jcond"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b1100 , 0 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; case 0b1000 : // JAL cout<<" Instruction : JAL"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b1101 , 0 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; } break; case 0b1100 : // Bcond cout<<" Instruction : Bcond"<<endl; _instructionControlSig = _prepareInstructionControlSig(0b1011 , 0 , _rDestCond , _opCodeExtImmH , _rSrcImmL); break; } _instructionControlSigQ.push_back(_instructionControlSig); cout<<" _instructionControlSig : "<<_instructionControlSig<<endl; cout<<"/**===================================CONTROLLER LOG===================================**/"<<endl<<endl<<endl; cout<<"@ "<<sc_time_stamp()<<"------End _runDecode--------"<<endl<<endl<<endl; } void _runRFRead () { cout<<"@ "<<sc_time_stamp()<<"------Start _runRFRead--------"<<endl<<endl<<endl; if(!_instructionControlSigQ.size()) { return; } sc_uint<48> _currentInstruction = _instructionControlSigQ.front(); sc_uint<4> _aluSig = _currentInstruction.range(16 , 13); _dataSize _op1 , _op2; if(_currentInstruction.range(12 , 12)) { // _isImmData = 1 _rfAddr1Out.write(_currentInstruction.range(11 , 8)); // Rdst sc_uint<16> parseData = _currentInstruction.range(7 , 4); // ImmHi<<4 + ImmLo parseData = parseData<<4; parseData += _currentInstruction.range(3 , 0); _rfDataOut.write(parseData); _isImmData.write(1); _rfRead.write(true); wait(10 , SC_PS); _op1 = _operand1In.read(); _op2 = _operand2In.read(); wait(10 , SC_PS); _rfRead.write(false); } else { _rfAddr1Out.write(_currentInstruction.range(11 , 8)); // Rdst _rfAddr2Out.write(_currentInstruction.range(3 , 0)); // Rsrc _isImmData.write(0); _rfRead.write(true); wait(10 , SC_PS); _op1 = _operand1In.read(); _op2 = _operand2In.read(); wait(10 , SC_PS); _rfRead.write(false); } _instructionControlSigQ[0].range(32 , 17) = _op1; _instructionControlSigQ[0].range(48 , 33) = _op2; if(_aluSig == 0b1100 || _aluSig == 0b1011) { // Jcond , Bcond _instructionControlSigQ[0].range(32 , 17) = _currentInstruction.range(3 , 0); _instructionControlSigQ[0].range(48 , 33) = PC; // Store PC as _operand2Out } cout<<"/**===================================CONTROLLER LOG===================================**/"<<endl; cout<<" Stage : RF Access"<<endl; cout<<" _instructionControlSig : "<<_instructionControlSigQ[0]<<endl; cout<<" Operand1 : "<<_op1<<endl; cout<<" Operand2 : "<<_op2<<endl; cout<<"/**===================================CONTROLLER LOG===================================**/"<<endl<<endl<<endl; cout<<"@ "<<sc_time_stamp()<<"------End _runRFRead--------"<<endl<<endl<<endl; } void _runExecution () { cout<<"@ "<<sc_time_stamp()<<"------Start _runExecution--------"<<endl<<endl<<endl; if(!_instructionControlSigQ.size()) { return; } sc_uint<49> _currentInstruction = _instructionControlSigQ.front(); _aluControlSig.write(_currentInstruction.range(16 , 13)); _condControlSig.write(_currentInstruction.range(11 , 8)); _isImmControlSig.write(_currentInstruction.range(12 , 12)); _operand1Out.write(_currentInstruction.range(32 , 17)); _operand2Out.write(_currentInstruction.range(48 , 33)); _aluEnable.write(1); wait(10 , SC_PS); _dataSize _res = _aluResultIn.read(); wait(10 , SC_PS); _aluEnable.write(0); _instructionControlSigQ[0].range(48 , 33) = _res; // Overwrite operand2. Only operand1 is required in _memAccess & _runRFWriteBack cout<<"/**===================================CONTROLLER LOG===================================**/"<<endl; cout<<" Stage : Execution"<<endl; cout<<" _instructionControlSig : "<<_instructionControlSigQ[0]<<endl; cout<<" Result : "<<_res<<endl; cout<<"/**===================================CONTROLLER LOG===================================**/"<<endl<<endl<<endl; cout<<"@ "<<sc_time_stamp()<<"------End _runExecution--------"<<endl<<endl<<endl; } void _runMemAccess () { cout<<"@ "<<sc_time_stamp()<<"------Start _runMemAccess--------"<<endl<<endl<<endl; if(!_instructionControlSigQ.size()) { return; } sc_uint<49> _currentInstruction = _instructionControlSigQ.front(); sc_uint<4> _aluSig = _currentInstruction.range(16 , 13); if(_aluSig == 0b1001) { // LOAD _dmAddrOut.write(_currentInstruction.range(48 , 33)); // Raddr value _dmRead.write(1); wait(10 , SC_PS); _dataSize _res = _dmDataIn.read(); wait(10 , SC_PS); _dmRead.write(0); _currentInstruction.range(48 , 33) = _res; // Overwrite operand2. Raddr value not required } else if(_aluSig == 0b1010) { // STOR _dmAddrOut.write(_currentInstruction.range(32 , 17)); // Raddr value _dmDataOut.write(_currentInstruction.range(48 , 33)); // Rsrc value _dmWrite.write(1); wait(10 , SC_PS); wait(10 , SC_PS); _dmWrite.write(0); } else if(_aluSig == 0b1011 || _aluSig == 0b1100) { // Jcond , Bcond PC = _currentInstruction.range(48 , 33); } cout<<"/**===================================CONTROLLER LOG===================================**/"<<endl; cout<<" Stage : Memory Access"<<endl; cout<<" _instructionControlSig : "<<_instructionControlSigQ[0]<<endl; cout<<"/**===================================CONTROLLER LOG===================================**/"<<endl<<endl<<endl; cout<<"@ "<<sc_time_stamp()<<"------End _runMemAccess--------"<<endl<<endl<<endl; } void _runRFWriteBack() { cout<<"@ "<<sc_time_stamp()<<"------Start _runRFWrite--------"<<endl<<endl<<endl; if(!_instructionControlSigQ.size()) { return; } sc_uint<49> _currentInstruction = _instructionControlSigQ.front(); sc_uint<4> _aluSig = _currentInstruction.range(16 , 13); if(_aluSig != 0b0010 && _aluSig != 0b1010 && _aluSig != 0b1011 && _aluSig != 0b1100) { // All except CMP , CMPI , STOR , Jcond , Bcond _rfAddr1Out.write(_currentInstruction.range(11 , 8)); // Rdst _rfDataOut.write(_currentInstruction.range(48 , 33)); // Result _rfWrite.write(1); wait(10 , SC_PS); wait(10 , SC_PS); _rfWrite.write(0); } _instructionControlSigQ.erase(_instructionControlSigQ.begin()); cout<<"/**===================================CONTROLLER LOG===================================**/"<<endl; cout<<" Stage : RF Write Back"<<endl; cout<<" _instructionControlSigQ Length : "<<_instructionControlSigQ.size()<<endl; cout<<"/**===================================CONTROLLER LOG===================================**/"<<endl<<endl<<endl; cout<<"@ "<<sc_time_stamp()<<"------End _runRFWrite--------"<<endl<<endl<<endl; } };
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_output_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "systemc.h" #define SIZE_I_IN 4 #define SIZE_J_IN 4 #define SIZE_K_IN 4 SC_MODULE(tensor_matrix_convolution) { sc_in_clk clock; sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN]; sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN]; SC_CTOR(tensor_matrix_convolution) { SC_METHOD(convolution); sensitive << clock.pos(); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { sensitive << data_a_in[i][j][k]; } sensitive << data_b_in[i][j]; } } } void convolution() { for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { int temporal = 0; for (int m = 0; m < i; m++) { for (int n = 0; n < j; n++) { for (int p = 0; p < k; p++) { temporal += data_a_in[m][n][p].read() * data_b_in[i - m][j - n].read(); } } } data_out[i][j] = temporal; } } } } };
/* * @ASCK */ #include <systemc.h> SC_MODULE (ID) { sc_in_clk clk; sc_in <sc_int<8>> prev_A; sc_in <sc_int<8>> prev_B; sc_in <sc_int<13>> prev_Imm; sc_in <sc_uint<3>> prev_Sa; sc_in <sc_uint<5>> prev_AluOp; sc_in <bool> prev_r; sc_in <bool> prev_w; sc_in <bool> prev_AluMux; sc_in <bool> prev_WbMux; sc_in <bool> prev_call; sc_in <bool> prev_regWrite; sc_in <sc_uint<3>> prev_rd; sc_out <sc_int<8>> next_A; sc_out <sc_int<8>> next_B; sc_out <sc_int<13>> next_Imm; sc_out <sc_uint<3>> next_Sa; sc_out <sc_uint<5>> next_AluOp; sc_out <bool> next_r; sc_out <bool> next_w; sc_out <bool> next_AluMux; sc_out <bool> next_WbMux; sc_out <bool> next_call; sc_out <bool> next_regWrite; sc_out <sc_uint<3>> next_rd; /* ** module global variables */ SC_CTOR (ID){ SC_THREAD (process); sensitive << clk.pos(); } void process () { while(true){ wait(); if(now_is_call){ wait(micro_acc_ev); } next_A.write(prev_A.read()); next_B.write(prev_B.read()); next_Imm.write(prev_Imm.read()); next_Sa.write(prev_Sa.read()); next_AluOp.write(prev_AluOp.read()); next_AluMux.write(prev_AluMux.read()); next_r.write(prev_r.read()); next_w.write(prev_w.read()); next_WbMux.write(prev_WbMux.read()); next_call.write(prev_call.read()); next_regWrite.write(prev_regWrite); next_rd.write(prev_rd.read()); } } };
/******************************************************************************** * 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: [email protected] * * [email protected] * * [email protected] * * * ******************************************************************************** * This code has been developed from an HEPSYCODE model used as demonstrator by * * University of L'Aquila. * *******************************************************************************/ #include "display.h" #include <systemc.h> void display::main() { int i = 1; system_display_payload system_display_payload_var; /* //implementation while(1) { system_display_payload_var = system_display_port_in->read(); cout << "Display-" << i << "\t at time \t" << sc_time_stamp().to_seconds() << endl; i++; } */ //implementation while(i <= 100) { system_display_payload_var = system_display_port_in->read(); cout << "Display-" << i <<": \t" << "\t at time \t" << sc_time_stamp().to_seconds() << endl; i++; } sc_stop(); }
// Copyright 2020 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: // // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD // // 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.h" #include "clockpacer.h" //Undocumented!!! Get chip temperature in Farenheit //Source: https://github.com/pcbreflux/espressif/blob/master/esp32/arduino/sketchbook/ESP32_int_temp_sensor/ESP32_int_temp_sensor.ino uint8_t temprature_sens_read(); float temperatureRead() { return (temprature_sens_read() - 32) / 1.8; } /* We need to use the C prototype style so that the weak alias will work. */ extern "C" { void __yield(); } void __yield() { /* We do a wait, as that hands the control back to the SystemC Scheduler, * which is also handling our FreeRTOS scheduler. */ wait(clockpacer.get_cpu_period()); } void yield() __attribute__ ((weak, alias("__yield"))); /* This is something often used inside the model and drivers for the model. */ void del1cycle() { if (clockpacer.is_thread()) clockpacer.wait_next_cpu_clk(); } #if CONFIG_AUTOSTART_ARDUINO /* extern TaskHandle_t loopTaskHandle; extern bool loopTaskWDTEnabled; void enableLoopWDT(){ if(loopTaskHandle != NULL){ if(esp_task_wdt_add(loopTaskHandle) != ESP_OK){ log_e("Failed to add loop task to WDT"); } else { loopTaskWDTEnabled = true; } } } void disableLoopWDT(){ if(loopTaskHandle != NULL && loopTaskWDTEnabled){ loopTaskWDTEnabled = false; if(esp_task_wdt_delete(loopTaskHandle) != ESP_OK){ log_e("Failed to remove loop task from WDT"); } } } void feedLoopWDT(){ esp_err_t err = esp_task_wdt_reset(); if(err != ESP_OK){ log_e("Failed to feed WDT! Error: %d", err); } } */ #endif /* void enableCore0WDT(){ TaskHandle_t idle_0 = xTaskGetIdleTaskHandleForCPU(0); if(idle_0 == NULL || esp_task_wdt_add(idle_0) != ESP_OK){ log_e("Failed to add Core 0 IDLE task to WDT"); } } void disableCore0WDT(){ TaskHandle_t idle_0 = xTaskGetIdleTaskHandleForCPU(0); if(idle_0 == NULL || esp_task_wdt_delete(idle_0) != ESP_OK){ log_e("Failed to remove Core 0 IDLE task from WDT"); } } #ifndef CONFIG_FREERTOS_UNICORE void enableCore1WDT(){ TaskHandle_t idle_1 = xTaskGetIdleTaskHandleForCPU(1); if(idle_1 == NULL || esp_task_wdt_add(idle_1) != ESP_OK){ log_e("Failed to add Core 1 IDLE task to WDT"); } } void disableCore1WDT(){ TaskHandle_t idle_1 = xTaskGetIdleTaskHandleForCPU(1); if(idle_1 == NULL || esp_task_wdt_delete(idle_1) != ESP_OK){ log_e("Failed to remove Core 1 IDLE task from WDT"); } } #endif */ /* BaseType_t xTaskCreateUniversal( TaskFunction_t pxTaskCode, const char * const pcName, const uint32_t usStackDepth, void * const pvParameters, UBaseType_t uxPriority, TaskHandle_t * const pxCreatedTask, const BaseType_t xCoreID ){ #ifndef CONFIG_FREERTOS_UNICORE if(xCoreID >= 0 && xCoreID < 2) { return xTaskCreatePinnedToCore(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask, xCoreID); } else { #endif return xTaskCreate(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask); #ifndef CONFIG_FREERTOS_UNICORE } #endif } */ /* micros and millis get the current time from the SystemC simulation time * instead of the CPU. */ unsigned long int micros() { return (unsigned long int)floor(sc_time_stamp().to_seconds() * 1000000); } unsigned long int millis() { return (unsigned long int)floor(sc_time_stamp().to_seconds() * 1000); } /* Delay does a SystemC wait. */ void delay(uint32_t del) { wait(del, SC_MS); } /* For the delayMicroseconds we do the same thing. We definitely do not want * the busy-wait loop that the original code uses. It bogs down too much the * simulation. */ void delayMicroseconds(uint32_t del) { wait(del, SC_US); } /* Not sure why these are here, but they do nothing, so they can remain here. */ void initVariant() __attribute__((weak)); void initVariant() {} void init() __attribute__((weak)); void init() {} bool verifyOta() __attribute__((weak)); bool verifyOta() { return true; } #ifdef CONFIG_BT_ENABLED //overwritten in esp32-hal-bt.c bool btInUse() __attribute__((weak)); bool btInUse(){ return false; } #endif /* void initArduino() { #ifdef CONFIG_APP_ROLLBACK_ENABLE const esp_partition_t *running = esp_ota_get_running_partition(); esp_ota_img_states_t ota_state; if (esp_ota_get_state_partition(running, &ota_state) == ESP_OK) { if (ota_state == ESP_OTA_IMG_PENDING_VERIFY) { if (verifyOta()) { esp_ota_mark_app_valid_cancel_rollback(); } else { log_e("OTA verification failed! Start rollback to the previous version ..."); esp_ota_mark_app_invalid_rollback_and_reboot(); } } } #endif //init proper ref tick value for PLL (uncomment if REF_TICK is different than 1MHz) //ESP_REG(APB_CTRL_PLL_TICK_CONF_REG) = APB_CLK_FREQ / REF_CLK_FREQ - 1; #ifdef F_CPU setCpuFrequencyMhz(F_CPU/1000000); #endif #if CONFIG_SPIRAM_SUPPORT psramInit(); #endif esp_log_level_set("*", CONFIG_LOG_DEFAULT_LEVEL); esp_err_t err = nvs_flash_init(); if(err == ESP_ERR_NVS_NO_FREE_PAGES){ const esp_partition_t* partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_NVS, NULL); if (partition != NULL) { err = esp_partition_erase_range(partition, 0, partition->size); if(!err){ err = nvs_flash_init(); } else { log_e("Failed to format the broken NVS partition!"); } } } if(err) { log_e("Failed to initialize NVS! Error: %u", err); } #ifdef CONFIG_BT_ENABLED if(!btInUse()){ esp_bt_controller_mem_release(ESP_BT_MODE_BTDM); } #endif init(); initVariant(); } */ //used by hal log const char *pathToFileName(const char * path) { size_t i = 0; size_t pos = 0; char * p = (char *)path; while(*p){ i++; if(*p == '/' || *p == '\\'){ pos = i; } p++; } return path+pos; }
/***************************************************************************** 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. *****************************************************************************/ /***************************************************************************** display.cpp -- Original Author: Rocco Jonack, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation: Teodor Vasilache and Dragos Dospinescu, AMIQ Consulting s.r.l. ([email protected]) Date: 2018-Feb-20 Description of Modification: Included the FC4SC library in order to collect functional coverage data and generate a coverage database. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include <systemc.h> #include "display.h" #include "fc4sc.hpp" void display::entry(){ // Reading Data when valid if high tmp1 = result.read(); cout << "Display : " << tmp1 << " " /* << " at time " << sc_time_stamp() << endl; */ << " at time " << sc_time_stamp().to_double() << endl; i++; // sample the data this->out_cg.sample(result, output_data_ready); if(i == 24) { cout << "Simulation of " << i << " items finished" /* << " at time " << sc_time_stamp() << endl; */ << " at time " << sc_time_stamp().to_double() << endl; // generate the coverage database from the collected data fc4sc::global::coverage_save("coverage_results.xml"); sc_stop(); }; } // EOF
/******************************************************************************** * 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: [email protected] * * [email protected] * * [email protected] * * * ******************************************************************************** * 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_03_ANN_INPUTS 2 // Number of inputs #define cD_03_ANN_OUTPUTS 1 // Number of outputs //----------------------------------------------------------------------------- // Physical constants //----------------------------------------------------------------------------- static double cD_03_I_0 = 77.3 ; // [A] Nominal current static double cD_03_T_0 = 298.15 ; // [K] Ambient temperature static double cD_03_R_0 = 0.01 ; // [Ω] Data-sheet R_DS_On (Drain-Source resistance in the On State) static double cD_03_V_0 = 47.2 ; // [V] Nominal voltage static double cD_03_Alpha = 0.002 ; // [Ω/K] Temperature coefficient of Drain-Source resistance in the On State static double cD_03_ThermalConstant = 0.75 ; static double cD_03_Tau = 0.02 ; // [s] Sampling period //----------------------------------------------------------------------------- // Status descriptors //----------------------------------------------------------------------------- typedef struct cD_03_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_03_DEVICE ; static cD_03_DEVICE cD_03_device; //----------------------------------------------------------------------------- // Mnemonics to access the array that contains the sampled data //----------------------------------------------------------------------------- #define cD_03_SAMPLE_LEN 3 // Array of SAMPLE_LEN elements #define cD_03_I_INDEX 0 // Current #define cD_03_V_INDEX 1 // Voltage #define cD_03_TIME_INDEX 2 // Time ///----------------------------------------------------------------------------- // Forward references //----------------------------------------------------------------------------- static int cD_03_initDescriptors(cD_03_DEVICE device) ; //static void getSample(int index, double sample[SAMPLE_LEN]) ; static void cD_03_cleanData(int index, double sample[cD_03_SAMPLE_LEN]) ; static double cD_03_extractFeatures(double tPrev, double iPrev, double iNow, double rPrev) ; static void cD_03_normalize(int index, double x[cD_03_ANN_INPUTS]) ; static double cD_03_degradationModel(double tNow) ; //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- int cD_03_initDescriptors(cD_03_DEVICE device) {HEPSY_S(cleanData_03_id) // for (int i = 0; i < NUM_DEV; i++) // { HEPSY_S(cleanData_03_id) device.t = cD_03_T_0 ; // Operating temperature = Ambient temperature HEPSY_S(cleanData_03_id) device.r = cD_03_R_0 ; // Operating R_DS_On = Data-sheet R_DS_On // printf("Init %d \n",i); // } HEPSY_S(cleanData_03_id) return( EXIT_SUCCESS ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void cD_03_cleanData(int index, double sample[cD_03_SAMPLE_LEN]) {HEPSY_S(cleanData_03_id) // the parameter "index" could be useful to retrieve the characteristics of the device HEPSY_S(cleanData_03_id) if ( sample[cD_03_I_INDEX] < 0 ) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) sample[cD_03_I_INDEX] = 0 ; HEPSY_S(cleanData_03_id)} else if ( sample[cD_03_I_INDEX] > (2.0 * cD_03_I_0) ) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) sample[cD_03_I_INDEX] = (2.0 * cD_03_I_0) ; // Postcondition: (0 <= sample[I_INDEX] <= 2.0*I_0) HEPSY_S(cleanData_03_id)} HEPSY_S(cleanData_03_id) if ( sample[cD_03_V_INDEX] < 0 ) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) sample[cD_03_V_INDEX] = 0 ; HEPSY_S(cleanData_03_id)} else if ( sample[cD_03_V_INDEX] > (2.0 * cD_03_V_0 ) ) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) sample[cD_03_V_INDEX] = (2.0 * cD_03_V_0) ; // Postcondition: (0 <= sample[V_INDEX] <= 2.0*V_0) HEPSY_S(cleanData_03_id)} } //----------------------------------------------------------------------------- // 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_03_extractFeatures(double tPrev, double iPrev, double iNow, double rPrev) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) double t ; // Temperature HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) double i = 0.5*(iPrev + iNow); // Average current // printf("cD_03_extractFeatures tPrev=%f\n",tPrev); HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) t = tPrev + // Previous temperature rPrev * (i * i) * cD_03_Tau - // Heat generated: P = I·R^2 cD_03_ThermalConstant * (tPrev - cD_03_T_0) * cD_03_Tau ; // Dissipation and heat capacity HEPSY_S(cleanData_03_id) 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_03_degradationModel(double tNow) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) double r ; //r = R_0 + Alpha * tNow ; HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) r = cD_03_R_0 * ( 2 - exp(-cD_03_Alpha*tNow) ); HEPSY_S(cleanData_03_id) return( r ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void cD_03_normalize(int index, double sample[cD_03_ANN_INPUTS]) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) double i ; double v ; // Precondition: (0 <= sample[I_INDEX] <= 2*I_0) && (0 <= sample[V_INDEX] <= 2*V_0) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) i = sample[cD_03_I_INDEX] <= cD_03_I_0 ? 0.0 : 1.0; HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) v = sample[cD_03_V_INDEX] <= cD_03_V_0 ? 0.0 : 1.0; HEPSY_S(cleanData_03_id) // Postcondition: (i in {0.0, 1.0}) and (v in {0.0, 1.0}) HEPSY_S(cleanData_03_id) sample[cD_03_I_INDEX] = i ; HEPSY_S(cleanData_03_id) sample[cD_03_V_INDEX] = v ; } void mainsystem::cleanData_03_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_03_sample[cD_03_SAMPLE_LEN] ; double x[cD_03_ANN_INPUTS + cD_03_ANN_OUTPUTS] ; // NOTE: commented, should be changed param by ref... //cD_03_initDescriptors(cD_03_device); HEPSY_S(cleanData_03_id) cD_03_device.t = cD_03_T_0 ; // Operating temperature = Ambient temperature HEPSY_S(cleanData_03_id) cD_03_device.r = cD_03_R_0 ; // Operating R_DS_On = Data-sheet R_DS_On // ### added for time related dynamics //static double cD_03_Tau = 0.02 ; // [s] Sampling period HEPSY_S(cleanData_03_id) double cD_03_last_sample_time = 0; //implementation HEPSY_S(cleanData_03_id) while(1) {HEPSY_S(cleanData_03_id) // content HEPSY_S(cleanData_03_id) sampleTimCord_cleanData_xx_payload_var = sampleTimCord_cleanData_03_channel->read(); HEPSY_S(cleanData_03_id) dev = sampleTimCord_cleanData_xx_payload_var.dev; HEPSY_S(cleanData_03_id) step = sampleTimCord_cleanData_xx_payload_var.step; HEPSY_S(cleanData_03_id) ex_time = sampleTimCord_cleanData_xx_payload_var.ex_time; HEPSY_S(cleanData_03_id) sample_i = sampleTimCord_cleanData_xx_payload_var.sample_i; HEPSY_S(cleanData_03_id) sample_v = sampleTimCord_cleanData_xx_payload_var.sample_v; // cout << "cleanData_03 rcv \t dev: " << dev // <<"\t step: " << step // <<"\t time_ex:" << ex_time // <<"\t i:" << sample_i // <<"\t v:" << sample_v // << endl; // reconstruct sample HEPSY_S(cleanData_03_id) cD_03_sample[cD_03_I_INDEX] = sample_i; HEPSY_S(cleanData_03_id) cD_03_sample[cD_03_V_INDEX] = sample_v; HEPSY_S(cleanData_03_id) cD_03_sample[cD_03_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) HEPSY_S(cleanData_03_id) cD_03_cleanData(dev, cD_03_sample) ; HEPSY_S(cleanData_03_id) cD_03_device.time_Ex = cD_03_sample[cD_03_TIME_INDEX] ; HEPSY_S(cleanData_03_id) cD_03_device.i = cD_03_sample[cD_03_I_INDEX] ; HEPSY_S(cleanData_03_id) cD_03_device.v = cD_03_sample[cD_03_V_INDEX] ; // ### added for time related dynamics //static double cD_03_Tau = 0.02 ; // [s] Sampling period HEPSY_S(cleanData_03_id) cD_03_Tau = ex_time - cD_03_last_sample_time; HEPSY_S(cleanData_03_id) cD_03_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) HEPSY_S(cleanData_03_id) cD_03_device.t = cD_03_extractFeatures( cD_03_device.t, // Previous temperature cD_03_device.i, // Previous current cD_03_sample[cD_03_I_INDEX], // Current at this step cD_03_device.r) ; // Previous resistance // ### D E G R A D A T I O N M O D E L (compute R_DS_On) HEPSY_S(cleanData_03_id) cD_03_device.r = cD_03_degradationModel(cD_03_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}) HEPSY_S(cleanData_03_id) x[0] = cD_03_device.i ; HEPSY_S(cleanData_03_id) x[1] = cD_03_device.v ; HEPSY_S(cleanData_03_id) cD_03_normalize(dev, x) ; // // ### P R E D I C T (simple XOR) // if ( annRun(index, x) != EXIT_SUCCESS ){ //prepare out data payload HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.dev = dev; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.step = step; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.ex_time = ex_time; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.device_i = cD_03_device.i; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.device_v = cD_03_device.v; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.device_t = cD_03_device.t; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.device_r = cD_03_device.r; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.x_0 = x[0]; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.x_1 = x[1]; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.x_2 = x[2]; HEPSY_S(cleanData_03_id) cleanData_03_ann_03_channel->write(cleanData_xx_ann_xx_payload_var); HEPSY_P(cleanData_03_id) } } //END
/******************************************************************************* * clkgen.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Emulates the clocks on the ESP32. ******************************************************************************* * 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 "Arduino.h" #include "clkgen.h" void clkgen::gen() { bool lvl = false; while(true) { apb_clk.write(lvl); lvl = !lvl; del1cycle(); } }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_scalar_deviation_function_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_vector_multiplication_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_input_d_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_vector_adder_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { vector_adder vector_adder("VECTOR_ADDER"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_a_in[SIZE_I_IN]; sc_signal<sc_int<64>> data_b_in[SIZE_I_IN]; sc_signal<sc_int<64>> data_out[SIZE_I_IN]; vector_adder.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { vector_adder.data_a_in[i](data_a_in[i]); vector_adder.data_b_in[i](data_b_in[i]); vector_adder.data_out[i](data_out[i]); } for (int i = 0; i < SIZE_I_IN; i++) { data_a_in[i] = i; data_b_in[i] = i + 1; } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); for (int i = 0; i < SIZE_I_IN; i++) { cout << "@" << sc_time_stamp() << ": data_out[" << i << "] = " << data_out[i].read() << endl; } return 0; }
/* * 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 "hwcore/tb/cnn/tb_pe.hpp" #include <systemc.h> unsigned errors = 0; const char simulation_name[] = "tb_pe"; 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"); return 0; tb_pe<sizeof(int) * 8, sizeof(int) * 4, 1> tb_01("tb_pe"); cout << "INFO: Simulating " << simulation_name << endl; sc_time time_out(1000, SC_US); sc_start(time_out); return errors ? 1 : 0; cout << "INFO: end time is: " << sc_time_stamp().to_string() << ", and max time is: " << time_out.to_string() << std::endl << std::flush; sc_assert(sc_time_stamp() != time_out); cout << "INFO: Post-processing " << simulation_name << endl; cout << "INFO: Simulation " << simulation_name << " " << (errors ? "FAILED" : "PASSED") << " with " << errors << " errors" << std::endl << std::flush; #ifdef __RTL_SIMULATION__ cout << "HW cosim done" << endl; #endif return errors ? 1 : 0; } // test2
#include <systemc.h> class sc_clockx : sc_module, sc_interface { public: sc_event edge; sc_event change; bool val; bool _val; int delta; private: int period; SC_HAS_PROCESS(sc_clockx); void run(void) { int tmp = period/2; edge.notify(SC_ZERO_TIME); change.notify(SC_ZERO_TIME); while(true) { wait(tmp, SC_NS); edge.notify(SC_ZERO_TIME); change.notify(SC_ZERO_TIME); val = !val; } } public: sc_clockx(sc_module_name name, int periodparam): sc_module(name) { SC_THREAD(run); period = periodparam; val = true; _val = true; } bool read() { return val; } void write(bool newval) { _val = newval; if (!(_val == val)) request_update(); } void update() { if (!(_val == val)) { val = _val; change.notify(SC_ZERO_TIME); delta = sc_delta_count(); } } };
//--------Function definitions for classes os and os_task--------- //-----You must modify this file as indicated by TODO comments---- #include "systemc.h" #include "os.h" using namespace std; // implementation of os_task methods //placeholder constructor since we have a pool os_task::os_task() { } os_task::~os_task() { } void os_task::instantiate(sc_core::sc_process_handle handle, const char *name, unsigned int priority) { static unsigned int count = 0; task_name = name; // All tasks are initially ready when created task_state = READY; task_id = count; task_priority = priority; task_handle = handle; activation_flag = rd_suspended_flag = wr_suspended_flag = false; count++; } const char *os_task::get_name() { return task_name.data(); } enum state os_task::get_state() { return task_state; } unsigned int os_task::get_id() { return task_id; } unsigned int os_task::get_priority() { return task_priority; } sc_core::sc_process_handle os_task::get_handle() { return task_handle; } void os_task::activate() { // TODO: set the activation flag and notify the event activation_flag = true; activation_event.notify(); task_state = RUNNING; return; } void os_task::wait_for_activation() { // TODO: If the activation flag is not set, // TODO: wait for it to be set if (activation_flag == false) { wait(activation_event); } // TODO: reset the activation flag activation_flag = false; // TODO: update the task state //task_state = SUSPENDED; return; } //os class method implementation os::os() { // empty constructor } os::~os() { } // dynamic task creation function // this function is called by the main SC thread in the top module // it may also be called by tasks to dynamically create children os_task *os::task_create(const char* name, unsigned int priority, sc_core::sc_process_handle h) { // get a task object from the pool static int count = 0; os_task *t = &(task_pool[count++]); // TODO: instantiate the user task in the OS model t->instantiate(h, name, priority); // TODO: add the task to the ALL_TASKS list ALL_TASKS.push_back(t); //newly created task is in the ready state // TODO: add it to READY vector list READY_TASKS.push_back(t); // return the task pointer return t; } // task initialization function // this function is called by the SystemC thread // for the task, at the very beginning void os::task_init() { os_task *t = NULL; // TODO: find this task's pointer "t" static int count = 0; t = &(task_pool[count++]); // TODO: wait for the task to be scheduled by the OS t->wait_for_activation(); cout << sc_time_stamp() << ": Task " << t->get_name() << " is initialized" << endl; return; } // task termination function // this function is called by the running task // to terminate itself void os::task_terminate() { // TODO: update the state of the task os_task *t = CURRENT; t->task_state = TERMINATED; // TODO: do a rescheduling on remaining tasks schedule(); // TODO: wait till end of simulation if no tasks remain bool all_terminated = true; for (int i = 0; i < ALL_TASKS.size(); i++) { os_task *temp_t = ALL_TASKS[i]; if (temp_t->get_state() != TERMINATED) { all_terminated = false; break; } } if (all_terminated) { wait(); } } // this function displays the states of // all the tasks in the order of their creation // It is called by the OS schedule method // whenever a rescheduling takes place void os::status() { cout << endl << sc_time_stamp() << ": STATUS" << endl; for (int i = 0; i < ALL_TASKS.size(); i++) { os_task *t = ALL_TASKS[i]; cout << t->get_name() << ": "; if (t->get_state() == RUNNING) cout << "RUNNING" << endl; else if (t->get_state() == READY) cout << "READY" << endl; else if (t->get_state() == SUSPENDED) cout << "SUSPENDED" << endl; else if (t->get_state() == TERMINATED) cout << "TERMINATED" << endl; } } void os::time_wait(sc_time t) { // TODO: consume time on the SystemC scheduler wait(t); return; } // end time_wait ERROR os::schedule() { // TODO: If there are no tasks or all tasks have terminated // TODO: Print the status and return code E_NO_TASKS if (READY_TASKS.empty()) { status(); return E_NO_TASKS; } bool all_terminated = true; for (int i = 0; i < ALL_TASKS.size(); i++) { os_task *t = ALL_TASKS[i]; if (t->get_state() != TERMINATED) { all_terminated = false; break; } } if (all_terminated) { status(); return E_NO_TASKS; } // TODO: If all tasks are suspended, just display // TODO: the states and return code E_OK bool not_all_suspended = false; for (int i = 0; i < ALL_TASKS.size(); i++) { os_task *t = ALL_TASKS[i]; if (t->get_state() != SUSPENDED) { not_all_suspended = true; break; } } // otherwise, we have some scheduling to do! // TODO: find the highest priority ready task if (not_all_suspended) { // TODO: remove the highest priority task from the ready list // TODO: and activate it! unsigned int task_index = 0; unsigned int priority = READY_TASKS[0]->get_priority(); for (int i = 1; i < READY_TASKS.size(); i++) { os_task *t = READY_TASKS[i]; if (t->get_priority() > priority) { task_index = i; priority = t->get_priority(); } } CURRENT = READY_TASKS[task_index]; READY_TASKS.erase(READY_TASKS.begin() + task_index); CURRENT->activate(); } // print out the status of all the tasks status(); return E_OK; } // end schedule void os::run() { // all the initial tasks have been created // kickstart the scheduler cout << "Initializing Scheduler... " << endl; schedule(); }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_tensor_product_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { tensor_product tensor_product("TENSOR_PRODUCT"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; sc_signal<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; sc_signal<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN]; tensor_product.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { tensor_product.data_a_in[i][j][k](data_a_in[i][j][k]); tensor_product.data_b_in[i][j][k](data_b_in[i][j][k]); tensor_product.data_out[i][j][k](data_out[i][j][k]); } } } for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { data_a_in[i][j][k] = i + j + k; data_b_in[i][j][k] = i - j - k; } } } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); for (int i = 0; i < SIZE_I_IN; i++) { for (int j = 0; j < SIZE_J_IN; j++) { for (int k = 0; k < SIZE_K_IN; k++) { cout << "@" << sc_time_stamp() << ": data_out[" << i << ", " << j << ", " << k << "] = " << data_out[i][j][k].read() << endl; } } } return 0; }
// ================================================================ // NVDLA Open Source Project // // Copyright(c) 2016 - 2017 NVIDIA Corporation. Licensed under the // NVDLA Open Hardware License; Check "LICENSE" which comes with // this distribution for more information. // ================================================================ // File Name: cdp_hls_wrapper.cpp #include "log.h" #include "ac_int.h" #include "ac_channel.h" #include "log.h" #include <systemc.h> #include "arnvdla.h" #define __STDC_FORMAT_MACROS #include <inttypes.h> #include "vlibs.h" #include "cdp_hls_wrapper.h" #pragma CTC SKIP int half2single(void *target, void *source, int numel) { unsigned short *hp = (unsigned short *) source; // Type pun input as an unsigned 16-bit int unsigned int *xp = (unsigned int *) target; // Type pun output as an unsigned 32-bit int unsigned short h, hs, he, hm; unsigned int xs, xe, xm; int xes; int e; static int checkieee = 1; // Flag to check for IEEE754, Endian, and word size double one = 1.0; // Used for checking IEEE754 floating point format unsigned int *ip; // Used for checking IEEE754 floating point format if( checkieee ) { // 1st call, so check for IEEE754, Endian, and word size ip = (unsigned int *) &one; if( *ip ) { // If Big Endian, then no adjustment } else { // If Little Endian, then adjustment will be necessary ip++; } if( *ip != 0x3FF00000u ) { // Check for exact IEEE 754 bit pattern of 1.0 return 1; // Floating point bit pattern is not IEEE 754 } if( sizeof(short) != 2 || sizeof(int) != 4 ) { return 1; // short is not 16-bits, or long is not 32-bits. } checkieee = 0; // Everything checks out OK } if( source == NULL || target == NULL ) // Nothing to convert (e.g., imag part of pure real) return 0; while( numel-- ) { h = *hp++; if( (h & 0x7FFFu) == 0 ) { // Signed zero *xp++ = ((unsigned int) h) << 16; // Return the signed zero } else { // Not zero hs = h & 0x8000u; // Pick off sign bit he = h & 0x7C00u; // Pick off exponent bits hm = h & 0x03FFu; // Pick off mantissa bits if( he == 0 ) { // Denormal will convert to normalized e = -1; // The following loop figures out how much extra to adjust the exponent do { e++; hm <<= 1; } while( (hm & 0x0400u) == 0 ); // Shift until leading bit overflows into exponent bit xs = ((unsigned int) hs) << 16; // Sign bit xes = ((int) (he >> 10)) - 15 + 127 - e; // Exponent unbias the halfp, then bias the single xe = (unsigned int) (xes << 23); // Exponent xm = ((unsigned int) (hm & 0x03FFu)) << 13; // Mantissa *xp++ = (xs | xe | xm); // Combine sign bit, exponent bits, and mantissa bits } else if( he == 0x7C00u ) { // Inf or NaN (all the exponent bits are set) if( hm == 0 ) { // If mantissa is zero ... *xp++ = (((unsigned int) hs) << 16) | ((unsigned int) 0x7F800000u); // Signed Inf } else { *xp++ = (unsigned int) 0xFFC00000u; // NaN, only 1st mantissa bit set } } else { // Normalized number xs = ((unsigned int) hs) << 16; // Sign bit xes = ((int) (he >> 10)) - 15 + 127; // Exponent unbias the halfp, then bias the single xe = (unsigned int) (xes << 23); // Exponent xm = ((unsigned int) hm) << 13; // Mantissa *xp++ = (xs | xe | xm); // Combine sign bit, exponent bits, and mantissa bits } } } return 0; } int single2half(void *target, void *source, int numel) { unsigned short *hp = (unsigned short *) target; // Type pun output as an unsigned 16-bit int unsigned int *xp = (unsigned int *) source; // Type pun input as an unsigned 32-bit int unsigned short hs, he, hm; unsigned int x, xs, xe, xm; int hes; static int checkieee = 1; // Flag to check for IEEE754, Endian, and word size double one = 1.0; // Used for checking IEEE754 floating point format unsigned int *ip; // Used for checking IEEE754 floating point format if( checkieee ) { // 1st call, so check for IEEE754, Endian, and word size ip = (unsigned int *) &one; if( *ip ) { // If Big Endian, then no adjustment } else { // If Little Endian, then adjustment will be necessary ip++; } if( *ip != 0x3FF00000u ) { // Check for exact IEEE 754 bit pattern of 1.0 return 1; // Floating point bit pattern is not IEEE 754 } if( sizeof(short) != 2 || sizeof(int) != 4 ) { return 1; // short is not 16-bits, or long is not 32-bits. } checkieee = 0; // Everything checks out OK } if( source == NULL || target == NULL ) { // Nothing to convert (e.g., imag part of pure real) return 0; } while( numel-- ) { x = *xp++; if( (x & 0x7FFFFFFFu) == 0 ) { // Signed zero *hp++ = (unsigned short) (x >> 16); // Return the signed zero } else { // Not zero xs = x & 0x80000000u; // Pick off sign bit xe = x & 0x7F800000u; // Pick off exponent bits xm = x & 0x007FFFFFu; // Pick off mantissa bits if( xe == 0 ) { // Denormal will underflow, return a signed zero *hp++ = (unsigned short) (xs >> 16); } else if( xe == 0x7F800000u ) { // Inf or NaN (all the exponent bits are set) if( xm == 0 ) { // If mantissa is zero ... *hp++ = (unsigned short) ((xs >> 16) | 0x7C00u); // Signed Inf } else { *hp++ = (unsigned short) 0xFE00u; // NaN, only 1st mantissa bit set } } else { // Normalized number hs = (unsigned short) (xs >> 16); // Sign bit hes = ((int)(xe >> 23)) - 127 + 15; // Exponent unbias the single, then bias the halfp if( hes >= 0x1F ) { // Overflow *hp++ = (unsigned short) ((xs >> 16) | 0x7C00u); // Signed Inf } else if( hes <= 0 ) { // Underflow if( (14 - hes) > 24 ) { // Mantissa shifted all the way off & no rounding possibility hm = (unsigned short) 0u; // Set mantissa to zero } else { xm |= 0x00800000u; // Add the hidden leading bit hm = (unsigned short) (xm >> (14 - hes)); // Mantissa if( (xm >> (13 - hes)) & 0x00000001u ) // Check for rounding hm += (unsigned short) 1u; // Round, might overflow into exp bit, but this is OK } *hp++ = (hs | hm); // Combine sign bit and mantissa bits, biased exponent is zero } else { he = (unsigned short) (hes << 10); // Exponent hm = (unsigned short) (xm >> 13); // Mantissa if( xm & 0x00001000u ) // Check for rounding *hp++ = (hs | he | hm) + (unsigned short) 1u; // Round, might overflow to inf, this is OK else *hp++ = (hs | he | hm); // No rounding } } } } return 0; } #pragma CTC ENDSKIP // Inputs: 12 HLS_FP17 after icvt // Outputs: 1 HLS_FP17 after Interplolation void HLS_CDP_lookup_lut ( vFp32Type square_sum, uint16_t lut_upper_index, bool le, // True: linear_exp table bool exp_mode, // Only for linear_exp table int16_t* lut, // LUT table uint64_t lut_start, uint64_t lut_end, int16_t slope_uflow_scale, // It's accutally signed value int16_t slope_oflow_scale, int16_t index_offset, int8_t index_select, // Outputs bool & underflow, bool & overflow, bool & lut_hit, ac_channel<vFp17Type> & chn_result_fp17) { #if !ASSERT_WAR_CONSTRAIN // assert(density_end - pow(2, cdp_lut_lo_index_select_ + 8) == density_start); #endif // Variables for sub input_offset vFp32Type lut_start_fp32, lut_end_fp32; vFp32Type lut_sub_result_fp32; ac_channel<vFp32Type> chn_square_sum_fp32; ac_channel<vFp32Type> chn_lut_start_fp32, chn_lut_end_fp32; ac_channel<vFp32Type> chn_lut_sub_result_fp32; ac_channel<vFp17Type> chn_lut_sub_result_fp17; float lut_sub_result_float; float lut_shifted; uint16_t lut_offset; int32_t lut_index; ac_channel<vFp17Type> chn_lut_offset_fp17; // Varibales for underflow/overflow vFp16Type slope_fp16; ac_channel<vFp16Type> chn_slope_fp16; ac_channel<vFp17Type> chn_slope_fp17; ac_channel<vFp17Type> chn_lo_sub_result_fp17; ac_channel<vFp17Type> chn_mul_result_fp17; ac_channel<vFp17Type> chn_result_lut_underflow; ac_channel<vFp17Type> chn_result_lut_overflow; // Variables for Interpolation uint16_t result_0, result_1; vFp16Type result_0_fp16, result_1_fp16; ac_channel<vFp16Type> chn_result_0_fp16, chn_result_1_fp16; vFp32Type result_0_fp32, result_1_fp32; ac_channel<vFp32Type> chn_result_0_fp32, chn_result_1_fp32; ac_channel<vFp17Type> chn_result_0_fp17; ac_channel<vFp17Type> chn_result_1_fp17; // ac_channel<vFp17Type> chn_result_underflow_fp17; // ac_channel<vFp17Type> chn_result_overflow_fp17; ac_channel<vFp32Type> chn_L1_minus_L0_fp32; ac_channel<vFp17Type> chn_L1_minus_L0_fp17; ac_channel<vFp17Type> chn_result_lut_tmp; //-------------------------------------------- underflow = false; overflow = false; //exp_underflow = false; //exp_overflow = false; lut_hit = false; //-------------------------------------------- // 1. sub offset lut_start_fp32 = lut_start; chn_lut_start_fp32.write(lut_start_fp32); chn_square_sum_fp32.write(square_sum); HLS_fp32_sub(chn_square_sum_fp32, chn_lut_start_fp32, chn_lut_sub_result_fp32); lut_sub_result_fp32 = chn_lut_sub_result_fp32.read(); lut_sub_result_float = *(float *)(&lut_sub_result_fp32); // vFp32Type is actually integer type cslDebug((70, "lut_start=0x%x, lut_sub_result=0x%x\n", (uint32_t)lut_start_fp32, (uint32_t)lut_sub_result_fp32)); if(lut_sub_result_float <= 0 || std::isnan(lut_sub_result_float)) { underflow = true; } if (!underflow) { if (le && exp_mode) { // Log2. If lo_sub_result_float is 0, exp will be 0 uint32_t tmp_uint32 = *(uint32_t*)(&lut_sub_result_float); int32_t exp_raw = (tmp_uint32 >> 23) & 0xff; // 8bits //int32_t exp = (exp_raw == 0)? 0 : exp_raw - 127; int32_t exp = exp_raw - 127; lut_index = exp - index_offset; lut_offset = (tmp_uint32 >> 7) & 0xffff; if(lut_index < 0) { lut_offset >>= -lut_index; lut_index = 0; underflow = true; } else if (lut_index >= lut_upper_index) { overflow = true; } cslDebug((70, "exp=%d, index_offset=%d, lut_index=%d, lut_offset=%d\n", exp, index_offset, lut_index, lut_offset)); } else { // lo or (le && linear_mode) // To int and Shift using float of C++ // In RTL, HLS is not used in below code if(index_select >= 0) lut_shifted = lut_sub_result_float / pow(2, index_select); else lut_shifted = lut_sub_result_float * pow(2, -index_select); overflow = lut_shifted >= lut_upper_index; lut_index = lut_shifted; lut_offset = (lut_shifted - int32_t(lut_shifted)) * 0x10000; // 16 MSB bits of fraction cslDebug((70, "index_select=%d, lut_shifted=%f, lut_index=%d, lut_offset=%d\n", index_select, lut_shifted, lut_index, lut_offset)); } } // Convert Fraction from special INT16 to HLS_FP17 vU16Type lut_offset_u16 = lut_offset; ac_channel<vU16Type> chn_lut_offset_u16; chn_lut_offset_u16.write(lut_offset_u16); HLS_uint16_to_fp17(chn_lut_offset_u16, chn_lut_offset_fp17); //if ((underflow || (le&&exp_underflow))) { if (underflow) { result_0 = lut[0]; result_0_fp16 = result_0; chn_result_0_fp16.write(result_0_fp16); cslDebug((70, "L0=0x%x\n", result_0)); // Convert result_lo_0 of HLS FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_result_0_fp16, chn_result_0_fp17); slope_fp16 = (int16_t)slope_uflow_scale; chn_slope_fp16.write(slope_fp16); // Convert FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_slope_fp16, chn_slope_fp17); // Convert FP32 to HLS_FP17 if(le && exp_mode) { float offset; #pragma CTC SKIP if(index_offset <= -127) { offset = 0; } #pragma CTC ENDSKIP else { offset = pow(2, index_offset); } ac_channel<vFp32Type> chn_offset, chn_offset_adj; chn_offset.write(*(vFp32Type *)(&offset)); chn_lut_start_fp32.write(lut_start_fp32); HLS_fp32_add(chn_lut_start_fp32, chn_offset, chn_offset_adj); chn_square_sum_fp32.write(square_sum); HLS_fp32_sub(chn_square_sum_fp32, chn_offset_adj, chn_lut_sub_result_fp32); } else { chn_lut_sub_result_fp32.write(lut_sub_result_fp32); } HLS_fp32_to_fp17(chn_lut_sub_result_fp32, chn_lut_sub_result_fp17); // chn_gap * slope HLS_fp17_mul(chn_lut_sub_result_fp17, chn_slope_fp17, chn_mul_result_fp17); HLS_fp17_add(chn_mul_result_fp17, chn_result_0_fp17, chn_result_fp17); } //else if ((overflow || (le&&exp_overflow))) { else if (overflow) { result_1 = lut[lut_upper_index]; result_1_fp16 = result_1; chn_result_1_fp16.write(result_1_fp16); cslDebug((70, "L1=0x%x\n", result_1)); // Convert result_lo_0 of HLS FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_result_1_fp16, chn_result_1_fp17); slope_fp16 = (int16_t)slope_oflow_scale; chn_slope_fp16.write(slope_fp16); // Convert FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_slope_fp16, chn_slope_fp17); // Convert FP32 to HLS_FP17 lut_end_fp32 = lut_end; chn_lut_end_fp32.write(lut_end_fp32); chn_square_sum_fp32.write(square_sum); HLS_fp32_sub(chn_square_sum_fp32, chn_lut_end_fp32, chn_lut_sub_result_fp32); HLS_fp32_to_fp17(chn_lut_sub_result_fp32, chn_lut_sub_result_fp17); // chn_gap * slope HLS_fp17_mul(chn_lut_sub_result_fp17, chn_slope_fp17, chn_mul_result_fp17); HLS_fp17_add(chn_mul_result_fp17, chn_result_1_fp17, chn_result_fp17); } else { result_0 = lut[lut_index]; result_1 = lut[lut_index+1]; result_0_fp16 = result_0; result_1_fp16 = result_1; chn_result_0_fp16.write(result_0_fp16); chn_result_1_fp16.write(result_1_fp16); cslDebug((70, "L0=0x%x, L1=0x%x\n", result_0, result_1)); // Convert HLS_FP16 to HLS_FP32 HLS_fp16_to_fp32(chn_result_0_fp16, chn_result_0_fp32); HLS_fp16_to_fp32(chn_result_1_fp16, chn_result_1_fp32); // Convert result_lo_0 of HLS FP16 to HLS_FP17 chn_result_0_fp16.write(result_0_fp16); HLS_fp16_to_fp17(chn_result_0_fp16, chn_result_0_fp17); // Interpolation HLS_fp32_sub(chn_result_1_fp32, chn_result_0_fp32, chn_L1_minus_L0_fp32); //vFp32Type L1_minus_L0_fp32 = chn_L1_minus_L0_fp32.read(); //cslDebug((70,"L1_minus_L0_fp32=0x%x\n", L1_minus_L0_fp32)); //chn_L1_minus_L0_fp32.write(L1_minus_L0_fp32); HLS_fp32_to_fp17(chn_L1_minus_L0_fp32, chn_L1_minus_L0_fp17); HLS_fp17_mul(chn_L1_minus_L0_fp17, chn_lut_offset_fp17, chn_result_lut_tmp); HLS_fp17_add(chn_result_lut_tmp, chn_result_0_fp17, chn_result_fp17); lut_hit = true; /* float L0_float, L1_float, L1_minus_L0_float, result_float; half2single(&L0_float,&result_0_fp16, 1); cslDebug((70,"L0: %f(0x%x)\n", L0_float, *(int *)(&L0_float) )); half2single(&L1_float,&result_1_fp16, 1); cslDebug((70,"L1: %f(0x%x)\n", L1_float, *(int *)(&L1_float) )); L1_minus_L0_float = L1_float - L0_float; cslDebug((70,"L1-L1: %f(0x%x)\n", L1_minus_L0_float, *(int *)(&L1_minus_L0_float) )); result_float = L0_float + L1_minus_L0_float * lut_offset; cslDebug((70,"result: %f(0x%x)\n", result_float, *(int *)(&result_float) ));*/ } } void HLS_CDP_lookup_fp16 ( int16_t *data_in, // 12 * fp17 int16_t *le_lut, int16_t *lo_lut, // Configurations uint16_t normalz_len, uint16_t raw_method, bool lut_uflow_priority, bool lut_oflow_priority, bool lut_hybrid_priority, uint64_t le_start, int16_t le_index_offset, int8_t le_index_select, uint64_t le_end, uint64_t lo_start, int8_t lo_index_select, uint64_t lo_end, uint16_t datin_offset, uint16_t datin_scale, uint8_t datin_shifter, uint32_t datout_offset, uint16_t datout_scale, uint8_t datout_shifter, int16_t le_slope_uflow_scale, int16_t le_slope_oflow_scale, int16_t lo_slope_uflow_scale, int16_t lo_slope_oflow_scale, bool sqsum_bypass, bool mul_bypass, int16_t *normalz_out, uint32_t *lut_u_flow, uint32_t *lut_o_flow, uint32_t *lut_le_hit, uint32_t *lut_lo_hit, uint32_t *lut_hybrid_hit) // 16bits { int i; // Outputs bool le_underflow; bool le_overflow; //bool exp_underflow; //bool exp_overflow; bool lo_underflow; bool lo_overflow; bool le_hit; bool lo_hit; // Variables int32_t icvt_data_out[12]; ac_channel<vFp32Type> fp17tofp32_out[12]; ac_channel<vFp32Type> square_array[12]; //ac_channel<vFp32Type> square_sum; vFp32Type square_result[12]; // Outputs of lut tables ac_channel<vFp17Type> chn_result_le_fp17; ac_channel<vFp17Type> chn_result_lo_fp17; // ac_channel<vFp17Type> chn_result_fp17; ac_channel<vFp17Type> chn_result_to_ocvt_fp17; ac_channel<vFp17Type> chn_ocvt_out_fp17; #if 0 // Initialization le_underflow = false; le_overflow = false; exp_underflow = false; exp_overflow = false; lo_underflow = false; lo_overflow = false; le_hit = false; lo_hit = false; #endif vFp32Type icvt_data_out_fp32[12]; float tmp[12], din_offset, din_scale; half2single(&din_offset, &datin_offset, 1); half2single(&din_scale, &datin_scale, 1); cslDebug((70, "Data before input converter(float)\n")); for(i=0; i<12; i++) { half2single(&tmp[i], &data_in[i], 1); cslDebug((70, "%f(0x%x) ", tmp[i], *(int *)(&tmp[i]) )); } cslDebug((70, "\n")); cslDebug((70, "Data after square(float)\n")); for(i=0; i<12; i++) { tmp[i] = tmp[i] * tmp[i]; cslDebug((70, "%f(0x%x) ", tmp[i], *(int *)(&tmp[i]) )); } cslDebug((70, "\n")); for(i=0; i<12; i++) { //***** Input Convertor (FP16->FP17) ****** cdp_icvt_hls(&data_in[i], datin_offset, datin_scale, datin_shifter, NVDLA_CDP_RDMA_D_DATA_FORMAT_0_INPUT_DATA_FP16, &icvt_data_out[i]);
//***** Convert FP17 to FP32 ****** ac_channel<vFp17Type> chn_a; chn_a.write(icvt_data_out[i]); HLS_fp17_to_fp32(chn_a, fp17tofp32_out[i]); icvt_data_out_fp32[i] = fp17tofp32_out[i].read(); ac_channel<vFp32Type> chn_b, chn_c; chn_b.write(icvt_data_out_fp32[i]); chn_c.write(icvt_data_out_fp32[i]); if(sqsum_bypass) { square_result[i] = icvt_data_out_fp32[i]; } else { HLS_fp32_mul(chn_b, chn_c, square_array[i]); // HLS_FP32 mul square_result[i] = square_array[i].read(); //keep data to re-write the square_array later } } // cslDebug((70, "Data after input convertor(FP17):\n")); // for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&icvt_data_out[i]) )); // cslDebug((70, "\n")); cslDebug((70, "Data after input convertor(FP32):\n")); for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&icvt_data_out_fp32[i]) )); cslDebug((70, "\n")); cslDebug((70, "Data after square:\n")); for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&square_result[i]) )); cslDebug((70, "\n")); //***** Per Element ****** for (i=0; i<4; i++) { le_underflow = false; le_overflow = false; //exp_underflow = false; //exp_overflow = false; lo_underflow = false; lo_overflow = false; le_hit = false; lo_hit = false; //re-write square_array in each iteration since it is empty after read for(int j=0; j<12; j++) square_array[j].write(square_result[j]); //***** Sum ****** vFp32Type square_sum_result; if(sqsum_bypass) { square_sum_result = square_array[i+4].read(); } else { ac_channel<vFp32Type> square_sum_1, square_sum_2; HLS_fp32_add(square_array[i+3], square_array[i+5], square_sum_1); //3 + 5 HLS_fp32_add(square_sum_1, square_array[i+4], square_sum_2); //sum3 = (3 + 5) + 4 ac_channel<vFp32Type> square_sum_3, square_sum_4; if(normalz_len > 0) //5+ elements { HLS_fp32_add(square_array[i+2], square_array[i+6], square_sum_3); //2 + 6 HLS_fp32_add(square_sum_2, square_sum_3, square_sum_4); //sum5 = sum3 + (2 + 6) } ac_channel<vFp32Type> square_sum_5, square_sum_6; if(normalz_len > 1) //7+ elements { HLS_fp32_add(square_array[i+1], square_array[i+7], square_sum_5); //1 + 7 HLS_fp32_add(square_sum_4, square_sum_5, square_sum_6); //sum7 = sum5 + (1 + 7) } ac_channel<vFp32Type> square_sum_7, square_sum_8; if(normalz_len > 2) //9 elements { HLS_fp32_add(square_array[i+0], square_array[i+8], square_sum_7); //1 + 7 HLS_fp32_add(square_sum_6, square_sum_7, square_sum_8); //sum9 = sum7 + (0 + 8) } switch(normalz_len) { case 0: square_sum_result = square_sum_2.read(); break; case 1: square_sum_result = square_sum_4.read(); break; case 2: square_sum_result = square_sum_6.read(); break; case 3: square_sum_result = square_sum_8.read(); break; #pragma CTC SKIP default: break; #pragma CTC ENDSKIP } } cslDebug((70, "Square sum: %x\n", *(int *)(&square_sum_result) )); // Look up Raw table if(NVDLA_CDP_S_LUT_CFG_0_LUT_LE_FUNCTION_EXPONENT == raw_method) { //raw lut is exponential cslDebug((70, "Lookup exp table\n")); HLS_CDP_lookup_lut(square_sum_result, 64, true, true, le_lut, le_start, le_end, le_slope_uflow_scale, le_slope_oflow_scale, le_index_offset, le_index_select, le_underflow, le_overflow, le_hit, chn_result_le_fp17); } else { // raw lut is linear cslDebug((70, "Lookup lin table\n")); HLS_CDP_lookup_lut(square_sum_result, 64, true, false, le_lut, le_start, le_end, le_slope_uflow_scale, le_slope_oflow_scale, le_index_offset, le_index_select, le_underflow, le_overflow, le_hit, chn_result_le_fp17); } cslDebug((70, "Lookup lo table\n")); // Look up LO(Linear Only) table HLS_CDP_lookup_lut(square_sum_result, 256, false, false, lo_lut, lo_start, lo_end, lo_slope_uflow_scale, lo_slope_oflow_scale, 0, lo_index_select, lo_underflow, lo_overflow, lo_hit, chn_result_lo_fp17); vFp17Type result_le = chn_result_le_fp17.read(); vFp17Type result_lo = chn_result_lo_fp17.read(); vFp17Type result_out; // Select result between RAW table and Density Table if(le_underflow && lo_underflow) { result_out = lut_uflow_priority? result_lo : result_le; (*lut_u_flow)++; } else if(le_overflow && lo_overflow) { result_out = lut_oflow_priority? result_lo : result_le; (*lut_o_flow)++; } else { if(le_hit ^ lo_hit) { result_out = le_hit? result_le : result_lo; if(le_hit) { (*lut_le_hit)++; } else { (*lut_lo_hit)++; } } else { if(lut_hybrid_priority) result_out = result_lo; else result_out = result_le; (*lut_hybrid_hit)++; } } cslDebug((70, "le:%x, lo:%x, out:%x\n" , *(int *)(&result_le), *(int *)(&result_lo), *(int *)(&result_out) )); if(mul_bypass) { float icvt_data_out_float = *(float *)&icvt_data_out_fp32[i+4]; if(std::isnan(icvt_data_out_float)) { chn_result_to_ocvt_fp17.write(icvt_data_out[i+4]); } else { chn_result_to_ocvt_fp17.write(result_out); } } else { ac_channel<vFp17Type> chn_result_fp17, chn_icvt_data_out_fp17; chn_result_fp17.write(result_out); vFp17Type icvt_data_out_fp17 = icvt_data_out[i+4]; chn_icvt_data_out_fp17.write(icvt_data_out_fp17); HLS_fp17_mul(chn_icvt_data_out_fp17, chn_result_fp17, chn_result_to_ocvt_fp17); } // Output Converter int64_t ocvt_data_in = chn_result_to_ocvt_fp17.read(); cslDebug((70, "ocvt_data_in:%x\n", (int)ocvt_data_in)); uint8_t flag; cdp_ocvt_hls(&ocvt_data_in, datout_offset, datout_scale, datout_shifter, NVDLA_CDP_RDMA_D_DATA_FORMAT_0_INPUT_DATA_FP16, &normalz_out[i], &flag); } }
// ================================================================ // NVDLA Open Source Project // // Copyright(c) 2016 - 2017 NVIDIA Corporation. Licensed under the // NVDLA Open Hardware License; Check "LICENSE" which comes with // this distribution for more information. // ================================================================ // File Name: cdp_hls_wrapper.cpp #include "log.h" #include "ac_int.h" #include "ac_channel.h" #include "log.h" #include <systemc.h> #include "arnvdla.h" #define __STDC_FORMAT_MACROS #include <inttypes.h> #include "vlibs.h" #include "cdp_hls_wrapper.h" #pragma CTC SKIP int half2single(void *target, void *source, int numel) { unsigned short *hp = (unsigned short *) source; // Type pun input as an unsigned 16-bit int unsigned int *xp = (unsigned int *) target; // Type pun output as an unsigned 32-bit int unsigned short h, hs, he, hm; unsigned int xs, xe, xm; int xes; int e; static int checkieee = 1; // Flag to check for IEEE754, Endian, and word size double one = 1.0; // Used for checking IEEE754 floating point format unsigned int *ip; // Used for checking IEEE754 floating point format if( checkieee ) { // 1st call, so check for IEEE754, Endian, and word size ip = (unsigned int *) &one; if( *ip ) { // If Big Endian, then no adjustment } else { // If Little Endian, then adjustment will be necessary ip++; } if( *ip != 0x3FF00000u ) { // Check for exact IEEE 754 bit pattern of 1.0 return 1; // Floating point bit pattern is not IEEE 754 } if( sizeof(short) != 2 || sizeof(int) != 4 ) { return 1; // short is not 16-bits, or long is not 32-bits. } checkieee = 0; // Everything checks out OK } if( source == NULL || target == NULL ) // Nothing to convert (e.g., imag part of pure real) return 0; while( numel-- ) { h = *hp++; if( (h & 0x7FFFu) == 0 ) { // Signed zero *xp++ = ((unsigned int) h) << 16; // Return the signed zero } else { // Not zero hs = h & 0x8000u; // Pick off sign bit he = h & 0x7C00u; // Pick off exponent bits hm = h & 0x03FFu; // Pick off mantissa bits if( he == 0 ) { // Denormal will convert to normalized e = -1; // The following loop figures out how much extra to adjust the exponent do { e++; hm <<= 1; } while( (hm & 0x0400u) == 0 ); // Shift until leading bit overflows into exponent bit xs = ((unsigned int) hs) << 16; // Sign bit xes = ((int) (he >> 10)) - 15 + 127 - e; // Exponent unbias the halfp, then bias the single xe = (unsigned int) (xes << 23); // Exponent xm = ((unsigned int) (hm & 0x03FFu)) << 13; // Mantissa *xp++ = (xs | xe | xm); // Combine sign bit, exponent bits, and mantissa bits } else if( he == 0x7C00u ) { // Inf or NaN (all the exponent bits are set) if( hm == 0 ) { // If mantissa is zero ... *xp++ = (((unsigned int) hs) << 16) | ((unsigned int) 0x7F800000u); // Signed Inf } else { *xp++ = (unsigned int) 0xFFC00000u; // NaN, only 1st mantissa bit set } } else { // Normalized number xs = ((unsigned int) hs) << 16; // Sign bit xes = ((int) (he >> 10)) - 15 + 127; // Exponent unbias the halfp, then bias the single xe = (unsigned int) (xes << 23); // Exponent xm = ((unsigned int) hm) << 13; // Mantissa *xp++ = (xs | xe | xm); // Combine sign bit, exponent bits, and mantissa bits } } } return 0; } int single2half(void *target, void *source, int numel) { unsigned short *hp = (unsigned short *) target; // Type pun output as an unsigned 16-bit int unsigned int *xp = (unsigned int *) source; // Type pun input as an unsigned 32-bit int unsigned short hs, he, hm; unsigned int x, xs, xe, xm; int hes; static int checkieee = 1; // Flag to check for IEEE754, Endian, and word size double one = 1.0; // Used for checking IEEE754 floating point format unsigned int *ip; // Used for checking IEEE754 floating point format if( checkieee ) { // 1st call, so check for IEEE754, Endian, and word size ip = (unsigned int *) &one; if( *ip ) { // If Big Endian, then no adjustment } else { // If Little Endian, then adjustment will be necessary ip++; } if( *ip != 0x3FF00000u ) { // Check for exact IEEE 754 bit pattern of 1.0 return 1; // Floating point bit pattern is not IEEE 754 } if( sizeof(short) != 2 || sizeof(int) != 4 ) { return 1; // short is not 16-bits, or long is not 32-bits. } checkieee = 0; // Everything checks out OK } if( source == NULL || target == NULL ) { // Nothing to convert (e.g., imag part of pure real) return 0; } while( numel-- ) { x = *xp++; if( (x & 0x7FFFFFFFu) == 0 ) { // Signed zero *hp++ = (unsigned short) (x >> 16); // Return the signed zero } else { // Not zero xs = x & 0x80000000u; // Pick off sign bit xe = x & 0x7F800000u; // Pick off exponent bits xm = x & 0x007FFFFFu; // Pick off mantissa bits if( xe == 0 ) { // Denormal will underflow, return a signed zero *hp++ = (unsigned short) (xs >> 16); } else if( xe == 0x7F800000u ) { // Inf or NaN (all the exponent bits are set) if( xm == 0 ) { // If mantissa is zero ... *hp++ = (unsigned short) ((xs >> 16) | 0x7C00u); // Signed Inf } else { *hp++ = (unsigned short) 0xFE00u; // NaN, only 1st mantissa bit set } } else { // Normalized number hs = (unsigned short) (xs >> 16); // Sign bit hes = ((int)(xe >> 23)) - 127 + 15; // Exponent unbias the single, then bias the halfp if( hes >= 0x1F ) { // Overflow *hp++ = (unsigned short) ((xs >> 16) | 0x7C00u); // Signed Inf } else if( hes <= 0 ) { // Underflow if( (14 - hes) > 24 ) { // Mantissa shifted all the way off & no rounding possibility hm = (unsigned short) 0u; // Set mantissa to zero } else { xm |= 0x00800000u; // Add the hidden leading bit hm = (unsigned short) (xm >> (14 - hes)); // Mantissa if( (xm >> (13 - hes)) & 0x00000001u ) // Check for rounding hm += (unsigned short) 1u; // Round, might overflow into exp bit, but this is OK } *hp++ = (hs | hm); // Combine sign bit and mantissa bits, biased exponent is zero } else { he = (unsigned short) (hes << 10); // Exponent hm = (unsigned short) (xm >> 13); // Mantissa if( xm & 0x00001000u ) // Check for rounding *hp++ = (hs | he | hm) + (unsigned short) 1u; // Round, might overflow to inf, this is OK else *hp++ = (hs | he | hm); // No rounding } } } } return 0; } #pragma CTC ENDSKIP // Inputs: 12 HLS_FP17 after icvt // Outputs: 1 HLS_FP17 after Interplolation void HLS_CDP_lookup_lut ( vFp32Type square_sum, uint16_t lut_upper_index, bool le, // True: linear_exp table bool exp_mode, // Only for linear_exp table int16_t* lut, // LUT table uint64_t lut_start, uint64_t lut_end, int16_t slope_uflow_scale, // It's accutally signed value int16_t slope_oflow_scale, int16_t index_offset, int8_t index_select, // Outputs bool & underflow, bool & overflow, bool & lut_hit, ac_channel<vFp17Type> & chn_result_fp17) { #if !ASSERT_WAR_CONSTRAIN // assert(density_end - pow(2, cdp_lut_lo_index_select_ + 8) == density_start); #endif // Variables for sub input_offset vFp32Type lut_start_fp32, lut_end_fp32; vFp32Type lut_sub_result_fp32; ac_channel<vFp32Type> chn_square_sum_fp32; ac_channel<vFp32Type> chn_lut_start_fp32, chn_lut_end_fp32; ac_channel<vFp32Type> chn_lut_sub_result_fp32; ac_channel<vFp17Type> chn_lut_sub_result_fp17; float lut_sub_result_float; float lut_shifted; uint16_t lut_offset; int32_t lut_index; ac_channel<vFp17Type> chn_lut_offset_fp17; // Varibales for underflow/overflow vFp16Type slope_fp16; ac_channel<vFp16Type> chn_slope_fp16; ac_channel<vFp17Type> chn_slope_fp17; ac_channel<vFp17Type> chn_lo_sub_result_fp17; ac_channel<vFp17Type> chn_mul_result_fp17; ac_channel<vFp17Type> chn_result_lut_underflow; ac_channel<vFp17Type> chn_result_lut_overflow; // Variables for Interpolation uint16_t result_0, result_1; vFp16Type result_0_fp16, result_1_fp16; ac_channel<vFp16Type> chn_result_0_fp16, chn_result_1_fp16; vFp32Type result_0_fp32, result_1_fp32; ac_channel<vFp32Type> chn_result_0_fp32, chn_result_1_fp32; ac_channel<vFp17Type> chn_result_0_fp17; ac_channel<vFp17Type> chn_result_1_fp17; // ac_channel<vFp17Type> chn_result_underflow_fp17; // ac_channel<vFp17Type> chn_result_overflow_fp17; ac_channel<vFp32Type> chn_L1_minus_L0_fp32; ac_channel<vFp17Type> chn_L1_minus_L0_fp17; ac_channel<vFp17Type> chn_result_lut_tmp; //-------------------------------------------- underflow = false; overflow = false; //exp_underflow = false; //exp_overflow = false; lut_hit = false; //-------------------------------------------- // 1. sub offset lut_start_fp32 = lut_start; chn_lut_start_fp32.write(lut_start_fp32); chn_square_sum_fp32.write(square_sum); HLS_fp32_sub(chn_square_sum_fp32, chn_lut_start_fp32, chn_lut_sub_result_fp32); lut_sub_result_fp32 = chn_lut_sub_result_fp32.read(); lut_sub_result_float = *(float *)(&lut_sub_result_fp32); // vFp32Type is actually integer type cslDebug((70, "lut_start=0x%x, lut_sub_result=0x%x\n", (uint32_t)lut_start_fp32, (uint32_t)lut_sub_result_fp32)); if(lut_sub_result_float <= 0 || std::isnan(lut_sub_result_float)) { underflow = true; } if (!underflow) { if (le && exp_mode) { // Log2. If lo_sub_result_float is 0, exp will be 0 uint32_t tmp_uint32 = *(uint32_t*)(&lut_sub_result_float); int32_t exp_raw = (tmp_uint32 >> 23) & 0xff; // 8bits //int32_t exp = (exp_raw == 0)? 0 : exp_raw - 127; int32_t exp = exp_raw - 127; lut_index = exp - index_offset; lut_offset = (tmp_uint32 >> 7) & 0xffff; if(lut_index < 0) { lut_offset >>= -lut_index; lut_index = 0; underflow = true; } else if (lut_index >= lut_upper_index) { overflow = true; } cslDebug((70, "exp=%d, index_offset=%d, lut_index=%d, lut_offset=%d\n", exp, index_offset, lut_index, lut_offset)); } else { // lo or (le && linear_mode) // To int and Shift using float of C++ // In RTL, HLS is not used in below code if(index_select >= 0) lut_shifted = lut_sub_result_float / pow(2, index_select); else lut_shifted = lut_sub_result_float * pow(2, -index_select); overflow = lut_shifted >= lut_upper_index; lut_index = lut_shifted; lut_offset = (lut_shifted - int32_t(lut_shifted)) * 0x10000; // 16 MSB bits of fraction cslDebug((70, "index_select=%d, lut_shifted=%f, lut_index=%d, lut_offset=%d\n", index_select, lut_shifted, lut_index, lut_offset)); } } // Convert Fraction from special INT16 to HLS_FP17 vU16Type lut_offset_u16 = lut_offset; ac_channel<vU16Type> chn_lut_offset_u16; chn_lut_offset_u16.write(lut_offset_u16); HLS_uint16_to_fp17(chn_lut_offset_u16, chn_lut_offset_fp17); //if ((underflow || (le&&exp_underflow))) { if (underflow) { result_0 = lut[0]; result_0_fp16 = result_0; chn_result_0_fp16.write(result_0_fp16); cslDebug((70, "L0=0x%x\n", result_0)); // Convert result_lo_0 of HLS FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_result_0_fp16, chn_result_0_fp17); slope_fp16 = (int16_t)slope_uflow_scale; chn_slope_fp16.write(slope_fp16); // Convert FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_slope_fp16, chn_slope_fp17); // Convert FP32 to HLS_FP17 if(le && exp_mode) { float offset; #pragma CTC SKIP if(index_offset <= -127) { offset = 0; } #pragma CTC ENDSKIP else { offset = pow(2, index_offset); } ac_channel<vFp32Type> chn_offset, chn_offset_adj; chn_offset.write(*(vFp32Type *)(&offset)); chn_lut_start_fp32.write(lut_start_fp32); HLS_fp32_add(chn_lut_start_fp32, chn_offset, chn_offset_adj); chn_square_sum_fp32.write(square_sum); HLS_fp32_sub(chn_square_sum_fp32, chn_offset_adj, chn_lut_sub_result_fp32); } else { chn_lut_sub_result_fp32.write(lut_sub_result_fp32); } HLS_fp32_to_fp17(chn_lut_sub_result_fp32, chn_lut_sub_result_fp17); // chn_gap * slope HLS_fp17_mul(chn_lut_sub_result_fp17, chn_slope_fp17, chn_mul_result_fp17); HLS_fp17_add(chn_mul_result_fp17, chn_result_0_fp17, chn_result_fp17); } //else if ((overflow || (le&&exp_overflow))) { else if (overflow) { result_1 = lut[lut_upper_index]; result_1_fp16 = result_1; chn_result_1_fp16.write(result_1_fp16); cslDebug((70, "L1=0x%x\n", result_1)); // Convert result_lo_0 of HLS FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_result_1_fp16, chn_result_1_fp17); slope_fp16 = (int16_t)slope_oflow_scale; chn_slope_fp16.write(slope_fp16); // Convert FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_slope_fp16, chn_slope_fp17); // Convert FP32 to HLS_FP17 lut_end_fp32 = lut_end; chn_lut_end_fp32.write(lut_end_fp32); chn_square_sum_fp32.write(square_sum); HLS_fp32_sub(chn_square_sum_fp32, chn_lut_end_fp32, chn_lut_sub_result_fp32); HLS_fp32_to_fp17(chn_lut_sub_result_fp32, chn_lut_sub_result_fp17); // chn_gap * slope HLS_fp17_mul(chn_lut_sub_result_fp17, chn_slope_fp17, chn_mul_result_fp17); HLS_fp17_add(chn_mul_result_fp17, chn_result_1_fp17, chn_result_fp17); } else { result_0 = lut[lut_index]; result_1 = lut[lut_index+1]; result_0_fp16 = result_0; result_1_fp16 = result_1; chn_result_0_fp16.write(result_0_fp16); chn_result_1_fp16.write(result_1_fp16); cslDebug((70, "L0=0x%x, L1=0x%x\n", result_0, result_1)); // Convert HLS_FP16 to HLS_FP32 HLS_fp16_to_fp32(chn_result_0_fp16, chn_result_0_fp32); HLS_fp16_to_fp32(chn_result_1_fp16, chn_result_1_fp32); // Convert result_lo_0 of HLS FP16 to HLS_FP17 chn_result_0_fp16.write(result_0_fp16); HLS_fp16_to_fp17(chn_result_0_fp16, chn_result_0_fp17); // Interpolation HLS_fp32_sub(chn_result_1_fp32, chn_result_0_fp32, chn_L1_minus_L0_fp32); //vFp32Type L1_minus_L0_fp32 = chn_L1_minus_L0_fp32.read(); //cslDebug((70,"L1_minus_L0_fp32=0x%x\n", L1_minus_L0_fp32)); //chn_L1_minus_L0_fp32.write(L1_minus_L0_fp32); HLS_fp32_to_fp17(chn_L1_minus_L0_fp32, chn_L1_minus_L0_fp17); HLS_fp17_mul(chn_L1_minus_L0_fp17, chn_lut_offset_fp17, chn_result_lut_tmp); HLS_fp17_add(chn_result_lut_tmp, chn_result_0_fp17, chn_result_fp17); lut_hit = true; /* float L0_float, L1_float, L1_minus_L0_float, result_float; half2single(&L0_float,&result_0_fp16, 1); cslDebug((70,"L0: %f(0x%x)\n", L0_float, *(int *)(&L0_float) )); half2single(&L1_float,&result_1_fp16, 1); cslDebug((70,"L1: %f(0x%x)\n", L1_float, *(int *)(&L1_float) )); L1_minus_L0_float = L1_float - L0_float; cslDebug((70,"L1-L1: %f(0x%x)\n", L1_minus_L0_float, *(int *)(&L1_minus_L0_float) )); result_float = L0_float + L1_minus_L0_float * lut_offset; cslDebug((70,"result: %f(0x%x)\n", result_float, *(int *)(&result_float) ));*/ } } void HLS_CDP_lookup_fp16 ( int16_t *data_in, // 12 * fp17 int16_t *le_lut, int16_t *lo_lut, // Configurations uint16_t normalz_len, uint16_t raw_method, bool lut_uflow_priority, bool lut_oflow_priority, bool lut_hybrid_priority, uint64_t le_start, int16_t le_index_offset, int8_t le_index_select, uint64_t le_end, uint64_t lo_start, int8_t lo_index_select, uint64_t lo_end, uint16_t datin_offset, uint16_t datin_scale, uint8_t datin_shifter, uint32_t datout_offset, uint16_t datout_scale, uint8_t datout_shifter, int16_t le_slope_uflow_scale, int16_t le_slope_oflow_scale, int16_t lo_slope_uflow_scale, int16_t lo_slope_oflow_scale, bool sqsum_bypass, bool mul_bypass, int16_t *normalz_out, uint32_t *lut_u_flow, uint32_t *lut_o_flow, uint32_t *lut_le_hit, uint32_t *lut_lo_hit, uint32_t *lut_hybrid_hit) // 16bits { int i; // Outputs bool le_underflow; bool le_overflow; //bool exp_underflow; //bool exp_overflow; bool lo_underflow; bool lo_overflow; bool le_hit; bool lo_hit; // Variables int32_t icvt_data_out[12]; ac_channel<vFp32Type> fp17tofp32_out[12]; ac_channel<vFp32Type> square_array[12]; //ac_channel<vFp32Type> square_sum; vFp32Type square_result[12]; // Outputs of lut tables ac_channel<vFp17Type> chn_result_le_fp17; ac_channel<vFp17Type> chn_result_lo_fp17; // ac_channel<vFp17Type> chn_result_fp17; ac_channel<vFp17Type> chn_result_to_ocvt_fp17; ac_channel<vFp17Type> chn_ocvt_out_fp17; #if 0 // Initialization le_underflow = false; le_overflow = false; exp_underflow = false; exp_overflow = false; lo_underflow = false; lo_overflow = false; le_hit = false; lo_hit = false; #endif vFp32Type icvt_data_out_fp32[12]; float tmp[12], din_offset, din_scale; half2single(&din_offset, &datin_offset, 1); half2single(&din_scale, &datin_scale, 1); cslDebug((70, "Data before input converter(float)\n")); for(i=0; i<12; i++) { half2single(&tmp[i], &data_in[i], 1); cslDebug((70, "%f(0x%x) ", tmp[i], *(int *)(&tmp[i]) )); } cslDebug((70, "\n")); cslDebug((70, "Data after square(float)\n")); for(i=0; i<12; i++) { tmp[i] = tmp[i] * tmp[i]; cslDebug((70, "%f(0x%x) ", tmp[i], *(int *)(&tmp[i]) )); } cslDebug((70, "\n")); for(i=0; i<12; i++) { //***** Input Convertor (FP16->FP17) ****** cdp_icvt_hls(&data_in[i], datin_offset, datin_scale, datin_shifter, NVDLA_CDP_RDMA_D_DATA_FORMAT_0_INPUT_DATA_FP16, &icvt_data_out[i]);
//***** Convert FP17 to FP32 ****** ac_channel<vFp17Type> chn_a; chn_a.write(icvt_data_out[i]); HLS_fp17_to_fp32(chn_a, fp17tofp32_out[i]); icvt_data_out_fp32[i] = fp17tofp32_out[i].read(); ac_channel<vFp32Type> chn_b, chn_c; chn_b.write(icvt_data_out_fp32[i]); chn_c.write(icvt_data_out_fp32[i]); if(sqsum_bypass) { square_result[i] = icvt_data_out_fp32[i]; } else { HLS_fp32_mul(chn_b, chn_c, square_array[i]); // HLS_FP32 mul square_result[i] = square_array[i].read(); //keep data to re-write the square_array later } } // cslDebug((70, "Data after input convertor(FP17):\n")); // for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&icvt_data_out[i]) )); // cslDebug((70, "\n")); cslDebug((70, "Data after input convertor(FP32):\n")); for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&icvt_data_out_fp32[i]) )); cslDebug((70, "\n")); cslDebug((70, "Data after square:\n")); for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&square_result[i]) )); cslDebug((70, "\n")); //***** Per Element ****** for (i=0; i<4; i++) { le_underflow = false; le_overflow = false; //exp_underflow = false; //exp_overflow = false; lo_underflow = false; lo_overflow = false; le_hit = false; lo_hit = false; //re-write square_array in each iteration since it is empty after read for(int j=0; j<12; j++) square_array[j].write(square_result[j]); //***** Sum ****** vFp32Type square_sum_result; if(sqsum_bypass) { square_sum_result = square_array[i+4].read(); } else { ac_channel<vFp32Type> square_sum_1, square_sum_2; HLS_fp32_add(square_array[i+3], square_array[i+5], square_sum_1); //3 + 5 HLS_fp32_add(square_sum_1, square_array[i+4], square_sum_2); //sum3 = (3 + 5) + 4 ac_channel<vFp32Type> square_sum_3, square_sum_4; if(normalz_len > 0) //5+ elements { HLS_fp32_add(square_array[i+2], square_array[i+6], square_sum_3); //2 + 6 HLS_fp32_add(square_sum_2, square_sum_3, square_sum_4); //sum5 = sum3 + (2 + 6) } ac_channel<vFp32Type> square_sum_5, square_sum_6; if(normalz_len > 1) //7+ elements { HLS_fp32_add(square_array[i+1], square_array[i+7], square_sum_5); //1 + 7 HLS_fp32_add(square_sum_4, square_sum_5, square_sum_6); //sum7 = sum5 + (1 + 7) } ac_channel<vFp32Type> square_sum_7, square_sum_8; if(normalz_len > 2) //9 elements { HLS_fp32_add(square_array[i+0], square_array[i+8], square_sum_7); //1 + 7 HLS_fp32_add(square_sum_6, square_sum_7, square_sum_8); //sum9 = sum7 + (0 + 8) } switch(normalz_len) { case 0: square_sum_result = square_sum_2.read(); break; case 1: square_sum_result = square_sum_4.read(); break; case 2: square_sum_result = square_sum_6.read(); break; case 3: square_sum_result = square_sum_8.read(); break; #pragma CTC SKIP default: break; #pragma CTC ENDSKIP } } cslDebug((70, "Square sum: %x\n", *(int *)(&square_sum_result) )); // Look up Raw table if(NVDLA_CDP_S_LUT_CFG_0_LUT_LE_FUNCTION_EXPONENT == raw_method) { //raw lut is exponential cslDebug((70, "Lookup exp table\n")); HLS_CDP_lookup_lut(square_sum_result, 64, true, true, le_lut, le_start, le_end, le_slope_uflow_scale, le_slope_oflow_scale, le_index_offset, le_index_select, le_underflow, le_overflow, le_hit, chn_result_le_fp17); } else { // raw lut is linear cslDebug((70, "Lookup lin table\n")); HLS_CDP_lookup_lut(square_sum_result, 64, true, false, le_lut, le_start, le_end, le_slope_uflow_scale, le_slope_oflow_scale, le_index_offset, le_index_select, le_underflow, le_overflow, le_hit, chn_result_le_fp17); } cslDebug((70, "Lookup lo table\n")); // Look up LO(Linear Only) table HLS_CDP_lookup_lut(square_sum_result, 256, false, false, lo_lut, lo_start, lo_end, lo_slope_uflow_scale, lo_slope_oflow_scale, 0, lo_index_select, lo_underflow, lo_overflow, lo_hit, chn_result_lo_fp17); vFp17Type result_le = chn_result_le_fp17.read(); vFp17Type result_lo = chn_result_lo_fp17.read(); vFp17Type result_out; // Select result between RAW table and Density Table if(le_underflow && lo_underflow) { result_out = lut_uflow_priority? result_lo : result_le; (*lut_u_flow)++; } else if(le_overflow && lo_overflow) { result_out = lut_oflow_priority? result_lo : result_le; (*lut_o_flow)++; } else { if(le_hit ^ lo_hit) { result_out = le_hit? result_le : result_lo; if(le_hit) { (*lut_le_hit)++; } else { (*lut_lo_hit)++; } } else { if(lut_hybrid_priority) result_out = result_lo; else result_out = result_le; (*lut_hybrid_hit)++; } } cslDebug((70, "le:%x, lo:%x, out:%x\n" , *(int *)(&result_le), *(int *)(&result_lo), *(int *)(&result_out) )); if(mul_bypass) { float icvt_data_out_float = *(float *)&icvt_data_out_fp32[i+4]; if(std::isnan(icvt_data_out_float)) { chn_result_to_ocvt_fp17.write(icvt_data_out[i+4]); } else { chn_result_to_ocvt_fp17.write(result_out); } } else { ac_channel<vFp17Type> chn_result_fp17, chn_icvt_data_out_fp17; chn_result_fp17.write(result_out); vFp17Type icvt_data_out_fp17 = icvt_data_out[i+4]; chn_icvt_data_out_fp17.write(icvt_data_out_fp17); HLS_fp17_mul(chn_icvt_data_out_fp17, chn_result_fp17, chn_result_to_ocvt_fp17); } // Output Converter int64_t ocvt_data_in = chn_result_to_ocvt_fp17.read(); cslDebug((70, "ocvt_data_in:%x\n", (int)ocvt_data_in)); uint8_t flag; cdp_ocvt_hls(&ocvt_data_in, datout_offset, datout_scale, datout_shifter, NVDLA_CDP_RDMA_D_DATA_FORMAT_0_INPUT_DATA_FP16, &normalz_out[i], &flag); } }
/***************************************************************************** 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. *****************************************************************************/ /***************************************************************************** numgen.cpp -- The implementation for the numgen module. Original Author: Amit Rao, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc.h" #include "numgen.h" // definition of the `generate' method void numgen::generate() { static double a = 134.56; static double b = 98.24; a -= 1.5; b -= 2.8; out1.write(a); out2.write(b); } // end of `generate' method
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_vector_module_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { vector_module vector_module("VECTOR_MODULE"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_in[SIZE_I_IN]; sc_signal<int> data_out; vector_module.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { vector_module.data_in[i](data_in[i]); } vector_module.data_out(data_out); for (int i = 0; i < SIZE_I_IN; i++) { data_in[i] = i; } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": data_out = " << data_out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_vector_module_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { vector_module vector_module("VECTOR_MODULE"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_in[SIZE_I_IN]; sc_signal<int> data_out; vector_module.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { vector_module.data_in[i](data_in[i]); } vector_module.data_out(data_out); for (int i = 0; i < SIZE_I_IN; i++) { data_in[i] = i; } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": data_out = " << data_out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_vector_module_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { vector_module vector_module("VECTOR_MODULE"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_in[SIZE_I_IN]; sc_signal<int> data_out; vector_module.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { vector_module.data_in[i](data_in[i]); } vector_module.data_out(data_out); for (int i = 0; i < SIZE_I_IN; i++) { data_in[i] = i; } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": data_out = " << data_out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_vector_module_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { vector_module vector_module("VECTOR_MODULE"); sc_signal<bool> clock; sc_signal<sc_int<64>> data_in[SIZE_I_IN]; sc_signal<int> data_out; vector_module.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { vector_module.data_in[i](data_in[i]); } vector_module.data_out(data_out); for (int i = 0; i < SIZE_I_IN; i++) { data_in[i] = i; } clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": data_out = " << data_out.read() << endl; return 0; }
/***************************************************************************** The following code is derived, directly or indirectly, from the SystemC source code Copyright (c) 1996-2014 by all Contributors. All Rights reserved. The contents of this file are subject to the restrictions and limitations set forth in the SystemC Open Source License (the "License"); You may not use this file except in compliance with such restrictions and limitations. You may obtain instructions on how to receive a copy of the License at http://www.accellera.org/. Software distributed by Contributors under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. *****************************************************************************/ /***************************************************************************** pic.cpp -- Programmable Interrupt Unit. Original Author: Martin Wang, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc.h" #include "pic.h" void pic::entry(){ if (ireq0.read() == true) { intreq.write(true); vectno.write(0); } else if (ireq1.read() == true) { intreq.write(true); vectno.write(1); } else if (ireq2.read() == true) { intreq.write(true); vectno.write(2); } else if (ireq3.read() == true) { intreq.write(true); vectno.write(2); } else { } if ((intack_cpu.read() == true) && (cs.read() == true)) { intreq.write(false); } } // EOF
#ifndef SOBEL_EDGE_DETECTOR_TLM_CPP #define SOBEL_EDGE_DETECTOR_TLM_CPP #include <systemc.h> using namespace sc_core; using namespace sc_dt; using namespace std; #include <tlm.h> #include "sobel_edge_detector_tlm.hpp" #include "address_map.hpp" #include "common_func.hpp" void sobel_edge_detector_tlm::do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address){ unsigned char sobel_results; unsigned char* sobel_results_ptr; sc_uint<8> local_result; dbgimgtarmodprint(use_prints, "Called do_when_read_transaction with an address %016llX and length %d", address, data_length); if ((address >= (SOBEL_INPUT_0_SIZE + SOBEL_INPUT_1_SIZE)) && (address < (SOBEL_INPUT_0_SIZE + SOBEL_INPUT_1_SIZE + SOBEL_OUTPUT_SIZE))) { Edge_Detector::address = address + SOBEL_INPUT_0_ADDRESS_LO; read(); for (int i = 0; i < data_length; i++) { local_result = Edge_Detector::data.range((i + 1) * 8 - 1, i * 8); sobel_results = (unsigned char)local_result; sobel_results_ptr = &sobel_results; memcpy((data + i), sobel_results_ptr, sizeof(char)); // dbgimgtarmodprint(use_prints, "Results on sobel read %01X", sobel_results); } dbgimgtarmodprint(true, "Returning gradient results, X gradient %0d Y gradient %0d", Edge_Detector::data.range(15, 0).to_int(), Edge_Detector::data.range(32, 16).to_int()); } else { sobel_results = 0; sobel_results_ptr = &sobel_results; for (int i =0; i < data_length; i++) { memcpy((data + i), sobel_results_ptr, sizeof(char)); // dbgimgtarmodprint(use_prints, "Results on sobel read %01X", sobel_results); } } } void sobel_edge_detector_tlm::do_when_write_transaction(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address) { dbgimgtarmodprint(use_prints, "Called do_when_write_transaction with an address %016llX and length %d", address, data_length); if (address < (SOBEL_INPUT_0_SIZE + SOBEL_INPUT_1_SIZE)) { if (address < SOBEL_INPUT_0_SIZE) { for (int i = 0; i < data_length; i++) { this->sobel_input[address + i] = *(data + i); } } else if (SOBEL_INPUT_0_SIZE <= address && address < SOBEL_INPUT_0_SIZE + SOBEL_INPUT_1_SIZE) { for (int i = 0; i < data_length; i++) { this->sobel_input[address + i - SOBEL_INPUT_0_SIZE] = *(data + i); } dbgimgtarmodprint(true, "Got full window, will compute sobel gradients"); } Edge_Detector::data = (this->sobel_input[7], this->sobel_input[6], this->sobel_input[5], this->sobel_input[4], this->sobel_input[3], this->sobel_input[2], this->sobel_input[1], this->sobel_input[0]); Edge_Detector::address = address + SOBEL_INPUT_0_ADDRESS_LO; write(); } } void sobel_edge_detector_tlm::read() { Edge_Detector::data = (sc_uint<32>(0), resultSobelGradientY, resultSobelGradientX); Edge_Detector::data = Edge_Detector::data >> ((Edge_Detector::address - SOBEL_OUTPUT_ADDRESS_LO) * 8); } void sobel_edge_detector_tlm::write() { wr_t.notify(0, SC_NS); } void sobel_edge_detector_tlm::wr() { while(1) { Edge_Detector::wait(wr_t); if ((Edge_Detector::address >= SOBEL_INPUT_0_ADDRESS_LO) && (Edge_Detector::address < SOBEL_INPUT_0_ADDRESS_HI)) { int j = 0; localWindow[0][0] = Edge_Detector::data.range((j + 1) * 8 - 1, j * 8); j++; localWindow[0][1] = Edge_Detector::data.range((j + 1) * 8 - 1, j * 8); j++; localWindow[0][2] = Edge_Detector::data.range((j + 1) * 8 - 1, j * 8); j++; localWindow[1][0] = Edge_Detector::data.range((j + 1) * 8 - 1, j * 8); j++; localWindow[1][1] = Edge_Detector::data.range((j + 1) * 8 - 1, j * 8); j++; localWindow[1][2] = Edge_Detector::data.range((j + 1) * 8 - 1, j * 8); j++; localWindow[2][0] = Edge_Detector::data.range((j + 1) * 8 - 1, j * 8); j++; localWindow[2][1] = Edge_Detector::data.range((j + 1) * 8 - 1, j * 8); gotLocalWindow.notify(0, SC_NS); } else if ((Edge_Detector::address >= SOBEL_INPUT_1_ADDRESS_LO) && (Edge_Detector::address < SOBEL_INPUT_1_ADDRESS_HI)) { localWindow[2][2] = data.range(7, 0); gotLocalWindow.notify(0, SC_NS); } } } #endif // SOBEL_EDGE_DETECTOR_TLM_CPP
/* * @ASCK */ #include <systemc.h> SC_MODULE (ID) { sc_in_clk clk; sc_in <sc_int<8>> prev_A; sc_in <sc_int<8>> prev_B; sc_in <sc_int<13>> prev_Imm; sc_in <sc_uint<3>> prev_Sa; sc_in <sc_uint<5>> prev_AluOp; sc_in <bool> prev_r; sc_in <bool> prev_w; sc_in <bool> prev_AluMux; sc_in <bool> prev_WbMux; sc_in <bool> prev_call; sc_in <bool> prev_regWrite; sc_in <sc_uint<3>> prev_rd; sc_out <sc_int<8>> next_A; sc_out <sc_int<8>> next_B; sc_out <sc_int<13>> next_Imm; sc_out <sc_uint<3>> next_Sa; sc_out <sc_uint<5>> next_AluOp; sc_out <bool> next_r; sc_out <bool> next_w; sc_out <bool> next_AluMux; sc_out <bool> next_WbMux; sc_out <bool> next_call; sc_out <bool> next_regWrite; sc_out <sc_uint<3>> next_rd; /* ** module global variables */ SC_CTOR (ID){ SC_THREAD (process); sensitive << clk.pos(); } void process () { while(true){ wait(); if(now_is_call){ wait(micro_acc_ev); } next_A.write(prev_A.read()); next_B.write(prev_B.read()); next_Imm.write(prev_Imm.read()); next_Sa.write(prev_Sa.read()); next_AluOp.write(prev_AluOp.read()); next_AluMux.write(prev_AluMux.read()); next_r.write(prev_r.read()); next_w.write(prev_w.read()); next_WbMux.write(prev_WbMux.read()); next_call.write(prev_call.read()); next_regWrite.write(prev_regWrite); next_rd.write(prev_rd.read()); } } };
#include <systemc.h> class sc_clockx : sc_module, sc_interface { public: sc_event edge; sc_event change; bool val; bool _val; int delta; private: int period; SC_HAS_PROCESS(sc_clockx); void run(void) { int tmp = period/2; edge.notify(SC_ZERO_TIME); change.notify(SC_ZERO_TIME); while(true) { wait(tmp, SC_NS); edge.notify(SC_ZERO_TIME); change.notify(SC_ZERO_TIME); val = !val; } } public: sc_clockx(sc_module_name name, int periodparam): sc_module(name) { SC_THREAD(run); period = periodparam; val = true; _val = true; } bool read() { return val; } void write(bool newval) { _val = newval; if (!(_val == val)) request_update(); } void update() { if (!(_val == val)) { val = _val; change.notify(SC_ZERO_TIME); delta = sc_delta_count(); } } };
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_inputs_vector_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_inputs_vector_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_inputs_vector_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_inputs_vector_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
// //------------------------------------------------------------// // Copyright 2009-2012 Mentor Graphics Corporation // // All Rights Reserved Worldwid // // // // 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 "tlm.h" #include <vector> #include <iomanip> #include <uvmc.h> using std::vector; using namespace sc_core; using namespace tlm; //------------------------------------------------------------------------------ // Title: UVMC Converter Example - SC In-Transaction // // This example's packet class defines ~do_pack~ and ~do_unpack~ methods that // are compatible with the default converter in SC. The default converter merely // delegates conversion to these two methods in the transaction class. // // (see UVMC_Converters_SC_InTrans.png) // // This approach is not very common in practice, as it couples your transaction // types to the UVMC library. // // Instead of defining member functions of the transaction type to do conversion, // you should instead implement a template specialization of uvmc_convert<T>. // This leaves conversion knowledge outside your transaction proper, and allows // you to define different conversion algorithms without requiring inheritance. // This example demonstrates use of a transaction class that defines the // conversion functionality in compliant ~do_pack~ and ~do_unpack~ methods. // Thus, an custom converter specialization will not be needed--the default // converter, which delegates to ~do_pack~ and ~do_unpack~ methods in the // transaction, is sufficient. // // Because most SC transactions do not implement the pack and unpack member // functions required by the default converter, a template specialization // definition is normally required. // // The default converter, uvmc_converter<T>, or any template specialization // of that converter for a given packet type, e.g. uvmc_converter<packet>, // is implicitly chosen by the C+ compiler. This means you will seldom need to // explicitly specify the converter type when connecting via <uvmc_connect>. // //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Group: User Library // // This section defines a transaction class and generic consumer model. The // transaction implements the ~do_pack~ and ~do_unpack~ methods required by the // default converter. // // Packing and unpacking involves streaming the contents of your transaction // fields into and out of the ~packer~ object provided as an argument to ~do_pack~ // and ~do_unpack~. The packer needs to have defined ~operator<<~ for each type // of field you stream. See <UVMC Type Support> for a list of supported // transaction field types. //------------------------------------------------------------------------------ // (begin inline source) namespace user_lib { using namespace uvmc; class packet_base { public: enum cmd_t { WRITE=0, READ, NOOP }; cmd_t cmd; unsigned int addr; vector<unsigned char> data; virtual void do_pack(uvmc_packer &packer) const { packer << cmd << addr << data; } virtual void do_unpack(uvmc_packer &packer) { packer >> cmd >> addr >> data; } }; class packet : public packet_base { public: unsigned int extra_int; virtual void do_pack(uvmc_packer &packer) const { packet_base::do_pack(packer); packer << extra_int; } virtual void do_unpack(uvmc_packer &packer) { packet_base::do_unpack(packer); packer >> extra_int; } }; // a generic target with a TLM1 put export #include "consumer.cpp" } // (end inline source) //------------------------------------------------------------------------------ // Group: Conversion code // // We do not need to define an external conversion class because it conversion // is built into the transaction proper. The default converter will delegate to // our transaction's ~do_pack~ and ~do_unpack~ methods. // // We do, however, define ~operator<< (ostream&)~ for our transaction type using // <UVMC_PRINT> macros. With this, we can print the transaction contents to any // output stream. // // For example // //| packet p; //| ...initialize p... //| cout << p; // // This produces output similar to // //| '{cmd:2 addr:1fa34f22 data:'{4a, 27, de, a2, 6b, 62, 8d, 1d, 6} } // // You can invoke the macros in any namepace in which the uvmc namespace // was imported and the macros #included. // //------------------------------------------------------------------------------ // (begin inline source) using namespace user_lib; UVMC_PRINT_3(packet_base,cmd,addr,data) UVMC_PRINT_EXT_1(packet,packet_base,extra_int) // (end inline source) //------------------------------------------------------------------------------ // Group: Testbench code // // This section defines our testbench environment. In the top-level module, we // instantiate the generic consumer model. We also register the consumer's ~in~ // export to have a UVMC connection with a lookup string, ~stimulus~. The // SV-side will register its producer's ~out~ port with the same lookup string. // UVMC will match these two strings to complete the cross-language connection, // i.e. the SV producer's ~out~ port will be bound to the SC consumer's // ~in~ export. //------------------------------------------------------------------------------ // (begin inline source) class sc_env : public sc_module { public: consumer<packet> cons; sc_env(sc_module_name nm) : cons("cons") { uvmc_connect(cons.in,"stimulus"); uvmc_connect(cons.ap,"checker"); } }; // Define sc_main, the vendor-independent means of starting a // SystemC simulation. int sc_main(int argc, char* argv[]) { sc_env env("env"); sc_start(); return 0; } // (end inline source)
// //------------------------------------------------------------// // Copyright 2009-2012 Mentor Graphics Corporation // // All Rights Reserved Worldwid // // // // 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 PACKET_H #define PACKET_H #include <vector> using std::vector; #include <systemc.h> #include <tlm.h> using namespace sc_core; class packet { public: short cmd; int addr; vector<char> data; }; //------------------------------------------------------------------------------ // Begin UVMC-specific code #include "uvmc.h" using namespace uvmc; UVMC_UTILS_3 (packet,cmd,addr,data) #endif // PACKET_H
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_addressing_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_addressing_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/************************************************************************** * * * Catapult(R) MatchLib Toolkit Example Design Library * * * * Software Version: 2.2 * * * * Release Date : Thu Aug 22 21:10:31 PDT 2024 * * Release Type : Production Release * * Release Build : 2.2.0 * * * * Copyright 2020 Siemens * * * ************************************************************************** * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * * implied. * * See the License for the specific language governing permissions and * * limitations under the License. * ************************************************************************** * * * The most recent version of this package is available at github. * * * *************************************************************************/ #include <systemc.h> #include "dut.h" #include <mc_scverify.h> using namespace::std; class Top : public sc_module { public: CCS_DESIGN(dut) CCS_INIT_S1(dut1); sc_clock clk; SC_SIG(bool, rst_bar); Connections::Combinational<dut::T> CCS_INIT_S1(out1); Connections::Combinational<dut::T> CCS_INIT_S1(in1); int matlab_input; bool matlab_input_valid; int matlab_output; bool matlab_output_valid; SC_CTOR(Top) : clk("clk", 1, SC_NS, 0.5,0,SC_NS,true) { sc_object_tracer<sc_clock> trace_clk(clk); dut1.clk(clk); dut1.rst_bar(rst_bar); dut1.out1(out1); dut1.in1(in1); SC_CTHREAD(reset, clk); SC_THREAD(stim); sensitive << clk.posedge_event(); async_reset_signal_is(rst_bar, false); SC_THREAD(resp); sensitive << clk.posedge_event(); async_reset_signal_is(rst_bar, false); } void stim() { CCS_LOG("Stimulus started"); in1.ResetWrite(); wait(); int i1 = 0; while (1) { #ifdef EXTERNAL_TESTBENCH if (matlab_input_valid) { in1.Push(matlab_input); matlab_input_valid = 0; } else { wait(); } #else in1.Push(i1++); if (i1 > 10) sc_stop(); #endif } } void resp() { out1.ResetRead(); wait(); while (1) { #ifdef EXTERNAL_TESTBENCH matlab_output = out1.Pop(); matlab_output_valid = 1; std::cout << "calling sc_pause()\n"; sc_pause(); #else CCS_LOG("See: " << out1.Pop()); #endif } } void reset() { rst_bar.write(0); wait(5); rst_bar.write(1); wait(); } }; Top *top_ptr{0}; // sc_main instantiates the SC hierarchy but does not run the simulation - that is handled elsewhere int sc_main(int argc, char **argv) { sc_report_handler::set_actions("/IEEE_Std_1666/deprecated", SC_DO_NOTHING); sc_report_handler::set_actions(SC_ERROR, SC_DISPLAY); // This function instantiates the design hiearchy including the testbench. sc_trace_file *trace_file_ptr = sc_trace_static::setup_trace_file("trace"); top_ptr = new Top("top"); trace_hierarchy(top_ptr, trace_file_ptr); #ifndef EXTERNAL_TESTBENCH sc_start(); #endif return 0; } #ifdef EXTERNAL_TESTBENCH // This class represents the SC simulator to Python or Matlab Mex class sc_simulator { public: sc_simulator() { sc_elab_and_sim(0, 0); } // This function represents the python or Matlab Mex function that would be called repeatedly // to process one (or more) data inputs and return one (or more) data outputs int process_one_sample(int in1) { top_ptr->matlab_input = in1; top_ptr->matlab_input_valid = true; std::cout << "calling sc_start()\n"; sc_start(); // This returns when sc_pause is called above return top_ptr->matlab_output; } }; // Python does not have a native C++ interface, so we export regular C functions to Python extern "C" { sc_simulator* sc_simulator_new() { return new sc_simulator(); } int process_one_sample(sc_simulator* sim, int in1) { return sim->process_one_sample(in1); } } #endif
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_addressing_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_addressing_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; 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_bus_main.cpp : sc_main Original Author: Ric Hilderink, Synopsys, Inc., 2001-10-11 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc.h" #include "simple_bus_test.h" int sc_main(int, char **) { simple_bus_test top("top"); sc_start(10000, SC_NS); 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_bus_main.cpp : sc_main Original Author: Ric Hilderink, Synopsys, Inc., 2001-10-11 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc.h" #include "simple_bus_test.h" int sc_main(int, char **) { simple_bus_test top("top"); sc_start(10000, SC_NS); 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_bus_main.cpp : sc_main Original Author: Ric Hilderink, Synopsys, Inc., 2001-10-11 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc.h" #include "simple_bus_test.h" int sc_main(int, char **) { simple_bus_test top("top"); sc_start(10000, SC_NS); return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_output_v_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_output_v_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_output_v_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_output_v_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_matrix_deviation_function_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/******************************************************************************* * dns.cpp -- Copyright 2019 Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This is a stubfile that sets several defines for a simplified version of * the LwIP to compile on the ESPMOD SystemC model. This is not a port of * the LwIP. ******************************************************************************* * 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 file was based off the work covered by the license below: * * Author: Jim Pettinato * April 2007 * * ported from uIP resolv.c Copyright (c) 2002-2003, Adam Dunkels. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <systemc.h> #include "dns.h" #include <IPAddress.h> #include "info.h" #include "esp_wifi_types.h" #include "esp_wifi.h" /** * @brief Set the DNS server. **/ void dns_setserver(uint8_t numdns, const ip_addr_t *dnsserver) { if (dnsserver == NULL) PRINTF_ERROR("WIFI", "Invalid DNS server pointer"); PRINTF_INFO("WIFI", "Setting DNS server %d to %s", numdns, IPAddress(dnsserver->u_addr.ip4.addr).toString().c_str()); }
/******************************************************************************* * task.cpp -- Copyright 2019 Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This file reimplements the freertos tasks to get them to compile under the * ESPMOD SystemC model. The tasks were rewrittent to spawn SC dynamic * threads. ******************************************************************************* * 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 file was based off the work covered by the license below: * FreeRTOS V8.2.0 - Copyright (C) 2015 Real Time Engineers Ltd. * All rights reserved * * FreeRTOS is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License (version 2) as published by the * Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception. * * FreeRTOS 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. Full license text is available on the following * link: http://www.freertos.org/a00114.html */ #define SC_INCLUDE_DYNAMIC_PROCESSES #include <systemc.h> #include "FreeRTOS.h" #include "task.h" void vTaskDelay( const TickType_t xTicksToDelay ) { /* We set the portTICK_RATE_MS to 1, so the value should be the * number in lilliseconds. Perhaps we should change this later. */ wait(xTicksToDelay, SC_MS); } BaseType_t xTaskCreatePinnedToCore( TaskFunction_t pvTaskCode, const char * const pcName, const uint32_t usStackDepth, void * const pvParameters, UBaseType_t uxPriority, TaskHandle_t * const pvCreatedTask, const BaseType_t xCoreID) { sc_spawn(sc_bind(pvTaskCode, pvParameters)); return pdTRUE; } void vTaskDelete( TaskHandle_t xTaskToDelete ) { }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_matrix_deviation_function_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_matrix_deviation_function_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_matrix_deviation_function_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_input_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // 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. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_lstm_input_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }