text
stringlengths
41
20k
/******************************************************************************* * TestSerial.cpp -- Copyright 2019 Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Generic Serial Class for communicating with a set of SystemC ports. * This class tries to mimic the behaviour used by the Hardware Serial * and SoftwareSerial classes used by the Arduino IDE. ******************************************************************************* * 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 "info.h" #include "TestSerial.h" #include "clockpacer.h" #include "Arduino.h" TestSerial::TestSerial() { taken = false; waiting = '\0'; uartno = -1; pinmodeset = false; } TestSerial::TestSerial(int _u) { if(_u < 0 || _u > 2) { printf("Invalid UART %d", _u); uartno = 0; } uartno = _u; taken = false; waiting = '\0'; pinmodeset = false; } TestSerial::TestSerial(int _rxpin, int _rxmode, int _txpin, int _txmode) { taken = false; waiting = '\0'; pinmodeset = true; rxpin = _rxpin; rxmode = _rxmode; txpin = _txpin; txmode = _txmode; } TestSerial::~TestSerial() {} void TestSerial::begin(int baudrate, int mode, int pinrx, int pintx) { if (baudrate <= 0) baudrate = 9600; PRINTF_INFO("TSER", "Setting UART %d Baud rate to %0d", uartno, baudrate); /* We set the pin modes. If a value was given in the arguments, we take it. * If not, we check the pinmodeset list. If it was set, we leave it as is. * If not, we go with the UART number. */ if (pinrx >= 0) rxpin = pinrx; else if (!pinmodeset) switch(uartno) { case 0: rxpin = RX; break; case 1: rxpin = 9; break; case 2: rxpin = 16; break; } if (pintx >= 0) txpin = pintx; else if (!pinmodeset) switch(uartno) { case 0: txpin = TX; break; case 1: txpin = 10; break; case 2: txpin = 17; break; } /* For the modes, we do the same. */ if (mode < 0 || !pinmodeset) { rxmode = INPUT; txmode = OUTPUT; } /* We first drive the TX level high. It is now an input, but when we change * the pin to be an output, it will not drive a zero. */ pinMode(rxpin, rxmode); pinMatrixInAttach(rxpin, (uartno == 0)?U0RXD_IN_IDX: (uartno == 1)?U1RXD_IN_IDX: (uartno == 2)?U2RXD_IN_IDX:0, false); pinMode(txpin, txmode); pinMatrixOutAttach(txpin, (uartno == 0)?U0TXD_OUT_IDX: (uartno == 1)?U1TXD_OUT_IDX: (uartno == 2)?U2TXD_OUT_IDX:0, false, false); } void TestSerial::setports(sc_fifo<unsigned char> *_to, sc_fifo<unsigned char> *_from) { to = _to; from = _from; } bool TestSerial::isinit() { if (from == NULL || to == NULL) return false; else return true; } void TestSerial::end() { PRINTF_INFO("TSER", "Ending Serial");} int TestSerial::printf(const char *fmt, ...) { char buff[128], *ptr; int resp; va_list argptr; va_start(argptr, fmt); resp = vsnprintf(buff, 127, fmt, argptr); va_end(argptr); ptr = buff; if (to == NULL) return 0; while(*ptr != '\0') { clockpacer.wait_next_apb_clk(); to->write(*ptr++); } return resp; } size_t TestSerial::write(uint8_t ch) { clockpacer.wait_next_apb_clk(); if (to == NULL) return 0; to->write(ch); return 1; } size_t TestSerial::write(const char* buf) { size_t sent = 0; clockpacer.wait_next_apb_clk(); while(*buf != '\0') { write(*buf); sent = sent + 1; buf = buf + 1; } return sent; } size_t TestSerial::write(const char* buf, size_t len) { size_t sent = 0; clockpacer.wait_next_apb_clk(); while(sent < len) { write(*buf); sent = sent + 1; buf = buf + 1; } return sent; } int TestSerial::availableForWrite() { /* We return if there is space in the buffer. */ if (to == NULL) return 0; return to->num_free(); } int TestSerial::available() { /* If we have something taken due to a peek, we need to inform the * requester that we still have something to return. So we have at * least one. If taken is false, then it depends on the number * available. */ clockpacer.wait_next_apb_clk(); if (from == NULL) return 0; if (taken) return 1 + from->num_available(); else return from->num_available(); } void TestSerial::flush() { /* For flush we get rid of the taken character and then we use the FIFO's * read to dump the rest. */ taken = false; while(from != NULL && from->num_available()>0) from->read(); } int TestSerial::read() { /* Anytime we leave the CPU we need to do a dummy delay. This makes sure * time advances, in case we happen to be in a timeout loop. */ clockpacer.wait_next_apb_clk(); if (from == NULL) return -1; if (taken) { taken = false; return waiting; } else if (!from->num_available()) return -1; return (int)from->read(); } int TestSerial::bl_read() { /* Just like the one above but it does a blocking read. Useful to cut * on polled reads. */ clockpacer.wait_next_apb_clk(); if (from == NULL) return -1; if (taken) { taken = false; return waiting; } return from->read(); } int TestSerial::bl_read(sc_time tmout) { /* And this is a blocking read with a timeout. */ clockpacer.wait_next_apb_clk(); if (from == NULL) return -1; if (taken) { taken = false; return waiting; } /* If there is nothing available, we wait for it to arrive or a timeout. */ if (available() == 0) { wait(tmout, from->data_written_event()); clockpacer.wait_next_apb_clk(); if (available() == 0) return -1; } /* If it was all good, we return it. */ return from->read(); } int TestSerial::peek() { clockpacer.wait_next_apb_clk(); if (from == NULL) return -1; if (taken) return waiting; else if (!from->num_available()) return -1; else { taken = true; waiting = from->read(); return waiting; } } int TestSerial::bl_peek() { clockpacer.wait_next_apb_clk(); if (from == NULL) return -1; if (taken) return waiting; else { taken = true; waiting = from->read(); return waiting; } } int TestSerial::bl_peek(sc_time tmout) { clockpacer.wait_next_apb_clk(); if (from == NULL) return -1; if (taken) return waiting; else { /* If there is nothing available,we wait for it to arrive or a timeout. */ if (available() == 0) { wait(tmout, from->data_written_event()); clockpacer.wait_next_apb_clk(); if (available() == 0) return -1; } taken = true; waiting = from->read(); return waiting; } }
#include <systemc.h> class sc_mutexx : public sc_prim_channel { public: sc_event _free; bool _locked; // blocks until mutex could be locked void lock() { while( _locked ) { wait( _free ); } _locked = true; } // returns false if mutex could not be locked bool trylock() { if( _locked ) return false; else return true; } // unlocks mutex void unlock() { _locked = false; _free.notify(); } // constructor sc_mutexx(){ // _locked = false; } };
// //------------------------------------------------------------// // 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. // //------------------------------------------------------------// //----------------------------------------------------------------------------- // Title- UVMC-based SC to SC Connections (not implemented yet) // // This example demonstrates connecting two SC components using UVMC. // // (see UVMC_Connections_SC2SC.png) // // In this example, we instantiate a <producer> and <consumer> // sc_module. Then two ~uvmc_connect~ calls are made, one for each side of // the connection. Because we use the same lookup string, "sc2sc", in each // of these calls, UVMC will establish the connection during binding resolution // at elaboration time. // // The connection must be valid, i.e. the port/export/interface types and // transaction type must be compatible, else an elaboration-time error will // result. // //----------------------------------------------------------------------------- // (- inline source) #include <systemc.h> using namespace sc_core; #include "consumer.h" #include "producer.h" #include "packet.h" int sc_main(int argc, char* argv[]) { producer prod("prod"); consumer cons("cons"); uvmc_connect(prod.out, "sc2sc"); uvmc_connect(cons.in, "sc2sc"); sc_start(-1); return 0; }
/******************************************************************************* * <DIRNAME>test.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This is the main testbench for the <DIRNAME>.ino test. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "<DIRNAME>test.h" #include <string> #include <vector> #include "info.h" <IFESPIDF>#include "main.h" /********************** * Function: trace() * inputs: trace file * outputs: none * return: none * globals: none * * Traces all signals in the design. For a signal to be traced it must be listed * here. This function should also call tracing in any subblocks, if desired. */ void <DIRNAME>test::trace(sc_trace_file *tf) { sc_trace(tf, led, led.name()); sc_trace(tf, rx, rx.name()); sc_trace(tf, tx, tx.name()); i_esp.trace(tf); } /********************** * Task: start_of_simulation(): * inputs: none * outputs: none * return: none * globals: none * * Runs commands at the beginning of the simulation. */ void <DIRNAME>test::start_of_simulation() { /* We add a deadtime to the uart client as the ESP sends a glitch down the * UART0 at power-up. */ i_uartclient.i_uart.set_deadtime(sc_time(5, SC_US)); } /********************** * Task: serflush(): * inputs: none * outputs: none * return: none * globals: none * * Dumps everything comming from the serial interface. */ void <DIRNAME>test::serflush() { //i_uartclient.i_uart.set_debug(true); i_uartclient.dump(); } /******************************************************************************* ** Testbenches ***************************************************************** *******************************************************************************/ void <DIRNAME>test::t0(void) { SC_REPORT_INFO("TEST", "Running Test T0."); wait(1, SC_MS); sc_stop(); PRINTF_INFO("TEST", "Waiting for power-up"); wait(500, SC_MS); } void <DIRNAME>test::testbench(void) { /* Now we check the test case and run the correct TB. */ printf("Starting Testbench Test%d @%s\n", tn, sc_time_stamp().to_string().c_str()); if (tn == 0) t0(); else SC_REPORT_ERROR("TEST", "Test number too large."); sc_stop(); }
/******************************************************************************* * 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(); } }
#include <systemc.h> #include <i2c_controller.h> void i2c_controller::clk_divider() { if(rst) { i2c_clk.write(1); } else { if(counter2 == 1) { bool t = i2c_clk.read(); i2c_clk.write(!t); counter2 = 0; } else { counter2 = counter2 + 1; } } } void i2c_controller::scl_controller() { if(rst) { i2c_scl_enable = 0; } else { if((state == IDLE) | (state == START) | (state == STOP)) { i2c_scl_enable = 0; } else { i2c_scl_enable = 1; } } } void i2c_controller::logic_fsm() { if(rst) { state = IDLE; } else { switch(state) { case IDLE: if(enable == 1) { state = START; saved_addr = (addr,rw); saved_data = data_in; } else { state = IDLE; } break; case START: counter = 7; state = ADDRESS; break; case ADDRESS: if(counter == 0) { state = READ_ACK; } else { counter = counter - 1; } break; case READ_ACK: if(i2c_sda ==(sc_logic) 0) { counter = 7; if(saved_addr[0] == 0) { state = WRITE_DATA; } else { state = READ_DATA; } } else { state = STOP; } break; case WRITE_DATA: if(counter == 0) { state = READ_ACK2; } else { counter = counter - 1; } break; case READ_ACK2: if((i2c_sda == 0) & (enable == 1)) { state = IDLE; } else { state = STOP; } break; case READ_DATA: data_from_slave[counter] = i2c_sda; if(counter == 0) { state = WRITE_ACK; } else { counter = counter - 1; } break; case WRITE_ACK: state = STOP; break; case STOP: state = IDLE; break; } } } void i2c_controller::data_fsm() { if(rst) { write_enable.write(1); i2c_sda.write((sc_logic)1); } else { switch(state) { case IDLE: break; case READ_ACK2: break; case START: write_enable.write(1); i2c_sda.write((sc_logic)0); break; case ADDRESS: { int t = saved_addr[counter]; i2c_sda.write((sc_logic) t); } break; case READ_ACK: i2c_sda.write(sc_logic('Z')); write_enable.write(0); break; case WRITE_DATA: { write_enable.write(1); sc_logic t = saved_data[counter]; i2c_sda.write((sc_logic) t); } break; case WRITE_ACK: i2c_sda.write((sc_logic) 0); write_enable.write(1); break; case READ_DATA: write_enable.write(0); break; case STOP: write_enable.write(1); i2c_sda.write((sc_logic)1); break; } } } void i2c_controller::ready_assign() { if((rst == 0) && (state == IDLE)) { ready.write(1); } else { ready.write(0); } } void i2c_controller::i2c_scl_assign() { if(i2c_scl_enable == 0) { i2c_scl.write((sc_logic)1); } else { i2c_scl.write((sc_logic)i2c_clk); } }
// ************************************************************************************** // 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 {} gp_t* allocate() { #ifdef DEBUG cout << "----------------------------- Called allocate(), #trans = " << ++count << endl; #endif 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 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 }; #endif
/******************************************************************************* * i2c.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Model for a I2C. ******************************************************************************* * 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 "i2c.h" #include "info.h" void i2c::transfer_th() { unsigned char p; bool rwbit; sda_en_o.write(false); scl_en_o.write(false); state = IDLE; while(true) { p = to.read(); snd.write(p); /* For the start and stop bit, we could be in the middle of a command, * therefore we cannot assume the bits are correct. */ if (p == 'S') { sda_en_o.write(false); scl_en_o.write(false); wait(625, SC_NS); sda_en_o.write(true); wait(625, SC_NS); scl_en_o.write(true); wait(1250, SC_NS); state = DEVID; } else if (p == 'P') { /* If the SDA is high, we need to take it low first. If not, we cam * go straight into the stop bit. */ wait(625, SC_NS); sda_en_o.write(true); wait(625, SC_NS); scl_en_o.write(false); wait(625, SC_NS); sda_en_o.write(false); wait(1250, SC_NS); state = IDLE; } else if (state == DEVID || state == WRITING) { if (p == '1') { wait(625, SC_NS); sda_en_o.write(false); wait(625, SC_NS); scl_en_o.write(false); wait(1250, SC_NS); scl_en_o.write(true); rwbit = true; } else if (p == '0') { wait(625, SC_NS); sda_en_o.write(true); wait(625, SC_NS); scl_en_o.write(false); wait(1250, SC_NS); scl_en_o.write(true); rwbit = false; } else if (p == 'Z') { sda_en_o.write(false); /* Then we tick the clock. */ wait(1250, SC_NS); scl_en_o.write(false); /* After the clock, we sample it. */ if (sda_i.read()) { snd.write('N'); from.write('N'); state = IDLE; } else { snd.write('A'); from.write('A'); /* If the readwrite bit is low and we are in the DEVID state * we go to the WRITING state. If we are already in the WRITING * state we remain in it. */ if (state == DEVID && !rwbit || state == WRITING) state= WRITING; else state = READING; } wait(1250, SC_NS); scl_en_o.write(true); } else wait(2500, SC_NS); } else if (state == READING) { if (p == 'N') { wait(625, SC_NS); sda_en_o.write(false); wait(625, SC_NS); scl_en_o.write(false); wait(1250, SC_NS); scl_en_o.write(true); state = IDLE; } else if (p == 'A') { wait(625, SC_NS); sda_en_o.write(true); wait(625, SC_NS); scl_en_o.write(false); wait(1250, SC_NS); scl_en_o.write(true); } else if (p == 'Z') { sda_en_o.write(false); wait(1250, SC_NS); scl_en_o.write(false); if (sda_i.read()) { from.write('1'); snd.write('1'); } else { from.write('0'); snd.write('0'); } wait(1250, SC_NS); scl_en_o.write(true); } else wait(2500, SC_NS); } } } void i2c::trace(sc_trace_file *tf) { sc_trace(tf, snd, snd.name()); }
/******************************************************************************** * 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: 19/Aug/2019 * * Authors: Vittoriano Muttillo, Luigi Pomante * * * * email: [email protected] * * [email protected] * * * ******************************************************************************** * This code has been developed from an HEPSYCODE model used as demonstrator by * * University of L'Aquila. * * * * The code is used as a working example in the 'Embedded Systems' course of * * the Master in Conputer Science Engineering offered by the * * University of L'Aquila * *******************************************************************************/ /******************************************************************************** * main.cpp : FirFirGCD main file. * *******************************************************************************/ /*! \mainpage HEPSYCODE FirFirGCD Application \section INTRODUCTION Hepsycode is a prototypal tool to improve the design time of embedded applications. It is based on a System-Level methodology for HW/SW Co-Design of Heterogeneous Parallel Dedicated Systems. The whole framework drives the designer from an Electronic System-Level (ESL) behavioral model, with related NF requirements, including real-time and mixed-criticality ones, to the final HW/SW implementation, considering specific HW technologies, scheduling policies and Inter-Process Communication (IPC) mechanisms. The system behavior modeling language introduced in Hepsycode, named HML (HEPSY Modeling Language), is based on the Communicating Sequential Processes (CSP) Model of Computation (MoC). It allows modeling the behavior of the system as a network of processes communicating through unidirectional synchronous channels. By means of HML it is possible to specify the System Behavior Model (SBM), an executable model of the system behavior, a set of Non Functional Constraints (NFC) and a set of Reference Inputs (RI) to be used for simulation-based activities. Through the execution of different steps, including a system-level Design Space Exploration (DSE) approach that allows the related co-design methodology to suggest an HW/SW partitioning of the application specification and a mapping of the partitioned entities onto an automatically defined heterogeneous multi-processor architecture, it is possible to proceed with system implementation. Hepsycode uses Eclipse MDE technologies, SystemC custom simulator implementation and an evolutionary genetic algorithm for partitioning activities, all integrated into an automatic framework that drive the designer from first input to final solution. \subsection WEBSITE <a href="http://www.hepsycode.com">www.hepsycode.com</a> \subsection LICENSE GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 (see <a href="https://www.gnu.org/licenses/gpl-3.0.en.html">gpl-3.0.en.html</a>) \subsection SUPPORT We currently support: Email: - Luigi Pomante: [email protected] - Vittoriano Muttillo: [email protected] - Main contact: [email protected] (please take care to use [HEPSYCODE SUPPORT] as object \subsection Additional information Research publications are available on <a href="http://www.hepsycode.com/">Hepsycode Website</a> and <a href="http://www.pomante.net/sito_gg/Publications.htm">Publications</a> \section Example Use Case FirFirGCD We provide an example Hepsycode project, called FirFirGCD (FFG). FFG is a synthetic application that takes in input pairs of values (triggered by Stimulus), makes two filtering actions (FIR8 and FIR16) and then makes the Greatest Common Divisor (GCD) between the filters outputs and displays the result. This application is composed of three main components: 2 Finite Impulse Response (FIR) digital filters and a Greatest Common Divisor (GCD) component, as show in the figure below. \image html ./HepsycodeModel/FirFirGCD_Model_0_0.png More details can be found at the link: <a href="http://www.hepsycode.com">www.hepsycode.com</a> */ /******************************************************************************** * main.cpp : Defines the HEPSIM2 main file. * * * * HEPSIM2 main file * * * ********************************************************************************/ /*! \file main.cpp \brief Main Documented file. Details. */ /** @defgroup firfirgcd_main_group FirFirGCD Main. * * MAIN * * @author V. Muttillo, L. Pomante * @date Apr. 2022 * @{ */ // start firfirgcd_main_group /******************************************************************************** *** Includes *** *******************************************************************************/ #include <iostream> #include <stdlib.h> #include <stdio.h> #include <vector> #include <iomanip> #include <time.h> #include <string.h> #include <systemc.h> #include "define.h" #include "sc_csp_channel_ifs.h" #include "datatype.h" #include "stim_gen.h" #include "mainsystem.h" #include "display.h" #include "sc_csp_channel.h" #include "SchedulingManager.h" #include "SystemManager.h" #include "tl.h" using namespace std; /******************************************************************************** *** Functions *** *******************************************************************************/ // Allocation of global SystemManager SystemManager *pSystemManager = new SystemManager(); // Allocation of global SchedulingManager SchedulingManager *pSchedulingManager = new SchedulingManager("SchedulingManager"); // It is a SC_MODULE (beacuse we need SC_THREADs) so the internal name is needed // CONCURRENCY SAMPLING CONTROL (only for timing concurrency) // Used to stop sampling SC_THREAD in SchedulingManager (in the future they will be external parameters) unsigned int sampling_period = 1000; // HW architecture dependent: tipically in the interval 10-1000 SC_NS bool stop_concurrency_sampling=false; // Used to stop sampling SC_THREAD in SchedulingManager ///////////////////////////////////////////////////////////////////////////////////////////// // PARTIALLY SBM DEPENDENT ///////////////////////////////////////////////////////////////////////////////////////////// int sc_main(int a, char* b[]) { ///////////////////////////////////////////////////////////////////////////////////////// /// Testbench and System (SBM dependent) ///////////////////////////////////////////////////////////////////////////////////////// /// Instantiation and connection of testbench and system sc_csp_channel< sc_uint<8> > stim1_channel(12); sc_csp_channel< sc_uint<8> > stim2_channel(13); sc_csp_channel< sc_uint<8> > result_channel(14); /// Instantiation and connection of testbench and system stim_gen mystimgen("mystimgen"); mystimgen.stim1_channel_port(stim1_channel); mystimgen.stim2_channel_port(stim2_channel); mainsystem mysystem("mysystem"); mysystem.stim1_channel_port(stim1_channel); mysystem.stim2_channel_port(stim2_channel); mysystem.result_channel_port(result_channel); display mydisplay("mydisplay"); mydisplay.result_channel_port(result_channel); ///////////////////////////////////////////////////////////////////////////////////////// /// Simulation management (maybe SBM dependent) ///////////////////////////////////////////////////////////////////////////////////////// // Time info sc_time end_sim, tot=sc_time(0, SC_MS), tot_sched_oh=sc_time(0, SC_MS); clock_t start = clock(); // Start simulation cout << endl; sc_start(); // Total simulated and simulation times end_sim=sc_time_stamp(); clock_t end = clock(); #if _WIN32 system("pause"); #endif ///////////////////////////////////////////////////////////////////////////////////////// /// Report (SBM independent) ///////////////////////////////////////////////////////////////////////////////////////// //LP: check tutti i save_csv, save_xml e trace #if defined(_SAVE_CSV_) // Initialize csv file for statistics storage ofstream myStatFile; myStatFile.open ("./Results.csv",std::ofstream::out | std::ofstream::app); string scenario_id; cout << "Insert Scenario ID: "; // Take input using cin cin >> scenario_id; myStatFile << "Scenario ID,"; myStatFile << scenario_id +","; // @suppress("Function cannot be resolved") #endif ///////////////////////////////////////////////////////////////////////////////////////// /// Timing DATA about simulation ///////////////////////////////////////////////////////////////////////////////////////// cout << endl << "FINAL SIMULATION TIME: " << (((float)(end - start)) / CLOCKS_PER_SEC) << endl; #if defined _SAVE_CSV_ myStatFile << "FINAL SIMULATION TIME,"; myStatFile << to_string((((float)(end - start)) / CLOCKS_PER_SEC)) +","; // @suppress("Function cannot be resolved") #endif cout << endl << "FINAL SIMULATED TIME: " << end_sim.to_seconds() << endl; #if defined _SAVE_CSV_ myStatFile << "FINAL SIMULATED TIME,"; myStatFile << to_string(end_sim.to_seconds()) +","; // @suppress("Function cannot be resolved") #endif ///////////////////////////////////////////////////////////////////////////////////////// // Processes DATA ///////////////////////////////////////////////////////////////////////////////////////// #if defined(_DEBUG_) // Print process mapping for DEBUG cout << endl << "PROCESSES MAPPING" << endl << endl; for (unsigned int j = 2; j<NPS; j++) { cout << "Process " << pSystemManager->VPS[j].name << "[" <<pSystemManager->VPS[j].id << "] is on BB" << pSystemManager->VBB[pSystemManager->allocationPS_BB[j]].getName()<< "[" << pSystemManager->allocationPS_BB[j] << "]" << endl; } cout << endl; #if _WIN32 system("pause"); #endif #endif // Number of times each process has been executed (i.e., number of loops) cout << endl << "PROCESSES PROFILING" << endl; #if defined _SAVE_CSV_ myStatFile << "PROCESSES PROFILING,"; #endif for( unsigned int j=2; j<NPS; j++) { cout << pSystemManager->VPS[j].id << ": " << pSystemManager->VPS[j].profiling << endl; #if defined _SAVE_CSV_ myStatFile << to_string(pSystemManager->VPS[j].profiling) +","; // @suppress("Function cannot be resolved") #endif } cout << endl; #if _WIN32 system("pause"); #endif // Number of bytes exchanged among process cout << endl << "PROCESSES COMMUNICATIONS MATRIX (#written bits from W to R)" << endl; cout << " "; for (int j = 0; j<NPS; j++) { cout << setw(4) << j; } cout << endl; for (int i = 0; i<NPS; i++) { cout << setw(2) << i << " "; for (int j = 0; j<NPS; j++) { pSchedulingManager->matrixCOM[i][j] = 0; for (int k = 0; k<NCH; k++) { if (pSystemManager->VCH[k].getW_id() == i && pSystemManager->VCH[k].getR_id() == j) { pSchedulingManager->matrixCOM[i][j] += pSystemManager->VCH[k].getWidth()*pSystemManager->VCH[k].getNum(); } } cout << setw(4) << pSchedulingManager->matrixCOM[i][j]; } cout << endl; } #if _WIN32 system("pause"); #endif #if defined(_TIMING_ENERGY_) cout << endl << "PROCESS TIME PROFILING" << endl; cout << endl << "Average NET TIME for each process:" << endl << endl; #if defined _SAVE_CSV_ myStatFile << "Average NET TIME,"; // @suppress("Function cannot be resolved") #endif for(unsigned i =2; i<pSystemManager->VPS.size(); i++) { cout << pSystemManager->VPS[i].id << " - " << pSystemManager->VPS[i].name << "\t\t" << (pSystemManager->VPS[i].processTime/pSystemManager->VPS[i].profiling).to_seconds() << endl; tot+=pSystemManager->VPS[i].processTime; #if defined _SAVE_CSV_ myStatFile << to_string((pSystemManager->VPS[i].processTime/pSystemManager->VPS[i].profiling).to_seconds()) +","; // @suppress("Function cannot be resolved") #endif } cout << "Total NET TIME for all the processes:" << tot.to_seconds() << endl; #if defined _SAVE_CSV_ myStatFile << "Total NET TIME,"; // @suppress("Function cannot be resolved") myStatFile << to_string(tot.to_seconds()) +","; // @suppress("Function cannot be resolved") #endif cout << endl << "Schedulers Overhead [time - #loops/#CS]" << endl; #if defined _SAVE_CSV_ myStatFile << "Schedulers Overhead,"; // @suppress("Function cannot be resolved") #endif for(int i = 0; i<NBB; i++) // Figures for SPP will be always 0 { cout << pSchedulingManager->sched_oh[i].to_seconds() << " - " << pSchedulingManager->sched_loops[i] << "/" << pSchedulingManager->sched_CS[i] << endl; tot_sched_oh += pSchedulingManager->sched_oh[i]; #if defined _SAVE_CSV_ myStatFile << to_string(pSchedulingManager->sched_oh[i].to_seconds()) +","; // @suppress("Function cannot be resolved") #endif } cout << "Total overhead for all the schedulers: " << tot_sched_oh.to_seconds() << endl; #if defined _SAVE_CSV_ myStatFile << "Tot Schedulers Overhead,"; // @suppress("Function cannot be resolved") myStatFile << to_string(tot_sched_oh.to_seconds()) +","; // @suppress("Function cannot be resolved") #endif cout << endl; #if _WIN32 system("pause"); #endif #endif ///////////////////////////////////////////////////////////////////////////////////////// /// Communications ///////////////////////////////////////////////////////////////////////////////////////// #if defined(_DEBUG_) cout << endl << "CHANNELS MAPPING" << endl << endl; for(unsigned int j=0; j<NCH; j++) { cout << "Channel " << pSystemManager->VCH[j].name <<"[" <<pSystemManager->VCH[j].id << "] is on Physical Link " << pSystemManager->VPL[pSystemManager->allocationCH_PL[j]].getName()<<"["<< pSystemManager->allocationCH_PL[j]<<"]"<<endl; } cout << endl; #if _WIN32 system("pause"); #endif #endif cout << endl << "COMMUNICATION PROFILING" << endl << endl; // Info about data transfers on CSP channels cout << endl << "CHANNELS PROFILING" << endl << endl; cout << "ID-W-R\tBIT\tNUM\tBIT*NUM\t[TIME(sec)]" << endl << endl; for( unsigned int j=0; j<NCH; j++) { cout << pSystemManager->VCH[j].id << "-" << pSystemManager->VCH[j].w_id << "-" << pSystemManager->VCH[j].r_id << ": " << pSystemManager->VCH[j].width << "\t" << pSystemManager->VCH[j].num << "\t" << pSystemManager->VCH[j].width*pSystemManager->VCH[j].num #if defined(_TIMING_ENERGY_) << "\t" << pSystemManager->VCH[j].working_time.to_seconds() #endif << endl; } cout << endl; #if _WIN32 system("pause"); #endif ///////////////////////////////////////////////////////////////////////////////////////// /// ENERGY DATA ///////////////////////////////////////////////////////////////////////////////////////// #if defined(_TIMING_ENERGY_) // Energy info double totEnergyProcesses = 0; double totEnergyChannels = 0; double totEnergySchedulers = 0; double totEnergyPartSchedulers = 0; double totEnergy = 0; cout << endl << "Average ENERGY for each process:" << endl; #if defined _SAVE_CSV_ myStatFile << "Energy For Processes,"; // @suppress("Function cannot be resolved") #endif for(unsigned i =2; i<pSystemManager->VPS.size(); i++) { cout << pSystemManager->VPS[i].id << " - " << pSystemManager->VPS[i].name << "\t\t" << (pSystemManager->VPS[i].energy/pSystemManager->VPS[i].profiling) <<" uJ"<< endl; totEnergyProcesses+=pSystemManager->VPS[i].getEnergy(); #if defined _SAVE_CSV_ myStatFile << to_string(pSystemManager->VPS[i].energy/pSystemManager->VPS[i].profiling) +","; // @suppress("Function cannot be resolved") #endif } cout<<endl; cout << "Total ENERGY for all the processes: " << totEnergyProcesses <<" uJ" <<endl; #if defined _SAVE_CSV_ myStatFile << "Total Energy Processes,"; // @suppress("Function cannot be resolved") myStatFile << to_string(totEnergyProcesses) +","; // @suppress("Function cannot be resolved") #endif cout << endl << "CHANNEL ENERGY:" << endl<<endl; cout<<"ID-W-R\tENERGY (uJ)"<<endl<<endl; for(unsigned int i = 0; i<NCH; i++) { cout << pSystemManager->VCH[i].id <<"-"<<pSystemManager->VCH[i].w_id << "-" << pSystemManager->VCH[i].r_id << "\t"<< pSystemManager->VCH[i].working_energy <<" uJ"<< endl; totEnergyChannels+=pSystemManager->VCH[i].working_energy; } cout<<endl; cout << "Total ENERGY for all the channels: " << totEnergyChannels <<" uJ" <<endl; cout << endl << "SCHEDULERS ENERGY:" << endl; #if defined _SAVE_CSV_ myStatFile << "SCHEDULERS ENERGY,"; // @suppress("Function cannot be resolved") #endif for(int i = 0; i<NBB; i++) // Figures for SPP will be always 0 { cout << pSchedulingManager->sched_en[i] << " uJ"<<endl; totEnergySchedulers+=pSchedulingManager->sched_en[i]; #if defined _SAVE_CSV_ myStatFile << to_string(pSchedulingManager->sched_en[i]) +","; // @suppress("Function cannot be resolved") #endif } cout<<endl; cout << "Total ENERGY for all the Schedulers: " << totEnergySchedulers <<" uJ" <<endl; #if defined _SAVE_CSV_ myStatFile << "TOT SCHEDULERS ENERGY,"; // @suppress("Function cannot be resolved") myStatFile << to_string(totEnergySchedulers) +","; #endif cout<<endl; totEnergy = totEnergyProcesses + totEnergyChannels + totEnergySchedulers + totEnergyPartSchedulers; cout << endl << "Total Energy (processes + channels + schedulers): " << totEnergy <<" uJ"<<endl; #if defined _LOAD_ pSystemMana
ger->deleteConcXmlEnergy(); pSystemManager->updateXmlEnergy(); #endif #if defined _SAVE_CSV_ myStatFile << "TOTAL ENERGY,"; myStatFile << to_string(totEnergy) +","; // @suppress("Function cannot be resolved") #endif #endif ///////////////////////////////////////////////////////////////////////////////////////// /// LOAD DATA ///////////////////////////////////////////////////////////////////////////////////////// #if (defined(_TIMING_ENERGY_) && defined(_LOAD_)) cout << endl << "LOAD ESTIMATION" << endl; double tot_proc_load = 0; pSystemManager->setFRT(end_sim); pSystemManager->loadEst(end_sim); for(unsigned i =2; i<pSystemManager->VPS.size(); i++) { cout <<endl<<"FRL:"<<" "<< pSystemManager->VPS[i].id << "-" << pSystemManager->VPS[i].name << " " << pSystemManager->getFRL()[i]; tot_proc_load += pSystemManager->getFRL()[i]; } cout << endl << endl << "FINAL TOTAL LOAD: " << tot_proc_load << endl << endl; pSystemManager->deleteConcXmlLoad(); pSystemManager->updateXmlLoad(); #endif ///////////////////////////////////////////////////////////////////////////////////////// /// Report (concurrency) ///////////////////////////////////////////////////////////////////////////////////////// #if ((!defined(_TIMING_ENERGY_)) || (defined(_TIMING_ENERGY_) && defined(_CONCURRENCY_))) // Printed only if (1) functional analizer or (2) timing concurrency // Number of times each process has been concurrently working with the others cout << endl << "POTENTIAL PROCESSES CONCURRENCY" << endl; cout << " "; for (int j=2; j<NPS; j++) { cout<< setw(8) << j; } cout<< endl; for (int i=2; i<NPS; i++) { cout << i << " " ; for (int j=2; j<NPS; j++) { cout<< setw(8) << pSchedulingManager->matrixCONC_PS_RR[i][j]; } cout<<endl; } #if _WIN32 system("pause"); #endif #endif #if (defined(_TIMING_ENERGY_) && defined(_CONCURRENCY_)) // Printed only if timing concurrency // Number of times each process has been concurrently working with the others cout << endl << "ACTUAL PROCESSES CONCURRENCY" << endl; cout << " "; for (int j=2; j<NPS; j++) { cout<< setw(8) << j; } cout<< endl; for (int i=2; i<NPS; i++) { cout << i << " " ; for (int j=2; j<NPS; j++) { cout<< setw(8) << pSchedulingManager->matrixCONC_PS_R[i][j]; } cout<<endl; } #if _WIN32 system("pause"); #endif #endif #if ((!defined(_TIMING_ENERGY_)) || (defined(_TIMING_ENERGY_) && defined(_CONCURRENCY_))) // Printed only if (1) functional analizer or (2) timing concurrency // Number of times each process has been concurrent with the others //with respect to the number of checks cout << endl << "NORMALIZED POTENTIAL PROCESSES CONCURRENCY (#TEST: " << pSchedulingManager->num_tests_CONC_PS_RR << ")" << endl; cout<< " "; for (int j=2; j<NPS; j++) { cout<< setw(8) << j; } cout<< endl; for (int i=2; i<NPS; i++) { cout<< setw(2) << i << " " ; for (int j=2; j<NPS; j++) { pSchedulingManager->matrixCONC_PS_RR_N[i][j] = pSchedulingManager->matrixCONC_PS_RR[i][j]/(float)pSchedulingManager->num_tests_CONC_PS_RR; cout<< setw(8) << setprecision(2) << pSchedulingManager->matrixCONC_PS_RR_N[i][j]; } cout<<endl; } #if _WIN32 system("pause"); #endif #endif #if (defined(_TIMING_ENERGY_) && defined(_CONCURRENCY_)) // Printed only if timing concurrency // Number of times each process has been concurrent with the others //with respect to the number of checks cout << endl << "NORMALIZED ACTUAL PROCESSES CONCURRENCY (#TEST: " << pSchedulingManager->num_tests_CONC_PS_R << ")" << endl; cout<< " "; for (int j=2; j<NPS; j++) { cout<< setw(8) << j; } cout<< endl; for (int i=2; i<NPS; i++) { cout<< setw(2) << i << " " ; for (int j=2; j<NPS; j++) { pSchedulingManager->matrixCONC_PS_R_N[i][j] = pSchedulingManager->matrixCONC_PS_R[i][j]/(float)pSchedulingManager->num_tests_CONC_PS_R; cout<< setw(8) << setprecision(2) << pSchedulingManager->matrixCONC_PS_R_N[i][j]; } cout<<endl; } #if _WIN32 system("pause"); #endif #endif #if ((!defined(_TIMING_ENERGY_)) || (defined(_TIMING_ENERGY_) && defined(_CONCURRENCY_))) // Printed only if (1) functional analizer or (2) timing concurrency // Number of times each channels has been concurrently working with the others cout << endl << "POTENTIAL CHANNELS CONCURRENCY" << endl; cout<< setw(2) << " "; for (int j=0; j<NCH; j++) { cout<< setw(8) << j; } cout<< endl; for (int i=0; i<NCH; i++) { cout<< setw(2) << i << " " ; for (int j=0; j<NCH; j++) { cout<< setw(8) << setprecision(2) << pSchedulingManager->matrixCONC_CH_RR[i][j]; } cout<<endl; } #if _WIN32 system("pause"); #endif #endif #if (defined(_TIMING_ENERGY_) && defined(_CONCURRENCY_)) // Printed only if timing concurrency // Number of times each channels has been concurrently working with the others cout << endl << "ACTUAL CHANNELS CONCURRENCY" << endl; cout<< setw(2) << " "; for (int j=0; j<NCH; j++) { cout<< setw(8) << j; } cout<< endl; for (int i=0; i<NCH; i++) { cout<< setw(2) << i << " " ; for (int j=0; j<NCH; j++) { cout<< setw(8) << setprecision(2) << pSchedulingManager->matrixCONC_CH_R[i][j]; } cout<<endl; } #if _WIN32 system("pause"); #endif #endif #if ((!defined(_TIMING_ENERGY_)) || (defined(_TIMING_ENERGY_) && defined(_CONCURRENCY_))) // Printed only if (1) functional analizer or (2) timing concurrency // Number of times each channels has been concurrently working with the others //with respect to the number of checks cout << endl << "NORMALIZED POTENTIAL CHANNELS CONCURRENCY (#TEST: " << pSchedulingManager->num_tests_CONC_CH_RR << ")" << endl; cout<< setw(2) << " "; for (int j=0; j<NCH; j++) { cout<< setw(8) << j; } cout<< endl; for (int i=0; i<NCH; i++) { cout<< setw(2) << i << " " ; for (int j=0; j<NCH; j++) { pSchedulingManager->matrixCONC_CH_RR_N[i][j] = pSchedulingManager->matrixCONC_CH_RR[i][j]/(float)pSchedulingManager->num_tests_CONC_CH_RR; cout<< setw(8) << setprecision(2) << pSchedulingManager->matrixCONC_CH_RR_N[i][j]; } cout<<endl; } #if _WIN32 system("pause"); #endif #endif #if (defined(_TIMING_ENERGY_) && defined(_CONCURRENCY_)) // Printed only if timing concurrency // Number of times each channels has been concurrently working with the others //with respect to the number of checks cout << endl << "NORMALIZED ACTUAL CHANNELS CONCURRENCY (#TEST: " << pSchedulingManager->num_tests_CONC_CH_R << ")" << endl; cout<< setw(2) << " "; for (int j=0; j<NCH; j++) { cout<< setw(8) << j; } cout<< endl; for (int i=0; i<NCH; i++) { cout<< setw(2) << i << " " ; for (int j=0; j<NCH; j++) { pSchedulingManager->matrixCONC_CH_R_N[i][j] = pSchedulingManager->matrixCONC_CH_R[i][j]/(float)pSchedulingManager->num_tests_CONC_CH_R; cout<< setw(8) << setprecision(2) << pSchedulingManager->matrixCONC_CH_R_N[i][j]; } cout<<endl; } #if _WIN32 system("pause"); #endif // Number of times each BB has been concurrently active with the others cout << endl << "ACTUAL BB CONCURRENCY" << endl; cout<< setw(2) << " "; for (int j=0; j<NBB; j++) { cout<< setw(8) << j; } cout<< endl; for (int i=0; i<NBB; i++) { cout<< setw(2) << i << " " ; for (int j=0; j<NBB; j++) { cout<< setw(8) << setprecision(2) << pSchedulingManager->matrixCONC_BB[i][j]; } cout<<endl; } #if _WIN32 system("pause"); #endif // Number of times each BB has been concurrently active with the others //with respect to the number of checks cout << endl << "NORMALIZED ACTUAL BB CONCURRENCY (#TEST: " << pSchedulingManager->num_tests_CONC_BB << ")" << endl; cout<< setw(2) << " "; for (int j=0; j<NBB; j++) { cout<< setw(8) << j; } cout<< endl; for (int i=0; i<NBB; i++) { cout<< setw(2) << i << " " ; for (int j=0; j<NBB; j++) { pSchedulingManager->matrixCONC_BB_N[i][j] = pSchedulingManager->matrixCONC_BB[i][j]/(float)pSchedulingManager->num_tests_CONC_BB; cout<< setw(8) << setprecision(2) << pSchedulingManager->matrixCONC_BB_N[i][j]; } cout<<endl; } #if _WIN32 system("pause"); #endif // Number of times a group of BBs have been concurrently active cout << endl << "ACTUAL BB GROUP CONCURRENCY" << endl; for (int j=0; j<NBB+1; j++) { cout << j << " ACTIVE BBs: " << pSchedulingManager->vectorCONC_BB[j] << endl; } // Number of times a group of BBs have been concurrently active cout << endl << "NORMALIZED ACTUAL BB GROUP CONCURRENCY (#TEST: " << pSchedulingManager->num_tests_CONC_BB << ")" << endl; for (int j=0; j<NBB+1; j++) { pSchedulingManager->vectorCONC_BB_N[j] = pSchedulingManager->vectorCONC_BB[j]/(float)pSchedulingManager->num_tests_CONC_BB; cout << j << " ACTIVE BBs: " << pSchedulingManager->vectorCONC_BB_N[j] << endl; } #if _WIN32 system("pause"); #endif #endif #if ((!defined(_TIMING_ENERGY_))) // || (defined(_TIMING_ENERGY_) && defined(_CONCURRENCY_))) // Printed only if (1) functional analizer or (2) timing concurrency cout << "Processes and Channels Concurrency, and Channels Communication XML update" << endl; // LP: Da controllare pSystemManager->deleteConcXmlConCom(); // LP: da controllare pSystemManager->updateXmlConCom(pSchedulingManager->matrixCONC_PS_RR_N, pSchedulingManager->matrixCOM, pSchedulingManager->matrixCONC_CH_RR_N); #endif #if defined _SAVE_CSV_ myStatFile << "\n";; // Save information about final population statistics into csv file myStatFile.close(); #endif #if _WIN32 system("pause"); #endif return 0; } /** @} */ // end of firfirgcd_main_group /******************************************************************************** *** EOF *** ********************************************************************************/
/******************************************************************************* * pcf8574.cpp -- Copyright 2020 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This is a crude model for the PN532 with firmware v1.6. It will work for * basic work with a PN532 system. ******************************************************************************* * 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 "pcf8574.h" #include "info.h" unsigned char pcf8574::sampleport() { unsigned char samp = 0; int cnt; for(cnt = 0; cnt < sig.size(); cnt = cnt + 1) { if (!sig[cnt]->read().islogic()) { PRINTF_WARN("PCF8574", "Sampled a signal at level %c", sig[cnt]->read().to_char()); } else if (sig[cnt]->read().ishigh()) samp = samp | (1 << cnt); } return samp; } void pcf8574::intr_th() { intr.write(GN_LOGIC_Z); while(1) { switch (sig.size()) { case 0: wait(clearintr_ev); break; case 1: wait(clearintr_ev | sig[0]->default_event()); break; case 2: wait(clearintr_ev | sig[0]->default_event() | sig[1]->default_event()); break; case 3: wait(clearintr_ev | sig[0]->default_event() | sig[1]->default_event() | sig[2]->default_event()); break; case 4: wait(clearintr_ev | sig[0]->default_event() | sig[1]->default_event() | sig[2]->default_event() | sig[3]->default_event()); break; case 5: wait(clearintr_ev | sig[0]->default_event() | sig[1]->default_event() | sig[2]->default_event() | sig[3]->default_event() | sig[4]->default_event()); break; case 6: wait(clearintr_ev | sig[0]->default_event() | sig[1]->default_event() | sig[2]->default_event() | sig[3]->default_event() | sig[4]->default_event() | sig[5]->default_event()); break; case 7: wait(clearintr_ev | sig[0]->default_event() | sig[1]->default_event() | sig[2]->default_event() | sig[3]->default_event() | sig[4]->default_event() | sig[5]->default_event() | sig[6]->default_event()); break; default: wait(clearintr_ev | sig[0]->default_event() | sig[1]->default_event() | sig[2]->default_event() | sig[3]->default_event() | sig[4]->default_event() | sig[5]->default_event() | sig[6]->default_event() | sig[7]->default_event()); break; } /* If we got a lowerintr we lower the line. Anything else raises it. * Note that we do not raise the interrupt while we were writing. */ if (clearintr_ev.triggered()) intr.write(GN_LOGIC_Z); else if (i2cstate != WRDATA && i2cstate != ACKWRD && i2cstate != ACKWR) intr.write(GN_LOGIC_0); } } void pcf8574::i2c_th(void) { int i; unsigned int devid, data; /* We begin initializing all ports to weak 1. */ for(i = 0; i < sig.size(); i = i + 1) { sig[i]->write(GN_LOGIC_W1); } /* The interrupt begins as Z. */ intr.write(GN_LOGIC_Z); /* Then we begin waiting for the I2C commands. */ while(1) { /* We wait for a change on either the SDA or the SCL. */ wait(); state.write((int)i2cstate); /* If we get Z or X, we ignore it. */ if (!scl.read().islogic()) { PRINTF_WARN("PN532", "SCL is not defined"); } else if (!sda.read().islogic()) { PRINTF_WARN("PN532", "SDA is not defined"); } /* At any time a start or stop bit can come in. */ else if (scl.read().ishigh() && sda.value_changed_event().triggered()) { if (sda.read().islow()) { /* START BIT */ i2cstate = DEVID; i = 7; devid = 0; } /* STOP BIT */ else i2cstate = IDLE; } /* The rest has to be data changes. For simplicity all data in and flow * control is here. The data returned is done on another branch. */ else if (scl.value_changed_event().triggered() && scl.read().ishigh()) switch(i2cstate) { case IDLE: break; case DEVID: /* We collect all bits of the device ID. The last bit is the R/W * bit. */ if (i > 0) devid = (devid << 1) + ((sda.read().ishigh())?1:0); /* If the ID matches, we can process it. */ else if (devid == device_id && sda.read().ishigh()) i2cstate=ACKRD; else if (devid == device_id && sda.read().islow()) i2cstate=ACKWR; /* If the devid does not match, we return Z. */ else i2cstate = RETZ; i = i - 1; break; /* If the address does not match, we return Z. */ case RETZ: i2cstate = IDLE; break; /* When we recognize the ACKRD, we sample the pins. This will be * returned via the I2C. */ case ACKRD: i = 7; i2cstate = READ; data = sampleport(); /* We also clear the interrupt. */ clearintr_ev.notify(); break; /* When we hit the ACKWR, all we do is clear the shiftregister to * begin to receive data. */ case ACKWR: i = 7; data = 0; i2cstate = WRDATA; /* We also clear the interrupt. */ clearintr_ev.notify(); break; /* Each bit is taken. */ case WRDATA: /* Just when we enter the WRDATA phase we need to release the SDA */ if (i == 7) sda.write(GN_LOGIC_Z); /* And the data we collect to drive in the WRD phase. */ data = (data << 1) + ((sda.read().ishigh())?1:0); if (i == 0) i2cstate = ACKWRD; else i = i - 1; break; /* When we have finished a write, we send back an ACK to the master. * We also will drive all pins strong. */ case ACKWRD: { /* We first take in the new drive value received. */ drive = data; /* In the ACKWRD state, we drive all pins strong, once we exit, we * lower the logic 1s to weak so that they can be read. */ if (i2cstate == ACKWRD) { int cnt; for (cnt = 0; cnt < sig.size(); cnt = cnt + 1) { sig[cnt]->write(((drive & (1<<cnt))>0)?GN_LOGIC_1:GN_LOGIC_0); } } /* Then we clear the shiftregister to begin to collect data from * the master. */ data = 0; i = 7; i2cstate = WRDATA; /* We also clear the interrupt. */ clearintr_ev.notify(); break; } /* Depending on the acknack we either return more data or not. */ case ACKNACK: if (sda.read().ishigh()) i2cstate = IDLE; else { /* If we got the ACK, we then clear the registers, sample the * I/Os and return to the read state. */ i2cstate = READ; i = 7; data = sampleport(); } break; /* On reads, we send the data after each bit change. Note: the driving * is done on the other edge. */ case READ: if (i == 0) i2cstate = ACKNACK; else i = i - 1; break; } /* Anytime the clock drops, we return data. We only do the data return * to keep the FSM simpler. */ else if (scl.value_changed_event().triggered() && scl.read().islow()) switch (i2cstate) { /* If we get an illegal code, we return Z. We remain here until * we get. */ case RETZ: sda.write(GN_LOGIC_Z); break; /* ACKWRD, ACKWR and ACKRD we return a 0. */ case ACKRD: case ACKWR: case ACKWRD: sda.write(GN_LOGIC_0); break; /* For the WRITE state, all we do is release the SDA so that the * master can write. */ case WRDATA: /* When we enter the WRDATA, we need to weaken the driving logic 1s. * We then scan through them and redrive any of them from 1 to W1. * We only need to do this if it is not all 0s. */ if (i == 7 && drive != 0x0) { int cnt; for (cnt = 0; cnt < sig.size(); cnt = cnt + 1) { if ((drive & (1<<cnt))>0) sig[cnt]->write(GN_LOGIC_W1); } } break; case ACKNACK: /* The SDA we float. */ sda.write(GN_LOGIC_Z); break; /* Each bit is returned. */ case READ: if ((data & (1 << i))>0) sda.write(GN_LOGIC_Z); else sda.write(GN_LOGIC_0); break; default: ; /* For the others we do nothing. */ } } } void pcf8574::trace(sc_trace_file *tf) { sc_trace(tf, state, state.name()); }
/* Problem 3 Testbench */ #include<systemc.h> #include<comm.cpp> SC_MODULE(communicationInterfaceTB) { sc_signal<sc_uint<12> > inData; sc_signal<bool> clock , reset , clear; sc_signal<sc_uint<4> > payloadOut; sc_signal<sc_uint<8> > countOut , errorOut; void clockSignal(); void clearSignal(); void resetSignal(); void inDataSignal(); communicationInterface* cI; SC_CTOR(communicationInterfaceTB) { cI = new communicationInterface ("CI"); cI->clock(clock); cI->inData(inData); cI->reset(reset); cI->clear(clear); cI->payloadOut(payloadOut); cI->countOut(countOut); cI->errorOut(errorOut); SC_THREAD(clockSignal); SC_THREAD(clearSignal); SC_THREAD(resetSignal); SC_THREAD(inDataSignal); } }; void communicationInterfaceTB::clockSignal() { while (true){ wait(20 , SC_NS); clock = false; wait(20 , SC_NS); clock = true; } } void communicationInterfaceTB::clearSignal() { while (true){ wait(10 , SC_NS); clear = false; wait(100 , SC_NS); clear = true; wait(10 , SC_NS); clear = false; wait(100 , SC_NS); } } void communicationInterfaceTB::resetSignal() { while (true) { wait(10 , SC_NS); reset = true; wait(70 , SC_NS); reset = false; wait(10 , SC_NS); reset = true; wait(1000 , SC_NS); } } void communicationInterfaceTB::inDataSignal() { while (true) { wait(10 , SC_NS); inData = 497; wait(30 , SC_NS); inData = 224; wait(50 , SC_NS); inData = 369; wait(30 , SC_NS); inData = 224; wait(30 , SC_NS); } } int sc_main(int argc , char* argv[]) { cout<<"@ "<<sc_time_stamp()<<"----------Start---------"<<endl; communicationInterfaceTB* cITB = new communicationInterfaceTB ("CITB"); cout<<"@ "<<sc_time_stamp()<<"----------Testbench Instance Created---------"<<endl; sc_trace_file* VCDFile; VCDFile = sc_create_vcd_trace_file("communication-interface"); cout<<"@ "<<sc_time_stamp()<<"----------VCD File Created---------"<<endl; sc_trace(VCDFile, cITB->clock, "Clock"); sc_trace(VCDFile, cITB->inData, "inData"); sc_trace(VCDFile, cITB->reset, "reset"); sc_trace(VCDFile, cITB->clear, "clear"); sc_trace(VCDFile, cITB->payloadOut, "payloadOut"); sc_trace(VCDFile, cITB->countOut, "countOut"); sc_trace(VCDFile, cITB->errorOut, "errorOut"); cout<<"@ "<<sc_time_stamp()<<"----------Start Simulation---------"<<endl; sc_start(4000, SC_NS); cout<<"@ "<<sc_time_stamp()<<"----------End Simulation---------"<<endl; return 0; }
/************************************************/ // Copyright tlm_noc contributors. // Author Mike // SPDX-License-Identifier: Apache-2.0 /************************************************/ #include <systemc.h> #include <tlm.h> #include <tlm_utils/peq_with_cb_and_phase.h> #include <tlm_utils/simple_initiator_socket.h> #include <tlm_utils/simple_target_socket.h> #include "pe_base.h" #include "host_base.h" #include "host.h" #include "router.h" #include "l2cache.h" #include "dumpWave.h" using namespace std; using namespace tlm; #include <systemc.h> #include <tlm.h> int sc_main (int, char **) { ofstream outfile("./build/wavedump.txt"); if (!outfile.is_open()) { std::cerr << "Error opening file!" << std::endl; return 1; } char blkName[100]; sc_set_time_resolution(1, SC_NS); int i = 0; int j = 0; int m = 0; int h = 0; // ----------------------------------- // // create object // ----------------------------------- // pe_base* pe[N_PE]; for (int i = 0; i < N_PE; i++) { sprintf(blkName, "PE%d", i); pe[i] = new pe_base(blkName); } i = 0; Router* R[N_PE]; for (int r = 0; r < N_PE_ROW; r++) { for (int c = 0; c < N_PE_COL; c++) { sprintf(blkName, "router(%d,%d)", r, c); R[i] = new Router(blkName, r, c); i++; } } host_base* HP[N_HOST_BASE +1]; for (int i = 0; i < N_HOST_BASE +1; i++) { if (i < 1) { sprintf(blkName, "Host_%d", i); HP[i] = new host(blkName, i); } else { sprintf(blkName, "HostDummy_%d", i); HP[i] = new host_base(blkName); } } l2cache* mem[N_SM]; for (int i = 0; i < N_SM; i++) { sprintf(blkName, "MEM%d", i); mem[i] = new l2cache(blkName); } // ----------------------------------- // // bind PEs // ----------------------------------- // for (int i = 0; i < N_PE; i++) { pe[i]->m_port.bind(R[i]->s_port[Local]); R[i]->m_port[Local].bind(pe[i]->s_port); } // ----------------------------------- // // East2West // ----------------------------------- // cout << "Route: Eest2West" << endl; for (int r = 0; r < N_PE_ROW; r++) { for (int c = 0; c < N_PE_COL-1; c++) { i = r*N_PE_ROW+c; j = i + 1; R[i]->m_port[West].bind(R[j]->s_port[West]); cout << "R" << i << "<---->" << "R" << j << " "; } cout << endl; } cout << "bind Host:" << endl; for (int r = 0; r < N_PE_ROW; r++) { i = r*N_PE_COL; HP[h++]->m_port.bind(R[i]->s_port[West]); cout << "Host" << h-1 << "<---->" << "R" << i << " "; cout << endl; } cout << "bind Mem" << endl; for (int r = 0; r < N_PE_ROW; r++) { i = (r+1)*N_PE_COL -1; R[i]->m_port[West].bind(mem[m++]->s_port); cout << "MEM" << m-1 << "<---->" << "R" << i << " "; cout << endl; } // ----------------------------------- // // West2East // ----------------------------------- // cout << "Route: West2East" << endl; for (int r = 0; r < N_PE_ROW; r++) { for (int c = N_PE_COL-1; c > 0; c--) { i = r*N_PE_ROW+c; j = i - 1; R[i]->m_port[East].bind(R[j]->s_port[East]); cout << "R" << i << "<---->" << "R" << j << " "; } cout << endl; } cout << "bind Host:" << endl; for (int r = 0; r < N_PE_ROW; r++) { i = (r+1)*N_PE_COL-1; HP[h++]->m_port.bind(R[i]->s_port[East]); cout << "Host" << h-1 << "<---->" << "R" << i << " "; cout << endl; } cout << "bind Mem" << endl; for (int r = 0; r < N_PE_ROW; r++) { i = r*N_PE_COL; R[i]->m_port[East].bind(mem[m++]->s_port); cout << "MEM" << m-1 << "<---->" << "R" << i << " "; cout << endl; } // ----------------------------------- // // South2North // ----------------------------------- // cout << "Route: South2North" << endl; for (int c = 0; c < N_PE_COL; c++) { for (int r = 0; r < N_PE_ROW-1; r++) { i = r*N_PE_COL+c; j = i + N_PE_COL; R[i]->m_port[North].bind(R[j]->s_port[North]); cout << "R" << i << "<---->" << "R" << j << " "; } cout << endl; } cout << "bind Host:" << endl; for (int c = 0; c < N_PE_COL; c++) { i = c; HP[h++]->m_port.bind(R[i]->s_port[North]); cout << "Host" << h-1 << "<---->" << "R" << i << " "; cout << endl; } cout << "bind Mem" << endl; for (int c = 0; c < N_PE_COL; c++) { i = (N_PE_ROW -1) * N_PE_COL + c; R[i]->m_port[North].bind(mem[m++]->s_port); cout << "MEM" << m-1 << "<---->" << "R" << i << " "; cout << endl; } // ----------------------------------- // // North2South // ----------------------------------- // cout << "Route: North2South" << endl; for (int c = 0; c < N_PE_COL; c++) { for (int r = N_PE_ROW-1; r > 0; r--) { i = r*N_PE_COL+c; j = i - N_PE_COL; R[i]->m_port[South].bind(R[j]->s_port[South]); cout << "R" << i << "<---->" << "R" << j << " "; } cout << endl; } cout << "bind Host:" << endl; for (int c = 0; c < N_PE_COL; c++) { i = (N_PE_ROW-1) * N_PE_COL+ c; HP[h++]->m_port.bind(R[i]->s_port[South]); cout << "Host" << h-1 << "<---->" << "R" << i << " "; cout << endl; } cout << "bind Mem" << endl; for (int c = 0; c < N_PE_COL; c++) { i = c; R[i]->m_port[South].bind(mem[m++]->s_port); cout << "MEM" << m-1 << "<---->" << "R" << i << " "; cout << endl; } sc_start(100, SC_MS); cout << "----dump Wavefrom file----" << endl; for (int i=0; i<9; i++) outfile << R[i]->sbuff << endl; return 0; }
/******************************************************************************** * 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 <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <unistd.h> ////////////////////////////// GENANN ////////////////// #ifdef __cplusplus extern "C" { #endif #ifndef ann_01_GENANN_RANDOM /* We use the following for uniform random numbers between 0 and 1. * If you have a better function, redefine this macro. */ #define ann_01_GENANN_RANDOM() (((double)rand())/RAND_MAX) #endif struct ann_01_genann; typedef double (*ann_01_genann_actfun)(const struct ann_01_genann *ann, double a); typedef struct ann_01_genann { /* How many inputs, outputs, and hidden neurons. */ int inputs, hidden_layers, hidden, outputs; /* Which activation function to use for hidden neurons. Default: gennann_act_sigmoid_cached*/ ann_01_genann_actfun activation_hidden; /* Which activation function to use for output. Default: gennann_act_sigmoid_cached*/ ann_01_genann_actfun activation_output; /* Total number of weights, and size of weights buffer. */ int total_weights; /* Total number of neurons + inputs and size of output buffer. */ int total_neurons; /* All weights (total_weights long). */ double *weight; /* Stores input array and output of each neuron (total_neurons long). */ double *output; /* Stores delta of each hidden and output neuron (total_neurons - inputs long). */ double *delta; } ann_01_genann; #ifdef __cplusplus } #endif ///////////////////////////////////// GENANN /////////////////////////// #ifndef ann_01_genann_act #define ann_01_genann_act_hidden ann_01_genann_act_hidden_indirect #define ann_01_genann_act_output ann_01_genann_act_output_indirect #else #define ann_01_genann_act_hidden ann_01_genann_act #define ann_01_genann_act_output ann_01_genann_act #endif #define ann_01_LOOKUP_SIZE 4096 double ann_01_genann_act_hidden_indirect(const struct ann_01_genann *ann, double a) { return ann->activation_hidden(ann, a); } double ann_01_genann_act_output_indirect(const struct ann_01_genann *ann, double a) { return ann->activation_output(ann, a); } const double ann_01_sigmoid_dom_min = -15.0; const double ann_01_sigmoid_dom_max = 15.0; double ann_01_interval; double ann_01_lookup[ann_01_LOOKUP_SIZE]; #ifdef __GNUC__ #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #define unused __attribute__((unused)) #else #define likely(x) x #define unlikely(x) x #define unused #pragma warning(disable : 4996) /* For fscanf */ #endif double ann_01_genann_act_sigmoid(const ann_01_genann *ann unused, double a) { if (a < -45.0) return 0; if (a > 45.0) return 1; return 1.0 / (1 + exp(-a)); } void ann_01_genann_init_sigmoid_lookup(const ann_01_genann *ann) { const double f = (ann_01_sigmoid_dom_max - ann_01_sigmoid_dom_min) / ann_01_LOOKUP_SIZE; int i; ann_01_interval = ann_01_LOOKUP_SIZE / (ann_01_sigmoid_dom_max - ann_01_sigmoid_dom_min); for (i = 0; i < ann_01_LOOKUP_SIZE; ++i) { ann_01_lookup[i] = ann_01_genann_act_sigmoid(ann, ann_01_sigmoid_dom_min + f * i); } } double ann_01_genann_act_sigmoid_cached(const ann_01_genann *ann unused, double a) { assert(!isnan(a)); if (a < ann_01_sigmoid_dom_min) return ann_01_lookup[0]; if (a >= ann_01_sigmoid_dom_max) return ann_01_lookup[ann_01_LOOKUP_SIZE - 1]; size_t j = (size_t)((a-ann_01_sigmoid_dom_min)*ann_01_interval+0.5); /* Because floating point... */ if (unlikely(j >= ann_01_LOOKUP_SIZE)) return ann_01_lookup[ann_01_LOOKUP_SIZE - 1]; return ann_01_lookup[j]; } double ann_01_genann_act_linear(const struct ann_01_genann *ann unused, double a) { return a; } double ann_01_genann_act_threshold(const struct ann_01_genann *ann unused, double a) { return a > 0; } void ann_01_genann_randomize(ann_01_genann *ann) { int i; for (i = 0; i < ann->total_weights; ++i) { double r = ann_01_GENANN_RANDOM(); /* Sets weights from -0.5 to 0.5. */ ann->weight[i] = r - 0.5; } } ann_01_genann *ann_01_genann_init(int inputs, int hidden_layers, int hidden, int outputs) { if (hidden_layers < 0) return 0; if (inputs < 1) return 0; if (outputs < 1) return 0; if (hidden_layers > 0 && hidden < 1) return 0; const int hidden_weights = hidden_layers ? (inputs+1) * hidden + (hidden_layers-1) * (hidden+1) * hidden : 0; const int output_weights = (hidden_layers ? (hidden+1) : (inputs+1)) * outputs; const int total_weights = (hidden_weights + output_weights); const int total_neurons = (inputs + hidden * hidden_layers + outputs); /* Allocate extra size for weights, outputs, and deltas. */ const int size = sizeof(ann_01_genann) + sizeof(double) * (total_weights + total_neurons + (total_neurons - inputs)); ann_01_genann *ret = (ann_01_genann *)malloc(size); if (!ret) return 0; ret->inputs = inputs; ret->hidden_layers = hidden_layers; ret->hidden = hidden; ret->outputs = outputs; ret->total_weights = total_weights; ret->total_neurons = total_neurons; /* Set pointers. */ ret->weight = (double*)((char*)ret + sizeof(ann_01_genann)); ret->output = ret->weight + ret->total_weights; ret->delta = ret->output + ret->total_neurons; ann_01_genann_randomize(ret); ret->activation_hidden = ann_01_genann_act_sigmoid_cached; ret->activation_output = ann_01_genann_act_sigmoid_cached; ann_01_genann_init_sigmoid_lookup(ret); return ret; } void ann_01_genann_free(ann_01_genann *ann) { /* The weight, output, and delta pointers go to the same buffer. */ free(ann); } //genann *genann_read(FILE *in) //genann *genann_copy(genann const *ann) double const *ann_01_genann_run(ann_01_genann const *ann, double const *inputs) { double const *w = ann->weight; double *o = ann->output + ann->inputs; double const *i = ann->output; /* Copy the inputs to the scratch area, where we also store each neuron's * output, for consistency. This way the first layer isn't a special case. */ memcpy(ann->output, inputs, sizeof(double) * ann->inputs); int h, j, k; if (!ann->hidden_layers) { double *ret = o; for (j = 0; j < ann->outputs; ++j) { double sum = *w++ * -1.0; for (k = 0; k < ann->inputs; ++k) { sum += *w++ * i[k]; } *o++ = ann_01_genann_act_output(ann, sum); } return ret; } /* Figure input layer */ for (j = 0; j < ann->hidden; ++j) { double sum = *w++ * -1.0; for (k = 0; k < ann->inputs; ++k) { sum += *w++ * i[k]; } *o++ = ann_01_genann_act_hidden(ann, sum); } i += ann->inputs; /* Figure hidden layers, if any. */ for (h = 1; h < ann->hidden_layers; ++h) { for (j = 0; j < ann->hidden; ++j) { double sum = *w++ * -1.0; for (k = 0; k < ann->hidden; ++k) { sum += *w++ * i[k]; } *o++ = ann_01_genann_act_hidden(ann, sum); } i += ann->hidden; } double const *ret = o; /* Figure output layer. */ for (j = 0; j < ann->outputs; ++j) { double sum = *w++ * -1.0; for (k = 0; k < ann->hidden; ++k) { sum += *w++ * i[k]; } *o++ = ann_01_genann_act_output(ann, sum); } /* Sanity check that we used all weights and wrote all outputs. */ assert(w - ann->weight == ann->total_weights); assert(o - ann->output == ann->total_neurons); return ret; } //void genann_train(genann const *ann, double const *inputs, double const *desired_outputs, double learning_rate) //void genann_write(genann const *ann, FILE *out) /////////////////////// ANN //////////////////////// #define ann_01_NUM_DEV 1 // The equipment is composed of NUM_DEV devices ... //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- #define ann_01_MAX_ANN 100 // Maximum MAX_ANN ANN #define ann_01_ANN_INPUTS 2 // Number of inputs #define ann_01_ANN_HIDDEN_LAYERS 1 // Number of hidden layers #define ann_01_ANN_HIDDEN_NEURONS 2 // Number of neurons of every hidden layer #define ann_01_ANN_OUTPUTS 1 // Number of outputs //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- #define ann_01_ANN_EPOCHS 10000 #define ann_01_ANN_DATASET 6 #define ann_01_ANN_LEARNING_RATE 3 // ... //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- #define ann_01_MAX_ERROR 0.00756 // 0.009 //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- static int ann_01_nANN = -1 ; // Number of ANN that have been created static ann_01_genann * ann_01_ann[ann_01_MAX_ANN] ; // Now up to MAX_ANN ann //static double ann_01_trainingInput[ann_01_ANN_DATASET][ann_01_ANN_INPUTS] = { {0, 0}, {0, 1}, {1, 0}, {1, 1}, {0, 1}, {0, 0} } ; //static double ann_01_trainingExpected[ann_01_ANN_DATASET][ann_01_ANN_OUTPUTS] = { {0}, {1}, {1}, {0}, {1}, {0} } ; static double ann_01_weights[] = { -3.100438, -7.155774, -7.437955, -8.132828, -5.583678, -5.327152, 5.564897, -12.201226, 11.771879 } ; // static double input[4][3] = {{0, 0, 1}, {0, 1, 1}, {1, 0, 1}, {1, 1, 1}}; // static double output[4] = {0, 1, 1, 0}; //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- static int ann_01_annCheck(int index); static int ann_01_annCreate(int n); //----------------------------------------------------------------------------- // Check the correctness of the index of the ANN //----------------------------------------------------------------------------- int ann_01_annCheck(int index) { if ( (index < 0) || (index >= ann_01_nANN) ) return( EXIT_FAILURE ); return( EXIT_SUCCESS ); } //----------------------------------------------------------------------------- // Create n ANN //----------------------------------------------------------------------------- int ann_01_annCreate(int n) { // If already created, or not legal number, or too many ANN, then error if ( (ann_01_nANN != -1) || (n <= 0) || (n > ann_01_MAX_ANN) ) return( EXIT_FAILURE ); // Create the ANN's for ( int i = 0; i < n; i++ ) { // New ANN with ANN_INPUT inputs, ANN_HIDDEN_LAYER hidden layers all with ANN_HIDDEN_NEURON neurons, and ANN_OUTPUT outputs ann_01_ann[i] = ann_01_genann_init(ann_01_ANN_INPUTS, ann_01_ANN_HIDDEN_LAYERS, ann_01_ANN_HIDDEN_NEURONS, ann_01_ANN_OUTPUTS); if ( ann_01_ann[i] == 0 ) { for (int j = 0; j < i; j++) ann_01_genann_free(ann_01_ann[j]) ; return( EXIT_FAILURE ); } } ann_01_nANN = n ; return( EXIT_SUCCESS ); } ////----------------------------------------------------------------------------- //// Create and train n identical ANN ////----------------------------------------------------------------------------- //int annCreateAndTrain(int n) //{ // if ( annCreate(n) != EXIT_SUCCESS ) // return( EXIT_FAILURE ); // // // Train the ANN's // for ( int index = 0; index < nANN; index++ ) // for ( int i = 0; i < ANN_EPOCHS; i++ ) // for ( int j = 0; j < ANN_DATASET; j++ ) // genann_train(ann[index], trainingInput[j], trainingExpected[j], ANN_LEARNING_RATE) ; // // return( EXIT_SUCCESS ); //} //----------------------------------------------------------------------------- // Create n identical ANN and set their weight //----------------------------------------------------------------------------- int ann_01_annCreateAndSetWeights(int n) { if ( ann_01_annCreate(n) != EXIT_SUCCESS ) return( EXIT_FAILURE ); // Set weights for ( int index = 0; index < ann_01_nANN; index++ ) for ( int i = 0; i < ann_01_ann[index]->total_weights; ++i ) ann_01_ann[index]->weight[i] = ann_01_weights[i] ; return( EXIT_SUCCESS ); } //----------------------------------------------------------------------------- // x[2] = x[0] XOR x[1] //----------------------------------------------------------------------------- int ann_01_annRun(int index, double x[ann_01_ANN_INPUTS + ann_01_ANN_OUTPUTS]) { if ( ann_01_annCheck(index) != EXIT_SUCCESS ) return( EXIT_FAILURE ) ; x[2] = * ann_01_genann_run(ann_01_ann[index], x) ; return( EXIT_SUCCESS ); } ////----------------------------------------------------------------------------- //// ////----------------------------------------------------------------------------- //int annPrintWeights(int index) //{ // if ( annCheck(index) != EXIT_SUCCESS ) // return( EXIT_FAILURE ) ; // // // printf("\n*** ANN index = %d\n", index) ; // for ( int i = 0; i < ann[index]->total_weights; ++i ) // printf("*** w%d = %f\n", i, ann[index]->weight[i]) ; // // return( EXIT_SUCCESS ); //} ////----------------------------------------------------------------------------- //// Run the index-th ANN k time on random input and return the number of error ////----------------------------------------------------------------------------- //int annTest(int index, int k) //{ // int x0; int x1; int y; // double x[2]; // double xor_ex; // int error = 0; // // if ( annCheck(index) != EXIT_SUCCESS ) // return( -1 ); // less than zero errors <==> the ANN isn't correctly created // // for (int i = 0; i < k; i++ ) // { // x0 = rand() % 2; x[0] = (double)x0; // x1 = rand() % 2; x[1] = (double)x1; // y = x0 ^ x1 ; // // xor_ex = * genann_run(ann[index], x); // if ( fabs(xor_ex - (double)y) > MAX_ERROR ) // { // error++ ; // printf("@@@ Error: ANN = %d, step = %d, x0 = %d, x1 = %d, y = %d, xor_ex = %f \n", index, i, x0, x1, y, xor_ex) ; // } // } // // if ( error ) // printf("@@@ ANN = %d: N� of errors = %d\n", index, error) ; // else // printf("*** ANN = %d: Test OK\n",index) ; // return( error ); //} //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void ann_01_annDestroy(void) { if ( ann_01_nANN == -1 ) return ; for ( int index = 0; index < ann_01_nANN; index++ ) ann_01_genann_free(ann_01_ann[index]) ; ann_01_nANN = -1 ; } void mainsystem::ann_01_main() { // datatype for channels cleanData_xx_ann_xx_payload cleanData_xx_ann_xx_payload_var; ann_xx_dataCollector_payload ann_xx_dataCollector_payload_var; double x[ann_01_ANN_INPUTS + ann_01_ANN_OUTPUTS] ; //int ann_01_index = 1; if ( ann_01_annCreateAndSetWeights(ann_01_NUM_DEV) != EXIT_SUCCESS ){ // Create and init ANN printf("Error Weights \n"); } //implementation HEPSY_S(ann_01_id) while(1) {HEPSY_S(ann_01_id) // content cleanData_xx_ann_xx_payload_var = cleanData_01_ann_01_channel->read(); ann_xx_dataCollector_payload_var.dev = cleanData_xx_ann_xx_payload_var.dev; ann_xx_dataCollector_payload_var.step = cleanData_xx_ann_xx_payload_var.step; ann_xx_dataCollector_payload_var.ex_time = cleanData_xx_ann_xx_payload_var.ex_time; ann_xx_dataCollector_payload_var.device_i = cleanData_xx_ann_xx_payload_var.device_i; ann_xx_dataCollector_payload_var.device_v = cleanData_xx_ann_xx_payload_var.device_v; ann_xx_dataCollector_payload_var.device_t = cleanData_xx_ann_xx_payload_var.device_t; ann_xx_dataCollector_payload_var.device_r = cleanData_xx_ann_xx_payload_var.device_r; x[0] = cleanData_xx_ann_xx_payload_var.x_0; x[1] = cleanData_xx_ann_xx_payload_var.x_1; x[2] = cleanData_xx_ann_xx_payload_var.x_2; //u = cleanData_xx_ann_xx_payload_var.step; ann_xx_dataCollector_payload_var.fault = cleanData_xx_ann_xx_payload_var.fault; //RUN THE ANN... // ### P R E D I C T (simple XOR) // if ( annRun(index, x) != EXIT_SUCCESS ){ // printf("Step = %u Index = %d ANN error.\n", u, index) ; // }else{ // device[index].fault = x[2] <= 0.5 ? 0 : 1 ; // } //u: cycle num if ( ann_01_annRun(0, x) != EXIT_SUCCESS ){ printf("Step = %d Index = %d ANN error.\n", (int)ann_xx_dataCollector_payload_var.step, (int)ann_xx_dataCollector_payload_var.dev) ; }else{ ann_xx_dataCollector_payload_var.fault = x[2] <= 0.5 ? 0 : 1 ; } ann_01_dataCollector_channel->write(ann_xx_dataCollector_payload_var); HEPSY_P(ann_01_id) } } // END
#include<systemc.h> #include<string> #include<vector> #include<map> #include<fstream> #include<nana/gui.hpp> #include<nana/gui/widgets/button.hpp> #include<nana/gui/widgets/menubar.hpp> #include<nana/gui/widgets/group.hpp> #include<nana/gui/widgets/textbox.hpp> #include<nana/gui/filebox.hpp> #include "top.hpp" #include "gui.hpp" using std::string; using std::vector; using std::map; using std::fstream; int sc_main(int argc, char *argv[]) { using namespace nana; vector<string> instruction_queue; string bench_name = ""; int nadd,nmul,nls, n_bits, bpb_size, cpu_freq; nadd = 3; nmul = nls = 2; n_bits = 2; bpb_size = 4; cpu_freq = 500; // definido em Mhz - 500Mhz default std::vector<int> sizes; bool spec = false; int mode = 0; bool fila = false; ifstream inFile; form fm(API::make_center(1024,700)); place plc(fm); place upper(fm); place lower(fm); listbox table(fm); listbox reg(fm); listbox instruct(fm); listbox rob(fm); menubar mnbar(fm); button start(fm); button run_all(fm); button clock_control(fm); button exit(fm); group clock_group(fm); label clock_count(clock_group); fm.caption("TFSim"); clock_group.caption("Ciclo"); clock_group.div("count"); grid memory(fm,rectangle(),10,50); // Tempo de latencia de uma instrucao // Novas instrucoes devem ser inseridas manualmente aqui map<string,int> instruct_time{{"DADD",4},{"DADDI",4},{"DSUB",6}, {"DSUBI",6},{"DMUL",10},{"DDIV",16},{"MEM",2}, {"SLT",1},{"SGT", 1}}; // Responsavel pelos modos de execução top top1("top"); start.caption("Start"); clock_control.caption("Next cycle"); run_all.caption("Run all"); exit.caption("Exit"); plc["rst"] << table; plc["btns"] << start << clock_control << run_all << exit; plc["memor"] << memory; plc["regs"] << reg; plc["rob"] << rob; plc["instr"] << instruct; plc["clk_c"] << clock_group; clock_group["count"] << clock_count; clock_group.collocate(); spec = false; //set_spec eh so visual set_spec(plc,spec); plc.collocate(); mnbar.push_back("Opções"); menu &op = mnbar.at(0); //menu::item_proxy spec_ip = op.append("Especulação"); auto spec_sub = op.create_sub_menu(0); // Modo com 1 preditor para todos os branchs spec_sub->append("1 Preditor", [&](menu::item_proxy &ip) { if(ip.checked()){ spec = true; mode = 1; spec_sub->checked(1, false); } else{ spec = false; mode = 0; } set_spec(plc,spec); }); // Modo com o bpb spec_sub->append("Branch Prediction Buffer", [&](menu::item_proxy &ip) { if(ip.checked()){ spec = true; mode = 2; spec_sub->checked(0, false); } else{ spec = false; mode = 0; } set_spec(plc, spec); }); spec_sub->check_style(0,menu::checks::highlight); spec_sub->check_style(1,menu::checks::highlight); op.append("Modificar valores..."); // novo submenu para escolha do tamanho do bpb e do preditor auto sub = op.create_sub_menu(1); sub->append("Tamanho do BPB e Preditor", [&](menu::item_proxy &ip) { inputbox ibox(fm, "", "Definir tamanhos"); inputbox::integer size("BPB", bpb_size, 2, 10, 2); inputbox::integer bits("N_BITS", n_bits, 1, 3, 1); if(ibox.show_modal(size, bits)){ bpb_size = size.value(); n_bits = bits.value(); } }); sub->append("Número de Estações de Reserva",[&](menu::item_proxy ip) { inputbox ibox(fm,"","Quantidade de Estações de Reserva"); inputbox::integer add("ADD/SUB",nadd,1,10,1); inputbox::integer mul("MUL/DIV",nmul,1,10,1); inputbox::integer sl("LOAD/STORE",nls,1,10,1); if(ibox.show_modal(add,mul,sl)) { nadd = add.value(); nmul = mul.value(); nls = sl.value(); } }); // Menu de ajuste dos tempos de latencia na interface // Novas instrucoes devem ser adcionadas manualmente aqui sub->append("Tempos de latência", [&](menu::item_proxy &ip) { inputbox ibox(fm,"","Tempos de latência para instruções"); inputbox::text dadd_t("DADD",std::to_string(instruct_time["DADD"])); inputbox::text daddi_t("DADDI",std::to_string(instruct_time["DADDI"])); inputbox::text dsub_t("DSUB",std::to_string(instruct_time["DSUB"])); inputbox::text dsubi_t("DSUBI",std::to_string(instruct_time["DSUBI"])); inputbox::text dmul_t("DMUL",std::to_string(instruct_time["DMUL"])); inputbox::text ddiv_t("DDIV",std::to_string(instruct_time["DDIV"])); inputbox::text mem_t("Load/Store",std::to_string(instruct_time["MEM"])); if(ibox.show_modal(dadd_t,daddi_t,dsub_t,dsubi_t,dmul_t,ddiv_t,mem_t)) { instruct_time["DADD"] = std::stoi(dadd_t.value()); instruct_time["DADDI"] = std::stoi(daddi_t.value()); instruct_time["DSUB"] = std::stoi(dsub_t.value()); instruct_time["DSUBI"] = std::stoi(dsubi_t.value()); instruct_time["DMUL"] = std::stoi(dmul_t.value()); instruct_time["DDIV"] = std::stoi(ddiv_t.value()); instruct_time["MEM"] = std::stoi(mem_t.value()); } }); sub->append("Frequência CPU", [&](menu::item_proxy &ip) { inputbox ibox(fm,"Em Mhz","Definir frequência da CPU"); inputbox::text freq("Frequência", std::to_string(cpu_freq)); if(ibox.show_modal(freq)){ cpu_freq = std::stoi(freq.value()); } }); sub->append("Fila de instruções", [&](menu::item_proxy &ip) { filebox fb(0,true); inputbox ibox(fm,"Localização do arquivo com a lista de instruções:"); inputbox::path caminho("",fb); if(ibox.show_modal(caminho)) { auto path = caminho.value(); inFile.open(path); if(!add_instructions(inFile,instruction_queue,instruct)) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else fila = true; } }); sub->append("Valores de registradores inteiros",[&](menu::item_proxy &ip) { filebox fb(0,true); inputbox ibox(fm,"Localização do arquivo de valores de registradores inteiros:"); inputbox::path caminho("",fb); if(ibox.show_modal(caminho)) { auto path = caminho.value(); inFile.open(path); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { auto reg_gui = reg.at(0); int value,i = 0; while(inFile >> value && i < 32) { reg_gui.at(i).text(1,std::to_string(value)); i++; } for(; i < 32 ; i++) reg_gui.at(i).text(1,"0"); inFile.close(); } } }); sub->append("Valores de registradores PF",[&](menu::item_proxy &ip) { filebox fb(0,true); inputbox ibox(fm,"Localização do arquivo de valores de registradores PF:"); inputbox::path caminho("",fb); if(ibox.show_modal(caminho)) { auto path = caminho.value(); inFile.open(path); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { auto reg_gui = reg.at(0); int i = 0; float value; while(inFile >> value && i < 32) { reg_gui.at(i).text(4,std::to_string(value)); i++; } for(; i < 32 ; i++) reg_gui.at(i).text(4,"0"); inFile.close(); } } }); sub->append("Valores de memória",[&](menu::item_proxy &ip) { filebox fb(0,true); inputbox ibox(fm,"Localização do arquivo de valores de memória:"); inputbox::path caminho("",fb); if(ibox.show_modal(caminho)) { auto path = caminho.value(); inFile.open(path); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { int i = 0; int value; while(inFile >> value && i < 500) { memory.Set(i,std::to_string(value)); i++; } for(; i < 500 ; i++) { memory.Set(i,"0"); } inFile.close(); } } }); op.append("Verificar conteúdo..."); auto new_sub = op.create_sub_menu(2); new_sub->append("Valores de registradores",[&](menu::item_proxy &ip) { filebox fb(0,true); inputbox ibox(fm,"Localização do arquivo de valores de registradores:"); inputbox::path caminho("",fb); if(ibox.show_modal(caminho)) { auto path = caminho.value(); inFile.open(path); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { string str; int reg_pos,i; bool is_float, ok; ok = true; while(inFile >> str) { if(str[0] == '$') { if(str[1] == 'f') { i = 2; is_float = true; } else { i = 1; is_float = false; } reg_pos = std::stoi(str.substr(i,str.size()-i)); auto reg_gui = reg.at(0); string value; inFile >> value; if(!is_float) { if(reg_gui.at(reg_pos).text(1) != value) { ok = false; break; } } else { if(std::stof(reg_gui.at(reg_pos).text(4)) != std::stof(value)) { ok = false; break; } } } } inFile.close(); msgbox msg("Verificação de registradores"); if(ok) { msg << "Registradores especificados apresentam valores idênticos!"; msg.icon(msgbox::icon_information); } else { msg << "Registradores especificados apresentam valores distintos!"; msg.icon(msgbox::icon_error); } msg.show(); } } }); new_sub->append("Valores de memória",[&](menu::item_proxy &ip) { filebox fb(0,true); inputbox ibox(fm,"Localização do arquivo de valores de memória:"); inputbox::path caminho("",fb); if(ibox.show_modal(caminho)) { auto path = caminho.value(); inFile.open(path); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { string value; bool ok; ok = true; for(int i = 0 ; i < 500 ; i++) { inFile >> value; if(std::stoi(memory.Get(i)) != (int)std::stol(value,nullptr,16)) { ok = false; break; } } inFile.close(); msgbox msg("Verificação de memória"); if(ok) { msg << "Endereços de memória especificados apresentam valores idênticos!"; msg.icon(msgbox::icon_information); } else { msg << "Endereços de memória especificados apresentam valores distintos!"; msg.icon(msgbox::icon_error); } msg.show(); } } }); op.append("Benchmarks"); auto bench_sub = op.create_sub_menu(3); bench_sub->append("Fibonacci",[&](menu::item_proxy &ip){ string path = "in/benchmarks/fibonacci/fibonacci.txt"; bench_name = "fibonacci"; inFile.open(path); if(!add_instructions(inFile,instruction_queue,instruct)) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else fila = true; }); bench_sub->append("Stall por Divisão",[&](menu::item_proxy &ip){ string path = "in/benchmarks/division_stall.txt"; inFile.open(path); if(!add_instructions(inFile,instruction_queue,instruct)) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else fila = true; }); bench_sub->append("Stress de Memória (Stores)",[&](menu::item_proxy &ip){ string path = "in/benchmarks/store_stress/store_stress.txt"; bench_name = "store_stress"; inFile.open(path); if(!add_instructions(inFile,instruction_queue,instruct)) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else fila = true; }); bench_sub->append("Stall por hazard estrutural (Adds)",[&](menu::item_proxy &ip){ string path = "in/benchmarks/res_stations_stall.txt"; inFile.open(path); if(!add_instructions(inFile,instruction_queue,instruct)) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else fila = true; }); bench_sub->append("Busca Linear",[&](menu::item_proxy &ip){ string path = "in/benchmarks/linear_search/linear_search.txt"; bench_name = "linear_search"; inFile.open(path); if(!add_instructions(inFile,instruction_queue,instruct)) show_message("Arquivo inválido","Não foi possível abrir o arquivo"); else fila = true; path = "in/benchmarks/linear_search/memory.txt"; inFile.open(path); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { int i = 0; int value; while(inFile >> value && i < 500) { memory.Set(i,std::to_string(value)); i++; } for(; i < 500 ; i++) { memory.Set(i,"0"); } inFile.close(); } path = "in/benchmarks/linear_search/regi_i.txt"; inFile.open(path); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { auto reg_gui = reg.at(0); int value,i = 0; while(inFile >> value && i < 32) { reg_gui.at(i).text(1,std::to_string(value)); i++; } for(; i < 32 ; i++) reg_gui.at(i).text(1,"0"); inFile.close(); } }); bench_sub->append("Busca Binária",[&](menu::item_proxy &ip){ string path = "in/benchmarks/binary_search/binary_search.txt"; bench_name = "binary_search"; inFile.open(path); if(!add_instructions(inFile,instruction_queue,instruct)) show_message("Arquivo inválido","Não foi possível abrir o arquivo"); else fila = true; path = "in/benchmarks/binary_search/memory.txt"; inFile.open(path); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { int i = 0; int value; while(inFile >> value && i < 500) { memory.Set(i,std::to_string(value)); i++; } for(; i < 500 ; i++) { memory.Set(i,"0"); } inFile.close(); } path = "in/benchmarks/binary_search/regs.txt"; inFile.open(path); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { auto reg_gui = reg.at(0); int value,i = 0; while(inFile >> value && i < 32) { reg_gui.at(i).text(1,std::to_string(value)); i++; } for(; i < 32 ; i++) reg_gui.at(i).text(1,"0"); inFile.close(); } }); bench_sub->append("Matriz Search",[&](menu::item_proxy &ip){ string path = "in/benchmarks/matriz_search/matriz_search.txt"; bench_name = "matriz_search"; inFile.open(path); if(!add_instructions(inFile,instruction_queue,instruct)) show_message("Arquivo inválido","Não foi possível abrir o arquivo"); else fila = true; path = "in/benchmarks/matriz_search/memory.txt"; inFile.open(path); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { int i = 0; int value; while(inFile >> value && i < 500) { memory.Set(i,std::to_string(value)); i++; } for(; i < 500 ; i++) { memory.Set(i,"0"); } inFile.close(); } path = "in/benchmarks/matriz_search/regs.txt"; inFile.open(path); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { auto reg_gui = reg.at(0); int value,i = 0; while(inFile >> value && i < 32) { reg_gui.at(i).text(1,std::to_string(value)); i++; } for(; i < 32 ; i++) reg_gui.at(i).text(1,"0"); inFile.close(); } }); bench_sub->append("Bubble Sort",[&](menu::item_proxy &ip){ string path = "in/benchmarks/bubble_sort/bubble_sort.txt"; bench_name = "bubble_sort"; inFile.open(path); if(!add_instructions(inFile,instruction_queue,instruct)) show_message("Arquivo inválido","Não foi possível abrir o arquivo"); else fila = true; path = "in/benchmarks/bubble_sort/memory.txt";
inFile.open(path); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { int i = 0; int value; while(inFile >> value && i < 500) { memory.Set(i,std::to_string(value)); i++; } for(; i < 500 ; i++) { memory.Set(i,"0"); } inFile.close(); } path = "in/benchmarks/bubble_sort/regs.txt"; inFile.open(path); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { auto reg_gui = reg.at(0); int value,i = 0; while(inFile >> value && i < 32) { reg_gui.at(i).text(1,std::to_string(value)); i++; } for(; i < 32 ; i++) reg_gui.at(i).text(1,"0"); inFile.close(); } }); bench_sub->append("Insertion Sort",[&](menu::item_proxy &ip){ string path = "in/benchmarks/insertion_sort/insertion_sort.txt"; bench_name = "insertion_sort"; inFile.open(path); if(!add_instructions(inFile,instruction_queue,instruct)) show_message("Arquivo inválido","Não foi possível abrir o arquivo"); else fila = true; path = "in/benchmarks/insertion_sort/memory.txt"; inFile.open(path); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { int i = 0; int value; while(inFile >> value && i < 500) { memory.Set(i,std::to_string(value)); i++; } for(; i < 500 ; i++) { memory.Set(i,"0"); } inFile.close(); } path = "in/benchmarks/insertion_sort/regs.txt"; inFile.open(path); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { auto reg_gui = reg.at(0); int value,i = 0; while(inFile >> value && i < 32) { reg_gui.at(i).text(1,std::to_string(value)); i++; } for(; i < 32 ; i++) reg_gui.at(i).text(1,"0"); inFile.close(); } }); bench_sub->append("Tick Tack",[&](menu::item_proxy &ip){ string path = "in/benchmarks/tick_tack/tick_tack.txt"; bench_name = "tick_tack"; inFile.open(path); if(!add_instructions(inFile,instruction_queue,instruct)) show_message("Arquivo inválido","Não foi possível abrir o arquivo"); else fila = true; path = "in/benchmarks/tick_tack/regs.txt"; inFile.open(path); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { auto reg_gui = reg.at(0); int value,i = 0; while(inFile >> value && i < 32) { reg_gui.at(i).text(1,std::to_string(value)); i++; } for(; i < 32 ; i++) reg_gui.at(i).text(1,"0"); inFile.close(); } }); vector<string> columns = {"#","Name","Busy","Op","Vj","Vk","Qj","Qk","A"}; for(unsigned int i = 0 ; i < columns.size() ; i++) { table.append_header(columns[i].c_str()); if(i && i != 3) table.column_at(i).width(45); else if (i == 3) table.column_at(i).width(60); else table.column_at(i).width(30); } columns = {"","Value","Qi"}; sizes = {30,75,40}; for(unsigned int k = 0 ; k < 2 ; k++) for(unsigned int i = 0 ; i < columns.size() ; i++) { reg.append_header(columns[i]); reg.column_at(k*columns.size() + i).width(sizes[i]); } auto reg_gui = reg.at(0); for(int i = 0 ; i < 32 ;i++) { string index = std::to_string(i); reg_gui.append("R" + index); reg_gui.at(i).text(3,"F" + index); } columns = {"Instruction","Issue","Execute","Write Result"}; sizes = {140,60,70,95}; for(unsigned int i = 0 ; i < columns.size() ; i++) { instruct.append_header(columns[i]); instruct.column_at(i).width(sizes[i]); } columns = {"Entry","Busy","Instruction","State","Destination","Value"}; sizes = {45,45,120,120,90,60}; for(unsigned int i = 0 ; i < columns.size() ; i++) { rob.append_header(columns[i]); rob.column_at(i).width(sizes[i]); } srand(static_cast <unsigned> (time(0))); for(int i = 0 ; i < 32 ; i++) { if(i) reg_gui.at(i).text(1,std::to_string(rand()%100)); else reg_gui.at(i).text(1,std::to_string(0)); reg_gui.at(i).text(2,"0"); reg_gui.at(i).text(4,std::to_string(static_cast <float> (rand()) / static_cast <float> (RAND_MAX/100.0))); reg_gui.at(i).text(5,"0"); } for(int i = 0 ; i < 500 ; i++) memory.Push(std::to_string(rand()%100)); for(int k = 1; k < argc; k+=2) { int i; if (strlen(argv[k]) > 2) show_message("Opção inválida",string("Opção \"") + string(argv[k]) + string("\" inválida")); else { char c = argv[k][1]; switch(c) { case 'q': inFile.open(argv[k+1]); if(!add_instructions(inFile,instruction_queue,instruct)) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else fila = true; break; case 'i': inFile.open(argv[k+1]); int value; i = 0; if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { while(inFile >> value && i < 32) { reg_gui.at(i).text(1,std::to_string(value)); i++; } for(; i < 32 ; i++) reg_gui.at(i).text(1,"0"); inFile.close(); } break; case 'f': float value_fp; i = 0; inFile.open(argv[k+1]); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { while(inFile >> value_fp && i < 32) { reg_gui.at(i).text(4,std::to_string(value_fp)); i++; } for(; i < 32 ; i++) reg_gui.at(i).text(4,"0"); inFile.close(); } break; case 'm': inFile.open(argv[k+1]); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { int value; i = 0; while(inFile >> value && i < 500) { memory.Set(i,std::to_string(value)); i++; } for(; i < 500 ; i++) { memory.Set(i,"0"); } inFile.close(); } break; case 'r': inFile.open(argv[k+1]); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { int value; if(inFile >> value && value <= 10 && value > 0) nadd = value; if(inFile >> value && value <= 10 && value > 0) nmul = value; if(inFile >> value && value <= 10 && value > 0) nls = value; inFile.close(); } break; case 's': spec = true; set_spec(plc,spec); //spec_ip.checked(true); k--; break; case 'l': inFile.open(argv[k+1]); if(!inFile.is_open()) show_message("Arquivo inválido","Não foi possível abrir o arquivo!"); else { string inst; int value; while(inFile >> inst) { if(inFile >> value && instruct_time.count(inst)) instruct_time[inst] = value; } } inFile.close(); break; default: show_message("Opção inválida",string("Opção \"") + string(argv[k]) + string("\" inválida")); break; } } } clock_control.enabled(false); run_all.enabled(false); start.events().click([&] { if(fila) { start.enabled(false); clock_control.enabled(true); run_all.enabled(true); //Desativa os menus apos inicio da execucao op.enabled(0,false); op.enabled(1,false); op.enabled(3,false); for(int i = 0; i < 2; i++) spec_sub->enabled(i, false); for(int i = 0 ; i < 8 ; i++) sub->enabled(i,false); for(int i = 0 ; i < 10 ; i++) bench_sub->enabled(i,false); if(spec){ // Flag mode setada pela escolha no menu if(mode == 1) top1.rob_mode(n_bits,nadd,nmul,nls,instruct_time,instruction_queue,table,memory,reg,instruct,clock_count,rob); else if(mode == 2) top1.rob_mode_bpb(n_bits, bpb_size, nadd,nmul,nls,instruct_time,instruction_queue,table,memory,reg,instruct,clock_count,rob); } else top1.simple_mode(nadd,nmul,nls,instruct_time,instruction_queue,table,memory,reg,instruct,clock_count); sc_start(); } else show_message("Fila de instruções vazia","A fila de instruções está vazia. Insira um conjunto de instruções para iniciar."); }); clock_control.events().click([&] { if(top1.get_queue().queue_is_empty() && top1.get_rob().rob_is_empty()) return; if(sc_is_running()) sc_start(); }); run_all.events().click([&]{ // enquanto queue e rob nao estao vazios, roda ate o fim while(!(top1.get_queue().queue_is_empty() && top1.get_rob().rob_is_empty())){ if(sc_is_running()) sc_start(); } top1.metrics(cpu_freq, mode, bench_name, n_bits); }); exit.events().click([] { sc_stop(); API::exit(); }); fm.show(); exec(); return 0; }
// Shows the non-blocking transport interface with the generic payload and sockets // Shows nb_transport being called on the forward and backward paths // No support for temporal decoupling // No support for DMI or debug transport interfaces #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" // User-defined extension class struct ID_extension: tlm::tlm_extension<ID_extension> { ID_extension() : transaction_id(0) {} virtual tlm_extension_base* clone() const { // Must override pure virtual clone method ID_extension* t = new ID_extension; t->transaction_id = this->transaction_id; return t; } // Must override pure virtual copy_from method virtual void copy_from(tlm_extension_base const &ext) { transaction_id = static_cast<ID_extension const &>(ext).transaction_id; } unsigned int transaction_id; }; // Initiator module generating generic payload transactions struct Initiator: sc_module { // TLM2 socket, defaults to 32-bits wide, generic payload, generic DMI mode sc_core::sc_in<bool> IO_request; tlm_utils::simple_initiator_socket<Initiator> socket; SC_HAS_PROCESS(Initiator); Initiator(sc_module_name initiator) // Construct and name socket { // Register callbacks for incoming interface method calls socket.register_nb_transport_bw(this, &Initiator::nb_transport_bw); SC_THREAD(thread_process); } void thread_process() { while (true) { // TLM2 generic payload transaction tlm::tlm_generic_payload trans; ID_extension* id_extension = new ID_extension; //trans.set_extension( id_extension ); // Add the extension to the transaction trans.set_extension( id_extension ); // Add the extension to the transaction // Generate a random sequence of reads and writes //for (int i = 0; i < 100; i++) //printf("%i",IO_request->read()); cout << "TLM Z value:" <<IO_request->read() << endl; if(IO_request->read() == 1) { int i = rand()%100; tlm::tlm_phase phase = tlm::BEGIN_REQ; sc_time delay = sc_time(10, SC_NS); tlm::tlm_command cmd = static_cast<tlm::tlm_command>(rand() % 2); trans.set_command( cmd ); trans.set_address( rand() % 0xFF ); if (cmd == tlm::TLM_WRITE_COMMAND) data = 0xFF000000 | i; trans.set_data_ptr( reinterpret_cast<unsigned char*>(&data) ); trans.set_data_length( 4 ); // Other fields default: byte enable = 0, streaming width = 0, DMI_hint = false, no extensions //Delay for BEGIN_REQ wait(10, SC_NS); tlm::tlm_sync_enum status; cout << name() << " BEGIN_REQ SENT" << " TRANS ID " << id_extension->transaction_id << " at time " << sc_time_stamp() << endl; status = socket->nb_transport_fw( trans, phase, delay ); // Non-blocking transport call // Check value returned from nb_transport switch (status) { case tlm::TLM_ACCEPTED: //Delay for END_REQ wait(10, SC_NS); cout << name() << " END_REQ SENT" << " TRANS ID " << id_extension->transaction_id << " at time " << sc_time_stamp() << endl; // Expect response on the backward path phase = tlm::END_REQ; status = socket->nb_transport_fw( trans, phase, delay ); // Non-blocking transport call break; case tlm::TLM_UPDATED: case tlm::TLM_COMPLETED: // Initiator obliged to check response status if (trans.is_response_error() ) SC_REPORT_ERROR("TLM2", "Response error from nb_transport_fw"); cout << "trans/fw = { " << (cmd ? 'W' : 'R') << ", " << hex << i << " } , data = " << hex << data << " at time " << sc_time_stamp() << ", delay = " << delay << endl; break; } while(IO_request==1){ wait(10,SC_NS); } id_extension->transaction_id++; } wait(10,SC_NS); } } // ********************************************* // TLM2 backward path non-blocking transport method // ********************************************* virtual tlm::tlm_sync_enum nb_transport_bw( tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_time& delay ) { tlm::tlm_command cmd = trans.get_command(); sc_dt::uint64 adr = trans.get_address(); ID_extension* id_extension = new ID_extension; trans.get_extension( id_extension ); if (phase == tlm::END_RESP) { //Delay for TLM_COMPLETE wait(delay); cout << name() << " END_RESP RECEIVED" << " TRANS ID " << id_extension->transaction_id << " at time " << sc_time_stamp() << endl; return tlm::TLM_COMPLETED; } if (phase == tlm::BEGIN_RESP) { // Initiator obliged to check response status if (trans.is_response_error() ) SC_REPORT_ERROR("TLM2", "Response error from nb_transport"); cout << "trans/bw = { " << (cmd ? 'W' : 'R') << ", " << hex << adr << " } , data = " << hex << data << " at time " << sc_time_stamp() << ", delay = " << delay << endl; //Delay wait(delay); cout << name () << " BEGIN_RESP RECEIVED" << " TRANS ID " << id_extension->transaction_id << " at time " << sc_time_stamp() << endl; return tlm::TLM_ACCEPTED; } } // Internal data buffer used by initiator with generic payload int data; }; // Target module representing a simple memory struct Memory: sc_module { // TLM-2 socket, defaults to 32-bits wide, base protocol tlm_utils::simple_target_socket<Memory> socket; enum { SIZE = 256 }; const sc_time LATENCY; SC_CTOR(Memory) : socket("socket"), LATENCY(10, SC_NS) { // Register callbacks for incoming interface method calls socket.register_nb_transport_fw(this, &Memory::nb_transport_fw); //socket.register_nb_transport_bw(this, &Memory::nb_transport_bw); // Initialize memory with random data for (int i = 0; i < SIZE; i++) mem[i] = 0xAA000000 | (rand() % 256); SC_THREAD(thread_process); } // TLM2 non-blocking transport method virtual tlm::tlm_sync_enum nb_transport_fw( tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_time& delay ) { sc_dt::uint64 adr = trans.get_address(); unsigned int len = trans.get_data_length(); unsigned char* byt = trans.get_byte_enable_ptr(); unsigned int wid = trans.get_streaming_width(); ID_extension* id_extension = new ID_extension; trans.get_extension( id_extension ); if(phase == tlm::END_REQ){ wait(delay); cout << name() << " END_REQ RECEIVED" << " TRANS ID " << id_extension->transaction_id << " at time " << sc_time_stamp() << endl; return tlm::TLM_COMPLETED; } if(phase == tlm::BEGIN_REQ){ // Obliged to check the transaction attributes for unsupported features // and to generate the appropriate error response if (byt != 0) { trans.set_response_status( tlm::TLM_BYTE_ENABLE_ERROR_RESPONSE ); return tlm::TLM_COMPLETED; } //if (len > 4 || wid < len) { // trans.set_response_status( tlm::TLM_BURST_ERROR_RESPONSE ); // return tlm::TLM_COMPLETED; //} // Now queue the transaction until the annotated time has elapsed trans_pending=&trans; phase_pending=phase; delay_pending=delay; e1.notify(); //Delay wait(delay); cout << name() << " BEGIN_REQ RECEIVED" << " TRANS ID " << id_extension->transaction_id << " at time " << sc_time_stamp() << endl; return tlm::TLM_ACCEPTED; } } // ********************************************* // Thread to call nb_transport on backward path // ********************************************* void thread_process() { while (true) { // Wait for an event to pop out of the back end of the queue wait(e1); //printf("ACCESING MEMORY\n"); //tlm::tlm_generic_payload* trans_ptr; tlm::tlm_phase phase; ID_extension* id_extension = new ID_extension; trans_pending->get_extension( id_extension ); tlm::tlm_command cmd = trans_pending->get_command(); sc_dt::uint64 adr = trans_pending->get_address() / 4; unsigned char* ptr = trans_pending->get_data_ptr(); unsigned int len = trans_pending->get_data_length(); unsigned char* byt = trans_pending->get_byte_enable_ptr(); unsigned int wid = trans_pending->get_streaming_width(); // Obliged to check address range and check for unsupported features, // i.e. byte enables, streaming, and bursts // Can ignore DMI hint and extensions // Using the SystemC report handler is an acceptable way of signalling an error if (adr >= sc_dt::uint64(SIZE) || byt != 0 || wid != 0 || len > 4) SC_REPORT_ERROR("TLM2", "Target does not support given generic payload transaction"); // Obliged to implement read and write commands if ( cmd == tlm::TLM_READ_COMMAND ) memcpy(ptr, &mem[adr], len); else if ( cmd == tlm::TLM_WRITE_COMMAND ) memcpy(&mem[adr], ptr, len); // Obliged to set response status to indicate successful completion trans_pending->set_response_status( tlm::TLM_OK_RESPONSE ); wait(20, SC_NS); delay_pending= (rand() % 4) * sc_time(10, SC_NS); cout << name() << " BEGIN_RESP SENT" << " TRANS ID " << id_extension->transaction_id << " at time " << sc_time_stamp() << endl; // Call on backward path to complete the transaction tlm::tlm_sync_enum status; phase = tlm::BEGIN_RESP; status = socket->nb_transport_bw( *trans_pending, phase, delay_pending ); // The target gets a final chance to read or update the transaction object at this point. // Once this process yields, the target must assume that the transaction object // will be deleted by the initiator // Check value returned from nb_transport switch (status) //case tlm::TLM_REJECTED: case tlm::TLM_ACCEPTED: wait(10, SC_NS); cout << name() << " END_RESP SENT" << " TRANS ID " << id_extension->transaction_id << " at time " << sc_time_stamp() << endl; // Expect response on the backward path phase = tlm::END_RESP; socket->nb_transport_bw( *trans_pending, phase, delay_pending ); // Non-blocking transport call //break; } } int mem[SIZE]; sc_event e1; tlm::tlm_generic_payload* trans_pending; tlm::tlm_phase phase_pending; sc_time delay_pending; }; SC_MODULE(TLM) { Initiator *initiator; Memory *memory; sc_core::sc_in<bool> IO_request; SC_HAS_PROCESS(TLM); TLM(sc_module_name tlm) // Construct and name socket { // Instantiate components initiator = new Initiator("initiator"); initiator->IO_request(IO_request); memory = new Memory ("memory"); // One initiator is bound directly to one target with no intervening bus // Bind initiator socket to target socket initiator->socket.bind(memory->socket); } };
/******************************************************************************** * 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> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #ifdef PATH_MAX #define dC_MAX_PATH_LEN PATH_MAX #endif #ifdef MAX_PATH #define dC_MAX_PATH_LEN MAX_PATH #endif //----------------------------------------------------------------------------- // Status descriptors //----------------------------------------------------------------------------- typedef struct dC_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 ; } dC_DEVICE ; static dC_DEVICE dC_device; ///----------------------------------------------------------------------------- // Log //----------------------------------------------------------------------------- static char dC_szOutFile[dC_MAX_PATH_LEN] ; // Change by command line option -f<filename> MAX_PATH static char dC_szWorkingDir[dC_MAX_PATH_LEN] ; static char dC_szHeader[] = "Stp\tDv\tTime\tTemp\tR_DS_On\tDevI\tDevV\tFault\n" ; FILE * dC_file = NULL ; /* * dC_writeLog(step, Device index, device) */ void dC_writeLog(int u, int index, dC_DEVICE device){ if ( dC_file != NULL ){ int w ; w = fprintf (dC_file, "%u\t%d\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%d\n", u, // Step index, // Device index device.time_Ex, // Time of sampling device.t, // Temperature device.r, // Resistance device.i, // Current device.v, // Voltage device.fault // ) ; if ( w <= 0 ){ fclose(dC_file) ; dC_file = NULL ; printf("Write file record error.\n") ; } } } void mainsystem::dataCollector_main() { // datatype for channels system_display_payload system_display_payload_var; ann_xx_dataCollector_payload ann_01_dataCollector_payload_var; ann_xx_dataCollector_payload ann_02_dataCollector_payload_var; ann_xx_dataCollector_payload ann_03_dataCollector_payload_var; ann_xx_dataCollector_payload ann_04_dataCollector_payload_var; //prepare file for the log... strcpy(dC_szOutFile, "log_dC.txt") ; // Open log file if( dC_szOutFile[0] != 0 ){ dC_file = fopen(dC_szOutFile, "w") ; // Warning: if the file already exists it is truncated to zero length if ( dC_file == NULL ){ printf("Open file error.\n") ; } else if( fprintf(dC_file, "%s", dC_szHeader) <= 0 ){ fclose(dC_file) ; dC_file = NULL ; printf("Write file header error.\n") ; }else{ printf("W O R K I N G D I R E C T O R Y : %s\n", getcwd(dC_szWorkingDir, dC_MAX_PATH_LEN)) ; printf("L O G F I L E : %s\n", dC_szOutFile) ; } } if ( dC_file != NULL ) fclose(dC_file); // Error should be checked int dev; int step; //implementation HEPSY_S(dataCollector_id) while(1) {HEPSY_S(dataCollector_id) // content dC_file = fopen(dC_szOutFile, "a") ; // read data ann_01_dataCollector_payload_var = ann_01_dataCollector_channel->read(); // encap in data_structure dev = ann_01_dataCollector_payload_var.dev; step = ann_01_dataCollector_payload_var.step; dC_device.time_Ex = ann_01_dataCollector_payload_var.ex_time; dC_device.i = ann_01_dataCollector_payload_var.device_i; dC_device.v = ann_01_dataCollector_payload_var.device_v; dC_device.t = ann_01_dataCollector_payload_var.device_t; dC_device.r = ann_01_dataCollector_payload_var.device_r; dC_device.fault = ann_01_dataCollector_payload_var.fault; // ### W R I T E L O G dC_writeLog(step, dev, dC_device); // read data ann_02_dataCollector_payload_var = ann_02_dataCollector_channel->read(); // encap in data_structure dev = ann_02_dataCollector_payload_var.dev; step = ann_02_dataCollector_payload_var.step; dC_device.time_Ex = ann_02_dataCollector_payload_var.ex_time; dC_device.i = ann_02_dataCollector_payload_var.device_i; dC_device.v = ann_02_dataCollector_payload_var.device_v; dC_device.t = ann_02_dataCollector_payload_var.device_t; dC_device.r = ann_02_dataCollector_payload_var.device_r; dC_device.fault = ann_02_dataCollector_payload_var.fault; // ### W R I T E L O G dC_writeLog(step, dev, dC_device); // read data ann_03_dataCollector_payload_var = ann_03_dataCollector_channel->read(); // encap in data_structure dev = ann_03_dataCollector_payload_var.dev; step = ann_03_dataCollector_payload_var.step; dC_device.time_Ex = ann_03_dataCollector_payload_var.ex_time; dC_device.i = ann_03_dataCollector_payload_var.device_i; dC_device.v = ann_03_dataCollector_payload_var.device_v; dC_device.t = ann_03_dataCollector_payload_var.device_t; dC_device.r = ann_03_dataCollector_payload_var.device_r; dC_device.fault = ann_03_dataCollector_payload_var.fault; // ### W R I T E L O G dC_writeLog(step, dev, dC_device); // read data ann_04_dataCollector_payload_var = ann_04_dataCollector_channel->read(); // encap in data_structure dev = ann_04_dataCollector_payload_var.dev; step = ann_04_dataCollector_payload_var.step; dC_device.time_Ex = ann_04_dataCollector_payload_var.ex_time; dC_device.i = ann_04_dataCollector_payload_var.device_i; dC_device.v = ann_04_dataCollector_payload_var.device_v; dC_device.t = ann_04_dataCollector_payload_var.device_t; dC_device.r = ann_04_dataCollector_payload_var.device_r; dC_device.fault = ann_04_dataCollector_payload_var.fault; // ### W R I T E L O G dC_writeLog(step, dev, dC_device); if ( dC_file != NULL ) fclose(dC_file); // Error should be checked //sending to display the last step system_display_payload_var.example = step; system_display_port_in->write(system_display_payload_var); HEPSY_P(dataCollector_id) } } //END
// 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 "esp32-hal-adc.h" #include "adc_types.h" #include "esp_attr.h" #include "driver/adc.h" #include <systemc.h> #include "info.h" static uint8_t __analogAttenuation = 3;//11db static uint8_t __analogWidth = 3;//12 bits static uint8_t __analogCycles = 8; static uint8_t __analogSamples = 0;//1 sample static uint8_t __analogClockDiv = 1; // Width of returned answer () static uint8_t __analogReturnedWidth = 12; void analogSetWidth(uint8_t bits){ if(bits < 9){ bits = 9; } else if(bits > 12){ bits = 12; } __analogWidth = bits - 9; adc1ptr->set_width(bits); adc2ptr->set_width(bits); } void analogSetCycles(uint8_t cycles){ PRINTF_WARN("ADC", "ADC cycles is not yet supported."); __analogCycles = cycles; } void analogSetSamples(uint8_t samples){ PRINTF_WARN("ADC", "ADC samples is not yet supported."); if(!samples){ return; } __analogSamples = samples - 1; } void analogSetClockDiv(uint8_t clockDiv){ if(!clockDiv){ return; } __analogClockDiv = clockDiv; adc_set_clk_div(clockDiv); } void analogSetAttenuation(adc_attenuation_t attenuation) { adc_atten_t at; int c; switch(attenuation) { /* For most measures, we do a simple conversion of the enums. */ case ADC_0db: at = ADC_ATTEN_DB_0; break; case ADC_2_5db: at = ADC_ATTEN_DB_2_5; break; case ADC_6db: at = ADC_ATTEN_DB_6; break; case ADC_11db: at = ADC_ATTEN_DB_11; break; /* If the value is illegal, we warn the user and assume that we can * simply drop the upper bits, as the original code from the Arduino IDF * does this. */ default: at = (adc_atten_t)((unsigned int)attenuation & (~3U)); PRINTF_WARN("ADC", "Using large Attenuation value, using %s", printatten(at)); break; } /* Now we set the attenuation of every channel */ for(c = 0; c < 8; c = c + 1) adc1_config_channel_atten((adc1_channel_t)c, at); for(c = 0; c < 10; c = c + 1) adc2_config_channel_atten((adc2_channel_t)c, at); } void IRAM_ATTR analogInit(){ static bool initialized = false; if(initialized){ return; } analogSetAttenuation((adc_attenuation_t)__analogAttenuation); analogSetCycles(__analogCycles); analogSetSamples(__analogSamples + 1);//in samples analogSetClockDiv(__analogClockDiv); analogSetWidth(__analogWidth + 9);//in bits /* We switch on the ADC in case it is not on. */ adc_power_on(); initialized = true; } void analogSetPinAttenuation(uint8_t pin, adc_attenuation_t attenuation) { /* This one is a bit different from the above one, but we are following * the Arduino-IDF. */ int8_t channel = digitalPinToAnalogChannel(pin); if(channel < 0 || attenuation > 3){ return ; } analogInit(); if(channel > 7){ adc2_config_channel_atten((adc2_channel_t)(channel-10), (adc_atten_t)attenuation); } else { adc1_config_channel_atten((adc1_channel_t)channel, (adc_atten_t)attenuation); } } bool IRAM_ATTR adcAttachPin(uint8_t pin){ int8_t channel = digitalPinToAnalogChannel(pin); if(channel < 0){ return false;//not adc pin } /* Not supported yet int8_t pad = digitalPinToTouchChannel(pin); if(pad >= 0){ uint32_t touch = READ_PERI_REG(SENS_SAR_TOUCH_ENABLE_REG); if(touch & (1 << pad)){ touch &= ~((1 << (pad + SENS_TOUCH_PAD_OUTEN2_S)) | (1 << (pad + SENS_TOUCH_PAD_OUTEN1_S)) | (1 << (pad + SENS_TOUCH_PAD_WORKEN_S))); WRITE_PERI_REG(SENS_SAR_TOUCH_ENABLE_REG, touch); } } else if(pin == 25){ CLEAR_PERI_REG_MASK(RTC_IO_PAD_DAC1_REG, RTC_IO_PDAC1_XPD_DAC | RTC_IO_PDAC1_DAC_XPD_FORCE);//stop dac1 } else if(pin == 26){ CLEAR_PERI_REG_MASK(RTC_IO_PAD_DAC2_REG, RTC_IO_PDAC2_XPD_DAC | RTC_IO_PDAC2_DAC_XPD_FORCE);//stop dac2 } */ pinMode(pin, ANALOG); analogInit(); return true; } bool IRAM_ATTR adcStart(uint8_t pin){ int8_t channel = digitalPinToAnalogChannel(pin); if(channel < 0){ return false;//not adc pin } if(channel > 9){ channel -= 10; adc2ptr->soc((int)channel); } else { adc1ptr->soc((int)channel); } return true; } bool IRAM_ATTR adcBusy(uint8_t pin){ int8_t channel = digitalPinToAnalogChannel(pin); if(channel < 0){ return false;//not adc pin } if(channel > 7) adc2ptr->busy(); return adc2ptr->busy(); } uint16_t IRAM_ATTR adcEnd(uint8_t pin) { int v; int8_t channel = digitalPinToAnalogChannel(pin); if(channel < 0){ return 0;//not adc pin } if(channel > 7){ adc2ptr->wait_eoc(); v = adc2ptr->getraw(); /* If it fails we return 0 */ if (v < 0) return 0; } else { adc1ptr->wait_eoc(); v = adc1ptr->getraw(); /* If it fails we return 0 */ if (v < 0) return 0; } return (uint16_t)v; } uint16_t IRAM_ATTR analogRead(uint8_t pin) { if(!adcAttachPin(pin) || !adcStart(pin)){ return 0; } return adcEnd(pin); } void analogReadResolution(uint8_t bits) { if(!bits || bits > 16){ return; } analogSetWidth(bits); // hadware from 9 to 12 __analogReturnedWidth = bits; // software from 1 to 16 } int hallRead() //hall sensor without LNA { PRINTF_ERROR("ADC", "Hall sensor not yet supported."); return 0; }
/******************************************************************************* * mux_in.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Model for the PCNT mux in the GPIO matrix. ******************************************************************************* * 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 "info.h" #include "mux_in.h" void mux_in::mux(int gpiosel) { if (gpiosel >= min_i.size()) { PRINTF_WARN("MUXPCNT", "Attempting to set GPIO Matrix to illegal pin %d.", gpiosel); return; } function = gpiosel; fchange_ev.notify(); } void mux_in::transfer() { bool nxval; while(true) { /* We simply copy the input onto the output. */ nxval = min_i[function]->read(); out_o.write(nxval); if (debug) { PRINTF_INFO("MUXIN", "mux_in %s is driving %c, function %d", name(), (nxval)?'H':'L', function); } /* We wait for a function change or a signal change. */ wait(fchange_ev | min_i[function]->value_changed_event()); } }
/* * SysPE testbench for Harvard cs148/248 only */ #include "SysPE.h" #include <systemc.h> #include <mc_scverify.h> #include <nvhls_int.h> #include <vector> #define NVHLS_VERIFY_BLOCKS (SysPE) #include <nvhls_verify.h> using namespace::std; #include <testbench/nvhls_rand.h> SC_MODULE (Source) { Connections::Out<SysPE::InputType> act_in; Connections::Out<SysPE::InputType> weight_in; Connections::Out<SysPE::AccumType> accum_in; Connections::In<SysPE::AccumType> accum_out; Connections::In<SysPE::InputType> act_out; Connections::In<SysPE::InputType> weight_out; sc_in <bool> clk; sc_in <bool> rst; bool start_src; vector<SysPE::InputType> act_list{0, -1, 3, -7, 15, -31, 63, -127}; vector<SysPE::AccumType> accum_list{0, -10, 30, -70, 150, -310, 630, -1270}; SysPE::InputType weight_data = 10; SysPE::AccumType accum_init = 0; SysPE::InputType act_out_src; SysPE::AccumType accum_out_src; SC_CTOR(Source) { SC_THREAD(run); sensitive << clk.pos(); async_reset_signal_is(rst, false); SC_THREAD(pop_result); sensitive << clk.pos(); async_reset_signal_is(rst, false); } void run() { SysPE::InputType _act; SysPE::AccumType _acc; act_in.Reset(); weight_in.Reset(); accum_in.Reset(); // Wait for initial reset wait(20.0, SC_NS); wait(); // Write wait to PE weight_in.Push(weight_data); wait(); for (int i=0; i< (int) act_list.size(); i++) { _act = act_list[i]; _acc = accum_list[i]; act_in.Push(_act); accum_in.Push(_acc); wait(); } // for wait(5); }// void run() void pop_result() { weight_out.Reset(); wait(); unsigned int i = 0, j = 0; bool correct = 1; while (1) { SysPE::InputType tmp; if (weight_out.PopNB(tmp)) { cout << sc_time_stamp() << ": Received Output Weight:" << " \t " << tmp << endl; } if (act_out.PopNB(act_out_src)) { cout << sc_time_stamp() << ": Received Output Activation:" << " \t " << act_out_src << "\t| Reference \t" << act_list[i] << endl; correct &= (act_list[i] == act_out_src); i++; } if (accum_out.PopNB(accum_out_src)) { int acc_ref = accum_list[j] + act_list[j]*weight_data; cout << sc_time_stamp() << ": Received Accumulated Output:" << "\t " << accum_out_src << "\t| Reference \t" << acc_ref << endl; correct &= (acc_ref == accum_out_src); j++; } wait(); if (i == act_list.size() && j == act_list.size()) break; }// while if (correct == 1) cout << "Implementation Correct :)" << endl; else cout << "Implementation Incorrect (:" << endl; }// void pop_result() }; SC_MODULE (testbench) { sc_clock clk; sc_signal<bool> rst; Connections::Combinational<SysPE::InputType> act_in; Connections::Combinational<SysPE::InputType> act_out; Connections::Combinational<SysPE::InputType> weight_in; Connections::Combinational<SysPE::InputType> weight_out; Connections::Combinational<SysPE::AccumType> accum_in; Connections::Combinational<SysPE::AccumType> accum_out; NVHLS_DESIGN(SysPE) PE; Source src; SC_HAS_PROCESS(testbench); testbench(sc_module_name name) : sc_module(name), clk("clk", 1, SC_NS, 0.5,0,SC_NS,true), rst("rst"), PE("PE"), src("src") { PE.clk(clk); PE.rst(rst); PE.act_in(act_in); PE.act_out(act_out); PE.weight_in(weight_in); PE.weight_out(weight_out); PE.accum_in(accum_in); PE.accum_out(accum_out); src.clk(clk); src.rst(rst); src.act_in(act_in); src.act_out(act_out); src.weight_in(weight_in); src.weight_out(weight_out); src.accum_in(accum_in); src.accum_out(accum_out); SC_THREAD(run); } void run() { rst = 1; wait(10.5, SC_NS); rst = 0; cout << "@" << sc_time_stamp() << " Asserting Reset " << endl ; wait(1, SC_NS); cout << "@" << sc_time_stamp() << " Deasserting Reset " << endl ; rst = 1; wait(10000,SC_NS); cout << "@" << sc_time_stamp() << " Stop " << endl ; sc_stop(); } }; int sc_main(int argc, char *argv[]) { nvhls::set_random_seed(); testbench my_testbench("my_testbench"); sc_start(); //cout << "CMODEL PASS" << endl; return 0; };
#ifndef IPS_FILTER_TLM_CPP #define IPS_FILTER_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 "ips_filter_tlm.hpp" #include "common_func.hpp" #include "important_defines.hpp" void ips_filter_tlm::do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address) { this->img_result = *(Filter<IPS_IN_TYPE_TB, IPS_OUT_TYPE_TB, IPS_FILTER_KERNEL_SIZE>::result_ptr); memcpy(data, Filter<IPS_IN_TYPE_TB, IPS_OUT_TYPE_TB, IPS_FILTER_KERNEL_SIZE>::result_ptr, sizeof(IPS_OUT_TYPE_TB)); } void ips_filter_tlm::do_when_write_transaction(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address) { IPS_OUT_TYPE_TB* result = new IPS_OUT_TYPE_TB; IPS_IN_TYPE_TB* img_window = new IPS_IN_TYPE_TB[3 * 3]; if ((IPS_FILTER_KERNEL_SIZE * IPS_FILTER_KERNEL_SIZE * sizeof(char)) != data_length) { SC_REPORT_FATAL("IPS_FILTER", "Illegal transaction size"); } for (int i = 0; i < IPS_FILTER_KERNEL_SIZE; i++) { for (int j = 0; j < IPS_FILTER_KERNEL_SIZE; j++) { *(img_window + ((i * IPS_FILTER_KERNEL_SIZE) + j)) = (IPS_IN_TYPE_TB)*(data + ((i * IPS_FILTER_KERNEL_SIZE) + j)); this->img_window[(i * IPS_FILTER_KERNEL_SIZE) + j] = (IPS_IN_TYPE_TB)*(data + ((i * IPS_FILTER_KERNEL_SIZE) + j)); } } filter(img_window, result); } #endif // IPS_FILTER_TLM_CPP
#include <systemc.h> #include <string> #include <vector> #include <map> #include <fstream> #include <nana/gui.hpp> #include <nana/gui/widgets/button.hpp> #include <nana/gui/widgets/menubar.hpp> #include <nana/gui/widgets/group.hpp> #include <nana/gui/widgets/textbox.hpp> #include <nana/gui/filebox.hpp> #include "top.hpp" #include "gui.hpp" using std::fstream; using std::map; using std::string; using std::vector; int sc_main(int argc, char *argv[]) { using namespace nana; vector<string> instruction_queue; string bench_name = ""; int nadd, nmul, nls, n_bits, bpb_size, cpu_freq, m_size; m_size = 2; nadd = 3; nmul = nls = 2; n_bits = 2; bpb_size = 4; cpu_freq = 500; // definido em Mhz - 500Mhz default std::vector<int> sizes; bool spec = false; int mode = 0; bool fila = false; ifstream inFile; form fm(API::make_center(1024, 700)); place plc(fm); place upper(fm); place lower(fm); listbox table(fm); listbox reg(fm); listbox instruct(fm); listbox rob(fm); menubar mnbar(fm); button start(fm); button run_all(fm); button clock_control(fm); button exit(fm); group clock_group(fm); label clock_count(clock_group); fm.caption("TFSim"); clock_group.caption("Ciclo"); clock_group.div("count"); grid memory(fm, rectangle(), 10, 50); // Tempo de latencia de uma instrucao // Novas instrucoes devem ser inseridas manualmente aqui map<string, int> instruct_time{{"DADD", 4}, {"DADDI", 4}, {"DSUB", 6}, {"DSUBI", 6}, {"DMUL", 10}, {"DDIV", 16}, {"MEM", 2}, {"SLT", 1}, {"SGT", 1}}; // Responsavel pelos modos de execução top top1("top"); start.caption("Start"); clock_control.caption("Next cycle"); run_all.caption("Run all"); exit.caption("Exit"); plc["rst"] << table; plc["btns"] << start << clock_control << run_all << exit; plc["memor"] << memory; plc["regs"] << reg; plc["rob"] << rob; plc["instr"] << instruct; plc["clk_c"] << clock_group; clock_group["count"] << clock_count; clock_group.collocate(); spec = false; // set_spec eh so visual set_spec(plc, spec); plc.collocate(); mnbar.push_back("Opções"); menu &op = mnbar.at(0); // menu::item_proxy spec_ip = op.append("Especulação"); auto spec_sub = op.create_sub_menu(0); // Modo com 1 preditor para todos os branchs spec_sub->append("1 Preditor", [&](menu::item_proxy &ip) { if(ip.checked()){ spec = true; mode = 1; spec_sub->checked(1, false); spec_sub->checked(2, false); } else{ spec = false; mode = 0; } set_spec(plc,spec); }); spec_sub->append("2 Preditor M,N", [&](menu::item_proxy &ip) { if (ip.checked()) { spec = true; mode = 3; spec_sub->checked(0, false); spec_sub->checked(2, false); } else { spec = false; mode = 0; } set_spec(plc,spec); }); // Modo com o bpb spec_sub->append("Branch Prediction Buffer", [&](menu::item_proxy &ip) { if (ip.checked()) { spec = true; mode = 2; spec_sub->checked(0, false); spec_sub->checked(1, false); } else { spec = false; mode = 0; } set_spec(plc, spec); }); spec_sub->check_style(0, menu::checks::highlight); spec_sub->check_style(1, menu::checks::highlight); spec_sub->check_style(2, menu::checks::highlight); op.append("Modificar valores..."); // novo submenu para escolha do tamanho do bpb e do preditor auto sub = op.create_sub_menu(1); sub->append("Tamanho do BPB e Preditor", [&](menu::item_proxy &ip) { inputbox ibox(fm, "", "Definir tamanhos"); inputbox::integer size("BPB", bpb_size, 2, 10, 2); inputbox::integer bits("N_BITS", n_bits, 1, 3, 1); inputbox::integer m_size_input("M_SIZE", m_size, 1, 8, 1); if (ibox.show_modal(size, bits, m_size_input)) { bpb_size = size.value(); n_bits = bits.value(); m_size = m_size_input.value(); } }); sub->append("Número de Estações de Reserva", [&](menu::item_proxy ip) { inputbox ibox(fm, "", "Quantidade de Estações de Reserva"); inputbox::integer add("ADD/SUB", nadd, 1, 10, 1); inputbox::integer mul("MUL/DIV", nmul, 1, 10, 1); inputbox::integer sl("LOAD/STORE", nls, 1, 10, 1); if (ibox.show_modal(add, mul, sl)) { nadd = add.value(); nmul = mul.value(); nls = sl.value(); } }); // Menu de ajuste dos tempos de latencia na interface // Novas instrucoes devem ser adcionadas manualmente aqui sub->append("Tempos de latência", [&](menu::item_proxy &ip) { inputbox ibox(fm, "", "Tempos de latência para instruções"); inputbox::text dadd_t("DADD", std::to_string(instruct_time["DADD"])); inputbox::text daddi_t("DADDI", std::to_string(instruct_time["DADDI"])); inputbox::text dsub_t("DSUB", std::to_string(instruct_time["DSUB"])); inputbox::text dsubi_t("DSUBI", std::to_string(instruct_time["DSUBI"])); inputbox::text dmul_t("DMUL", std::to_string(instruct_time["DMUL"])); inputbox::text ddiv_t("DDIV", std::to_string(instruct_time["DDIV"])); inputbox::text mem_t("Load/Store", std::to_string(instruct_time["MEM"])); if (ibox.show_modal(dadd_t, daddi_t, dsub_t, dsubi_t, dmul_t, ddiv_t, mem_t)) { instruct_time["DADD"] = std::stoi(dadd_t.value()); instruct_time["DADDI"] = std::stoi(daddi_t.value()); instruct_time["DSUB"] = std::stoi(dsub_t.value()); instruct_time["DSUBI"] = std::stoi(dsubi_t.value()); instruct_time["DMUL"] = std::stoi(dmul_t.value()); instruct_time["DDIV"] = std::stoi(ddiv_t.value()); instruct_time["MEM"] = std::stoi(mem_t.value()); } }); sub->append("Frequência CPU", [&](menu::item_proxy &ip) { inputbox ibox(fm, "Em Mhz", "Definir frequência da CPU"); inputbox::text freq("Frequência", std::to_string(cpu_freq)); if (ibox.show_modal(freq)) { cpu_freq = std::stoi(freq.value()); } }); sub->append("Fila de instruções", [&](menu::item_proxy &ip) { filebox fb(0, true); inputbox ibox(fm, "Localização do arquivo com a lista de instruções:"); inputbox::path caminho("", fb); if (ibox.show_modal(caminho)) { auto path = caminho.value(); inFile.open(path); if (!add_instructions(inFile, instruction_queue, instruct)) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else fila = true; } }); sub->append("Valores de registradores inteiros", [&](menu::item_proxy &ip) { filebox fb(0, true); inputbox ibox(fm, "Localização do arquivo de valores de registradores inteiros:"); inputbox::path caminho("", fb); if (ibox.show_modal(caminho)) { auto path = caminho.value(); inFile.open(path); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { auto reg_gui = reg.at(0); int value, i = 0; while (inFile >> value && i < 32) { reg_gui.at(i).text(1, std::to_string(value)); i++; } for (; i < 32; i++) reg_gui.at(i).text(1, "0"); inFile.close(); } } }); sub->append("Valores de registradores PF", [&](menu::item_proxy &ip) { filebox fb(0, true); inputbox ibox(fm, "Localização do arquivo de valores de registradores PF:"); inputbox::path caminho("", fb); if (ibox.show_modal(caminho)) { auto path = caminho.value(); inFile.open(path); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { auto reg_gui = reg.at(0); int i = 0; float value; while (inFile >> value && i < 32) { reg_gui.at(i).text(4, std::to_string(value)); i++; } for (; i < 32; i++) reg_gui.at(i).text(4, "0"); inFile.close(); } } }); sub->append("Valores de memória", [&](menu::item_proxy &ip) { filebox fb(0, true); inputbox ibox(fm, "Localização do arquivo de valores de memória:"); inputbox::path caminho("", fb); if (ibox.show_modal(caminho)) { auto path = caminho.value(); inFile.open(path); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { int i = 0; int value; while (inFile >> value && i < 500) { memory.Set(i, std::to_string(value)); i++; } for (; i < 500; i++) { memory.Set(i, "0"); } inFile.close(); } } }); op.append("Verificar conteúdo..."); auto new_sub = op.create_sub_menu(2); new_sub->append("Valores de registradores", [&](menu::item_proxy &ip) { filebox fb(0, true); inputbox ibox(fm, "Localização do arquivo de valores de registradores:"); inputbox::path caminho("", fb); if (ibox.show_modal(caminho)) { auto path = caminho.value(); inFile.open(path); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { string str; int reg_pos, i; bool is_float, ok; ok = true; while (inFile >> str) { if (str[0] == '$') { if (str[1] == 'f') { i = 2; is_float = true; } else { i = 1; is_float = false; } reg_pos = std::stoi(str.substr(i, str.size() - i)); auto reg_gui = reg.at(0); string value; inFile >> value; if (!is_float) { if (reg_gui.at(reg_pos).text(1) != value) { ok = false; break; } } else { if (std::stof(reg_gui.at(reg_pos).text(4)) != std::stof(value)) { ok = false; break; } } } } inFile.close(); msgbox msg("Verificação de registradores"); if (ok) { msg << "Registradores especificados apresentam valores idênticos!"; msg.icon(msgbox::icon_information); } else { msg << "Registradores especificados apresentam valores distintos!"; msg.icon(msgbox::icon_error); } msg.show(); } } }); new_sub->append("Valores de memória", [&](menu::item_proxy &ip) { filebox fb(0, true); inputbox ibox(fm, "Localização do arquivo de valores de memória:"); inputbox::path caminho("", fb); if (ibox.show_modal(caminho)) { auto path = caminho.value(); inFile.open(path); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { string value; bool ok; ok = true; for (int i = 0; i < 500; i++) { inFile >> value; if (std::stoi(memory.Get(i)) != (int)std::stol(value, nullptr, 16)) { ok = false; break; } } inFile.close(); msgbox msg("Verificação de memória"); if (ok) { msg << "Endereços de memória especificados apresentam valores idênticos!"; msg.icon(msgbox::icon_information); } else { msg << "Endereços de memória especificados apresentam valores distintos!"; msg.icon(msgbox::icon_error); } msg.show(); } } }); op.append("Benchmarks"); auto bench_sub = op.create_sub_menu(3); bench_sub->append("Fibonacci", [&](menu::item_proxy &ip) { string path = "in/benchmarks/fibonacci/fibonacci.txt"; bench_name = "fibonacci"; inFile.open(path); if (!add_instructions(inFile, instruction_queue, instruct)) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else fila = true; }); bench_sub->append("Stall por Divisão", [&](menu::item_proxy &ip) { string path = "in/benchmarks/division_stall.txt"; inFile.open(path); if (!add_instructions(inFile, instruction_queue, instruct)) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else fila = true; }); bench_sub->append("Stress de Memória (Stores)", [&](menu::item_proxy &ip) { string path = "in/benchmarks/store_stress/store_stress.txt"; bench_name = "store_stress"; inFile.open(path); if (!add_instructions(inFile, instruction_queue, instruct)) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else fila = true; }); bench_sub->append("Stall por hazard estrutural (Adds)", [&](menu::item_proxy &ip) { string path = "in/benchmarks/res_stations_stall.txt"; inFile.open(path); if (!add_instructions(inFile, instruction_queue, instruct)) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else fila = true; }); bench_sub->append("Busca Linear", [&](menu::item_proxy &ip) { string path = "in/benchmarks/linear_search/linear_search.txt"; bench_name = "linear_search"; inFile.open(path); if (!add_instructions(inFile, instruction_queue, instruct)) show_message("Arquivo inválido", "Não foi possível abrir o arquivo"); else fila = true; path = "in/benchmarks/linear_search/memory.txt"; inFile.open(path); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { int i = 0; int value; while (inFile >> value && i < 500) { memory.Set(i, std::to_string(value)); i++; } for (; i < 500; i++) { memory.Set(i, "0"); } inFile.close(); } path = "in/benchmarks/linear_search/regi_i.txt"; inFile.open(path); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { auto reg_gui = reg.at(0); int value, i = 0; while (inFile >> value && i < 32) { reg_gui.at(i).text(1, std::to_string(value)); i++; } for (; i < 32; i++) reg_gui.at(i).text(1, "0"); inFile.close(); } }); bench_sub->append("Busca Binária", [&](menu::item_proxy &ip) { string path = "in/benchmarks/binary_search/binary_search.txt"; bench_name = "binary_search"; inFile.open(path); if (!add_instructions(inFile, instruction_queue, instruct)) show_message("Arquivo inválido", "Não foi possível abrir o arquivo"); else fila = true; path = "in/benchmarks/binary_search/memory.txt"; inFile.open(path); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { int i = 0; int value; while (inFile >> value && i < 500) { memory.Set(i, std::to_string(value)); i++; } for (; i < 500; i++) { memory.Set(i, "0"); } inFile.close(); } path = "in/benchmarks/binary_search/regs.txt"; inFile.open(path); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { auto reg_gui = reg.at(0); int value, i = 0; while (inFile >> value && i < 32) { reg_gui.at(i).text(1, std::to_string(value)); i++; } for (; i < 32; i++) reg_gui.at(i).text(1, "0"); inFile.close(); } }); bench_sub->append("Matriz Search", [&](menu::item_proxy &ip) { string path = "in/benchmarks/matriz_search/matriz_search.txt"; bench_name = "matriz_search"; inFile.open(path); if (!add_instructions(inFile, instruction_queue, instruct)) show_message("Arquivo inválido", "Não foi possível abrir o arquivo"); else fila = true; path = "in/benchmarks/matriz_search/memory.txt"; inFile.open(path); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { int i = 0; int value; while (inFile >> value && i < 500) { memory.Set(i, std::to_string(value)); i++; } for (; i < 500; i++) { memory.Set(i, "0"); } inFile.close(); } path = "in/benchmarks/matriz_search/regs.txt"; inFile.open(path); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { auto reg_gui = reg.at(0); int value, i = 0; while (inFile >> value
&& i < 32) { reg_gui.at(i).text(1, std::to_string(value)); i++; } for (; i < 32; i++) reg_gui.at(i).text(1, "0"); inFile.close(); } }); bench_sub->append("Bubble Sort", [&](menu::item_proxy &ip) { string path = "in/benchmarks/bubble_sort/bubble_sort.txt"; bench_name = "bubble_sort"; inFile.open(path); if (!add_instructions(inFile, instruction_queue, instruct)) show_message("Arquivo inválido", "Não foi possível abrir o arquivo"); else fila = true; path = "in/benchmarks/bubble_sort/memory.txt"; inFile.open(path); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { int i = 0; int value; while (inFile >> value && i < 500) { memory.Set(i, std::to_string(value)); i++; } for (; i < 500; i++) { memory.Set(i, "0"); } inFile.close(); } path = "in/benchmarks/bubble_sort/regs.txt"; inFile.open(path); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { auto reg_gui = reg.at(0); int value, i = 0; while (inFile >> value && i < 32) { reg_gui.at(i).text(1, std::to_string(value)); i++; } for (; i < 32; i++) reg_gui.at(i).text(1, "0"); inFile.close(); } }); bench_sub->append("Insertion Sort", [&](menu::item_proxy &ip) { string path = "in/benchmarks/insertion_sort/insertion_sort.txt"; bench_name = "insertion_sort"; inFile.open(path); if (!add_instructions(inFile, instruction_queue, instruct)) show_message("Arquivo inválido", "Não foi possível abrir o arquivo"); else fila = true; path = "in/benchmarks/insertion_sort/memory.txt"; inFile.open(path); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { int i = 0; int value; while (inFile >> value && i < 500) { memory.Set(i, std::to_string(value)); i++; } for (; i < 500; i++) { memory.Set(i, "0"); } inFile.close(); } path = "in/benchmarks/insertion_sort/regs.txt"; inFile.open(path); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { auto reg_gui = reg.at(0); int value, i = 0; while (inFile >> value && i < 32) { reg_gui.at(i).text(1, std::to_string(value)); i++; } for (; i < 32; i++) reg_gui.at(i).text(1, "0"); inFile.close(); } }); bench_sub->append("Tick Tack", [&](menu::item_proxy &ip) { string path = "in/benchmarks/tick_tack/tick_tack.txt"; bench_name = "tick_tack"; inFile.open(path); if (!add_instructions(inFile, instruction_queue, instruct)) show_message("Arquivo inválido", "Não foi possível abrir o arquivo"); else fila = true; path = "in/benchmarks/tick_tack/regs.txt"; inFile.open(path); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { auto reg_gui = reg.at(0); int value, i = 0; while (inFile >> value && i < 32) { reg_gui.at(i).text(1, std::to_string(value)); i++; } for (; i < 32; i++) reg_gui.at(i).text(1, "0"); inFile.close(); } }); bench_sub->append("Double Interaction", [&](menu::item_proxy &ip) { string path = "in/benchmarks/double_interaction/double_interaction.txt"; bench_name = "double_interaction"; inFile.open(path); if (!add_instructions(inFile, instruction_queue, instruct)) show_message("Arquivo inválido", "Não foi possível abrir o arquivo"); else fila = true; }); bench_sub->append("Linear Search Extended", [&](menu::item_proxy &ip) { string path = "in/benchmarks/linear_search_extended/linear_search_extended.txt"; bench_name = "linear_search_extended"; inFile.open(path); if (!add_instructions(inFile, instruction_queue, instruct)) show_message("Arquivo inválido", "Não foi possível abrir o arquivo"); else fila = true; }); bench_sub->append("Log Calc", [&](menu::item_proxy &ip) { string path = "in/benchmarks/log_calc/log_calc.txt"; bench_name = "log_calc"; inFile.open(path); if (!add_instructions(inFile, instruction_queue, instruct)) show_message("Arquivo inválido", "Não foi possível abrir o arquivo"); else fila = true; }); bench_sub->append("Simple Loop", [&](menu::item_proxy &ip) { string path = "in/benchmarks/simple_loop/simple_loop.txt"; bench_name = "simple_loop"; inFile.open(path); if (!add_instructions(inFile, instruction_queue, instruct)) show_message("Arquivo inválido", "Não foi possível abrir o arquivo"); else fila = true; }); vector<string> columns = {"#", "Name", "Busy", "Op", "Vj", "Vk", "Qj", "Qk", "A"}; for (unsigned int i = 0; i < columns.size(); i++) { table.append_header(columns[i].c_str()); if (i && i != 3) table.column_at(i).width(45); else if (i == 3) table.column_at(i).width(60); else table.column_at(i).width(30); } columns = {"", "Value", "Qi"}; sizes = {30, 75, 40}; for (unsigned int k = 0; k < 2; k++) for (unsigned int i = 0; i < columns.size(); i++) { reg.append_header(columns[i]); reg.column_at(k * columns.size() + i).width(sizes[i]); } auto reg_gui = reg.at(0); for (int i = 0; i < 32; i++) { string index = std::to_string(i); reg_gui.append("R" + index); reg_gui.at(i).text(3, "F" + index); } columns = {"Instruction", "Issue", "Execute", "Write Result"}; sizes = {140, 60, 70, 95}; for (unsigned int i = 0; i < columns.size(); i++) { instruct.append_header(columns[i]); instruct.column_at(i).width(sizes[i]); } columns = {"Entry", "Busy", "Instruction", "State", "Destination", "Value"}; sizes = {45, 45, 120, 120, 90, 60}; for (unsigned int i = 0; i < columns.size(); i++) { rob.append_header(columns[i]); rob.column_at(i).width(sizes[i]); } srand(static_cast<unsigned>(time(0))); for (int i = 0; i < 32; i++) { if (i) reg_gui.at(i).text(1, std::to_string(rand() % 100)); else reg_gui.at(i).text(1, std::to_string(0)); reg_gui.at(i).text(2, "0"); reg_gui.at(i).text(4, std::to_string(static_cast<float>(rand()) / static_cast<float>(RAND_MAX / 100.0))); reg_gui.at(i).text(5, "0"); } for (int i = 0; i < 500; i++) memory.Push(std::to_string(rand() % 100)); for (int k = 1; k < argc; k += 2) { int i; if (strlen(argv[k]) > 2) show_message("Opção inválida", string("Opção \"") + string(argv[k]) + string("\" inválida")); else { char c = argv[k][1]; switch (c) { case 'q': inFile.open(argv[k + 1]); if (!add_instructions(inFile, instruction_queue, instruct)) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else fila = true; break; case 'i': inFile.open(argv[k + 1]); int value; i = 0; if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { while (inFile >> value && i < 32) { reg_gui.at(i).text(1, std::to_string(value)); i++; } for (; i < 32; i++) reg_gui.at(i).text(1, "0"); inFile.close(); } break; case 'f': float value_fp; i = 0; inFile.open(argv[k + 1]); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { while (inFile >> value_fp && i < 32) { reg_gui.at(i).text(4, std::to_string(value_fp)); i++; } for (; i < 32; i++) reg_gui.at(i).text(4, "0"); inFile.close(); } break; case 'm': inFile.open(argv[k + 1]); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { int value; i = 0; while (inFile >> value && i < 500) { memory.Set(i, std::to_string(value)); i++; } for (; i < 500; i++) { memory.Set(i, "0"); } inFile.close(); } break; case 'r': inFile.open(argv[k + 1]); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { int value; if (inFile >> value && value <= 10 && value > 0) nadd = value; if (inFile >> value && value <= 10 && value > 0) nmul = value; if (inFile >> value && value <= 10 && value > 0) nls = value; inFile.close(); } break; case 's': spec = true; set_spec(plc, spec); // spec_ip.checked(true); k--; break; case 'l': inFile.open(argv[k + 1]); if (!inFile.is_open()) show_message("Arquivo inválido", "Não foi possível abrir o arquivo!"); else { string inst; int value; while (inFile >> inst) { if (inFile >> value && instruct_time.count(inst)) instruct_time[inst] = value; } } inFile.close(); break; default: show_message("Opção inválida", string("Opção \"") + string(argv[k]) + string("\" inválida")); break; } } } clock_control.enabled(false); run_all.enabled(false); start.events().click([&] { if (fila) { start.enabled(false); clock_control.enabled(true); run_all.enabled(true); // Desativa os menus apos inicio da execucao op.enabled(0, false); op.enabled(1, false); op.enabled(3, false); for (int i = 0; i < 2; i++) spec_sub->enabled(i, false); for (int i = 0; i < 8; i++) sub->enabled(i, false); for (int i = 0; i < 10; i++) bench_sub->enabled(i, false); if (spec) { // Flag mode setada pela escolha no menu if (mode == 1) top1.rob_mode(n_bits, nadd, nmul, nls, instruct_time, instruction_queue, table, memory, reg, instruct, clock_count, rob); else if(mode == 3) top1.rob_mode_mn(n_bits,nadd,nmul,nls,instruct_time,instruction_queue,table,memory,reg,instruct,clock_count,rob, m_size); else if (mode == 2) top1.rob_mode_bpb(n_bits, bpb_size, nadd, nmul, nls, instruct_time, instruction_queue, table, memory, reg, instruct, clock_count, rob); } else top1.simple_mode(nadd, nmul, nls, instruct_time, instruction_queue, table, memory, reg, instruct, clock_count); sc_start(); } else show_message("Fila de instruções vazia", "A fila de instruções está vazia. Insira um conjunto de instruções para iniciar."); }); clock_control.events().click([&] { if (top1.get_queue().queue_is_empty() && top1.get_rob().rob_is_empty()) return; if (sc_is_running()) sc_start(); }); run_all.events().click([&] { // enquanto queue e rob nao estao vazios, roda ate o fim while (!(top1.get_queue().queue_is_empty() && top1.get_rob().rob_is_empty())) { if (sc_is_running()) sc_start(); } top1.metrics(cpu_freq, mode, bench_name, n_bits); }); exit.events().click([] { sc_stop(); API::exit(); }); fm.show(); exec(); return 0; }
#ifndef IMG_ROUTER_CPP #define IMG_ROUTER_CPP // #include "tlm_transaction.cpp" #include "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> #include <ostream> #include "common_func.hpp" #include "img_generic_extension.hpp" //#include "tlm_queue.cpp" #include "important_defines.hpp" //const char* tlm_enum_names[] = {"TLM_ACCEPTED", "TLM_UPDATED", "TLM_COMPLETED"}; struct tlm_item{ tlm::tlm_generic_payload *transaction; tlm::tlm_phase phase; sc_time delay; tlm_item(tlm::tlm_generic_payload *transaction = 0, tlm::tlm_phase phase = tlm::BEGIN_REQ, sc_time delay = sc_time(0, SC_NS)){} tlm_item& operator=(const tlm_item& rhs){ transaction = rhs.transaction; phase = rhs.phase; delay = rhs.delay; return *this; } bool operator==(const tlm_item& rhs){ return transaction == rhs.transaction && phase == rhs.phase && delay == rhs.delay; } friend std::ostream& operator<<(std::ostream& os, const tlm_item& val) { os << "Transaction Pointer = " << val.transaction << "; phase = " << val.phase << "; delay = " << val.delay << std::endl; return os; } }; // inline void sc_trace(sc_trace_file*& f, const tlm_item& val, std::string name) { // sc_trace(f, val.transaction, name + ".transaction"); // sc_trace(f, val.phase, name + ".phase"); // sc_trace(f, val.delay, name + ".delay"); // } // Initiator module generating generic payload transactions template<unsigned int N_TARGETS> struct img_router: sc_module { // TLM2.0 Socket tlm_utils::simple_target_socket<img_router> target_socket; tlm_utils::simple_initiator_socket<img_router>* initiator_socket[N_TARGETS]; //Memory Manager for transaction memory allocation mm memory_manager; //Payload event queue with callback and phase tlm_utils::peq_with_cb_and_phase<img_router> bw_m_peq; //For initiator access tlm_utils::peq_with_cb_and_phase<img_router> fw_m_peq; //For target access //Delay sc_time bw_delay; sc_time fw_delay; //TLM Items queue sc_fifo<tlm_item> fw_fifo; sc_fifo<tlm_item> bw_fifo; //DEBUG unsigned int transaction_in_fw_path_id = 0; unsigned int transaction_in_bw_path_id = 0; bool use_prints; //Constructor SC_CTOR(img_router) : target_socket("socket"), bw_m_peq(this, &img_router::bw_peq_cb), fw_m_peq(this, &img_router::fw_peq_cb), fw_fifo(10), bw_fifo(2), use_prints(true) // Construct and name socket { // Register callbacks for incoming interface method calls target_socket.register_nb_transport_fw(this, &img_router::nb_transport_fw); for (unsigned int i = 0; i < N_TARGETS; i++) { char txt[20]; sprintf(txt, "socket_%d", i); initiator_socket[i] = new tlm_utils::simple_initiator_socket<img_router>(txt); (*initiator_socket[i]).register_nb_transport_bw(this, &img_router::nb_transport_bw); } SC_THREAD(fw_thread); SC_THREAD(bw_thread); #ifdef DISABLE_ROUTER_DEBUG this->use_prints = false; #endif //DISABLE_ROUTER_DEBUG checkprintenable(use_prints); } //Address Decoding #define IMG_FILTER_INITIATOR_ID 0 #define IMG_SOBEL_INITIATOR_ID 1 #define IMG_MEMORY_INITIATOR_ID 2 #define IMG_ETHERNET_INITIATOR_ID 3 #define IMG_VGA_INITIATOR_ID 4 #define INVALID_INITIATOR_ID 5 unsigned int decode_address (sc_dt::uint64 address) { switch(address) { // To Filter case IMG_FILTER_KERNEL_ADDRESS_LO: { dbgmodprint(use_prints, "Decoded address %016llX corresponds to Filter module.", address); return IMG_FILTER_INITIATOR_ID; } // To/from Sobel case SOBEL_INPUT_0_ADDRESS_LO: case SOBEL_INPUT_1_ADDRESS_LO: case SOBEL_OUTPUT_ADDRESS_LO: { dbgmodprint(use_prints, "Decoded address %016llX corresponds to Sobel module.", address); return IMG_SOBEL_INITIATOR_ID; } case IMG_OUTPUT_ADDRESS_LO ... (IMG_OUTPUT_ADDRESS_HI - 1): case IMG_OUTPUT_SIZE_ADDRESS_LO: case IMG_OUTPUT_DONE_ADDRESS_LO: case IMG_OUTPUT_STATUS_ADDRESS_LO: { dbgmodprint(use_prints, "Decoded address %016llX corresponds to Ethernet module.", address); return IMG_ETHERNET_INITIATOR_ID; } // To/from Input Image case IMG_INPUT_ADDRESS_LO ... (IMG_INPUT_ADDRESS_HI - 1): case IMG_INPUT_START_ADDRESS_LO: case IMG_INPUT_DONE_ADDRESS_LO: { dbgmodprint(use_prints, "Decoded address %016llX corresponds to VGA module.", address); return IMG_VGA_INITIATOR_ID; } // To/From Memory Valid addresses case MEMORY_ADDRESS_LO ... (MEMORY_ADDRESS_HI - 1) : { dbgmodprint(use_prints, "Decoded address %016llX corresponds to Memory.", address); return IMG_MEMORY_INITIATOR_ID; } default: { dbgmodprint(true, "[ERROR] Decoding invalid address %016llX.", address); SC_REPORT_FATAL("[IMG ROUTER]", "Received address is invalid, does not match any hardware block"); return INVALID_INITIATOR_ID; } } } // TLM2 backward path non-blocking transport method virtual tlm::tlm_sync_enum nb_transport_bw(tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_time& delay ) { img_generic_extension* img_ext; //Call event queue tlm_item item; item.transaction = &trans; item.phase = phase; item.delay = delay; trans.get_extension(img_ext); if (bw_fifo.num_free() == 0) { dbgmodprint(use_prints, "[BW_FIFO] FIFO is FULL. Waiting..."); wait(bw_fifo.data_read_event()); } bw_fifo.nb_write(item); wait(bw_fifo.data_written_event()); dbgmodprint(use_prints, "[BW_FIFO] Pushed transaction #%0d", img_ext->transaction_number); return tlm::TLM_ACCEPTED; } // TLM2 forward path non-blocking transport method virtual tlm::tlm_sync_enum nb_transport_fw(tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_time& delay ) { img_generic_extension* img_ext; //Call event queue tlm_item item; item.transaction = &trans; item.phase = phase; item.delay = delay; trans.get_extension(img_ext); if (fw_fifo.num_free() == 0) { dbgmodprint(use_prints, "[FW_FIFO] FIFO is FULL. Waiting..."); wait(fw_fifo.data_read_event()); } fw_fifo.nb_write(item); wait(fw_fifo.data_written_event()); dbgmodprint(use_prints, "[FW_FIFO] Pushed transaction #%0d", img_ext->transaction_number); return tlm::TLM_ACCEPTED; } void fw_thread() { while(true) { img_generic_extension* img_ext; tlm::tlm_generic_payload* trans_ptr = new tlm::tlm_generic_payload; tlm::tlm_phase phase; sc_time delay; tlm_item item; if (fw_fifo.num_available() == 0) { wait(fw_fifo.data_written_event()); } fw_fifo.nb_read(item); wait(fw_fifo.data_read_event()); trans_ptr = item.transaction; phase = item.phase; delay = item.delay; (*trans_ptr).get_extension(img_ext); dbgmodprint(use_prints, "[FW_FIFO] Popped transaction #%0d", img_ext->transaction_number); fw_m_peq.notify(*trans_ptr, phase, delay); wait(fw_delay); } } void bw_thread() { while(true) { img_generic_extension* img_ext; tlm::tlm_generic_payload* trans_ptr = new tlm::tlm_generic_payload; tlm::tlm_phase phase; sc_time delay; tlm_item item; if (bw_fifo.num_available() == 0) { wait(bw_fifo.data_written_event()); } bw_fifo.nb_read(item); wait(bw_fifo.data_read_event()); trans_ptr = item.transaction; phase = item.phase; delay = item.delay; (*trans_ptr).get_extension(img_ext); dbgmodprint(use_prints, "[BW_FIFO] Popped transaction #%0d", img_ext->transaction_number); bw_m_peq.notify(*trans_ptr, phase, delay); wait(bw_delay); } } //Payload event and queue callback to handle transactions received from target void bw_peq_cb(tlm::tlm_generic_payload& trans, const tlm::tlm_phase& phase) { img_generic_extension* img_ext; trans.get_extension(img_ext); tlm::tlm_phase local_phase = phase; sc_dt::uint64 address = trans.get_address(); this->transaction_in_bw_path_id = img_ext->transaction_number; dbgmodprint(use_prints, "Received transaction #%0d with address %016llX in backward path. Redirecting transaction to CPU", img_ext->transaction_number, address); target_socket->nb_transport_bw(trans, local_phase, this->bw_delay); } void fw_peq_cb(tlm::tlm_generic_payload& trans, const tlm::tlm_phase& phase) { img_generic_extension* img_ext; trans.get_extension(img_ext); tlm::tlm_phase local_phase = phase; sc_dt::uint64 address = trans.get_address(); this->transaction_in_fw_path_id = img_ext->transaction_number; unsigned int initiator_id = decode_address(address); dbgmodprint(use_prints, "Received transaction #%0d with address %016llX in forward path. Redirecting transaction through initiator %d", img_ext->transaction_number, address, initiator_id); (*initiator_socket[initiator_id])->nb_transport_fw(trans, local_phase, this->fw_delay); } void set_delays(sc_time fw_delay, sc_time bw_delay) { this->bw_delay = bw_delay; this->fw_delay = fw_delay; } } ; #endif
#ifndef RGB2GRAY_TLM_CPP #define RGB2GRAY_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 "rgb2gray_tlm.hpp" #include "common_func.hpp" void rgb2gray_tlm::do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address){ unsigned char pixel_value; pixel_value = this->obtain_gray_value(); dbgimgtarmodprint(use_prints, "%0u", pixel_value); memcpy(data, &pixel_value, sizeof(char)); } void rgb2gray_tlm::do_when_write_transaction(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address){ unsigned char rgb_values[3]; int j = 0; for (unsigned char *i = data; (i - data) < 3; i++) { rgb_values[j] = *i; dbgimgtarmodprint(use_prints, "VAL: %0ld -> %0u", i - data, *i); j++; } this->set_rgb_pixel(rgb_values[0], rgb_values[1], rgb_values[2]); } #endif // RGB2GRAY_TLM_CPP
#include <systemc.h> #include "counter.cpp" int sc_main (int argc, char* argv[]) { sc_signal<bool> clock; sc_signal<bool> reset; sc_signal<bool> enable; sc_signal<sc_uint<4> > counter_out; int i = 0; // Connect the DUT first_counter counter("COUNTER"); counter.clock(clock); counter.reset(reset); counter.enable(enable); counter.counter_out(counter_out); // Open VCD file sc_trace_file *wf = sc_create_vcd_trace_file("counter"); wf->set_time_unit(1, SC_NS); // Dump the desired signals sc_trace(wf, clock, "clock"); sc_trace(wf, reset, "reset"); sc_trace(wf, enable, "enable"); sc_trace(wf, counter_out, "count"); sc_start(1,SC_NS); // Initialize all variables reset = 0; // initial value of reset enable = 0; // initial value of enable for (i=0;i<5;i++) { clock = 0; sc_start(1,SC_NS); clock = 1; sc_start(1,SC_NS); } reset = 1; // Assert the reset cout << "@" << sc_time_stamp() <<" Asserting reset\n" << endl; for (i=0;i<10;i++) { clock = 0; sc_start(1,SC_NS); clock = 1; sc_start(1,SC_NS); } reset = 0; // De-assert the reset cout << "@" << sc_time_stamp() <<" De-Asserting reset\n" << endl; for (i=0;i<5;i++) { clock = 0; sc_start(1,SC_NS); clock = 1; sc_start(1,SC_NS); } cout << "@" << sc_time_stamp() <<" Asserting Enable\n" << endl; enable = 1; // Assert enable for (i=0;i<20;i++) { clock = 0; sc_start(1,SC_NS); clock = 1; sc_start(1,SC_NS); } cout << "@" << sc_time_stamp() <<" De-Asserting Enable\n" << endl; enable = 0; // De-assert enable cout << "@" << sc_time_stamp() <<" Terminating simulation\n" << endl; sc_close_vcd_trace_file(wf); return 0;// Terminate simulation }
/******************************************************************************** * 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 <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <unistd.h> ////////////////////////////// GENANN ////////////////// #ifdef __cplusplus extern "C" { #endif #ifndef ann_02_GENANN_RANDOM /* We use the following for uniform random numbers between 0 and 1. * If you have a better function, redefine this macro. */ #define ann_02_GENANN_RANDOM() (((double)rand())/RAND_MAX) #endif struct ann_02_genann; typedef double (*ann_02_genann_actfun)(const struct ann_02_genann *ann, double a); typedef struct ann_02_genann { /* How many inputs, outputs, and hidden neurons. */ int inputs, hidden_layers, hidden, outputs; /* Which activation function to use for hidden neurons. Default: gennann_act_sigmoid_cached*/ ann_02_genann_actfun activation_hidden; /* Which activation function to use for output. Default: gennann_act_sigmoid_cached*/ ann_02_genann_actfun activation_output; /* Total number of weights, and size of weights buffer. */ int total_weights; /* Total number of neurons + inputs and size of output buffer. */ int total_neurons; /* All weights (total_weights long). */ double *weight; /* Stores input array and output of each neuron (total_neurons long). */ double *output; /* Stores delta of each hidden and output neuron (total_neurons - inputs long). */ double *delta; } ann_02_genann; #ifdef __cplusplus } #endif ///////////////////////////////////// GENANN /////////////////////////// #ifndef ann_02_genann_act #define ann_02_genann_act_hidden ann_02_genann_act_hidden_indirect #define ann_02_genann_act_output ann_02_genann_act_output_indirect #else #define ann_02_genann_act_hidden ann_02_genann_act #define ann_02_genann_act_output ann_02_genann_act #endif #define ann_02_LOOKUP_SIZE 4096 double ann_02_genann_act_hidden_indirect(const struct ann_02_genann *ann, double a) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return ann->activation_hidden(ann, a); } double ann_02_genann_act_output_indirect(const struct ann_02_genann *ann, double a) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return ann->activation_output(ann, a); } const double ann_02_sigmoid_dom_min = -15.0; const double ann_02_sigmoid_dom_max = 15.0; double ann_02_interval; double ann_02_lookup[ann_02_LOOKUP_SIZE]; #ifdef __GNUC__ #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #define unused __attribute__((unused)) #else #define likely(x) x #define unlikely(x) x #define unused #pragma warning(disable : 4996) /* For fscanf */ #endif double ann_02_genann_act_sigmoid(const ann_02_genann *ann unused, double a) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) if (a < -45.0) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return 0; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) if (a > 45.0) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return 1; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return 1.0 / (1 + exp(-a)); } void ann_02_genann_init_sigmoid_lookup(const ann_02_genann *ann) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) const double f = (ann_02_sigmoid_dom_max - ann_02_sigmoid_dom_min) / ann_02_LOOKUP_SIZE; HEPSY_S(ann_02_id) int i; HEPSY_S(ann_02_id) ann_02_interval = ann_02_LOOKUP_SIZE / (ann_02_sigmoid_dom_max - ann_02_sigmoid_dom_min); HEPSY_S(ann_02_id) for (i = 0; i < ann_02_LOOKUP_SIZE; ++i) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) ann_02_lookup[i] = ann_02_genann_act_sigmoid(ann, ann_02_sigmoid_dom_min + f * i); HEPSY_S(ann_02_id) } } double ann_02_genann_act_sigmoid_cached(const ann_02_genann *ann unused, double a) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) assert(!isnan(a)); HEPSY_S(ann_02_id) if (a < ann_02_sigmoid_dom_min) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return ann_02_lookup[0]; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) if (a >= ann_02_sigmoid_dom_max) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return ann_02_lookup[ann_02_LOOKUP_SIZE - 1]; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) size_t j = (size_t)((a-ann_02_sigmoid_dom_min)*ann_02_interval+0.5); /* Because floating point... */ HEPSY_S(ann_02_id) if (unlikely(j >= ann_02_LOOKUP_SIZE)) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return ann_02_lookup[ann_02_LOOKUP_SIZE - 1]; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) return ann_02_lookup[j]; } double ann_02_genann_act_linear(const struct ann_02_genann *ann unused, double a) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return a; } double ann_02_genann_act_threshold(const struct ann_02_genann *ann unused, double a) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return a > 0; } void ann_02_genann_randomize(ann_02_genann *ann) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) int i; HEPSY_S(ann_02_id) for (i = 0; i < ann->total_weights; ++i) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) double r = ann_02_GENANN_RANDOM(); /* Sets weights from -0.5 to 0.5. */ HEPSY_S(ann_02_id) ann->weight[i] = r - 0.5; HEPSY_S(ann_02_id) } } ann_02_genann *ann_02_genann_init(int inputs, int hidden_layers, int hidden, int outputs) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) if (hidden_layers < 0) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return 0; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) if (inputs < 1) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return 0; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) if (outputs < 1) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return 0; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) if (hidden_layers > 0 && hidden < 1) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return 0; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) const int hidden_weights = hidden_layers ? (inputs+1) * hidden + (hidden_layers-1) * (hidden+1) * hidden : 0; HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) const int output_weights = (hidden_layers ? (hidden+1) : (inputs+1)) * outputs; HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) const int total_weights = (hidden_weights + output_weights); HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) const int total_neurons = (inputs + hidden * hidden_layers + outputs); /* Allocate extra size for weights, outputs, and deltas. */ HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) const int size = sizeof(ann_02_genann) + sizeof(double) * (total_weights + total_neurons + (total_neurons - inputs)); HEPSY_S(ann_02_id) ann_02_genann *ret = (ann_02_genann *)malloc(size); HEPSY_S(ann_02_id) if (!ret) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return 0; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) ret->inputs = inputs; HEPSY_S(ann_02_id) ret->hidden_layers = hidden_layers; HEPSY_S(ann_02_id) ret->hidden = hidden; HEPSY_S(ann_02_id) ret->outputs = outputs; HEPSY_S(ann_02_id) ret->total_weights = total_weights; HEPSY_S(ann_02_id) ret->total_neurons = total_neurons; /* Set pointers. */ HEPSY_S(ann_02_id) ret->weight = (double*)((char*)ret + sizeof(ann_02_genann)); HEPSY_S(ann_02_id) ret->output = ret->weight + ret->total_weights; HEPSY_S(ann_02_id) ret->delta = ret->output + ret->total_neurons; HEPSY_S(ann_02_id) ann_02_genann_randomize(ret); HEPSY_S(ann_02_id) ret->activation_hidden = ann_02_genann_act_sigmoid_cached; HEPSY_S(ann_02_id) ret->activation_output = ann_02_genann_act_sigmoid_cached; HEPSY_S(ann_02_id) ann_02_genann_init_sigmoid_lookup(ret); HEPSY_S(ann_02_id) return ret; } void ann_02_genann_free(ann_02_genann *ann) {HEPSY_S(ann_02_id) /* The weight, output, and delta pointers go to the same buffer. */ HEPSY_S(ann_02_id) free(ann); } //genann *genann_read(FILE *in) //genann *genann_copy(genann const *ann) double const *ann_02_genann_run(ann_02_genann const *ann, double const *inputs) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) double const *w = ann->weight; HEPSY_S(ann_02_id) double *o = ann->output + ann->inputs; HEPSY_S(ann_02_id) double const *i = ann->output; /* Copy the inputs to the scratch area, where we also store each neuron's * output, for consistency. This way the first layer isn't a special case. */ HEPSY_S(ann_02_id) memcpy(ann->output, inputs, sizeof(double) * ann->inputs); HEPSY_S(ann_02_id) int h, j, k; HEPSY_S(ann_02_id) if (!ann->hidden_layers) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) double *ret = o; HEPSY_S(ann_02_id) for (j = 0; j < ann->outputs; ++j) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) double sum = *w++ * -1.0; HEPSY_S(ann_02_id) for (k = 0; k < ann->inputs; ++k) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) sum += *w++ * i[k]; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) *o++ = ann_02_genann_act_output(ann, sum); HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) return ret; HEPSY_S(ann_02_id) } /* Figure input layer */ HEPSY_S(ann_02_id) for (j = 0; j < ann->hidden; ++j) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) double sum = *w++ * -1.0; HEPSY_S(ann_02_id) for (k = 0; k < ann->inputs; ++k) { HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) sum += *w++ * i[k]; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) *o++ = ann_02_genann_act_hidden(ann, sum); HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) i += ann->inputs; /* Figure hidden layers, if any. */ HEPSY_S(ann_02_id) for (h = 1; h < ann->hidden_layers; ++h) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) for (j = 0; j < ann->hidden; ++j) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) double sum = *w++ * -1.0; HEPSY_S(ann_02_id) for (k = 0; k < ann->hidden; ++k) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) sum += *w++ * i[k]; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) *o++ = ann_02_genann_act_hidden(ann, sum); HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) i += ann->hidden; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) double const *ret = o; /* Figure output layer. */ HEPSY_S(ann_02_id) for (j = 0; j < ann->outputs; ++j) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) double sum = *w++ * -1.0; HEPSY_S(ann_02_id) for (k = 0; k < ann->hidden; ++k) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) sum += *w++ * i[k]; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) *o++ = ann_02_genann_act_output(ann, sum); HEPSY_S(ann_02_id) } /* Sanity check that we used all weights and wrote all outputs. */ HEPSY_S(ann_02_id) assert(w - ann->weight == ann->total_weights); HEPSY_S(ann_02_id) assert(o - ann->output == ann->total_neurons); HEPSY_S(ann_02_id) return ret; } //void genann_train(genann const *ann, double const *inputs, double const *desired_outputs, double learning_rate) //void genann_write(genann const *ann, FILE *out) /////////////////////// ANN //////////////////////// #define ann_02_NUM_DEV 1 // The equipment is composed of NUM_DEV devices ... //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- #define ann_02_MAX_ANN 100 // Maximum MAX_ANN ANN #define ann_02_ANN_INPUTS 2 // Number of inputs #define ann_02_ANN_HIDDEN_LAYERS 1 // Number of hidden layers #define ann_02_ANN_HIDDEN_NEURONS 2 // Number of neurons of every hidden layer #define ann_02_ANN_OUTPUTS 1 // Number of outputs //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- #define ann_02_ANN_EPOCHS 10000 #define ann_02_ANN_DATASET 6 #define ann_02_ANN_LEARNING_RATE 3 // ... //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- #define ann_02_MAX_ERROR 0.00756 // 0.009 //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- static int ann_02_nANN = -1 ; // Number of ANN that have been created static ann_02_genann * ann_02_ann[ann_02_MAX_ANN] ; // Now up to MAX_ANN ann //static double ann_02_trainingInput[ann_02_ANN_DATASET][ann_02_ANN_INPUTS] = { {0, 0}, {0, 1}, {1, 0}, {1, 1}, {0, 1}, {0, 0} } ; //static double ann_02_trainingExpected[ann_02_ANN_DATASET][ann_02_ANN_OUTPUTS] = { {0}, {1}, {1}, {0}, {1}, {0} } ; static double ann_02_weights[] = { -3.100438, -7.155774, -7.437955, -8.132828, -5.583678, -5.327152, 5.564897, -12.201226, 11.771879 } ; // static double input[4][3] = {{0, 0, 1}, {0, 1, 1}, {1, 0, 1}, {1, 1, 1}}; // static double output[4] = {0, 1, 1, 0}; //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- static int ann_02_annCheck(int index); static int ann_02_annCreate(int n); //----------------------------------------------------------------------------- // Check the correctness of the index of the ANN //----------------------------------------------------------------------------- int ann_02_annCheck(int index) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) if( (index < 0) || (index >= ann_02_nANN) ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return( EXIT_FAILURE ); HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) return( EXIT_SUCCESS ); } //----------------------------------------------------------------------------- // Create n ANN //----------------------------------------------------------------------------- int ann_02_annCreate(int n) {HEPSY_S(ann_02_id) // If already created, or not legal number, or too many ANN, then error HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) if( (ann_02_nANN != -1) || (n <= 0) || (n > ann_02_MAX_ANN) ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return( EXIT_FAILURE ); } // Create the ANN's HEPSY_S(ann_02_id) for ( int i = 0; i < n; i++ ) {HEPSY_S(ann_02_id) // New ANN with ANN_INPUT inputs, ANN_HIDDEN_LAYER hidden layers all with ANN_HIDDEN_NEURON neurons, and ANN_OUTPUT outputs HEPSY_S(ann_02_id) ann_02_ann[i] = ann_02_genann_init(ann_02_ANN_INPUTS, ann_02_ANN_HIDDEN_LAYERS, ann_02_ANN_HIDDEN_NEURONS, ann_02_ANN_OUTPUTS); HEPSY_S(ann_02_id) if ( ann_02_ann[i] == 0 ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) for (int j = 0; j < i; j++) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) ann_02_genann_free(ann_02_ann[j]) ; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) return( EXIT_FAILURE ); HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) ann_02_nANN = n ; HEPSY_S(ann_02_id) return( EXIT_SUCCESS ); } ////----------------------------------------------------------------------------- //// Create and train n identical ANN ////----------------------------------------------------------------------------- //int annCreateAndTrain(int n) //{ // if ( annCreate(n) != EXIT_SUCCESS ) // return( EXIT_FAILURE ); // // // Train the ANN's // for ( int index = 0; index < nANN; index++ ) // for ( int i = 0; i < ANN_EPOCHS; i++ ) // for ( int j = 0; j < ANN_DATASET; j++ ) // genann_train(ann[index], trainingInput[j], trainingExpected[j], ANN_LEARNING_RATE) ; // // return( EXIT_SUCCESS ); //} //----------------------------------------------------------------------------- // Create n identical ANN and set their weight //----------------------------------------------------------------------------- int ann_02_annCreateAndSetWeights(int n) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) if( ann_02_annCreate(n) != EXIT_SUCCESS ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return( EXIT_FAILURE ); HEPSY_S(ann_02_id) } // Set weights HEPSY_S(ann_02_id) for ( int index = 0; index < ann_02_nANN; index++ ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) for( int i = 0; i < ann_02_ann[index]->total_weights; ++i ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) ann_02_ann[index]->weight[i] = ann_02_weights[i] ; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) return( EXIT_SUCCESS ); } //----------------------------------------------------------------------------- // x[2] = x[0] XOR x[1] //----------------------------------------------------------------------------- int ann_02_annRun(int index, double x[ann_02_ANN_INPUTS + ann_02_ANN_OUTPUTS]) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) if( ann_02_annCheck(index) != EXIT_SUCCESS ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return( EXIT_FAILURE ) ; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) x[2] = * ann_02_genann_run(ann_02_ann[index], x) ; HEPSY_S(ann_02_id) return( EXIT_SUCCESS ); } ////----------------------------------------------------------------------------- //// ////----------------------------------------------------------------------------- //int annPrintWeights(int index) //{ // if ( annCheck(index) != EXIT_SUCCESS ) // return( EXIT_FAILURE ) ; // // // printf("\n*** ANN index = %d\n", index) ; // for ( int i = 0; i < ann[index]->total_weights; ++i ) // printf("*** w%d = %f\n", i, ann[index]->weight[i]) ; // // return( EXIT_SUCCESS ); //} ////-------------------------------------------------------
---------------------- //// Run the index-th ANN k time on random input and return the number of error ////----------------------------------------------------------------------------- //int annTest(int index, int k) //{ // int x0; int x1; int y; // double x[2]; // double xor_ex; // int error = 0; // // if ( annCheck(index) != EXIT_SUCCESS ) // return( -1 ); // less than zero errors <==> the ANN isn't correctly created // // for (int i = 0; i < k; i++ ) // { // x0 = rand() % 2; x[0] = (double)x0; // x1 = rand() % 2; x[1] = (double)x1; // y = x0 ^ x1 ; // // xor_ex = * genann_run(ann[index], x); // if ( fabs(xor_ex - (double)y) > MAX_ERROR ) // { // error++ ; // printf("@@@ Error: ANN = %d, step = %d, x0 = %d, x1 = %d, y = %d, xor_ex = %f \n", index, i, x0, x1, y, xor_ex) ; // } // } // // if ( error ) // printf("@@@ ANN = %d: N� of errors = %d\n", index, error) ; // else // printf("*** ANN = %d: Test OK\n",index) ; // return( error ); //} //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void ann_02_annDestroy(void) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) if( ann_02_nANN == -1 ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return ; } HEPSY_S(ann_02_id) for ( int index = 0; index < ann_02_nANN; index++ ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) ann_02_genann_free(ann_02_ann[index]) ; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) ann_02_nANN = -1 ; } void mainsystem::ann_02_main() { // datatype for channels cleanData_xx_ann_xx_payload cleanData_xx_ann_xx_payload_var; ann_xx_dataCollector_payload ann_xx_dataCollector_payload_var; double x[ann_02_ANN_INPUTS + ann_02_ANN_OUTPUTS] ; //int ann_02_index = 1; HEPSY_S(ann_02_id) if( ann_02_annCreateAndSetWeights(ann_02_NUM_DEV) != EXIT_SUCCESS ) {HEPSY_S(ann_02_id) // Create and init ANN HEPSY_S(ann_02_id) printf("Error Weights \n"); HEPSY_S(ann_02_id) } //implementation HEPSY_S(ann_02_id) while(1) {HEPSY_S(ann_02_id) // content HEPSY_S(ann_02_id)cleanData_xx_ann_xx_payload_var = cleanData_02_ann_02_channel->read(); HEPSY_S(ann_02_id) ann_xx_dataCollector_payload_var.dev = cleanData_xx_ann_xx_payload_var.dev; HEPSY_S(ann_02_id) ann_xx_dataCollector_payload_var.step = cleanData_xx_ann_xx_payload_var.step; HEPSY_S(ann_02_id) ann_xx_dataCollector_payload_var.ex_time = cleanData_xx_ann_xx_payload_var.ex_time; HEPSY_S(ann_02_id) ann_xx_dataCollector_payload_var.device_i = cleanData_xx_ann_xx_payload_var.device_i; HEPSY_S(ann_02_id) ann_xx_dataCollector_payload_var.device_v = cleanData_xx_ann_xx_payload_var.device_v; HEPSY_S(ann_02_id) ann_xx_dataCollector_payload_var.device_t = cleanData_xx_ann_xx_payload_var.device_t; HEPSY_S(ann_02_id) ann_xx_dataCollector_payload_var.device_r = cleanData_xx_ann_xx_payload_var.device_r; HEPSY_S(ann_02_id) x[0] = cleanData_xx_ann_xx_payload_var.x_0; HEPSY_S(ann_02_id) x[1] = cleanData_xx_ann_xx_payload_var.x_1; HEPSY_S(ann_02_id) x[2] = cleanData_xx_ann_xx_payload_var.x_2; //u = cleanData_xx_ann_xx_payload_var.step; HEPSY_S(ann_02_id) ann_xx_dataCollector_payload_var.fault = cleanData_xx_ann_xx_payload_var.fault; //RUN THE ANN... // ### P R E D I C T (simple XOR) // if ( annRun(index, x) != EXIT_SUCCESS ){ // printf("Step = %u Index = %d ANN error.\n", u, index) ; // }else{ // device[index].fault = x[2] <= 0.5 ? 0 : 1 ; // } //u: cycle num HEPSY_S(ann_02_id) if( ann_02_annRun(0, x) != EXIT_SUCCESS ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) printf("Step = %d Index = %d ANN error.\n", (int)ann_xx_dataCollector_payload_var.step, (int)ann_xx_dataCollector_payload_var.dev) ; HEPSY_S(ann_02_id) } else {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) ann_xx_dataCollector_payload_var.fault = x[2] <= 0.5 ? 0 : 1 ; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) ann_02_dataCollector_channel->write(ann_xx_dataCollector_payload_var); HEPSY_P(ann_02_id) } } // END
#include <systemc.h> SC_MODULE( or_gate ) { sc_inout<bool> a; sc_inout<bool> b; sc_out<bool> c; void or_process( void ) { c = a.read() || b.read(); } void test_process( void ) { assert( (a.read() || b.read() ) == c.read() ); } SC_CTOR( or_gate ) { } }; int sc_main( int argc, char * argv[] ) { sc_signal<bool> s1; sc_signal<bool> s2; sc_signal<bool> s3; s1.write(true); s2.write(false); s3.write(true); or_gate gate("or_gate"); gate.a(s1); gate.b(s2); gate.c(s3); // gate.or_process(); gate.test_process(); return 0; }
#ifndef PACKET_GENERATOR_CPP #define PACKET_GENERATOR_CPP #include <systemc-ams.h> #include <systemc.h> #include "packetGenerator.h" void packetGenerator::set_attributes() { // Set a timestep for the TDF module set_timestep(sample_time); } void packetGenerator::fill_data(unsigned char* data, int packet_length) { local_data = new unsigned char[packet_length]; memcpy(local_data, data, packet_length * sizeof(char)); actual_data_length = packet_length; bytes_sent = 0; // Insert first the preamble create_pack_of_data(preamble_data, 8); preamble_in_process = true; } void packetGenerator::create_pack_of_data(unsigned char* data, int packet_length) { int actual_length = (packet_length * 2 > N) ? N : packet_length * 2; unsigned char tmp_data; sc_dt::sc_bv<N * 4> tmp_data_in = 0; sc_dt::sc_bv<N> tmp_data_valid = 0; for (int i = 0; i < actual_length; i++) { tmp_data = *(data + (i/2)); if ((i % 2) == 1) { tmp_data = tmp_data >> 4; } tmp_data_in.range(i * 4 + 3, i * 4) = tmp_data; tmp_data_valid[i] = 1; } data_to_send = tmp_data_in; data_valid_to_send = tmp_data_valid; n2_data_valid = data_valid_to_send; n1_data_valid = n2_data_valid; } void packetGenerator::processing() { sc_dt::sc_bv<N * 4> tmp_data_to_send = data_to_send; sc_dt::sc_bv<N> tmp_data_valid_to_send = data_valid_to_send; bool manual_update = false; if ((tmp_data_valid_to_send.or_reduce() == 0) && (preamble_in_process == true)) { sc_dt::sc_bv<32> local_length = 0; preamble_in_process = false; local_length = (unsigned int)actual_data_length; data_to_send = 0; data_to_send.range(31, 0) = local_length; data_valid_to_send = "11111111"; tmp_data_to_send = data_to_send; tmp_data_valid_to_send = data_valid_to_send; n2_data_valid = data_valid_to_send; n1_data_valid = n2_data_valid; } else if ((tmp_data_valid_to_send.or_reduce() == 0) && (actual_data_length > 0)) { if (actual_data_length > 8) { create_pack_of_data((local_data + bytes_sent), 8); actual_data_length -= 8; bytes_sent += 8; } else { create_pack_of_data((local_data + bytes_sent), actual_data_length); actual_data_length = 0; delete[] local_data; } } n1_data_out = n2_data_out; n1_data_out_valid = n2_data_out_valid; n1_data_valid = n2_data_valid; if (tmp_data_valid_to_send.or_reduce()) { for (int i = 0; i < N; i++) { if (tmp_data_valid_to_send[i] == 1) { if ((bitCount == 0) && (tmp_data_out_valid == false) && (n1_data_out_valid == false)) { tmp_data_valid_to_send[i] = 0; n2_data_out = tmp_data_to_send.range(i * 4 + 3, i * 4); n2_data_out_valid = true; n2_data_valid = tmp_data_valid_to_send; #ifndef USING_TLM_TB_EN std::cout << "@" << sc_time_stamp() << " Inside generate_packet(): data to sent " << n2_data_out << std::endl; #endif // USING_TLM_TB_EN break; } else if ((bitCount == 0) && (tmp_data_out_valid == true)) { tmp_data_valid_to_send[i] = 0; data_out.write(tmp_data_to_send.range(i * 4 + 3, i * 4)); data_out_valid.write(1); tmp_data_out_valid = true; data_valid_to_send_ = tmp_data_valid_to_send; n2_data_out = tmp_data_to_send.range(i * 4 + 3, i * 4); n2_data_out_valid = true; n2_data_valid = tmp_data_valid_to_send; n1_data_out = n2_data_out; n1_data_out_valid = n2_data_out_valid; n1_data_valid = n2_data_valid; manual_update = true; #ifndef USING_TLM_TB_EN std::cout << "@" << sc_time_stamp() << " Inside generate_packet(): data to sent " << n2_data_out << std::endl; #endif // USING_TLM_TB_EN break; } } } } if (!manual_update) { data_out_valid.write(n1_data_out_valid); tmp_data_out_valid = n1_data_out_valid; } if (tmp_data_out_valid == true) { bitCount++; } if (bitCount == 5) { bitCount = 0; if (!manual_update) { n2_data_out_valid = false; n1_data_out_valid = n2_data_out_valid; data_out_valid.write(true); tmp_data_out_valid = true; } } if (!manual_update) { data_valid_to_send = n1_data_valid; data_out.write(n1_data_out); } n1_sigBitCount = n2_sigBitCount; n2_sigBitCount = bitCount; n1_sigBitCount_.write(n1_sigBitCount); n2_sigBitCount_.write(n2_sigBitCount); sigBitCount.write(n1_sigBitCount); tmp_data_out_valid_.write(tmp_data_out_valid); n2_data_out_valid_.write(n2_data_out_valid); n2_data_out_.write(n2_data_out); n2_data_valid_.write(n2_data_valid); n1_data_out_valid_.write(n1_data_out_valid); n1_data_out_.write(n1_data_out); n1_data_valid_.write(n1_data_valid); data_in_.write(data_in); data_in_valid_.write(data_in_valid); data_to_send_.write(data_to_send); data_valid_to_send_.write(data_valid_to_send); remaining_bytes_to_send.write(actual_data_length); } #endif // PACKET_GENERATOR_CPP
#include <systemc.h> SC_MODULE( or_gate ) { sc_inout<bool> a; sc_inout<bool> b; sc_out<bool> c; void or_process( void ) { c = a.read() || b.read(); } void test_process( void ) { assert( (a.read() || b.read() ) == c.read() ); } SC_CTOR( or_gate ) { } }; int sc_main( int argc, char * argv[] ) { sc_signal<bool> s1; sc_signal<bool> s2; sc_signal<bool> s3; s1.write(true); s2.write(false); s3.write(true); or_gate gate("or_gate"); gate.a(s1); gate.b(s2); gate.c(s3); // gate.or_process(); gate.test_process(); return 0; }
#include <systemc.h> class sc_mutexx : public sc_prim_channel { public: sc_event _free; bool _locked; // blocks until mutex could be locked void lock() { while( _locked ) { wait( _free ); } _locked = true; } // returns false if mutex could not be locked bool trylock() { if( _locked ) return false; else return true; } // unlocks mutex void unlock() { _locked = false; _free.notify(); } // constructor sc_mutexx(){ // _locked = false; } };
/***************************************************************************** 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. *****************************************************************************/ /***************************************************************************** stimulus.cpp -- Original Author: Rocco Jonack, 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 "stimulus.h" void stimulus::entry() { cycle++; // sending some reset values if (cycle<4) { reset.write(true); input_valid.write(false); } else { reset.write(false); input_valid.write( false ); // sending normal mode values if (cycle%10==0) { input_valid.write(true); sample.write( (int)send_value1 ); cout << "Stimuli : " << (int)send_value1 << " at time " /* << sc_time_stamp() << endl; */ << sc_time_stamp().to_double() << endl; send_value1++; }; } }
#include <crave/SystemC.hpp> #include <crave/ConstrainedRandom.hpp> #include <systemc.h> #include <boost/timer.hpp> using crave::rand_obj; using crave::randv; using sc_dt::sc_bv; using sc_dt::sc_uint; struct ALU12 : public rand_obj { randv< sc_bv<2> > op ; randv< sc_uint<12> > a, b ; ALU12() : op(this), a(this), b(this) { constraint ( (op() != 0x0) || ( 4095 >= a() + b() ) ); constraint ( (op() != 0x1) || ((4095 >= a() - b()) && (b() <= a()) ) ); constraint ( (op() != 0x2) || ( 4095 >= a() * b() ) ); constraint ( (op() != 0x3) || ( b() != 0 ) ); } friend std::ostream & operator<< (std::ostream & o, ALU12 const & alu) { o << alu.op << ' ' << alu.a << ' ' << alu.b ; return o; } }; int sc_main (int argc, char** argv) { boost::timer timer; ALU12 c; c.next(); std::cout << "first: " << timer.elapsed() << "\n"; for (int i=0; i<1000; ++i) { c.next(); } std::cout << "complete: " << timer.elapsed() << "\n"; return 0; }
/* Problem 3 Design */ #include<systemc.h> SC_MODULE(communicationInterface) { sc_in<sc_uint<12> > inData; sc_in<bool> clock , reset , clear; sc_out<sc_uint<4> > payloadOut; sc_out<sc_uint<8> > countOut , errorOut; void validateData(); SC_CTOR(communicationInterface) { SC_METHOD(validateData); sensitive<<clock.pos(); } }; void communicationInterface::validateData() { cout<<"@ "<<sc_time_stamp()<<"----------Start validateData---------"<<endl; if(reset.read() == false || clear.read() == true) { payloadOut.write(0); countOut.write(0); errorOut.write(0); return; } sc_uint<4> header = inData.read().range(11 , 8) , payload = inData.read().range(7 , 4); sc_uint<1> parity = inData.read().range(0 , 0); sc_uint<2> parityCheck = 0; if(header == 1) { payloadOut.write(payload); countOut.write(countOut.read() + 1); } while(payload) { parityCheck++; payload &= payload - 1; } errorOut.write(errorOut.read() + (parityCheck%2 && parity ? 1 : 0)); }
//**************************************************************************************** // MIT License //**************************************************************************************** // Copyright (c) 2012-2020 University of Bremen, Germany. // Copyright (c) 2015-2020 DFKI GmbH Bremen, Germany. // Copyright (c) 2020 Johannes Kepler University Linz, Austria. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //**************************************************************************************** #include <crave/SystemC.hpp> #include <crave/ConstrainedRandom.hpp> #include <systemc.h> #include <boost/timer.hpp> using crave::rand_obj; using crave::randv; using sc_dt::sc_bv; using sc_dt::sc_uint; struct ALU24 : public rand_obj { randv<sc_bv<2> > op; randv<sc_uint<24> > a, b; ALU24(rand_obj* parent = 0) : rand_obj(parent), op(this), a(this), b(this) { constraint((op() != 0x0) || (16777215 >= a() + b())); constraint((op() != 0x1) || ((16777215 >= a() - b()) && (b() <= a()))); constraint((op() != 0x2) || (16777215 >= a() * b())); constraint((op() != 0x3) || (b() != 0)); } friend std::ostream& operator<<(std::ostream& o, ALU24 const& alu) { o << alu.op << ' ' << alu.a << ' ' << alu.b; return o; } }; int sc_main(int argc, char** argv) { crave::init("crave.cfg"); boost::timer timer; ALU24 c; CHECK(c.next()); std::cout << "first: " << timer.elapsed() << "\n"; for (int i = 0; i < 1000; ++i) { CHECK(c.next()); } std::cout << "complete: " << timer.elapsed() << "\n"; return 0; }
/* Problem 1 Testbench */ #include<systemc.h> #include<sd.cpp> SC_MODULE(sequenceDetectorTB) { sc_signal<bool> clock , reset , clear , input , output , state; void clockSignal(); void resetSignal(); void clearSignal(); void inputSignal(); sequenceDetector* sd; SC_CTOR(sequenceDetectorTB) { sd = new sequenceDetector ("SD"); sd->clock(clock); sd->reset(reset); sd->clear(clear); sd->input(input); sd->output(output); sd->state(state); SC_THREAD(clockSignal); SC_THREAD(resetSignal); SC_THREAD(clearSignal); SC_THREAD(inputSignal); } }; void sequenceDetectorTB::clockSignal() { while (true){ wait(20 , SC_NS); clock = false; wait(20 , SC_NS); clock = true; } } void sequenceDetectorTB::resetSignal() { while (true){ wait(10 , SC_NS); reset = true; wait(90 , SC_NS); reset = false; wait(10 , SC_NS); reset = true; wait(1040 , SC_NS); } } void sequenceDetectorTB::clearSignal() { while (true) { wait(50 , SC_NS); clear = false; wait(90 , SC_NS); clear = true; wait(10 , SC_NS); clear = false; wait(760 , SC_NS); } } void sequenceDetectorTB::inputSignal() { while (true) { wait(25 , SC_NS); input = true; wait(65, SC_NS); input = false; wait(30 , SC_NS); input = true; wait(40 , SC_NS); input = false; } } int sc_main(int argc , char* argv[]) { cout<<"@ "<<sc_time_stamp()<<"----------Start---------"<<endl; sequenceDetectorTB* sdTB = new sequenceDetectorTB ("SDTB"); cout<<"@ "<<sc_time_stamp()<<"----------Testbench Instance Created---------"<<endl; sc_trace_file* VCDFile; VCDFile = sc_create_vcd_trace_file("sequence-detector"); cout<<"@ "<<sc_time_stamp()<<"----------VCD File Created---------"<<endl; sc_trace(VCDFile, sdTB->clock, "Clock"); sc_trace(VCDFile, sdTB->reset, "Reset"); sc_trace(VCDFile, sdTB->clear, "Clear"); sc_trace(VCDFile, sdTB->input, "Input"); sc_trace(VCDFile, sdTB->state, "State"); sc_trace(VCDFile, sdTB->output, "Output"); cout<<"@ "<<sc_time_stamp()<<"----------Start Simulation---------"<<endl; sc_start(4000, SC_NS); cout<<"@ "<<sc_time_stamp()<<"----------End Simulation---------"<<endl; return 0; }
#include <systemc.h> #include "SYSTEM.h"
// Copyright 2019 Glenn Ramalho - RFIDo Design // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // This code was based off the work from Espressif Systems covered by the // License: // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <systemc.h> #include "gn_semaphore.h" #include "clockpacer.h" #include "spimod.h" #include "info.h" #include "esp32-hal-spi.h" #include "esp32-hal.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/semphr.h" #include "rom/ets_sys.h" #include "esp_attr.h" //#include "esp_intr.h" #include "rom/gpio.h" #include "soc/spi_reg.h" #include "soc/spi_struct.h" #include "soc/io_mux_reg.h" #include "soc/gpio_sig_map.h" #include "soc/dport_reg.h" #define SPI_CLK_IDX(p) ((p==0)?SPICLK_OUT_IDX:((p==1)?SPICLK_OUT_IDX:((p==2)?HSPICLK_OUT_IDX:((p==3)?VSPICLK_OUT_IDX:0)))) #define SPI_MISO_IDX(p) ((p==0)?SPIQ_OUT_IDX:((p==1)?SPIQ_OUT_IDX:((p==2)?HSPIQ_OUT_IDX:((p==3)?VSPIQ_OUT_IDX:0)))) #define SPI_MOSI_IDX(p) ((p==0)?SPID_IN_IDX:((p==1)?SPID_IN_IDX:((p==2)?HSPID_IN_IDX:((p==3)?VSPID_IN_IDX:0)))) #define SPI_SPI_SS_IDX(n) ((n==0)?SPICS0_OUT_IDX:((n==1)?SPICS1_OUT_IDX:((n==2)?SPICS2_OUT_IDX:SPICS0_OUT_IDX))) #define SPI_HSPI_SS_IDX(n) ((n==0)?HSPICS0_OUT_IDX:((n==1)?HSPICS1_OUT_IDX:((n==2)?HSPICS2_OUT_IDX:HSPICS0_OUT_IDX))) #define SPI_VSPI_SS_IDX(n) ((n==0)?VSPICS0_OUT_IDX:((n==1)?VSPICS1_OUT_IDX:((n==2)?VSPICS2_OUT_IDX:VSPICS0_OUT_IDX))) #define SPI_SS_IDX(p, n) ((p==0)?SPI_SPI_SS_IDX(n):((p==1)?SPI_SPI_SS_IDX(n):((p==2)?SPI_HSPI_SS_IDX(n):((p==3)?SPI_VSPI_SS_IDX(n):0)))) #define SPI_INUM(u) (2) #define SPI_INTR_SOURCE(u) ((u==0)?ETS_SPI0_INTR_SOURCE:((u==1)?ETS_SPI1_INTR_SOURCE:((u==2)?ETS_SPI2_INTR_SOURCE:((p==3)?ETS_SPI3_INTR_SOURCE:0)))) struct spi_struct_t { spi_dev_t * dev; #if !CONFIG_DISABLE_HAL_LOCKS xSemaphoreHandle lock; #endif uint8_t num; }; gn_semaphore i_gn_semaphore_spi2("SPI2", 1); gn_semaphore i_gn_semaphore_spi3("SPI3", 1); #if CONFIG_DISABLE_HAL_LOCKS #define SPI_MUTEX_LOCK() #define SPI_MUTEX_UNLOCK() static spi_t _spi_bus_array[4] = { {NULL, 0}, /* The model does not yet support this SPI */ {NULL, 1}, /* The model does not yet support this SPI */ {SPI2, 2}, {SPI3, 3} }; #else #define SPI_MUTEX_LOCK() do {} while (xSemaphoreTake(spi->lock, portMAX_DELAY) != pdPASS) #define SPI_MUTEX_UNLOCK() xSemaphoreGive(spi->lock) static spi_t _spi_bus_array[4] = { {NULL, NULL, 0}, /* The model does not yet support this SPI */ {NULL, NULL, 1}, /* The model does not yet support this SPI */ {&SPI2, NULL, 2}, {&SPI3, NULL, 3} }; #endif void spiAttachSCK(spi_t * spi, int8_t sck) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } if(sck < 0) { if(spi->num == HSPI) { sck = 14; } else if(spi->num == VSPI) { sck = 18; } else { sck = 6; } } pinMode(sck, OUTPUT); pinMatrixOutAttach(sck, SPI_CLK_IDX(spi->num), false, false); } void spiAttachMISO(spi_t * spi, int8_t miso) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } if(miso < 0) { if(spi->num == HSPI) { miso = 12; } else if(spi->num == VSPI) { miso = 19; } else { miso = 7; } } SPI_MUTEX_LOCK(); pinMode(miso, INPUT); pinMatrixInAttach(miso, SPI_MISO_IDX(spi->num), false); SPI_MUTEX_UNLOCK(); } void spiAttachMOSI(spi_t * spi, int8_t mosi) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } if(mosi < 0) { if(spi->num == HSPI) { mosi = 13; } else if(spi->num == VSPI) { mosi = 23; } else { mosi = 8; } } pinMode(mosi, OUTPUT); pinMatrixOutAttach(mosi, SPI_MOSI_IDX(spi->num), false, false); } void spiDetachSCK(spi_t * spi, int8_t sck) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } if(sck < 0) { if(spi->num == HSPI) { sck = 14; } else if(spi->num == VSPI) { sck = 18; } else { sck = 6; } } pinMatrixOutDetach(sck, false, false); pinMode(sck, INPUT); } void spiDetachMISO(spi_t * spi, int8_t miso) { if(!spi) { return; } if(miso < 0) { if(spi->num == HSPI) { miso = 12; } else if(spi->num == VSPI) { miso = 19; } else { miso = 7; } } pinMatrixInDetach(SPI_MISO_IDX(spi->num), false, false); pinMode(miso, INPUT); } void spiDetachMOSI(spi_t * spi, int8_t mosi) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } if(mosi < 0) { if(spi->num == HSPI) { mosi = 13; } else if(spi->num == VSPI) { mosi = 23; } else { mosi = 8; } } pinMatrixOutDetach(mosi, false, false); pinMode(mosi, INPUT); } void spiAttachSS(spi_t * spi, uint8_t cs_num, int8_t ss) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } if(cs_num > 2) { return; } if(ss < 0) { cs_num = 0; if(spi->num == HSPI) { ss = 15; } else if(spi->num == VSPI) { ss = 5; } else { ss = 11; } } pinMode(ss, OUTPUT); pinMatrixOutAttach(ss, SPI_SS_IDX(spi->num, cs_num), false, false); spiEnableSSPins(spi, (1 << cs_num)); } void spiDetachSS(spi_t * spi, int8_t ss) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } if(ss < 0) { if(spi->num == HSPI) { ss = 15; } else if(spi->num == VSPI) { ss = 5; } else { ss = 11; } } pinMatrixOutDetach(ss, false, false); pinMode(ss, INPUT); } void _update(spi_t *spi) { if (spi->num == HSPI) hspiptr->update(); else if (spi->num == VSPI) vspiptr->update(); } void _waitdone(spi_t *spi) { if (spi->num == HSPI) hspiptr->waitdone(); else if (spi->num == VSPI) vspiptr->waitdone(); } void spiEnableSSPins(spi_t * spi, uint8_t cs_mask) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } SPI_MUTEX_LOCK(); spi->dev->pin.val &= ~(cs_mask & SPI_CS_MASK_ALL); _update(spi); SPI_MUTEX_UNLOCK(); } void spiDisableSSPins(spi_t * spi, uint8_t cs_mask) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } SPI_MUTEX_LOCK(); spi->dev->pin.val |= (cs_mask & SPI_CS_MASK_ALL); _update(spi); SPI_MUTEX_UNLOCK(); } void spiSSEnable(spi_t * spi) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } SPI_MUTEX_LOCK(); spi->dev->user.cs_setup = 1; spi->dev->user.cs_hold = 1; _update(spi); SPI_MUTEX_UNLOCK(); } void spiSSDisable(spi_t * spi) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } SPI_MUTEX_LOCK(); spi->dev->user.cs_setup = 0; spi->dev->user.cs_hold = 0; _update(spi); SPI_MUTEX_UNLOCK(); } void spiSSSet(spi_t * spi) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } SPI_MUTEX_LOCK(); spi->dev->pin.cs_keep_active = 1; _update(spi); SPI_MUTEX_UNLOCK(); } void spiSSClear(spi_t * spi) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } SPI_MUTEX_LOCK(); spi->dev->pin.cs_keep_active = 0; _update(spi); SPI_MUTEX_UNLOCK(); } uint32_t spiGetClockDiv(spi_t * spi) { if(!spi) { return 0; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return 0; } return spi->dev->clock.val; } void spiSetClockDiv(spi_t * spi, uint32_t clockDiv) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } SPI_MUTEX_LOCK(); spi->dev->clock.val = clockDiv; _update(spi); SPI_MUTEX_UNLOCK(); } uint8_t spiGetDataMode(spi_t * spi) { if(!spi) { return 0; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return 0; } bool idleEdge = spi->dev->pin.ck_idle_edge; bool outEdge = spi->dev->user.ck_out_edge; if(idleEdge) { if(outEdge) { return SPI_MODE2; } return SPI_MODE3; } if(outEdge) { return SPI_MODE1; } return SPI_MODE0; } void spiSetDataMode(spi_t * spi, uint8_t dataMode) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } SPI_MUTEX_LOCK(); switch (dataMode) { case SPI_MODE1: spi->dev->pin.ck_idle_edge = 0; spi->dev->user.ck_out_edge = 1; break; case SPI_MODE2: spi->dev->pin.ck_idle_edge = 1; spi->dev->user.ck_out_edge = 1; break; case SPI_MODE3: spi->dev->pin.ck_idle_edge = 1; spi->dev->user.ck_out_edge = 0; break; case SPI_MODE0: default: spi->dev->pin.ck_idle_edge = 0; spi->dev->user.ck_out_edge = 0; break; } _update(spi); SPI_MUTEX_UNLOCK(); } uint8_t spiGetBitOrder(spi_t * spi) { if(!spi) { return 0; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return 0; } return (spi->dev->ctrl.wr_bit_order | spi->dev->ctrl.rd_bit_order) == 0; } void spiSetBitOrder(spi_t * spi, uint8_t bitOrder) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } SPI_MUTEX_LOCK(); if (SPI_MSBFIRST == bitOrder) { spi->dev->ctrl.wr_bit_order = 0; spi->dev->ctrl.rd_bit_order = 0; } else if (SPI_LSBFIRST == bitOrder) { spi->dev->ctrl.wr_bit_order = 1; spi->dev->ctrl.rd_bit_order = 1; } _update(spi); SPI_MUTEX_UNLOCK(); } static void _on_apb_change(void * arg, apb_change_ev_t ev_type, uint32_t old_apb, uint32_t new_apb) { spi_t * spi = (spi_t *)arg; if(ev_type == APB_BEFORE_CHANGE){ SPI_MUTEX_LOCK(); _waitdone(spi); } else { spi->dev->clock.val = spiFrequencyToClockDiv(old_apb / ((spi->dev->clock.clkdiv_pre + 1) * (spi->dev->clock.clkcnt_n + 1))); _update(spi); SPI_MUTEX_UNLOCK(); } } void spiStopBus(spi_t * spi) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } SPI_MUTEX_LOCK(); spi->dev->slave.trans_done = 0; spi->dev->slave.slave_mode = 0; spi->dev->pin.val = 0; spi->dev->user.val = 0; spi->dev->user1.val = 0; spi->dev->ctrl.val = 0; spi->dev->ctrl1.val = 0; spi->dev->ctrl2.val = 0; spi->dev->clock.val = 0; _update(spi); SPI_MUTEX_UNLOCK(); //removeApbChangeCallback(spi, _on_apb_change); } spi_t * spiStartBus(uint8_t spi_num, uint32_t clockDiv, uint8_t dataMode, uint8_t bitOrder) { if(spi_num > 3){ return NULL; } spi_t * spi = &_spi_bus_array[spi_num]; #if !CONFIG_DISABLE_HAL_LOCKS if(spi->lock == NULL){ /* Instead of calling xSemaphoreCreateMutex we need to assign one of the * local semaphores. */ if (spi_num == 2) spi->lock = &i_gn_semaphore_spi2; else if (spi_num == 3) spi->lock = &i_gn_semaphore_spi3; else return NULL; } #endif if(spi_num == HSPI) { DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_SPI_CLK_EN); DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI_RST); } else if(spi_num == VSPI) { DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_SPI_CLK_EN_2); DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI_RST_2); } else { DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_SPI_CLK_EN_1); DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI_RST_1); } spiStopBus(spi); spiSetDataMode(spi, dataMode); spiSetBitOrder(spi, bitOrder); spiSetClockDiv(spi, clockDiv); SPI_MUTEX_LOCK(); spi->dev->user.usr_mosi = 1; spi->dev->user.usr_miso = 1; spi->dev->user.doutdin = 1; int i; for(i=0; i<16; i++) { spi->dev->data_buf[i] = 0x00000000; } _update(spi); SPI_MUTEX_UNLOCK(); //addApbChangeCallback(spi, _on_apb_change); return spi; } void spiWaitReady(spi_t * spi) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } _waitdone(spi); } void spiWrite(spi_t * spi, const uint32_t *data, uint8_t len) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } int i; if(len > 16) { len = 16; } SPI_MUTEX_LOCK(); spi->dev->mosi_dlen.usr_mosi_dbitlen = (len * 32) - 1; spi->dev->miso_dlen.usr_miso_dbitlen = 0; for(i=0; i<len; i++) { spi->dev->data_buf[i] = data[i]; } spi->dev->cmd.usr = 1; _update(spi); _waitdone(spi); SPI_MUTEX_UNLOCK(); } void spiTransfer(spi_t * spi, uint32_t *data, uint8_t len) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } int i; if(len > 16) { len = 16; } SPI_MUTEX_LOCK(); spi->dev->mosi_dlen.usr_mosi_dbitlen = (len * 32) - 1; spi->dev->miso_dlen.usr_miso_dbitlen = (len * 32) - 1; for(i=0; i<len; i++) { spi->dev->data_buf[i] = data[i]; } spi->dev->cmd.usr = 1; _update(spi); _waitdone(spi); for(i=0; i<len; i++) { data[i] = spi->dev->data_buf[i]; } SPI_MUTEX_UNLOCK(); } void spiWriteByte(spi_t * spi, uint8_t data) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } SPI_MUTEX_LOCK(); spi->dev->mosi_dlen.usr_mosi_dbitlen = 7; spi->dev->miso_dlen.usr_miso_dbitlen = 0; spi->dev->data_buf[0] = data; spi->dev->cmd.usr = 1; _update(spi); _waitdone(spi); SPI_MUTEX_UNLOCK(); } uint8_t spiTransferByte(spi_t * spi, uint8_t data) { if(!spi) { return 0; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return 0; } SPI_MUTEX_LOCK(); spi->dev->mosi_dlen.usr_mosi_dbitlen = 7; spi->dev->miso_dlen.usr_miso_dbitlen = 7; spi->dev->data_buf[0] = data; spi->dev->cmd.usr = 1; _update(spi); _waitdone(spi); data = spi->dev->data_buf[0] & 0xFF; SPI_MUTEX_UNLOCK(); return data; } static uint32_t __spiTranslate32(uint32_t data) { union { uint32_t l; uint8_t b[4]; } out; out.l = data; return out.b[3] | (out.b[2] << 8) | (out.b[1] << 16) | (out.b[0] << 24); } void spiWriteWord(spi_t * spi, uint16_t data) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } if(!spi->dev->ctrl.wr_bit_order){ data = (data >> 8) | (data << 8); } SPI_MUTEX_LOCK(); spi->dev->mosi_dlen.usr_mosi_dbitlen = 15; spi->dev->miso_dlen.usr_miso_dbitlen = 0; spi->dev->data_buf[0] = data; spi->dev->cmd.usr = 1; _update(spi); _waitdone(spi); SPI_MUTEX_UNLOCK(); } uint16_t spiTransferWord(spi_t * spi, uint16_t data) { if(!spi) { return 0; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return 0; } if(!spi->dev->ctrl.wr_bit_order){ data = (data >> 8) | (data << 8); } SPI_MUTEX_LOCK(); spi->dev->mosi_dlen.usr_mosi_dbitlen = 15; spi->dev->miso_dlen.usr_miso_dbitlen = 15; spi->dev->data_buf[0] = data; spi->dev->cmd.usr = 1; _update(spi); _waitdone(spi); data = spi->dev->data_buf[0]; SPI_MUTEX_UNLOCK(); if(!spi->dev->ctrl.rd_bit_order){ data = (data >> 8) | (data << 8); } return data; } void spiWriteLong(spi_t * spi, uint32_t data) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } if(!spi->dev->ctrl.wr_bit_order){ data = __spiTranslate32(data); } SPI_MUTEX_LOCK(); spi->dev->mosi_dlen.usr_mosi_dbitlen = 31; spi->dev->miso_dlen.usr_miso_dbitlen = 0; spi->dev->data_buf[0] = data; spi->dev->cmd.usr = 1; _update(spi); _waitdone(spi); SPI_MUTEX_UNLOCK(); } uint32_t spiTransferLong(spi_t * spi, uint32_t data) { if(!spi) {
return 0; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return 0; } if(!spi->dev->ctrl.wr_bit_order){ data = __spiTranslate32(data); } SPI_MUTEX_LOCK(); spi->dev->mosi_dlen.usr_mosi_dbitlen = 31; spi->dev->miso_dlen.usr_miso_dbitlen = 31; spi->dev->data_buf[0] = data; spi->dev->cmd.usr = 1; _update(spi); _waitdone(spi); data = spi->dev->data_buf[0]; SPI_MUTEX_UNLOCK(); if(!spi->dev->ctrl.rd_bit_order){ data = __spiTranslate32(data); } return data; } static void __spiTransferBytes(spi_t * spi, const uint8_t * data, uint8_t * out, uint32_t bytes) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } unsigned int i; if(bytes > 64) { bytes = 64; } uint32_t words = (bytes + 3) / 4;//16 max uint32_t wordsBuf[16] = {0,}; uint8_t * bytesBuf = (uint8_t *) wordsBuf; if(data) { memcpy(bytesBuf, data, bytes);//copy data to buffer } else { memset(bytesBuf, 0xFF, bytes); } spi->dev->mosi_dlen.usr_mosi_dbitlen = ((bytes * 8) - 1); spi->dev->miso_dlen.usr_miso_dbitlen = ((bytes * 8) - 1); for(i=0; i<words; i++) { spi->dev->data_buf[i] = wordsBuf[i]; //copy buffer to spi fifo } spi->dev->cmd.usr = 1; _update(spi); _waitdone(spi); if(out) { for(i=0; i<words; i++) { wordsBuf[i] = spi->dev->data_buf[i];//copy spi fifo to buffer } memcpy(out, bytesBuf, bytes);//copy buffer to output } } void spiTransferBytes(spi_t * spi, const uint8_t * data, uint8_t * out, uint32_t size) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } SPI_MUTEX_LOCK(); while(size) { if(size > 64) { __spiTransferBytes(spi, data, out, 64); size -= 64; if(data) { data += 64; } if(out) { out += 64; } } else { __spiTransferBytes(spi, data, out, size); size = 0; } } SPI_MUTEX_UNLOCK(); } void spiTransferBits(spi_t * spi, uint32_t data, uint32_t * out, uint8_t bits) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } SPI_MUTEX_LOCK(); spiTransferBitsNL(spi, data, out, bits); SPI_MUTEX_UNLOCK(); } /* * Manual Lock Management * */ #define MSB_32_SET(var, val) { uint8_t * d = (uint8_t *)&(val); (var) = d[3] | (d[2] << 8) | (d[1] << 16) | (d[0] << 24); } #define MSB_24_SET(var, val) { uint8_t * d = (uint8_t *)&(val); (var) = d[2] | (d[1] << 8) | (d[0] << 16); } #define MSB_16_SET(var, val) { (var) = (((val) & 0xFF00) >> 8) | (((val) & 0xFF) << 8); } #define MSB_PIX_SET(var, val) { uint8_t * d = (uint8_t *)&(val); (var) = d[1] | (d[0] << 8) | (d[3] << 16) | (d[2] << 24); } void spiTransaction(spi_t * spi, uint32_t clockDiv, uint8_t dataMode, uint8_t bitOrder) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } SPI_MUTEX_LOCK(); spi->dev->clock.val = clockDiv; switch (dataMode) { case SPI_MODE1: spi->dev->pin.ck_idle_edge = 0; spi->dev->user.ck_out_edge = 1; break; case SPI_MODE2: spi->dev->pin.ck_idle_edge = 1; spi->dev->user.ck_out_edge = 1; break; case SPI_MODE3: spi->dev->pin.ck_idle_edge = 1; spi->dev->user.ck_out_edge = 0; break; case SPI_MODE0: default: spi->dev->pin.ck_idle_edge = 0; spi->dev->user.ck_out_edge = 0; break; } if (SPI_MSBFIRST == bitOrder) { spi->dev->ctrl.wr_bit_order = 0; spi->dev->ctrl.rd_bit_order = 0; } else if (SPI_LSBFIRST == bitOrder) { spi->dev->ctrl.wr_bit_order = 1; spi->dev->ctrl.rd_bit_order = 1; } _update(spi); } void spiSimpleTransaction(spi_t * spi) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } SPI_MUTEX_LOCK(); } void spiEndTransaction(spi_t * spi) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } SPI_MUTEX_UNLOCK(); } void IRAM_ATTR spiWriteByteNL(spi_t * spi, uint8_t data) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } spi->dev->mosi_dlen.usr_mosi_dbitlen = 7; spi->dev->miso_dlen.usr_miso_dbitlen = 0; spi->dev->data_buf[0] = data; spi->dev->cmd.usr = 1; _update(spi); _waitdone(spi); } uint8_t spiTransferByteNL(spi_t * spi, uint8_t data) { if(!spi) { return 0; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return 0; } spi->dev->mosi_dlen.usr_mosi_dbitlen = 7; spi->dev->miso_dlen.usr_miso_dbitlen = 7; spi->dev->data_buf[0] = data; spi->dev->cmd.usr = 1; _update(spi); _waitdone(spi); data = spi->dev->data_buf[0] & 0xFF; return data; } void IRAM_ATTR spiWriteShortNL(spi_t * spi, uint16_t data) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } if(!spi->dev->ctrl.wr_bit_order){ MSB_16_SET(data, data); } spi->dev->mosi_dlen.usr_mosi_dbitlen = 15; spi->dev->miso_dlen.usr_miso_dbitlen = 0; spi->dev->data_buf[0] = data; spi->dev->cmd.usr = 1; _update(spi); _waitdone(spi); } uint16_t spiTransferShortNL(spi_t * spi, uint16_t data) { if(!spi) { return 0; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return 0; } if(!spi->dev->ctrl.wr_bit_order){ MSB_16_SET(data, data); } spi->dev->mosi_dlen.usr_mosi_dbitlen = 15; spi->dev->miso_dlen.usr_miso_dbitlen = 15; spi->dev->data_buf[0] = data; spi->dev->cmd.usr = 1; _update(spi); _waitdone(spi); data = spi->dev->data_buf[0] & 0xFFFF; if(!spi->dev->ctrl.rd_bit_order){ MSB_16_SET(data, data); } return data; } void IRAM_ATTR spiWriteLongNL(spi_t * spi, uint32_t data) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } if(!spi->dev->ctrl.wr_bit_order){ MSB_32_SET(data, data); } spi->dev->mosi_dlen.usr_mosi_dbitlen = 31; spi->dev->miso_dlen.usr_miso_dbitlen = 0; spi->dev->data_buf[0] = data; spi->dev->cmd.usr = 1; _update(spi); _waitdone(spi); } uint32_t spiTransferLongNL(spi_t * spi, uint32_t data) { if(!spi) { return 0; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return 0; } if(!spi->dev->ctrl.wr_bit_order){ MSB_32_SET(data, data); } spi->dev->mosi_dlen.usr_mosi_dbitlen = 31; spi->dev->miso_dlen.usr_miso_dbitlen = 31; spi->dev->data_buf[0] = data; spi->dev->cmd.usr = 1; _update(spi); _waitdone(spi); data = spi->dev->data_buf[0]; if(!spi->dev->ctrl.rd_bit_order){ MSB_32_SET(data, data); } return data; } void spiWriteNL(spi_t * spi, const void * data_in, uint32_t len){ size_t longs = len >> 2; if(len & 3){ longs++; } uint32_t * data = (uint32_t*)data_in; size_t c_len = 0, c_longs = 0; while(len){ c_len = (len>64)?64:len; c_longs = (longs > 16)?16:longs; spi->dev->mosi_dlen.usr_mosi_dbitlen = (c_len*8)-1; spi->dev->miso_dlen.usr_miso_dbitlen = 0; for (size_t i=0; i<c_longs; i++) { spi->dev->data_buf[i] = data[i]; } spi->dev->cmd.usr = 1; _update(spi); _waitdone(spi); data += c_longs; longs -= c_longs; len -= c_len; } } void spiTransferBytesNL(spi_t * spi, const void * data_in, uint8_t * data_out, uint32_t len){ if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } size_t longs = len >> 2; if(len & 3){ longs++; } uint32_t * data = (uint32_t*)data_in; uint32_t * result = (uint32_t*)data_out; size_t c_len = 0, c_longs = 0; while(len){ c_len = (len>64)?64:len; c_longs = (longs > 16)?16:longs; spi->dev->mosi_dlen.usr_mosi_dbitlen = (c_len*8)-1; spi->dev->miso_dlen.usr_miso_dbitlen = (c_len*8)-1; if(data){ for (size_t i=0; i<c_longs; i++) { spi->dev->data_buf[i] = data[i]; } } else { for (size_t i=0; i<c_longs; i++) { spi->dev->data_buf[i] = 0xFFFFFFFF; } } spi->dev->cmd.usr = 1; _update(spi); _waitdone(spi); if(result){ for (size_t i=0; i<c_longs; i++) { result[i] = spi->dev->data_buf[i]; } } if(data){ data += c_longs; } if(result){ result += c_longs; } longs -= c_longs; len -= c_len; } } void spiTransferBitsNL(spi_t * spi, uint32_t data, uint32_t * out, uint8_t bits) { if(!spi) { return; } else if (spi->dev == NULL) { PRINTF_INFO("HALSPI", "Attempting to access unsupported SPI%d", spi->num); return; } if(bits > 32) { bits = 32; } uint32_t bytes = (bits + 7) / 8;//64 max uint32_t mask = (((uint64_t)1 << bits) - 1) & 0xFFFFFFFF; data = data & mask; if(!spi->dev->ctrl.wr_bit_order){ if(bytes == 2) { MSB_16_SET(data, data); } else if(bytes == 3) { MSB_24_SET(data, data); } else { MSB_32_SET(data, data); } } spi->dev->mosi_dlen.usr_mosi_dbitlen = (bits - 1); spi->dev->miso_dlen.usr_miso_dbitlen = (bits - 1); spi->dev->data_buf[0] = data; spi->dev->cmd.usr = 1; _update(spi); _waitdone(spi); data = spi->dev->data_buf[0]; if(out) { *out = data; if(!spi->dev->ctrl.rd_bit_order){ if(bytes == 2) { MSB_16_SET(*out, data); } else if(bytes == 3) { MSB_24_SET(*out, data); } else { MSB_32_SET(*out, data); } } } } void IRAM_ATTR spiWritePixelsNL(spi_t * spi, const void * data_in, uint32_t len){ size_t longs = len >> 2; if(len & 3){ longs++; } bool msb = !spi->dev->ctrl.wr_bit_order; uint32_t * data = (uint32_t*)data_in; size_t c_len = 0, c_longs = 0, l_bytes = 0; while(len){ c_len = (len>64)?64:len; c_longs = (longs > 16)?16:longs; l_bytes = (c_len & 3); spi->dev->mosi_dlen.usr_mosi_dbitlen = (c_len*8)-1; spi->dev->miso_dlen.usr_miso_dbitlen = 0; for (size_t i=0; i<c_longs; i++) { if(msb){ if(l_bytes && i == (c_longs - 1)){ if(l_bytes == 2){ MSB_16_SET(spi->dev->data_buf[i], data[i]); } else { spi->dev->data_buf[i] = data[i] & 0xFF; } } else { MSB_PIX_SET(spi->dev->data_buf[i], data[i]); } } else { spi->dev->data_buf[i] = data[i]; } } spi->dev->cmd.usr = 1; _update(spi); _waitdone(spi); data += c_longs; longs -= c_longs; len -= c_len; } } /* * Clock Calculators * * */ typedef union { uint32_t value; struct { uint32_t clkcnt_l: 6; /*it must be equal to spi_clkcnt_N.*/ uint32_t clkcnt_h: 6; /*it must be floor((spi_clkcnt_N+1)/2-1).*/ uint32_t clkcnt_n: 6; /*it is the divider of spi_clk. So spi_clk frequency is system/(spi_clkdiv_pre+1)/(spi_clkcnt_N+1)*/ uint32_t clkdiv_pre: 13; /*it is pre-divider of spi_clk.*/ uint32_t clk_equ_sysclk: 1; /*1: spi_clk is eqaul to system 0: spi_clk is divided from system clock.*/ }; } spiClk_t; #define ClkRegToFreq(reg) (apb_freq / (((reg)->clkdiv_pre + 1) * ((reg)->clkcnt_n + 1))) uint32_t spiClockDivToFrequency(uint32_t clockDiv) { uint32_t apb_freq = getApbFrequency(); spiClk_t reg = { clockDiv }; return ClkRegToFreq(&reg); } uint32_t abs(uint32_t a) { long r = abs((long) a); if (r > UINT32_MAX) return UINT32_MAX; else return (uint32_t)r; } uint32_t spiFrequencyToClockDiv(uint32_t freq) { uint32_t apb_freq = getApbFrequency(); if(freq >= apb_freq) { return SPI_CLK_EQU_SYSCLK; } const spiClk_t minFreqReg = { 0x7FFFF000 }; uint32_t minFreq = ClkRegToFreq((spiClk_t*) &minFreqReg); if(freq < minFreq) { return minFreqReg.value; } uint8_t calN = 1; spiClk_t bestReg = { 0 }; int32_t bestFreq = 0; while(calN <= 0x3F) { spiClk_t reg = { 0 }; int32_t calFreq; int32_t calPre; int8_t calPreVari = -2; reg.clkcnt_n = calN; while(calPreVari++ <= 1) { calPre = (((apb_freq / (reg.clkcnt_n + 1)) / freq) - 1) + calPreVari; if(calPre > 0x1FFF) { reg.clkdiv_pre = 0x1FFF; } else if(calPre <= 0) { reg.clkdiv_pre = 0; } else { reg.clkdiv_pre = calPre; } reg.clkcnt_l = ((reg.clkcnt_n + 1) / 2); calFreq = ClkRegToFreq(&reg); if(calFreq == (int32_t) freq) { memcpy(&bestReg, &reg, sizeof(bestReg)); break; } else if(calFreq < (int32_t) freq) { if(abs(freq - calFreq) < abs(freq - bestFreq)) { bestFreq = calFreq; memcpy(&bestReg, &reg, sizeof(bestReg)); } } } if(calFreq == (int32_t) freq) { break; } calN++; } return bestReg.value; }
#include <crave/SystemC.hpp> #include <crave/ConstrainedRandom.hpp> #include <systemc.h> #include <boost/timer.hpp> using crave::rand_obj; using crave::randv; using sc_dt::sc_bv; using sc_dt::sc_uint; struct ALU32 : public rand_obj { randv< sc_bv<2> > op ; randv< sc_uint<32> > a, b ; ALU32() : op(this), a(this), b(this) { constraint ( (op() != 0x0) || ( 4294967295u >= a() + b() ) ); constraint ( (op() != 0x1) || ((4294967295u >= a() - b()) && (b() <= a()) ) ); constraint ( (op() != 0x2) || ( 4294967295u >= a() * b() ) ); constraint ( (op() != 0x3) || ( b() != 0 ) ); } friend std::ostream & operator<< (std::ostream & o, ALU32 const & alu) { o << alu.op << ' ' << alu.a << ' ' << alu.b ; return o; } }; int sc_main (int argc, char** argv) { boost::timer timer; ALU32 c; c.next(); std::cout << "first: " << timer.elapsed() << "\n"; for (int i=0; i<1000; ++i) { c.next(); } std::cout << "complete: " << timer.elapsed() << "\n"; return 0; }
/** * 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; } };
#include <systemc.h> #include "full_adder.h" #include "tb.h" SC_MODULE( SYSTEM ) { //Module Declarations tb *tb0; full_adder *full_adder0; //Local signal declarations sc_signal<bool> sig_inp_a, sig_inp_b, sig_inp_cin, sig_sum, sig_co; SC_HAS_PROCESS(SYSTEM); SYSTEM( sc_module_name nm) : sc_module (nm) { //Module instance signal connections tb0 = new tb("tb0"); tb0->inp_a( sig_inp_a ); tb0->inp_b( sig_inp_b ); tb0->inp_cin( sig_inp_cin ); tb0->sum( sig_sum ); tb0->co( sig_co ); full_adder0 = new full_adder("full_adder0"); full_adder0->inp_a( sig_inp_a ); full_adder0->inp_b( sig_inp_b ); full_adder0->inp_cin( sig_inp_cin ); full_adder0->sum( sig_sum ); full_adder0->co( sig_co ); } //Destructor ~SYSTEM(){ delete tb0; delete full_adder0; } }; SYSTEM *top = NULL; int sc_main( int argc, char* argv[] ){ // Connect the modules top = new SYSTEM( "top" ); // Set up the tracing sc_trace_file* pTraceFile = sc_create_vcd_trace_file("trace_file"); sc_trace(pTraceFile, top->sig_inp_a, "inp_a"); sc_trace(pTraceFile, top->sig_inp_b, "inp_b"); sc_trace(pTraceFile, top->sig_inp_cin, "inp_cin"); sc_trace(pTraceFile, top->sig_sum, "sum"); sc_trace(pTraceFile, top->sig_co, "co"); // Start the simulation sc_start(); // Close the tracing sc_close_vcd_trace_file(pTraceFile); return 0; }
/******************************************************************************* * sc_main.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * The sc_main is the first function always called by the SystemC environment. * This one takes as arguments a test name and an option: * * testname.x [testnumber] [+waveform] * * testnumber - test to run, 0 for t0, 1 for t1, etc. Default = 0. * +waveform - generate VCD file for top level signals. * ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "SmallScreentest.h" SmallScreentest i_SmallScreentest("i_SmallScreentest"); int sc_main(int argc, char *argv[]) { int tn; bool wv = false; if (argc > 3) { SC_REPORT_ERROR("MAIN", "Too many arguments used in call"); return 1; } /* If no arguments are given, argc=1, there is no waveform and we run * test 0. */ else if (argc == 1) { tn = 0; wv = false; } /* If we have at least one argument, we check if it is the waveform command. * If it is, we set a tag. If we have two arguments, we assume the second * one is the test number. */ else if (strcmp(argv[1], "+waveform")==0) { wv = true; /* If two arguments were given (argc=3) we assume the second one is the * test name. If the testnumber was not given, we run test 0. */ if (argc == 3) tn = atoi(argv[2]); else tn = 0; } /* For the remaining cases, we check. If there are two arguments, the first * one must be the test number and the second one might be the waveform * option. If we see 2 arguments, we do that. If we do not, then we just * have a testcase number. */ else { if (argc == 3 && strcmp(argv[2], "+waveform")==0) wv = true; else wv = false; tn = atoi(argv[1]); } /* We start the wave tracing. */ sc_trace_file *tf = NULL; if (wv) { tf = sc_create_vcd_trace_file("waves"); i_SmallScreentest.trace(tf); } /* We need to connect the Arduino pin library to the gpios. */ i_SmallScreentest.i_esp.pininit(); /* Set the test number */ i_SmallScreentest.tn = tn; /* And run the simulation. */ sc_start(); if (wv) sc_close_vcd_trace_file(tf); exit(0); }
/* Print.cpp - Base class that provides print() and println() Copyright (c) 2008 David A. Mellis. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 23 November 2006 by David A. Mellis Modified December 2014 by Ivan Grokhotkov Modified May 2015 by Michael C. Miller - ESP31B progmem support Modified 25 July 2019 by Glenn Ramalho - fixed a small bug */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include "Arduino.h" #include <systemc.h> #include "info.h" #include "Print.h" extern "C" { #include "time.h" } // Public Methods ////////////////////////////////////////////////////////////// /* default implementation: may be overridden */ size_t Print::write(const uint8_t *buffer, size_t size) { size_t n = 0; while(size--) { n += write(*buffer++); } return n; } size_t Print::printf(const char *format, ...) { char loc_buf[64]; char * temp = loc_buf; va_list arg; va_list copy; va_start(arg, format); va_copy(copy, arg); int len = vsnprintf(NULL, 0, format, copy); va_end(copy); if (len < 0) { PRINTF_WARN("PRINTF", "vnprintf returned an error."); return 0; } if((unsigned int)len >= sizeof(loc_buf)){ temp = new char[len+1]; if(temp == NULL) { return 0; } } len = vsnprintf(temp, len+1, format, arg); write((uint8_t*)temp, len); va_end(arg); if(temp != loc_buf) { delete[] temp; } return len; } size_t Print::print(const __FlashStringHelper *ifsh) { return print(reinterpret_cast<const char *>(ifsh)); } size_t Print::print(const String &s) { return write(s.c_str(), s.length()); } size_t Print::print(const char str[]) { return write(str); } size_t Print::print(char c) { return write(c); } size_t Print::print(unsigned char b, int base) { return print((unsigned long) b, base); } size_t Print::print(int n, int base) { return print((long) n, base); } size_t Print::print(unsigned int n, int base) { return print((unsigned long) n, base); } size_t Print::print(long n, int base) { if(base == 0) { return write(n); } else if(base == 10) { if(n < 0) { int t = print('-'); n = -n; return printNumber(n, 10) + t; } return printNumber(n, 10); } else { return printNumber(n, base); } } size_t Print::print(unsigned long n, int base) { if(base == 0) { return write(n); } else { return printNumber(n, base); } } size_t Print::print(double n, int digits) { return printFloat(n, digits); } size_t Print::println(const __FlashStringHelper *ifsh) { size_t n = print(ifsh); n += println(); return n; } size_t Print::print(const Printable& x) { return x.printTo(*this); } size_t Print::print(struct tm * timeinfo, const char * format) { const char * f = format; if(!f){ f = "%c"; } char buf[64]; size_t written = strftime(buf, 64, f, timeinfo); print(buf); return written; } size_t Print::println(void) { return print("\r\n"); } size_t Print::println(const String &s) { size_t n = print(s); n += println(); return n; } size_t Print::println(const char c[]) { size_t n = print(c); n += println(); return n; } size_t Print::println(char c) { size_t n = print(c); n += println(); return n; } size_t Print::println(unsigned char b, int base) { size_t n = print(b, base); n += println(); return n; } size_t Print::println(int num, int base) { size_t n = print(num, base); n += println(); return n; } size_t Print::println(unsigned int num, int base) { size_t n = print(num, base); n += println(); return n; } size_t Print::println(long num, int base) { size_t n = print(num, base); n += println(); return n; } size_t Print::println(unsigned long num, int base) { size_t n = print(num, base); n += println(); return n; } size_t Print::println(double num, int digits) { size_t n = print(num, digits); n += println(); return n; } size_t Print::println(const Printable& x) { size_t n = print(x); n += println(); return n; } size_t Print::println(struct tm * timeinfo, const char * format) { size_t n = print(timeinfo, format); n += println(); return n; } // Private Methods ///////////////////////////////////////////////////////////// size_t Print::printNumber(unsigned long n, uint8_t base) { char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte. char *str = &buf[sizeof(buf) - 1]; *str = '\0'; // prevent crash if called with base == 1 if(base < 2) { base = 10; } do { unsigned long m = n; n /= base; char c = m - base * n; *--str = c < 10 ? c + '0' : c + 'A' - 10; } while(n); return write(str); } size_t Print::printFloat(double number, uint8_t digits) { size_t n = 0; if(isnan(number)) { return print("nan"); } if(isinf(number)) { return print("inf"); } if(number > 4294967040.0) { return print("ovf"); // constant determined empirically } if(number < -4294967040.0) { return print("ovf"); // constant determined empirically } // Handle negative numbers if(number < 0.0) { n += print('-'); number = -number; } // Round correctly so that print(1.999, 2) prints as "2.00" double rounding = 0.5; for(uint8_t i = 0; i < digits; ++i) { rounding /= 10.0; } number += rounding; // Extract the integer part of the number and print it unsigned long int_part = (unsigned long) number; double remainder = number - (double) int_part; n += print(int_part); // Print the decimal point, but only if there are digits beyond if(digits > 0) { n += print("."); } // Extract digits from the remainder one at a time while(digits-- > 0) { remainder *= 10.0; int toPrint = int(remainder); n += print(toPrint); remainder -= toPrint; } return n; }
#include <systemc.h> // // Every HW component class has to be derived from :class:`hwt.hwModule.HwModule` class // // .. hwt-autodoc:: // SC_MODULE(Showcase0) { // ports sc_in<sc_uint<32>> a; sc_in<sc_int<32>> b; sc_out<sc_uint<32>> c; sc_in_clk clk; sc_out<sc_uint<1>> cmp_0; sc_out<sc_uint<1>> cmp_1; sc_out<sc_uint<1>> cmp_2; sc_out<sc_uint<1>> cmp_3; sc_out<sc_uint<1>> cmp_4; sc_out<sc_uint<1>> cmp_5; sc_out<sc_uint<32>> contOut; sc_in<sc_uint<32>> d; sc_in<sc_uint<1>> e; sc_out<sc_uint<1>> f; sc_out<sc_uint<16>> fitted; sc_out<sc_uint<8>> g; sc_out<sc_uint<8>> h; sc_in<sc_uint<2>> i; sc_out<sc_uint<8>> j; sc_out<sc_uint<32>> k; sc_out<sc_uint<1>> out; sc_out<sc_uint<1>> output; sc_in<sc_uint<1>> rst_n; sc_out<sc_uint<8>> sc_signal_0; // component instances // internal signals sc_uint<32> const_private_signal = sc_uint<32>("0x0000007B"); sc_int<8> fallingEdgeRam[4]; sc_uint<1> r = sc_uint<1>("0b0"); sc_uint<2> r_0 = sc_uint<2>("0b00"); sc_uint<2> r_1 = sc_uint<2>("0b00"); sc_signal<sc_uint<1>> r_next; sc_signal<sc_uint<2>> r_next_0; sc_signal<sc_uint<2>> r_next_1; sc_uint<8> rom[4] = {sc_uint<8>("0x00"), sc_uint<8>("0x01"), sc_uint<8>("0x02"), sc_uint<8>("0x03"), }; void assig_process_c() { c.write(static_cast<sc_uint<32>>(a.read() + static_cast<sc_uint<32>>(b.read()))); } void assig_process_cmp_0() { cmp_0.write(a.read() < sc_uint<32>("0x00000004")); } void assig_process_cmp_1() { cmp_1.write(a.read() > sc_uint<32>("0x00000004")); } void assig_process_cmp_2() { cmp_2.write(b.read() <= sc_int<32>("0x00000004")); } void assig_process_cmp_3() { cmp_3.write(b.read() >= sc_int<32>("0x00000004")); } void assig_process_cmp_4() { cmp_4.write(b.read() != sc_int<32>("0x00000004")); } void assig_process_cmp_5() { cmp_5.write(b.read() == sc_int<32>("0x00000004")); } void assig_process_contOut() { contOut.write(static_cast<sc_uint<32>>(const_private_signal)); } void assig_process_f() { f.write(r); } void assig_process_fallingEdgeRam() { sc_signal<sc_uint<32>> tmpConcat_0; tmpConcat_0.write((sc_uint<24>("0x000000"), static_cast<sc_uint<8>>(static_cast<sc_uint<8>>(fallingEdgeRam[r_1])), )); { (fallingEdgeRam[r_1]).write(static_cast<sc_int<8>>(a.read().range(sc_int<32>("0x00000008"), sc_int<32>("0x00000000")))); k = tmpConcat_0.read(); } } void assig_process_fitted() { fitted.write(static_cast<sc_uint<16>>(a.read().range(sc_int<32>("0x00000010"), sc_int<32>("0x00000000")))); } void assig_process_g() { sc_signal<sc_uint<2>> tmpConcat_1; sc_signal<sc_uint<8>> tmpConcat_0; tmpConcat_1.write((a.read()[sc_int<32>("0x00000001")] & b.read()[sc_int<32>("0x00000001")], a.read()[sc_int<32>("0x00000000")] ^ b.read()[sc_int<32>("0x00000000")] | a.read()[sc_int<32>("0x00000001")], )); tmpConcat_0.write((tmpConcat_1.read(), static_cast<sc_uint<6>>(a.read().range(sc_int<32>("0x00000006"), sc_int<32>("0x00000000"))), )); g.write(tmpConcat_0.read()); } void assig_process_h() { if (a.read()[sc_int<32>("0x00000002")] == sc_uint<1>("0b1")) if (r == sc_uint<1>("0b1")) h.write(sc_uint<8>("0x00")); else if (a.read()[sc_int<32>("0x00000001")] == sc_uint<1>("0b1")) h.write(sc_uint<8>("0x01")); else h.write(sc_uint<8>("0x02")); } void assig_process_j() { j = static_cast<sc_uint<8>>(rom[r_1]); } void assig_process_out() { out.write(sc_uint<1>("0b0")); } void assig_process_output() { output.write(sc_uint<1>("0bX")); } void assig_process_r() { if (rst_n.read() == sc_uint<1>("0b0")) { r_1 = sc_uint<2>("0b00"); r_0 = sc_uint<2>("0b00"); r = sc_uint<1>("0b0"); } else { r_1 = r_next_1.read(); r_0 = r_next_0.read(); r = r_next.read(); } } void assig_process_r_next() { r_next_0.write(i.read()); } void assig_process_r_next_0() { r_next_1.write(r_0); } void assig_process_r_next_1() { if (r == sc_uint<1>("0b0")) r_next.write(e.read()); else r_next.write(r); } void assig_process_sc_signal_0() { switch(a.read()) { case sc_uint<32>("0x00000001"): { sc_signal_0.write(sc_uint<8>("0x00")); break; } case sc_uint<32>("0x00000002"): { sc_signal_0.write(sc_uint<8>("0x01")); break; } case sc_uint<32>("0x00000003"): { sc_signal_0.write(sc_uint<8>("0x03")); break; } default: sc_signal_0.write(sc_uint<8>("0x04")); } } SC_CTOR(Showcase0) { SC_METHOD(assig_process_c); sensitive << a << b; SC_METHOD(assig_process_cmp_0); sensitive << a; SC_METHOD(assig_process_cmp_1); sensitive << a; SC_METHOD(assig_process_cmp_2); sensitive << b; SC_METHOD(assig_process_cmp_3); sensitive << b; SC_METHOD(assig_process_cmp_4); sensitive << b; SC_METHOD(assig_process_cmp_5); sensitive << b; assig_process_contOut(); SC_METHOD(assig_process_f); sensitive << r; SC_METHOD(assig_process_fallingEdgeRam); sensitive << clk.neg(); SC_METHOD(assig_process_fitted); sensitive << a; SC_METHOD(assig_process_g); sensitive << a << b; SC_METHOD(assig_process_h); sensitive << a << r; SC_METHOD(assig_process_j); sensitive << clk.pos(); assig_process_out(); assig_process_output(); SC_METHOD(assig_process_r); sensitive << clk.pos(); SC_METHOD(assig_process_r_next); sensitive << i; SC_METHOD(assig_process_r_next_0); sensitive << r_0; SC_METHOD(assig_process_r_next_1); sensitive << e << r; SC_METHOD(assig_process_sc_signal_0); sensitive << a; // connect ports } };
#ifndef SOBEL_EDGE_DETECTOR_TLM_CPP #define SOBEL_EDGE_DETECTOR_TLM_CPP #include <systemc.h> using namespace sc_core; using namespace sc_dt; using namespace std; #include <tlm.h> #include <tlm_utils/simple_initiator_socket.h> #include <tlm_utils/simple_target_socket.h> #include <tlm_utils/peq_with_cb_and_phase.h> #include "sobel_edge_detector_tlm.hpp" #include "common_func.hpp" void sobel_edge_detector_tlm::do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address){ short int sobel_results[4]; sc_int<16> local_result; dbgimgtarmodprint(use_prints, "Calling do_when_read_transaction"); Edge_Detector::address = address; read(); for (int i = 0; i < 4; i++) { local_result = Edge_Detector::data.range((i + 1) * 16 - 1, i * 16).to_int(); sobel_results[i] = (short int)local_result; dbgimgtarmodprint(use_prints, "%0d", sobel_results[i]); } memcpy(data, sobel_results, 4 * sizeof(short int)); } void sobel_edge_detector_tlm::do_when_write_transaction(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address) { sc_uint<8> values[8]; dbgimgtarmodprint(use_prints, "Calling do_when_write_transaction"); for (int i = 0; i < 8; i++) { values[i] = *(data + i); } Edge_Detector::data = (values[7], values[6], values[5], values[4], values[3], values[2], values[1], values[0]); Edge_Detector::address = address; write(); } void sobel_edge_detector_tlm::read() { if ((Edge_Detector::address - SOBEL_OUTPUT_ADDRESS_LO) == 0) { Edge_Detector::data = (sc_uint<32>(0), resultSobelGradientY, resultSobelGradientX); } } void sobel_edge_detector_tlm::write() { wr_t.notify(0, SC_NS); } #endif // SOBEL_EDGE_DETECTOR_TLM_CPP
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************************/ /** * @file main.cpp * @brief This function instantiates a parameter OWNER, CONFIGURATOR and an * OBSERVER class * @author P V S Phaneendra, CircuitSutra Technologies Pvt. Ltd. * @date 12th September, 2011 (Monday) */ #include <cci_configuration> #include <systemc.h> #include <string> #include "ex16_parameter_owner.h" #include "ex16_parameter_configurer.h" #include "ex16_observer.h" /** * @fn int sc_main(int sc_argc, char* sc_argv[]) * @brief The main testbench function, instantiates an obserers, own, and configurer * @param sc_argc The number of input arguments * @param sc_argv The list of the input arhuments * @return An interger representing the exit status of the function. */ int sc_main(int sc_argc, char* sc_argv[]) { cci::cci_register_broker(new cci_utils::broker("DEFAULT_BROKER")); // Creating an originator to access the global broker const std::string myOrgStr = "sc_main_originator"; cci::cci_originator myOriginator(myOrgStr); // Get handle of the broker using the originator cci::cci_broker_handle globalBroker = cci::cci_get_global_broker(myOriginator); // Set preset value to the 'int_param' of 'parameter_owner' class before // their constructor begins SC_REPORT_INFO("sc_main", "[MAIN] : Setting preset value" " 's_address:256,d_address:512,index:0' to UDT"); // Demonstrating use of 'set_preset_cci_value' API to assign // preset value before the construction of the model hierarchy begins. std::string init_str("{\"s_address\":256,\"d_address\":512,\"index\":0}"); globalBroker.set_preset_cci_value("param_owner.User_data_type_param", cci::cci_value::from_json(init_str)); // Instantiation of sc_modules ex16_parameter_owner param_owner("param_owner"); ex16_parameter_configurer param_cfgr("param_cfgr"); // Instantiate the observer class ex16_observer observer_obj; SC_REPORT_INFO("sc_main", "Begin Simulation."); sc_core::sc_start(12.0, sc_core::SC_NS); SC_REPORT_INFO("sc_main", "End Simulation."); return EXIT_SUCCESS; } // sc_main
#include <systemc.h> #include <and.h> #include <testbench.h> int sc_main(int argv, char* argc[]) { sc_time PERIOD(10,SC_NS); sc_time DELAY(10,SC_NS); sc_clock clock("clock",PERIOD,0.5,DELAY,true); And and1("and1"); testbench tb("tb"); sc_signal<bool> a_sg,b_sg,c_sg; and1.a(a_sg); and1.b(b_sg); and1.c(c_sg); tb.a(a_sg); tb.b(b_sg); tb.c(c_sg); tb.clk(clock); sc_start(); return 0; }
/* * 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; };
/******************************************************************************** * 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. * *******************************************************************************/ /* * SystemManager.cpp * * Created on: 07 ott 2016 * Author: daniele */ #include <systemc.h> #include <iostream> #include <stdlib.h> #include <stdio.h> #include <vector> #include <string.h> #include "tl.h" #include "pugixml.hpp" #include "SystemManager.h" using namespace std; using namespace pugi; //////////////////////////// // SBM INDEPENDENT //////////////////////////// // Constructor SystemManager::SystemManager() { VPS = generateProcessInstances(); VCH = generateChannelInstances(); VBB = generateBBInstances(); VPL = generatePhysicalLinkInstances(); mappingPS(); mappingCH(); } // Fill process data structure VPS from xml file (application.xml) vector<Process> SystemManager:: generateProcessInstances(){ vector<Process> vps2; int exp_id = 0; int processId; pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(APPLICATION); xml_node instancesPS2 = doc.child("instancesPS"); for (pugi::xml_node xn_process = instancesPS2.first_child(); !xn_process.empty(); xn_process = xn_process.next_sibling()){ Process pi; // Process Name pi.setName(xn_process.child_value("name")); // Process id processId = atoi((char*) xn_process.child_value("id")); pi.setId(processId); // Process Priority pi.setPriority(atoi((char*) xn_process.child_value("priority"))); // Process Criticality pi.setCriticality(atoi((char*) xn_process.child_value("criticality"))); // Process eqGate (HW size) xml_node eqGate = xn_process.child("eqGate"); pi.setEqGate((float)eqGate.attribute("value").as_int()); // Process dataType pi.setDataType(atoi((char*) xn_process.child_value("dataType"))); // Process MemSize (SW Size) xml_node memSize = xn_process.child("memSize"); xml_node codeSize = memSize.child("codeSize"); for (pugi::xml_node processorModel = codeSize.child("processorModel"); processorModel; processorModel = processorModel.next_sibling()) { pi.setCodeSize( processorModel.attribute("name").as_string(), processorModel.attribute("value").as_int() ); } xml_node dataSize = memSize.child("dataSize"); for (pugi::xml_node processorModel = dataSize.child("processorModel"); processorModel; processorModel = processorModel.next_sibling()) { pi.setDataSize( processorModel.attribute("name").as_string(), processorModel.attribute("value").as_int() ); } // Process Affinity xml_node affinity = xn_process.child("affinity"); for (pugi::xml_node processorType = affinity.child("processorType"); processorType; processorType = processorType.next_sibling()) { string processorType_name = processorType.attribute("name").as_string(); float affinity_value = processorType.attribute("value").as_float(); pi.setAffinity(processorType_name, affinity_value); } // Process Concurrency xml_node concurrency = xn_process.child("concurrency"); for (pugi::xml_node xn_cprocessId = concurrency.child("processId"); xn_cprocessId; xn_cprocessId = xn_cprocessId.next_sibling()) { unsigned int process_id_n = xn_cprocessId.attribute("id").as_int(); float process_concurrency_value = xn_cprocessId.attribute("value").as_float(); pi.setConcurrency(process_id_n, process_concurrency_value); } // Process Load xml_node load = xn_process.child("load"); for (pugi::xml_node processorId = load.child("processorId"); processorId; processorId = processorId.next_sibling()) { unsigned int processor_id_n = processorId.attribute("id").as_int(); float process_load_value = processorId.attribute("value").as_float(); pi.setLoad(processor_id_n, process_load_value); } // Process time (init) pi.processTime = sc_time(0, SC_MS); // Process energy (init) pi.setEnergy(0); // Process Communication // TO DO if(processId == exp_id){ vps2.push_back(pi); exp_id++; } else { cout << "XML for application is corrupted\n"; exit(11); } } if(exp_id != NPS){ cout << "XML for application is corrupted (NPS)\n"; exit(11); } doc.reset(); return vps2; } // Fill channel data structure VCH from xml file vector<Channel> SystemManager:: generateChannelInstances() { vector<Channel> vch; // parsing xml file xml_document myDoc; xml_parse_result myResult = myDoc.load_file(APPLICATION); xml_node instancesLL = myDoc.child("instancesLL"); //channel parameters xml_node_iterator seqChannel_it; for (seqChannel_it=instancesLL.begin(); seqChannel_it!=instancesLL.end(); ++seqChannel_it){ xml_node_iterator channel_node_it = seqChannel_it->begin(); Channel ch; char* temp; // CH-NAME string name = channel_node_it->child_value(); ch.setName(name); // CH-ID channel_node_it++; temp = (char*) channel_node_it->child_value(); int id = atoi(temp); ch.setId(id); // writer ID channel_node_it++; temp = (char*) channel_node_it->child_value(); int w_id = atoi(temp); ch.setW_id(w_id); // reader ID channel_node_it++; temp = (char*) channel_node_it->child_value(); int r_id = atoi(temp); ch.setR_id(r_id); // CH-width (logical width) channel_node_it++; temp = (char*) channel_node_it->child_value(); int width = atoi(temp); ch.setWidth(width); ch.setNum(0); vch.push_back(ch); } return vch; } /* * for a given processID, increments the profiling variable * (the number of "loops" executed by the process) */ void SystemManager::PS_Profiling(int processId) { VPS[processId].profiling++; } // Check if a process is allocated on a SPP bool SystemManager::checkSPP(int processId) { return VBB[allocationPS_BB[processId]].getProcessors()[0].getProcessorType() == "SPP"; } // Return a subset of allocationPS by considering only processes mapped to BB with ID equal to bb_unit_id vector<int> SystemManager::getAllocationPS_BB(int bb_id) { vector<int> pu_alloc; for (unsigned int j = 2; j < allocationPS_BB.size(); j++) // 0 and 1 are the testbench { if (allocationPS_BB[j] == bb_id) pu_alloc.push_back(j); } return pu_alloc; } ///// UPDATE XML Concurrency and Communication void SystemManager::deleteConcXmlConCom() { pugi::xml_document myDoc; pugi::xml_parse_result myResult = myDoc.load_file("./XML/application.xml"); cout << "XML Delete result: " << myResult.description() << endl; //method 2: use object/node structure pugi::xml_node instancesPS = myDoc.child("instancesPS"); xml_node processes = instancesPS.child("process"); for (int i = 0; i < NPS; i++){ xml_node concom = processes.child("concurrency"); for (pugi::xml_node processorId = concom.child("processId"); processorId; processorId = processorId.next_sibling()) { concom.remove_child(processorId); } xml_node concom2 = processes.child("comunication"); for (pugi::xml_node processorId = concom2.child("rec"); processorId; processorId = processorId.next_sibling()) { concom2.remove_child(processorId); } processes = processes.next_sibling(); } xml_node instancesCH = myDoc.child("instancesLL"); xml_node processesCH = instancesCH.child("logical_link"); for (int i = 0; i < NCH; i++){ xml_node concom3 = processesCH.child("concurrency"); for (pugi::xml_node processorId = concom3.child("channelId"); processorId; processorId = processorId.next_sibling()) { concom3.remove_child(processorId); } processesCH = processesCH.next_sibling(); } myDoc.save_file("./XML/application.xml"); cout << endl; } void SystemManager::updateXmlConCom(float matrixCONC_PS_N[NPS][NPS], unsigned int matrixCOM[NPS][NPS], float matrixCONC_CH_N[NCH][NCH]) { pugi::xml_document myDoc; pugi::xml_parse_result myResult = myDoc.load_file("./XML/application.xml"); cout << "XML result: " << myResult.description() << endl; //method 2: use object/node structure pugi::xml_node instancesPS = myDoc.child("instancesPS"); for (xml_node_iterator seqProcess_it = instancesPS.begin(); seqProcess_it != instancesPS.end(); ++seqProcess_it){ int Id = atoi(seqProcess_it->child_value("id")); if (seqProcess_it->child("concurrency")){ pugi::xml_node concurrency = seqProcess_it->child("concurrency"); for (int i = 0; i<NPS; i++){ if (i != Id){ pugi::xml_node conc_it = concurrency.append_child("processId"); conc_it.append_attribute("id").set_value(i); conc_it.append_attribute("value").set_value(matrixCONC_PS_N[Id][i]); } } } else{ pugi::xml_node concurrency = seqProcess_it->append_child("concurrency"); for (int i = 0; i<NPS; i++){ if (i != Id){ pugi::xml_node conc_it = concurrency.append_child("processId"); conc_it.append_attribute("id").set_value(i); conc_it.append_attribute("value").set_value(matrixCONC_PS_N[Id][i]); } } } } //method 2: use object/node structure pugi::xml_node instancesCOM = myDoc.child("instancesPS"); for (pugi::xml_node_iterator seqProcess_it = instancesCOM.begin(); seqProcess_it != instancesCOM.end(); ++seqProcess_it){ int Id = atoi(seqProcess_it->child_value("id")); if (seqProcess_it->child("comunication")){ pugi::xml_node comunication = seqProcess_it->child("comunication"); for (int i = 0; i<NPS; i++){ if (i != Id){ pugi::xml_node com_it = comunication.append_child("rec"); com_it.append_attribute("idRec").set_value(i); com_it.append_attribute("value").set_value(matrixCOM[Id][i]); } } } else{ pugi::xml_node comunication = seqProcess_it->append_child("comunication"); for (int i = 0; i<NPS; i++){ if (i != Id){ pugi::xml_node com_it = comunication.append_child("rec"); com_it.append_attribute("idRec").set_value(i); com_it.append_attribute("value").set_value(matrixCOM[Id][i]); } } } } pugi::xml_node instancesLL = myDoc.child("instancesLL"); for (xml_node_iterator seqLink_it = instancesLL.begin(); seqLink_it != instancesLL.end(); ++seqLink_it){ int Id = atoi(seqLink_it->child_value("id")); if (seqLink_it->child("concurrency")){ pugi::xml_node concurrencyL = seqLink_it->child("concurrency"); for (int i = 0; i<NCH; i++){ if (i != Id){ pugi::xml_node concL_it = concurrencyL.append_child("channelId"); concL_it.append_attribute("id").set_value(i); concL_it.append_attribute("value").set_value(matrixCONC_CH_N[Id][i]); } } } else{ pugi::xml_node concurrencyL = seqLink_it->append_child("concurrency"); for (int i = 0; i<NCH; i++){ if (i != Id){ pugi::xml_node concL_it = concurrencyL.append_child("channelId"); concL_it.append_attribute("id").set_value(i); concL_it.append_attribute("value").set_value(matrixCONC_CH_N[Id][i]); } } } } cout << "Saving result: " << myDoc.save_file("./XML/application.xml") << endl; myDoc.reset(); cout << endl; } #if defined(_TIMING_ENERGY_) // Fill VBB data structure from xml file (instancesTL.xml) vector<BasicBlock> SystemManager::generateBBInstances(){ /***************************** * LOAD BASIC BLOCKS *****************************/ char* temp; vector<BasicBlock> vbb; // parsing xml file xml_document myDoc; xml_parse_result myResult = myDoc.load_file("./XML/instancesTL.xml"); xml_node instancesBB = myDoc.child("instancesBB"); for (xml_node_iterator seqBB_it=instancesBB.begin(); seqBB_it!=instancesBB.end(); ++seqBB_it){ xml_node_iterator BB_it = seqBB_it->begin(); BasicBlock bb; //BB-ID int id = atoi(BB_it->child_value()); bb.setId(id); //BB-NAME BB_it++; string BBname = BB_it->child_value(); bb.setName(BBname); //BB-TYPE BB_it++; string type = BB_it->child_value(); bb.setType(type); // PROCESSING UNIT BB_it++; vector<ProcessingUnit> vpu; for(xml_node child = seqBB_it->child("processingUnit");child;child= child.next_sibling("processingUnit")){ xml_node_iterator pu_it = child.begin(); ProcessingUnit pu; //PU-NAME string puName = pu_it->child_value(); pu.setName(puName); //PU-ID pu_it++; int idPU = atoi(pu_it->child_value()); pu.setId(idPU); //Processor Type pu_it++; string puType = pu_it->child_value(); pu.setProcessorType(puType); // PU-cost pu_it++; float idCost = (float) atof(pu_it->child_value()); pu.setCost(idCost); //PU-ISA pu_it++; string puISA = pu_it->child_value(); pu.setISA(puISA); // PU-Frequency (MHz) pu_it++; float idFreq = (float) atof(pu_it->child_value()); pu.setFrequency(idFreq); // PU-CC4CS float** array = new float*[5]; //Int8 pu_it++; float idCC4CSminint8 = (float) atof(pu_it->child_value()); pu_it++; float idCC4CSmaxint8 = (float) atof(pu_it->child_value()); //Int16 pu_it++; float idCC4CSminint16 = (float) atof(pu_it->child_value()); pu_it++; float idCC4CSmaxint16 = (float) atof(pu_it->child_value()); //Int32 pu_it++; float idCC4CSminint32 = (float) atof(pu_it->child_value()); pu_it++; float idCC4CSmaxint32 = (float) atof(pu_it->child_value()); //Float pu_it++; float idCC4CSminfloat = (float) atof(pu_it->child_value()); pu_it++; float idCC4CSmaxfloat = (float) atof(pu_it->child_value()); //Tot pu_it++; float idCC4CSmin = (float) atof(pu_it->child_value()); pu_it++; float idCC4CSmax = (float) atof(pu_it->child_value()); array[0] = new float[2]; array[0][0] = idCC4CSminint8; array[0][1] = idCC4CSmaxint8; array[1] = new float[2]; array[1][0] = idCC4CSminint16; array[1][1] = idCC4CSmaxint16; array[2] = new float[2]; array[2][0] = idCC4CSminint32; array[2][1] = idCC4CSmaxint32; array[3] = new float[2]; array[3][0] = idCC4CSminfloat; array[3][1] = idCC4CSmaxfloat; array[4] = new float[2]; array[4][0] = idCC4CSmin; array[4][1] = idCC4CSmax; pu.setCC4S(array); // PU-Power (W) pu_it++; float idPow = (float) atof(pu_it->child_value()); pu.setPower(idPow); // PU-MIPS pu_it++; float idMIPS = (float) atof(pu_it->child_value()); pu.setMIPS(idMIPS); // PU-I4CS pu_it++; float idI4CSmin = (float) atof(pu_it->child_value()); pu.setI4CSmin(idI4CSmin); pu_it++; float idI4CSmax = (float) atof(pu_it->child_value()); pu.setI4CSmax(idI4CSmax); // PU-Vdd (V) pu_it++; float idVdd = (float)atof(pu_it->child_value()); pu.setVdd(idVdd); // PU-Idd (A) pu_it++; float idIdd = (float)atof(pu_it->child_value()); pu.setIdd(idIdd); // PU-overheadCS (us) pu_it++; float idOver = (float)atof(pu_it->child_value()); pu.setOverheadCS(sc_time((int)idOver, SC_US)); vpu.push_back(pu); } // LOACL MEMORY bb.setProcessor(vpu); BB_it++; xml_node instancesLM = seqBB_it->child("localMemory"); xml_node_iterator lm_it = instancesLM.begin(); //CODE SIZE int lmCodeSize = (int)atof(lm_it->child_value()); bb.setCodeSize(lmCodeSize); //DATA SIZE lm_it++; int lmDataSize = (int)atof(lm_it->child_value()); bb.setDataSize(lmDataSize); //eQG lm_it++; temp = (char*)lm_it->child_value(); int lmEqG = (int)atof(temp); bb.setEqG(lmEqG); // Comunication BB_it++; xml_node instancesCU = seqBB_it->child("communicationUnit"); xml_node_iterator cu_it = instancesCU.begin(); // TO DO // Free Running time BB_it++; xml_node instancesFRT = seqBB_it->child("loadEstimation"); xml_node_iterator frt_it = instancesFRT.begin(); float lmFreeRunningTime = frt_it->attribute("value").as_float(); bb.setFRT(lmFreeRunningTime); vbb.push_back(bb); } return vbb; } #else /* This method generates a dummy instance of a basic block. Each BB contains more than one processing unit inside. */ vector<BasicBlock> SystemManager::generateBBInstances(){ vector<BasicBlock> vbb; for (int i = 0; i < NBB; i++){ BasicBlock bb; //BB-ID bb.setId(i); //BB-NAME bb.setName("dummy"); //BB-TYPE bb.setType("dummy"); // PROCESSING UNIT vector<ProcessingUnit> vpu; for (int j = 0; j < 4; j++){ // each block contains at most 4 pu ProcessingUnit pu; //PU-NAME pu.setName("dummy"); //PU-ID int idPU = j; pu.setId(idPU); //Processor Type pu.setProcessorType("dummy"); //// PU-cost //pu.setCost(0); //PU-ISA pu.setISA("dummy"); // PU-Frequency (MHz) pu.setFrequency(0); // PU-CC4CS float** array = new float*[5]; //TODO: eliminare **? //Int8 float idCC4CSminint8 = 0; float idCC4CSmaxint8 = 0; //Int16 float idCC4CSminint16 = 0; float idCC4CSmaxint16 = 0; //Int32 float idCC4CSminint32 = 0; float idCC4CSmaxint32 = 0; //Float float idCC4CSminfloat = 0; float idCC4CSmaxfloat = 0; //Tot float idCC4CSmin = 0; float idCC4CSmax = 0; //TODO: ciclo con tutti 0! array[0] = new float[2]; array[0][0] = idCC4CSminint8; array[0][1] = idCC4CSmaxint8; array[1] = new float[2]; array[1][0] = idCC4CSminint16; array[1][1] = idCC4CSmaxint16; array[2] = new float[2]; array[2][0] = idCC4CSminint32; array[2][1] = idCC4CSmaxint32; array[3] = new float[2]; array[3][0] = idCC4CSminfloat; array[3][1] = idCC4CSmaxfloat; array[4] = new float[2]; array[4][0] = idCC4CSmin; array[4][1] = idCC4CSmax; pu.setCC4S(array); // PU-Power (W) pu.setPower(0); // PU-MIPS float idMIPS = 0; pu.setMIPS(idMIPS); // PU-I4CS fl
oat idI4CSmin = 0; pu.setI4CSmin(idI4CSmin); float idI4CSmax = 0; pu.setI4CSmax(idI4CSmax); // PU-Vdd (V) float idVdd = 0; pu.setVdd(idVdd); // PU-Idd (A) float idIdd = 0; pu.setIdd(idIdd); // PU-overheadCS (us) float idOver = 0; pu.setOverheadCS(sc_time((int)idOver, SC_US)); vpu.push_back(pu); } bb.setProcessor(vpu); // LOCAL MEMORY //CODE SIZE bb.setCodeSize(0); //DATA SIZE bb.setDataSize(0); //eQG bb.setEqG(0); // Free Running time float lmFreeRunningTime = 0; bb.setFRT(lmFreeRunningTime); vbb.push_back(bb); } return vbb; } #endif #if defined(_TIMING_ENERGY_) // Fill link data structure VPL from xml file (instancesTL.xml) vector<PhysicalLink> SystemManager:: generatePhysicalLinkInstances() { vector<PhysicalLink> VPL; PhysicalLink l; // parsing xml file xml_document myDoc; xml_parse_result myResult = myDoc.load_file("./XML/instancesTL.xml"); xml_node instancesPL = myDoc.child("instancesPL"); //link parameters xml_node_iterator seqLink_it; for (seqLink_it=instancesPL.begin(); seqLink_it!=instancesPL.end(); ++seqLink_it){ xml_node_iterator link_node_it = seqLink_it->begin(); char* temp; // Link NAME string name = link_node_it->child_value(); l.setName(name); // Link ID link_node_it++; temp = (char*) link_node_it->child_value(); unsigned int id = atoi(temp); l.setId(id); // Link PHYSICAL WIDTH link_node_it++; temp = (char*) link_node_it->child_value(); unsigned int physical_width = atoi(temp); l.setPhysicalWidth(physical_width); // Link TCOMM link_node_it++; temp = (char*) link_node_it->child_value(); float tc = (float) atof(temp); sc_time tcomm(tc, SC_MS); l.setTcomm(tcomm); // Link TACOMM link_node_it++; temp = (char*) link_node_it->child_value(); float tac = (float) atof(temp); sc_time tacomm(tac, SC_MS); l.setTAcomm(tacomm); // Link BANDWIDTH link_node_it++; temp = (char*) link_node_it->child_value(); unsigned int bandwidth = atoi(temp); l.setBandwidth(bandwidth); // Link a2 (coefficient needed to compute energy of the communication) link_node_it++; temp = (char*) link_node_it->child_value(); float a2 = (float) atof(temp); l.seta2(a2); // Link a1 (coefficient needed to compute energy of the communication) link_node_it++; temp = (char*) link_node_it->child_value(); float a1 = (float) atof(temp); l.seta1(a1); VPL.push_back(l); } return VPL; } #else vector<PhysicalLink> SystemManager::generatePhysicalLinkInstances() { vector<PhysicalLink> VPL; for (int i = 0; i < NPL; i++){ PhysicalLink pl; pl.setId(i); pl.setName("dummy"); pl.physical_width=1; // width of the physical link pl.tcomm=sc_time(0, SC_MS); // LP: (bandwidth / phisycal_widht = 1/sec=hz (inverto)) ( per 1000) (non sforare i 5 ms) pl.tacomm=sc_time(0, SC_MS); // LP: tcomm * K (es:K=1) pl.bandwidth=0; // bandwidth in bit/s pl.a2=0; // a2 coefficient of energy curve pl.a1=0; // a1 coefficient of energy curve VPL.push_back(pl); } return VPL; } #endif #if defined(_TIMING_ENERGY_) // Fill allocationPS data structure from xml file void SystemManager:: mappingPS() { int exp_id = 0; // parsing xml file xml_document myDoc; xml_parse_result myResult = myDoc.load_file(MAPPING_PS_BB); xml_node mapping = myDoc.child("mapping"); //mapping parameters (process to processor) xml_node_iterator mapping_it; for (mapping_it=mapping.begin(); mapping_it!=mapping.end(); ++mapping_it){ xml_node_iterator child_mapping_it = mapping_it->begin(); int processId = child_mapping_it->attribute("PSid").as_int(); //string processorName = child_mapping_it->attribute("PRname").as_string(); string bbName = child_mapping_it->attribute("BBname").as_string(); int bbId = child_mapping_it->attribute("value").as_int(); int processingunitID = child_mapping_it->attribute("PUid").as_int(); //added ************** int partitionID = child_mapping_it->attribute("PTid").as_int(); //added ************** if(processId == exp_id){ allocationPS_BB.push_back(bbId); exp_id++; } else { cout << "XML for allocation is corrupted\n"; exit(11); } } } #else void SystemManager::mappingPS(){ for (int j = 0; j<NPS; j++){ int bbId = 0; allocationPS_BB.push_back(bbId); } } #endif #if defined(_TIMING_ENERGY_) // Fill allocationCH_PL data structure from xml file void SystemManager::mappingCH() { int exp_id = 0; // parsing xml file xml_document myDoc; xml_parse_result myResult = myDoc.load_file(MAPPING_LC_PL); xml_node mapping = myDoc.child("mapping"); //mapping parameters (channel to link) xml_node_iterator mapping_it; for (mapping_it=mapping.begin(); mapping_it!=mapping.end(); ++mapping_it){ xml_node_iterator child_mapping_it = mapping_it->begin(); int channelId = child_mapping_it->attribute("CHid").as_int(); string linkName = child_mapping_it->attribute("Lname").as_string(); int linkId = child_mapping_it->attribute("value").as_int(); if(channelId == exp_id){ allocationCH_PL.push_back(linkId); exp_id++; } else { cout << "XML for allocation is corrupted\n"; exit(11); } } } #else void SystemManager::mappingCH(){ for (int j = 0; j < NCH; j++){ int linkId = 0; allocationCH_PL.push_back(linkId); } } #endif ///// OTHER METHODS //////// // Evaluate the simulated time for the execution of a statement /* * for a given processID, returns the simulated time * (the time needed by processor, for the allocated process, to * to execute a statement) */ sc_time SystemManager:: updateSimulatedTime(int processId) { // Id representing process dominant datatype int dataType = VPS[processId].getDataType(); //*********************VPU WAS CHANGED IN VBB********************** float CC4Smin = VBB[allocationPS_BB[processId]].getProcessors()[0].getCC4S()[dataType][0]; // Average/min number of clock cycles needed by the PU to execute a C statement float CC4Smax = VBB[allocationPS_BB[processId]].getProcessors()[0].getCC4S()[dataType][1]; // Average/max number of clock cycles needed by the PU to execute a C statement // Affinity-based interpolation and round up of CC4CSaff unsigned int CC4Saff = (unsigned int) ceil(CC4Smin + ((CC4Smax-CC4Smin)*(1-VPS[processId].getAffinityByName(VBB[allocationPS_BB[processId]].getProcessors()[0].getProcessorType())))); float frequency = VBB[allocationPS_BB[processId]].getProcessors()[0].getFrequency(); // Frequency of the processor (MHz) sc_time value((CC4Saff/(frequency*1000)), SC_MS); // Average time (ms) needed to execute a C statement return value; } // The computation depends on the value setted for energyComputation (EPI or EPC) float SystemManager:: updateEstimatedEnergy(int processId) { float J4CS; float P; if(energyComputation == "EPC") { // EPC --> J4CS = CC4CSaff * EPC = CC4CSaff * (P/f) // Id representing process dominant datatype int dataType = VPS[processId].getDataType(); //I HAVE TO ADD A LOOP IN ORDER TO TAKE THE PARAMETERS OF EACH PROCESSOR (?) ********************** float CC4Smin = VBB[allocationPS_BB[processId]].getProcessors()[0].getCC4S()[dataType][0]; // Average/min number of clock cycles needed by the PU to execute a C statement //float CC4Smin = VBB[allocationPS_BB[processId]].getCC4S()[dataType][0]; // Average/min number of clock cycles needed by the PU to execute a C statement //float CC4Smax = VBB[allocationPS_BB[processId]].getCC4S()[dataType][1]; float CC4Smax = VBB[allocationPS_BB[processId]].getProcessors()[0].getCC4S()[dataType][1];// Average/max number of clock cycles needed by the PU to execute a C statement // Affinity-based interpolation float CC4Saff = CC4Smin + ((CC4Smax-CC4Smin)*(1-VPS[processId].getAffinityByName(VBB[allocationPS_BB[processId]].getProcessors()[0].getProcessorType()))); if(this->checkSPP(processId)) { // if the process is on a SPP (HW) --> P = Vdd * Idd (V*A = W) P = VBB[allocationPS_BB[processId]].getProcessors()[0].getVdd() * VBB[allocationPS_BB[processId]].getProcessors()[0].getIdd(); } else { // if the process is on a GPP/DSP (SW) --> P (W) P = VBB[allocationPS_BB[processId]].getProcessors()[0].getPower(); } // EPC = P/f (W/MHz = uJ) float EPC = P / VBB[allocationPS_BB[processId]].getProcessors()[0].getFrequency(); J4CS = CC4Saff * EPC; // uJ } else { // EPI if(this->checkSPP(processId)) { // if the process is on a SPP (HW) --> J4CS = CC4CSaff * P * (1/f) // Id representing process dominant datatype int dataType = VPS[processId].getDataType(); float CC4Smin = VBB[allocationPS_BB[processId]].getProcessors()[0].getCC4S()[dataType][0]; // Average/min number of clock cycles needed by the PU to execute a C statement float CC4Smax = VBB[allocationPS_BB[processId]].getProcessors()[0].getCC4S()[dataType][1]; // Average/max number of clock cycles needed by the PU to execute a C statement // Affinity-based interpolation float CC4Saff = CC4Smin + ((CC4Smax-CC4Smin)*(1-VPS[processId].getAffinityByName(VBB[allocationPS_BB[processId]].getProcessors()[0].getProcessorType()))); // P = Vdd * Idd (V*A = W) P = VBB[allocationPS_BB[processId]].getProcessors()[0].getVdd() * VBB[allocationPS_BB[processId]].getProcessors()[0].getIdd(); J4CS = CC4Saff * (P / VBB[allocationPS_BB[processId]].getProcessors()[0].getFrequency()); // uJ } else { // if the process is on a GPP/DSP (SW) --> J4CS = I4CSaff * EPI = I4CSaff * (P/MIPS) float I4CSmin = VBB[allocationPS_BB[processId]].getProcessors()[0].getI4CSmin(); // Average/min number of assembly instructions to execute a C statement float I4CSmax = VBB[allocationPS_BB[processId]].getProcessors()[0].getI4CSmax(); // Average/max number of assembly instructions to execute a C statement // Affinity-based interpolation float I4CSaff = I4CSmin + ((I4CSmax-I4CSmin)*(1-VPS[processId].getAffinityByName(VBB[allocationPS_BB[processId]].getProcessors()[0].getProcessorType()))); P = VBB[allocationPS_BB[processId]].getProcessors()[0].getPower(); // Watt // EPI = P/MIPS (uJ/instr) float EPI = P / VBB[allocationPS_BB[processId]].getProcessors()[0].getMIPS(); J4CS = I4CSaff * EPI; // uJ } } return J4CS; } // Increase processTime for each statement void SystemManager:: increaseSimulatedTime(int processId) { VPS[processId].processTime += updateSimulatedTime(processId); // Cumulated sum of the statement execution time } // Increase energy for each statement void SystemManager:: increaseEstimatedEnergy(int processId) { VPS[processId].energy += updateEstimatedEnergy(processId); // Cumulated sum of the statement execution energy } // Increase processTime for the wait of the timers void SystemManager::increaseTimer(int processId, sc_time delta) { VPS[processId].processTime += delta; // Cumulated sum of the statement execution time } // Energy XML Updates void SystemManager::deleteConcXmlEnergy(){ char* temp; int Id; pugi::xml_document myDoc; pugi::xml_parse_result myResult = myDoc.load_file("./XML/application.xml"); cout << "XML Delete result: " << myResult.description() << endl; //method 2: use object/node structure pugi::xml_node instancesPS = myDoc.child("instancesPS"); xml_node processes = instancesPS.child("process"); for(int i = 0; i < NPS; i++){ temp = (char*) processes.child_value("id"); Id = atoi(temp); //id process xml_node energy = processes.child("energy"); for (pugi::xml_node processorId = energy.child("processorId"); processorId; processorId = processorId.next_sibling()) { unsigned int processor_id_n = processorId.attribute("id").as_int();// float process_load_value = processorId.attribute("value").as_float();// if(allocationPS_BB[Id] == processor_id_n){ energy.remove_child(processorId); } } processes = processes.next_sibling(); } myDoc.save_file("./XML/application.xml"); cout<<endl; ///////////////////////////////////// pugi::xml_document myDoc2; pugi::xml_parse_result myResult2 = myDoc2.load_file("./XML/instancesTL.xml"); cout << "XML result: " << myResult2.description() << endl; pugi::xml_node instancesBB = myDoc2.child("instancesBB"); xml_node basicBlock = instancesBB.child("basicBlock"); for(int i = 0; i < NBB; i++){ temp = (char*) basicBlock.child_value("id"); Id = atoi(temp); //id process xml_node energyEst = basicBlock.child("energyEstimation"); for (pugi::xml_node energyTOT = energyEst.child("energyTOT"); energyTOT; energyTOT = energyTOT.next_sibling()) { unsigned int processor_id_n = energyTOT.attribute("id").as_int();// float energy_value = energyTOT.attribute("value").as_float();// if(Id == allocationPS_BB[2]){ energyEst.remove_child(energyTOT); } } basicBlock = basicBlock.next_sibling(); } cout << "Saving result: " << myDoc2.save_file("./XML/instancesTL.xml") << endl; cout<<endl; } void SystemManager:: updateXmlEnergy() { pugi::xml_document myDoc; pugi::xml_parse_result myResult = myDoc.load_file("./XML/application.xml"); cout << "XML result: " << myResult.description() << endl; //method 2: use object/node structure pugi::xml_node instancesPS = myDoc.child("instancesPS"); /////////////////////// ENERGY ////////////////////////////// pugi::xml_node instancesPS2 = myDoc.child("instancesPS"); float sumEnergyTot=0; for (xml_node_iterator seqProcess_it2=instancesPS2.begin(); seqProcess_it2!=instancesPS2.end(); ++seqProcess_it2){ int Id = atoi(seqProcess_it2->child_value("id")); if(seqProcess_it2->child("energy")){ pugi::xml_node energy = seqProcess_it2->child("energy"); pugi::xml_node energy_it = energy.append_child("processorId"); energy_it.append_attribute("id").set_value(allocationPS_BB[Id]); energy_it.append_attribute("value").set_value(VPS[Id].getEnergy()); }else{ pugi::xml_node energy = seqProcess_it2->append_child("energy"); pugi::xml_node energy_it = energy.append_child("processorId"); energy_it.append_attribute("id").set_value(allocationPS_BB[Id]); energy_it.append_attribute("value").set_value(VPS[Id].getEnergy()); } sumEnergyTot+=VPS[Id].getEnergy(); } cout << "Saving result: " << myDoc.save_file("./XML/application.xml") << endl; myDoc.reset(); cout<<endl; pugi::xml_document myDoc2; pugi::xml_parse_result myResult2 = myDoc2.load_file("./XML/instancesTL.xml"); cout << "XML result: " << myResult2.description() << endl; xml_node instancesBB = myDoc2.child("instancesBB"); for (xml_node_iterator seqBB_it=instancesBB.begin(); seqBB_it!=instancesBB.end(); ++seqBB_it){ int Id = atoi(seqBB_it->child_value("id")); ///////////////////// ENERGY //////////////////////// if(Id == allocationPS_BB[2]){ if(seqBB_it->child("energyEstimation")){ pugi::xml_node energyEstimation = seqBB_it->child("energyEstimation"); xml_node entot_node = energyEstimation.append_child("energyTOT"); entot_node.append_attribute("id").set_value(allocationPS_BB[2]); entot_node.append_attribute("value").set_value(sumEnergyTot); }else{ pugi::xml_node energyEstimation = seqBB_it->append_child("energyEstimation"); xml_node entot_node = energyEstimation.append_child("energyTOT"); entot_node.append_attribute("id").set_value(allocationPS_BB[2]); entot_node.append_attribute("value").set_value(sumEnergyTot); } } } cout << "Saving result: " << myDoc2.save_file("./XML/instancesTL.xml") << endl; myDoc2.reset(); cout<<endl; } // Load Metrics sc_time SystemManager::getFRT(){ return this->FRT; } void SystemManager::setFRT(sc_time x){ FRT = x; } float* SystemManager:: loadEst(sc_time FRT_n){ for(unsigned i =2; i<VPS.size(); i++){ FRL[i] = (float) ((VPS[i].processTime/VPS[i].profiling)/(FRT_n/VPS[i].profiling)); // } return FRL; } float* SystemManager:: getFRL(){ return this->FRL; } // Load XML Updates void SystemManager::deleteConcXmlLoad(){ char* temp; int Id; pugi::xml_document myDoc; pugi::xml_parse_result myResult = myDoc.load_file("./XML/application.xml"); cout << "XML Delete result: " << myResult.description() << endl; //method 2: use object/node structure pugi::xml_node instancesPS = myDoc.child("instancesPS"); xml_node processes = instancesPS.child("process"); for(int i = 0; i < NPS; i++){ temp = (char*) processes.child_value("id"); Id = atoi(temp); //id process xml_node load = processes.child("load"); for (pugi::xml_node processorId = load.child("processorId"); processorId; processorId = processorId.next_sibling()) { unsigned int processor_id_n = processorId.attribute("id").as_int();// float process_load_value = processorId.attribute("value").as_float();// if(allocationPS_BB[Id] == processor_id_n){ load.remove_child(processorId); } } /* xml_node WCET = processes.child("WCET"); for (pugi::xml_node processorId = WCET.child("processorId"); processorId; processorId = processorId.next_sibling()) { WCET.remove_child(processorId); } xml_node Period = processes.child("Period"); for (pugi::xml_node processorId = Period.child("processorId"); processorId; processorId = processorId.next_sibling()) { Period.remove_child(processorId); } xml_node Deadline = processes.child("Deadline"); for (pugi::xml_node processorId = Deadline.child("processorId"); processorId; processorId = processorId.next_sibling()) { Deadline.remove_child(processorId); } */ processes = processes.next_sibling(); } myDoc.save_file("./XML/application.xml"); cout<<endl; pugi::xml_document myDoc2; pugi::xml_parse_result myResult2 = myDoc2.load_file("./XML/instancesTL.xml"); cout << "XML result: " << myResult2.description() << endl; pugi::xml_node instancesBB = myDoc2.child("instancesBB"); xml_node basicBlock = instancesBB.child("basicBlock"); for(int i = 0; i < NBB; i++){ temp = (char*) basicBlock.child_value("id"); Id = atoi(temp); //id process xml_node loadEst = basicBlock.child("loadEstimation"); for (pugi::xml_node loadTOT = loadEst.child("FreeRunningTime"); loadTOT; loadTOT = loadTOT.next_sibling()) { unsigned int processor_id_n = loadTOT.attribute("id").as_int();// float energy_value = loadTOT.attribute("value").as_float();// if(Id == allocationPS_BB[2]){ loadEst.remove_child(loadTOT); } } basicBlock = basicBlock.next_sibling(); } cout << "Saving result: " << myDoc2.save_file("./XML/instancesTL.xml") << endl; myDoc2.reset(); cout<<endl; } void SystemManager:: updateXmlLoad() { pugi::xml_document myDoc; pugi::xml_parse_result myResult = myDoc.load_file("./XML/application.xml"); cout << "XML result: " << myResult.description() << endl; //method 2: use object/node structure pugi::xml_node instancesPS = myDoc.child("instancesPS"); for (xml_node_iterator seqProcess_it=instancesPS.begin(); seqProcess_it!=instancesPS.end(); ++seqProcess_it){ int Id = atoi(seqProcess_it->child_value("id")); ///////////////////// LOAD //////////////////////////// if(seqProcess_it->child("load")){ pugi::xml_node load = seqProcess_it->child("load"); pugi::xml_node load_it = load.append_child("processorId"); load_it.append_attribute("id").set_value(allocationPS_BB[Id]); load_it.append_attribute("value").set_value(FRL[Id]); }else{ pugi::xml_node load = seqProcess_it->append_child("load"); pugi::xml_node load_it = load.append_child("processorId"); load_it.append_attribute("id").set_value(allocationPS_BB[Id]); load_it.append_attribute("value").set_value(FRL[Id]); } } /////////////////////// WCET ////////////////////////////// ////method 2: use
object/node structure //pugi::xml_node instancesPS2 = myDoc.child("instancesPS"); //for (pugi::xml_node_iterator seqProcess_it=instancesPS2.begin(); seqProcess_it!=instancesPS2.end(); ++seqProcess_it){ // int Id = atoi(seqProcess_it->child_value("id")); // // if(seqProcess_it->child("WCET")){ // pugi::xml_node comunication = seqProcess_it->child("WCET"); // for (int i=0; i<NPS; i++){ // if(i!=Id){ // pugi::xml_node wcet_it = comunication.append_child("processorId"); // double wcet_task = (VPS[Id].processTime.to_seconds()); // wcet_it.append_attribute("id").set_value(i); // wcet_it.append_attribute("value").set_value((wcet_task/VPS[Id].profiling)*1000000.0); // } // } // }else{ // pugi::xml_node WCET = seqProcess_it->append_child("WCET"); // for (int i=0; i<VPU.size(); i++){ // if(i!=Id){ // pugi::xml_node wcet_it = WCET.append_child("processorId"); // double wcet_task = (VPS[Id].processTime.to_seconds()); // wcet_it.append_attribute("id").set_value(i); // wcet_it.append_attribute("value").set_value((wcet_task/VPS[Id].profiling)*1000000.0); // } // } // } //} /////////////////////// PERIOD ////////////////////////////// //pugi::xml_node instancesPS3 = myDoc.child("instancesPS"); //for (xml_node_iterator seqLink_it=instancesPS3.begin(); seqLink_it!=instancesPS3.end(); ++seqLink_it){ // int Id = atoi(seqLink_it->child_value("id")); // // if(seqLink_it->child("Period")){ // pugi::xml_node Period = seqLink_it->child("Period"); // for (int i=0; i<NPS; i++){ // if(i!=Id){ // pugi::xml_node period_it = Period.append_child("processorId"); // period_it.append_attribute("id").set_value(i); // double period_value = (FRT.to_seconds()); // period_it.append_attribute("value").set_value((period_value/VPS[Id].profiling)*1000000.0); // } // } // }else{ // pugi::xml_node Period = seqLink_it->append_child("Period"); // for (int i=0; i<NPS; i++){ // if(i!=Id){ // pugi::xml_node period_it = Period.append_child("processorId"); // period_it.append_attribute("id").set_value(i); // double period_value = (FRT.to_seconds()); // period_it.append_attribute("value").set_value((period_value/VPS[Id].profiling)*1000000.0); // } // } // } //} ///////////////////////// DEADLINE ////////////////////////////// // pugi::xml_node instancesPS4 = myDoc.child("instancesPS"); //for (xml_node_iterator seqLink_it=instancesPS4.begin(); seqLink_it!=instancesPS4.end(); ++seqLink_it){ // int Id = atoi(seqLink_it->child_value("id")); // if(seqLink_it->child("Deadline")){ // pugi::xml_node Deadline = seqLink_it->child("Deadline"); // for (int i=0; i<NPS; i++){ // if(i!=Id){ // pugi::xml_node dead_it = Deadline.append_child("processorId"); // dead_it.append_attribute("id").set_value(i); // double deadline_value = (FRT.to_seconds()); // double dead_tot = (deadline_value/VPS[Id].profiling)*1000000.0; // cout<<"VPS["<<Id<<"].profiling --> "<<VPS[Id].profiling<<endl; // dead_it.append_attribute("value").set_value(dead_tot); // } // } // }else{ // pugi::xml_node Deadline = seqLink_it->append_child("Deadline"); // for (int i=0; i<NPS; i++){ // if(i!=Id){ // pugi::xml_node dead_it = Deadline.append_child("processorId"); // dead_it.append_attribute("id").set_value(i); // double deadline_value = (FRT.to_seconds()); // double dead_tot = (deadline_value/VPS[Id].profiling)*1000000.0; // dead_it.append_attribute("value").set_value(dead_tot); // } // } // } //} cout << "Saving result: " << myDoc.save_file("./XML/application.xml") << endl; myDoc.reset(); cout<<endl; /* pugi::xml_document myDoc2; pugi::xml_parse_result myResult2 = myDoc2.load_file("./XML/instancesTL.xml"); cout << "XML result: " << myResult2.description() << endl; xml_node instancesBB = myDoc2.child("instancesBB"); for (xml_node_iterator seqBB_it=instancesBB.begin(); seqBB_it!=instancesBB.end(); ++seqBB_it){ int Id = atoi(seqBB_it->child_value("id")); ///////////////////// LOAD //////////////////////////// if(seqBB_it->child("loadEstimation")){ pugi::xml_node loadEstimation = seqBB_it->child("loadEstimation"); xml_node frl_node = loadEstimation.child("FreeRunningTime"); if(!(allocationPS_BB[Id] != Id)) { sc_time local_frt = FRT; //frl_node.attribute("value")=(local_frt.to_double()*1000); //another solution for the number conversion frl_node.attribute("value")=(local_frt.to_seconds()*1000); } }else{ pugi::xml_node loadEstimation = seqBB_it->append_child("loadEstimation"); xml_node frl_node = loadEstimation.append_child("FreeRunningTime"); if(allocationPS_BB[Id] == Id) { sc_time local_frt = FRT; //frl_node.attribute("value")=(local_frt.to_double()*1000); //another solution for the number conversion frl_node.attribute("value")=(local_frt.to_seconds()*1000); } } } cout << "Saving result: " << myDoc2.save_file("./XML/instancesTL.xml") << endl; myDoc2.reset(); cout<<endl; */ /////////////////////////////////////////////////// pugi::xml_document myDoc2; pugi::xml_parse_result myResult2 = myDoc2.load_file("./XML/instancesTL.xml"); cout << "XML result: " << myResult2.description() << endl; xml_node instancesBB = myDoc2.child("instancesBB"); for (xml_node_iterator seqBB_it=instancesBB.begin(); seqBB_it!=instancesBB.end(); ++seqBB_it){ int Id = atoi(seqBB_it->child_value("id")); ///////////////////// ENERGY //////////////////////// if(Id == allocationPS_BB[2]){ if(seqBB_it->child("loadEstimation")){ pugi::xml_node energyEstimation = seqBB_it->child("loadEstimation"); xml_node entot_node = energyEstimation.append_child("FreeRunningTime"); entot_node.append_attribute("id").set_value(allocationPS_BB[2]); sc_time local_frt = FRT; entot_node.append_attribute("value").set_value(local_frt.to_seconds()*1000); }else{ pugi::xml_node energyEstimation = seqBB_it->append_child("energyEstimation"); xml_node entot_node = energyEstimation.append_child("energyTOT"); entot_node.append_attribute("id").set_value(allocationPS_BB[2]); sc_time local_frt = FRT; entot_node.append_attribute("value").set_value(local_frt.to_seconds()*1000); } } } cout << "Saving result: " << myDoc2.save_file("./XML/instancesTL.xml") << endl; myDoc2.reset(); cout<<endl; }
/******************************************************************************** * 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 <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <unistd.h> ////////////////////////////// GENANN ////////////////// #ifdef __cplusplus extern "C" { #endif #ifndef ann_04_GENANN_RANDOM /* We use the following for uniform random numbers between 0 and 1. * If you have a better function, redefine this macro. */ #define ann_04_GENANN_RANDOM() (((double)rand())/RAND_MAX) #endif struct ann_04_genann; typedef double (*ann_04_genann_actfun)(const struct ann_04_genann *ann, double a); typedef struct ann_04_genann { /* How many inputs, outputs, and hidden neurons. */ int inputs, hidden_layers, hidden, outputs; /* Which activation function to use for hidden neurons. Default: gennann_act_sigmoid_cached*/ ann_04_genann_actfun activation_hidden; /* Which activation function to use for output. Default: gennann_act_sigmoid_cached*/ ann_04_genann_actfun activation_output; /* Total number of weights, and size of weights buffer. */ int total_weights; /* Total number of neurons + inputs and size of output buffer. */ int total_neurons; /* All weights (total_weights long). */ double *weight; /* Stores input array and output of each neuron (total_neurons long). */ double *output; /* Stores delta of each hidden and output neuron (total_neurons - inputs long). */ double *delta; } ann_04_genann; #ifdef __cplusplus } #endif ///////////////////////////////////// GENANN /////////////////////////// #ifndef ann_04_genann_act #define ann_04_genann_act_hidden ann_04_genann_act_hidden_indirect #define ann_04_genann_act_output ann_04_genann_act_output_indirect #else #define ann_04_genann_act_hidden ann_04_genann_act #define ann_04_genann_act_output ann_04_genann_act #endif #define ann_04_LOOKUP_SIZE 4096 double ann_04_genann_act_hidden_indirect(const struct ann_04_genann *ann, double a) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return ann->activation_hidden(ann, a); } double ann_04_genann_act_output_indirect(const struct ann_04_genann *ann, double a) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return ann->activation_output(ann, a); } const double ann_04_sigmoid_dom_min = -15.0; const double ann_04_sigmoid_dom_max = 15.0; double ann_04_interval; double ann_04_lookup[ann_04_LOOKUP_SIZE]; #ifdef __GNUC__ #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #define unused __attribute__((unused)) #else #define likely(x) x #define unlikely(x) x #define unused #pragma warning(disable : 4996) /* For fscanf */ #endif double ann_04_genann_act_sigmoid(const ann_04_genann *ann unused, double a) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) if (a < -45.0) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return 0; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) if (a > 45.0) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return 1; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return 1.0 / (1 + exp(-a)); } void ann_04_genann_init_sigmoid_lookup(const ann_04_genann *ann) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) const double f = (ann_04_sigmoid_dom_max - ann_04_sigmoid_dom_min) / ann_04_LOOKUP_SIZE; HEPSY_S(ann_04_id) int i; HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) ann_04_interval = ann_04_LOOKUP_SIZE / (ann_04_sigmoid_dom_max - ann_04_sigmoid_dom_min); HEPSY_S(ann_04_id) for (i = 0; i < ann_04_LOOKUP_SIZE; ++i) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) ann_04_lookup[i] = ann_04_genann_act_sigmoid(ann, ann_04_sigmoid_dom_min + f * i); HEPSY_S(ann_04_id) } } double ann_04_genann_act_sigmoid_cached(const ann_04_genann *ann unused, double a) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) assert(!isnan(a)); HEPSY_S(ann_04_id) if (a < ann_04_sigmoid_dom_min) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return ann_04_lookup[0]; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) if (a >= ann_04_sigmoid_dom_max) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return ann_04_lookup[ann_04_LOOKUP_SIZE - 1]; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) size_t j = (size_t)((a-ann_04_sigmoid_dom_min)*ann_04_interval+0.5); /* Because floating point... */ HEPSY_S(ann_04_id) if (unlikely(j >= ann_04_LOOKUP_SIZE)) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return ann_04_lookup[ann_04_LOOKUP_SIZE - 1]; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) return ann_04_lookup[j]; } double ann_04_genann_act_linear(const struct ann_04_genann *ann unused, double a) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return a; } double ann_04_genann_act_threshold(const struct ann_04_genann *ann unused, double a) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return a > 0; } void ann_04_genann_randomize(ann_04_genann *ann) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) int i; HEPSY_S(ann_04_id) for (i = 0; i < ann->total_weights; ++i) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) double r = ann_04_GENANN_RANDOM(); /* Sets weights from -0.5 to 0.5. */ HEPSY_S(ann_04_id) ann->weight[i] = r - 0.5; HEPSY_S(ann_04_id) } } ann_04_genann *ann_04_genann_init(int inputs, int hidden_layers, int hidden, int outputs) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) if (hidden_layers < 0) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return 0; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) if (inputs < 1) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return 0; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) if (outputs < 1) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return 0; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) if (hidden_layers > 0 && hidden < 1) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return 0; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) const int hidden_weights = hidden_layers ? (inputs+1) * hidden + (hidden_layers-1) * (hidden+1) * hidden : 0; HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) const int output_weights = (hidden_layers ? (hidden+1) : (inputs+1)) * outputs; HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) const int total_weights = (hidden_weights + output_weights); HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) const int total_neurons = (inputs + hidden * hidden_layers + outputs); /* Allocate extra size for weights, outputs, and deltas. */ HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) const int size = sizeof(ann_04_genann) + sizeof(double) * (total_weights + total_neurons + (total_neurons - inputs)); HEPSY_S(ann_04_id) ann_04_genann *ret = (ann_04_genann *)malloc(size); HEPSY_S(ann_04_id) if (!ret) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return 0; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) ret->inputs = inputs; HEPSY_S(ann_04_id) ret->hidden_layers = hidden_layers; HEPSY_S(ann_04_id) ret->hidden = hidden; HEPSY_S(ann_04_id) ret->outputs = outputs; HEPSY_S(ann_04_id) ret->total_weights = total_weights; HEPSY_S(ann_04_id) ret->total_neurons = total_neurons; /* Set pointers. */ HEPSY_S(ann_04_id) ret->weight = (double*)((char*)ret + sizeof(ann_04_genann)); HEPSY_S(ann_04_id) ret->output = ret->weight + ret->total_weights; HEPSY_S(ann_04_id) ret->delta = ret->output + ret->total_neurons; HEPSY_S(ann_04_id) ann_04_genann_randomize(ret); HEPSY_S(ann_04_id) ret->activation_hidden = ann_04_genann_act_sigmoid_cached; HEPSY_S(ann_04_id) ret->activation_output = ann_04_genann_act_sigmoid_cached; HEPSY_S(ann_04_id) ann_04_genann_init_sigmoid_lookup(ret); HEPSY_S(ann_04_id) return ret; } void ann_04_genann_free(ann_04_genann *ann) {HEPSY_S(ann_04_id) /* The weight, output, and delta pointers go to the same buffer. */ HEPSY_S(ann_04_id) free(ann); } //genann *genann_read(FILE *in) //genann *genann_copy(genann const *ann) double const *ann_04_genann_run(ann_04_genann const *ann, double const *inputs) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) double const *w = ann->weight; HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) double *o = ann->output + ann->inputs; HEPSY_S(ann_04_id) double const *i = ann->output; /* Copy the inputs to the scratch area, where we also store each neuron's * output, for consistency. This way the first layer isn't a special case. */ HEPSY_S(ann_04_id) memcpy(ann->output, inputs, sizeof(double) * ann->inputs); HEPSY_S(ann_04_id) int h, j, k; HEPSY_S(ann_04_id) if (!ann->hidden_layers) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) double *ret = o; HEPSY_S(ann_04_id) for (j = 0; j < ann->outputs; ++j) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) double sum = *w++ * -1.0; HEPSY_S(ann_04_id) for (k = 0; k < ann->inputs; ++k) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) sum += *w++ * i[k]; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) *o++ = ann_04_genann_act_output(ann, sum); HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) return ret; HEPSY_S(ann_04_id) } /* Figure input layer */ HEPSY_S(ann_04_id) for (j = 0; j < ann->hidden; ++j) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) double sum = *w++ * -1.0; HEPSY_S(ann_04_id) for (k = 0; k < ann->inputs; ++k) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) sum += *w++ * i[k]; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) *o++ = ann_04_genann_act_hidden(ann, sum); HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) i += ann->inputs; /* Figure hidden layers, if any. */ HEPSY_S(ann_04_id) for (h = 1; h < ann->hidden_layers; ++h) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) for (j = 0; j < ann->hidden; ++j) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) double sum = *w++ * -1.0; HEPSY_S(ann_04_id) for (k = 0; k < ann->hidden; ++k) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) sum += *w++ * i[k]; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) *o++ = ann_04_genann_act_hidden(ann, sum); HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) i += ann->hidden; HEPSY_S(ann_04_id) } double const *ret = o; /* Figure output layer. */ for (j = 0; j < ann->outputs; ++j) { double sum = *w++ * -1.0; for (k = 0; k < ann->hidden; ++k) { sum += *w++ * i[k]; } *o++ = ann_04_genann_act_output(ann, sum); } /* Sanity check that we used all weights and wrote all outputs. */ assert(w - ann->weight == ann->total_weights); assert(o - ann->output == ann->total_neurons); return ret; } //void genann_train(genann const *ann, double const *inputs, double const *desired_outputs, double learning_rate) //void genann_write(genann const *ann, FILE *out) /////////////////////// ANN //////////////////////// #define ann_04_NUM_DEV 1 // The equipment is composed of NUM_DEV devices ... //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- #define ann_04_MAX_ANN 100 // Maximum MAX_ANN ANN #define ann_04_ANN_INPUTS 2 // Number of inputs #define ann_04_ANN_HIDDEN_LAYERS 1 // Number of hidden layers #define ann_04_ANN_HIDDEN_NEURONS 2 // Number of neurons of every hidden layer #define ann_04_ANN_OUTPUTS 1 // Number of outputs //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- #define ann_04_ANN_EPOCHS 10000 #define ann_04_ANN_DATASET 6 #define ann_04_ANN_LEARNING_RATE 3 // ... //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- #define ann_04_MAX_ERROR 0.00756 // 0.009 //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- static int ann_04_nANN = -1 ; // Number of ANN that have been created static ann_04_genann * ann_04_ann[ann_04_MAX_ANN] ; // Now up to MAX_ANN ann //static double ann_04_trainingInput[ann_04_ANN_DATASET][ann_04_ANN_INPUTS] = { {0, 0}, {0, 1}, {1, 0}, {1, 1}, {0, 1}, {0, 0} } ; //static double ann_04_trainingExpected[ann_04_ANN_DATASET][ann_04_ANN_OUTPUTS] = { {0}, {1}, {1}, {0}, {1}, {0} } ; static double ann_04_weights[] = { -3.100438, -7.155774, -7.437955, -8.132828, -5.583678, -5.327152, 5.564897, -12.201226, 11.771879 } ; // static double input[4][3] = {{0, 0, 1}, {0, 1, 1}, {1, 0, 1}, {1, 1, 1}}; // static double output[4] = {0, 1, 1, 0}; //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- static int ann_04_annCheck(int index); static int ann_04_annCreate(int n); //----------------------------------------------------------------------------- // Check the correctness of the index of the ANN //----------------------------------------------------------------------------- int ann_04_annCheck(int index) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) if ( (index < 0) || (index >= ann_04_nANN) ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return( EXIT_FAILURE ); HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) return( EXIT_SUCCESS ); } //----------------------------------------------------------------------------- // Create n ANN //----------------------------------------------------------------------------- int ann_04_annCreate(int n) {HEPSY_S(ann_04_id) // If already created, or not legal number, or too many ANN, then error HEPSY_S(ann_04_id) if ( (ann_04_nANN != -1) || (n <= 0) || (n > ann_04_MAX_ANN) ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return( EXIT_FAILURE ); HEPSY_S(ann_04_id) } // Create the ANN's HEPSY_S(ann_04_id) for ( int i = 0; i < n; i++ ) {HEPSY_S(ann_04_id) // New ANN with ANN_INPUT inputs, ANN_HIDDEN_LAYER hidden layers all with ANN_HIDDEN_NEURON neurons, and ANN_OUTPUT outputs HEPSY_S(ann_04_id) ann_04_ann[i] = ann_04_genann_init(ann_04_ANN_INPUTS, ann_04_ANN_HIDDEN_LAYERS, ann_04_ANN_HIDDEN_NEURONS, ann_04_ANN_OUTPUTS); HEPSY_S(ann_04_id) if( ann_04_ann[i] == 0 ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) for (int j = 0; j < i; j++) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) ann_04_genann_free(ann_04_ann[j]) ; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) return( EXIT_FAILURE ); HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) ann_04_nANN = n ; HEPSY_S(ann_04_id) return( EXIT_SUCCESS ); } ////----------------------------------------------------------------------------- //// Create and train n identical ANN ////----------------------------------------------------------------------------- //int annCreateAndTrain(int n) //{ // if ( annCreate(n) != EXIT_SUCCESS ) // return( EXIT_FAILURE ); // // // Train the ANN's // for ( int index = 0; index < nANN; index++ ) // for ( int i = 0; i < ANN_EPOCHS; i++ ) // for ( int j = 0; j < ANN_DATASET; j++ ) // genann_train(ann[index], trainingInput[j], trainingExpected[j], ANN_LEARNING_RATE) ; // // return( EXIT_SUCCESS ); //} //----------------------------------------------------------------------------- // Create n identical ANN and set their weight //----------------------------------------------------------------------------- int ann_04_annCreateAndSetWeights(int n) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) if( ann_04_annCreate(n) != EXIT_SUCCESS ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return( EXIT_FAILURE ); HEPSY_S(ann_04_id) } // Set weights HEPSY_S(ann_04_id) for ( int index = 0; index < ann_04_nANN; index++ ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) for ( int i = 0; i < ann_04_ann[index]->total_weights; ++i ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) ann_04_ann[index]->weight[i] = ann_04_weights[i] ; HEPSY_S(ann_04_id)} HEPSY_S(ann_04_id)} HEPSY_S(ann_04_id) return( EXIT_SUCCESS ); } //----------------------------------------------------------------------------- // x[2] = x[0] XOR x[1] //----------------------------------------------------------------------------- int ann_04_annRun(int index, double x[ann_04_ANN_INPUTS + ann_04_ANN_OUTPUTS]) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) if( ann_04_annCheck(index) != EXIT_SUCCESS ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return( EXIT_FAILURE ) ; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) x[2] = * ann_04_genann_run(ann_04_ann[index], x) ; HEPSY_S(ann_04_id) return( EXIT_SUCCESS ); } ////----------------------------------------------------------------------------- //// ////----------------------------------------------------------------------------- //int annPrintWeights(int index) //{ // if ( annCheck(index) != EXIT_SUCCESS ) // return( EXIT_FAILURE ) ; // // // printf("\n*** ANN index = %d\n", index) ; // for ( int i = 0; i < ann[index]->total_weights; ++i ) // printf("*** w%d = %f\n", i, ann[index]->weight[i]) ; // // return( EXIT_SUCCESS ); //} ////----------------------------------------------------------------------------- //// Run the index-th ANN k time on random input and return the numb
er of error ////----------------------------------------------------------------------------- //int annTest(int index, int k) //{ // int x0; int x1; int y; // double x[2]; // double xor_ex; // int error = 0; // // if ( annCheck(index) != EXIT_SUCCESS ) // return( -1 ); // less than zero errors <==> the ANN isn't correctly created // // for (int i = 0; i < k; i++ ) // { // x0 = rand() % 2; x[0] = (double)x0; // x1 = rand() % 2; x[1] = (double)x1; // y = x0 ^ x1 ; // // xor_ex = * genann_run(ann[index], x); // if ( fabs(xor_ex - (double)y) > MAX_ERROR ) // { // error++ ; // printf("@@@ Error: ANN = %d, step = %d, x0 = %d, x1 = %d, y = %d, xor_ex = %f \n", index, i, x0, x1, y, xor_ex) ; // } // } // // if ( error ) // printf("@@@ ANN = %d: N� of errors = %d\n", index, error) ; // else // printf("*** ANN = %d: Test OK\n",index) ; // return( error ); //} //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void ann_04_annDestroy(void) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) if ( ann_04_nANN == -1 ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) return ; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) for ( int index = 0; index < ann_04_nANN; index++ ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) ann_04_genann_free(ann_04_ann[index]) ; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) ann_04_nANN = -1 ; } void mainsystem::ann_04_main() { // datatype for channels cleanData_xx_ann_xx_payload cleanData_xx_ann_xx_payload_var; ann_xx_dataCollector_payload ann_xx_dataCollector_payload_var; double x[ann_04_ANN_INPUTS + ann_04_ANN_OUTPUTS] ; //int ann_04_index = 1; HEPSY_S(ann_04_id) if( ann_04_annCreateAndSetWeights(ann_04_NUM_DEV) != EXIT_SUCCESS ) {HEPSY_S(ann_04_id) // Create and init ANN HEPSY_S(ann_04_id) printf("Error Weights \n"); HEPSY_S(ann_04_id) } //implementation HEPSY_S(ann_04_id) while(1) {HEPSY_S(ann_04_id) // content HEPSY_S(ann_04_id) cleanData_xx_ann_xx_payload_var = cleanData_04_ann_04_channel->read(); HEPSY_S(ann_04_id) ann_xx_dataCollector_payload_var.dev = cleanData_xx_ann_xx_payload_var.dev; HEPSY_S(ann_04_id) ann_xx_dataCollector_payload_var.step = cleanData_xx_ann_xx_payload_var.step; HEPSY_S(ann_04_id) ann_xx_dataCollector_payload_var.ex_time = cleanData_xx_ann_xx_payload_var.ex_time; HEPSY_S(ann_04_id) ann_xx_dataCollector_payload_var.device_i = cleanData_xx_ann_xx_payload_var.device_i; HEPSY_S(ann_04_id) ann_xx_dataCollector_payload_var.device_v = cleanData_xx_ann_xx_payload_var.device_v; HEPSY_S(ann_04_id) ann_xx_dataCollector_payload_var.device_t = cleanData_xx_ann_xx_payload_var.device_t; HEPSY_S(ann_04_id) ann_xx_dataCollector_payload_var.device_r = cleanData_xx_ann_xx_payload_var.device_r; HEPSY_S(ann_04_id) x[0] = cleanData_xx_ann_xx_payload_var.x_0; HEPSY_S(ann_04_id) x[1] = cleanData_xx_ann_xx_payload_var.x_1; HEPSY_S(ann_04_id) x[2] = cleanData_xx_ann_xx_payload_var.x_2; //u = cleanData_xx_ann_xx_payload_var.step; HEPSY_S(ann_04_id) ann_xx_dataCollector_payload_var.fault = cleanData_xx_ann_xx_payload_var.fault; //RUN THE ANN... // ### P R E D I C T (simple XOR) // if ( annRun(index, x) != EXIT_SUCCESS ){ // printf("Step = %u Index = %d ANN error.\n", u, index) ; // }else{ // device[index].fault = x[2] <= 0.5 ? 0 : 1 ; // } //u: cycle num HEPSY_S(ann_04_id) if ( ann_04_annRun(0, x) != EXIT_SUCCESS ) {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) printf("Step = %d Index = %d ANN error.\n", (int)ann_xx_dataCollector_payload_var.step, (int)ann_xx_dataCollector_payload_var.dev) ; HEPSY_S(ann_04_id) } else {HEPSY_S(ann_04_id) HEPSY_S(ann_04_id) ann_xx_dataCollector_payload_var.fault = x[2] <= 0.5 ? 0 : 1 ; HEPSY_S(ann_04_id) } HEPSY_S(ann_04_id) ann_04_dataCollector_channel->write(ann_xx_dataCollector_payload_var); HEPSY_P(ann_04_id) } } // END
/***************************************************************************** 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
/* * Copyright (C) 2020 GreenWaves Technologies, SAS, ETH Zurich and * University of Bologna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Authors: Germain Haugou, GreenWaves Technologies ([email protected]) */ #include <gv/gvsoc.hpp> #include <algorithm> #include <dlfcn.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <vp/json.hpp> #include <systemc.h> #include "main_systemc.hpp" static gv::Gvsoc *sc_gvsoc; class my_module : public sc_module, public gv::Gvsoc_user { public: SC_HAS_PROCESS(my_module); my_module(sc_module_name nm, gv::Gvsoc *gvsoc) : sc_module(nm), gvsoc(gvsoc) { SC_THREAD(run); } void run() { while(1) { int64_t time = (int64_t)sc_time_stamp().to_double(); int64_t next_timestamp = gvsoc->step_until(time); // when we are not executing the engine, it is retained so that no one else // can execute it while we are leeting the systemv engine executes. // On the contrary, if someone else is retaining it, we should not let systemv // update the time. // If so, just call again the step function so that we release the engine for // a while. if (gvsoc->retain_count() == 1) { if (next_timestamp == -1) { wait(sync_event); } else { wait(next_timestamp - time, SC_PS, sync_event); } } } } void was_updated() override { sync_event.notify(); } void has_ended() override { sc_stop(); } gv::Gvsoc *gvsoc; sc_event sync_event; }; int sc_main(int argc, char *argv[]) { sc_start(); return sc_gvsoc->join(); } int requires_systemc(const char *config_path) { // In case GVSOC was compiled with SystemC, check if we have at least one SystemC component // and if so, forward the launch to the dedicated SystemC launcher js::Config *js_config = js::import_config_from_file(config_path); if (js_config) { js::Config *gv_config = js_config->get("target/gvsoc"); if (gv_config) { return gv_config->get_child_bool("systemc"); } } return 0; } int systemc_launcher(const char *config_path) { gv::GvsocConf conf = { .config_path=config_path, .api_mode=gv::Api_mode::Api_mode_sync }; gv::Gvsoc *gvsoc = gv::gvsoc_new(&conf); gvsoc->open(); gvsoc->start(); sc_gvsoc = gvsoc; my_module module("Gvsoc SystemC wrapper", gvsoc); gvsoc->bind(&module); return sc_core::sc_elab_and_sim(0, NULL); }
// ---------------------------------------------------------------------------- // SystemC SCVerify Flow -- sysc_sim_trans.cpp // // HLS version: 10.4b/841621 Production Release // HLS date: Thu Oct 24 17:20:07 PDT 2019 // Flow Packages: HDL_Tcl 8.0a, SCVerify 10.4 // // Generated by: [email protected] // Generated date: Fri Apr 17 23:30:03 EDT 2020 // // ---------------------------------------------------------------------------- // // ------------------------------------- // sysc_sim_wrapper // Represents a new SC_MODULE having the same interface as the original model SysTop_rtl // ------------------------------------- // #ifndef TO_QUOTED_STRING #define TO_QUOTED_STRING(x) TO_QUOTED_STRING1(x) #define TO_QUOTED_STRING1(x) #x #endif // Hold time for the SCVerify testbench to account for the gate delay after downstream synthesis in pico second(s) // Hold time value is obtained from 'top_gate_constraints.cpp', which is generated at the end of RTL synthesis #ifdef CCS_DUT_GATE extern double __scv_hold_time; #else double __scv_hold_time = 0.0; // default for non-gate simulation is zero #endif #ifndef SC_USE_STD_STRING #define SC_USE_STD_STRING #endif #include "../../../../../cmod/lab3/SysTop/SysTop.h" #include <systemc.h> #include <mc_scverify.h> #include <mt19937ar.c> #include "mc_dut_wrapper.h" namespace CCS_RTL { class sysc_sim_wrapper : public sc_module { public: // Interface Ports sc_core::sc_in<bool > clk; sc_core::sc_in<bool > rst; Connections::In<InputSetup::WriteReq, Connections::SYN_PORT > write_req; Connections::In<ac_int<6, false >, Connections::SYN_PORT > start; Connections::In<ac_int<8, true >, Connections::SYN_PORT > weight_in_vec[8]; Connections::Out<ac_int<32, true >, Connections::SYN_PORT > accum_out_vec[8]; // Data objects sc_signal< bool > ccs_rtl_SIG_clk; sc_signal< sc_logic > ccs_rtl_SIG_rst; sc_signal< sc_logic > ccs_rtl_SIG_write_req_val; sc_signal< sc_logic > ccs_rtl_SIG_write_req_rdy; sc_signal< sc_lv<69> > ccs_rtl_SIG_write_req_msg; sc_signal< sc_logic > ccs_rtl_SIG_start_val; sc_signal< sc_logic > ccs_rtl_SIG_start_rdy; sc_signal< sc_lv<6> > ccs_rtl_SIG_start_msg; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_0_val; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_1_val; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_2_val; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_3_val; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_4_val; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_5_val; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_6_val; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_7_val; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_0_rdy; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_1_rdy; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_2_rdy; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_3_rdy; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_4_rdy; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_5_rdy; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_6_rdy; sc_signal< sc_logic > ccs_rtl_SIG_weight_in_vec_7_rdy; sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_0_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_1_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_2_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_3_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_4_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_5_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_6_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_weight_in_vec_7_msg; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_0_val; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_1_val; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_2_val; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_3_val; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_4_val; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_5_val; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_6_val; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_7_val; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_0_rdy; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_1_rdy; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_2_rdy; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_3_rdy; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_4_rdy; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_5_rdy; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_6_rdy; sc_signal< sc_logic > ccs_rtl_SIG_accum_out_vec_7_rdy; sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_0_msg; sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_1_msg; sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_2_msg; sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_3_msg; sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_4_msg; sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_5_msg; sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_6_msg; sc_signal< sc_lv<32> > ccs_rtl_SIG_accum_out_vec_7_msg; // Named Objects // Module instance pointers HDL::ccs_DUT_wrapper ccs_rtl; // Declare processes (SC_METHOD and SC_THREAD) void update_proc(); // Constructor SC_HAS_PROCESS(sysc_sim_wrapper); sysc_sim_wrapper( const sc_module_name& nm ) : ccs_rtl( "ccs_rtl", TO_QUOTED_STRING(TOP_HDL_ENTITY) ) , clk("clk") , rst("rst") , write_req("write_req") , start("start") , weight_in_vec() , accum_out_vec() , ccs_rtl_SIG_clk("ccs_rtl_SIG_clk") , ccs_rtl_SIG_rst("ccs_rtl_SIG_rst") , ccs_rtl_SIG_write_req_val("ccs_rtl_SIG_write_req_val") , ccs_rtl_SIG_write_req_rdy("ccs_rtl_SIG_write_req_rdy") , ccs_rtl_SIG_write_req_msg("ccs_rtl_SIG_write_req_msg") , ccs_rtl_SIG_start_val("ccs_rtl_SIG_start_val") , ccs_rtl_SIG_start_rdy("ccs_rtl_SIG_start_rdy") , ccs_rtl_SIG_start_msg("ccs_rtl_SIG_start_msg") , ccs_rtl_SIG_weight_in_vec_0_val("ccs_rtl_SIG_weight_in_vec_0_val") , ccs_rtl_SIG_weight_in_vec_1_val("ccs_rtl_SIG_weight_in_vec_1_val") , ccs_rtl_SIG_weight_in_vec_2_val("ccs_rtl_SIG_weight_in_vec_2_val") , ccs_rtl_SIG_weight_in_vec_3_val("ccs_rtl_SIG_weight_in_vec_3_val") , ccs_rtl_SIG_weight_in_vec_4_val("ccs_rtl_SIG_weight_in_vec_4_val") , ccs_rtl_SIG_weight_in_vec_5_val("ccs_rtl_SIG_weight_in_vec_5_val") , ccs_rtl_SIG_weight_in_vec_6_val("ccs_rtl_SIG_weight_in_vec_6_val") , ccs_rtl_SIG_weight_in_vec_7_val("ccs_rtl_SIG_weight_in_vec_7_val") , ccs_rtl_SIG_weight_in_vec_0_rdy("ccs_rtl_SIG_weight_in_vec_0_rdy") , ccs_rtl_SIG_weight_in_vec_1_rdy("ccs_rtl_SIG_weight_in_vec_1_rdy") , ccs_rtl_SIG_weight_in_vec_2_rdy("ccs_rtl_SIG_weight_in_vec_2_rdy") , ccs_rtl_SIG_weight_in_vec_3_rdy("ccs_rtl_SIG_weight_in_vec_3_rdy") , ccs_rtl_SIG_weight_in_vec_4_rdy("ccs_rtl_SIG_weight_in_vec_4_rdy") , ccs_rtl_SIG_weight_in_vec_5_rdy("ccs_rtl_SIG_weight_in_vec_5_rdy") , ccs_rtl_SIG_weight_in_vec_6_rdy("ccs_rtl_SIG_weight_in_vec_6_rdy") , ccs_rtl_SIG_weight_in_vec_7_rdy("ccs_rtl_SIG_weight_in_vec_7_rdy") , ccs_rtl_SIG_weight_in_vec_0_msg("ccs_rtl_SIG_weight_in_vec_0_msg") , ccs_rtl_SIG_weight_in_vec_1_msg("ccs_rtl_SIG_weight_in_vec_1_msg") , ccs_rtl_SIG_weight_in_vec_2_msg("ccs_rtl_SIG_weight_in_vec_2_msg") , ccs_rtl_SIG_weight_in_vec_3_msg("ccs_rtl_SIG_weight_in_vec_3_msg") , ccs_rtl_SIG_weight_in_vec_4_msg("ccs_rtl_SIG_weight_in_vec_4_msg") , ccs_rtl_SIG_weight_in_vec_5_msg("ccs_rtl_SIG_weight_in_vec_5_msg") , ccs_rtl_SIG_weight_in_vec_6_msg("ccs_rtl_SIG_weight_in_vec_6_msg") , ccs_rtl_SIG_weight_in_vec_7_msg("ccs_rtl_SIG_weight_in_vec_7_msg") , ccs_rtl_SIG_accum_out_vec_0_val("ccs_rtl_SIG_accum_out_vec_0_val") , ccs_rtl_SIG_accum_out_vec_1_val("ccs_rtl_SIG_accum_out_vec_1_val") , ccs_rtl_SIG_accum_out_vec_2_val("ccs_rtl_SIG_accum_out_vec_2_val") , ccs_rtl_SIG_accum_out_vec_3_val("ccs_rtl_SIG_accum_out_vec_3_val") , ccs_rtl_SIG_accum_out_vec_4_val("ccs_rtl_SIG_accum_out_vec_4_val") , ccs_rtl_SIG_accum_out_vec_5_val("ccs_rtl_SIG_accum_out_vec_5_val") , ccs_rtl_SIG_accum_out_vec_6_val("ccs_rtl_SIG_accum_out_vec_6_val") , ccs_rtl_SIG_accum_out_vec_7_val("ccs_rtl_SIG_accum_out_vec_7_val") , ccs_rtl_SIG_accum_out_vec_0_rdy("ccs_rtl_SIG_accum_out_vec_0_rdy") , ccs_rtl_SIG_accum_out_vec_1_rdy("ccs_rtl_SIG_accum_out_vec_1_rdy") , ccs_rtl_SIG_accum_out_vec_2_rdy("ccs_rtl_SIG_accum_out_vec_2_rdy") , ccs_rtl_SIG_accum_out_vec_3_rdy("ccs_rtl_SIG_accum_out_vec_3_rdy") , ccs_rtl_SIG_accum_out_vec_4_rdy("ccs_rtl_SIG_accum_out_vec_4_rdy") , ccs_rtl_SIG_accum_out_vec_5_rdy("ccs_rtl_SIG_accum_out_vec_5_rdy") , ccs_rtl_SIG_accum_out_vec_6_rdy("ccs_rtl_SIG_accum_out_vec_6_rdy") , ccs_rtl_SIG_accum_out_vec_7_rdy("ccs_rtl_SIG_accum_out_vec_7_rdy") , ccs_rtl_SIG_accum_out_vec_0_msg("ccs_rtl_SIG_accum_out_vec_0_msg") , ccs_rtl_SIG_accum_out_vec_1_msg("ccs_rtl_SIG_accum_out_vec_1_msg") , ccs_rtl_SIG_accum_out_vec_2_msg("ccs_rtl_SIG_accum_out_vec_2_msg") , ccs_rtl_SIG_accum_out_vec_3_msg("ccs_rtl_SIG_accum_out_vec_3_msg") , ccs_rtl_SIG_accum_out_vec_4_msg("ccs_rtl_SIG_accum_out_vec_4_msg") , ccs_rtl_SIG_accum_out_vec_5_msg("ccs_rtl_SIG_accum_out_vec_5_msg") , ccs_rtl_SIG_accum_out_vec_6_msg("ccs_rtl_SIG_accum_out_vec_6_msg") , ccs_rtl_SIG_accum_out_vec_7_msg("ccs_rtl_SIG_accum_out_vec_7_msg") { // Instantiate other modules ccs_rtl.clk(ccs_rtl_SIG_clk); ccs_rtl.rst(ccs_rtl_SIG_rst); ccs_rtl.write_req_val(ccs_rtl_SIG_write_req_val); ccs_rtl.write_req_rdy(ccs_rtl_SIG_write_req_rdy); ccs_rtl.write_req_msg(ccs_rtl_SIG_write_req_msg); ccs_rtl.start_val(ccs_rtl_SIG_start_val); ccs_rtl.start_rdy(ccs_rtl_SIG_start_rdy); ccs_rtl.start_msg(ccs_rtl_SIG_start_msg); ccs_rtl.weight_in_vec_0_val(ccs_rtl_SIG_weight_in_vec_0_val); ccs_rtl.weight_in_vec_1_val(ccs_rtl_SIG_weight_in_vec_1_val); ccs_rtl.weight_in_vec_2_val(ccs_rtl_SIG_weight_in_vec_2_val); ccs_rtl.weight_in_vec_3_val(ccs_rtl_SIG_weight_in_vec_3_val); ccs_rtl.weight_in_vec_4_val(ccs_rtl_SIG_weight_in_vec_4_val); ccs_rtl.weight_in_vec_5_val(ccs_rtl_SIG_weight_in_vec_5_val); ccs_rtl.weight_in_vec_6_val(ccs_rtl_SIG_weight_in_vec_6_val); ccs_rtl.weight_in_vec_7_val(ccs_rtl_SIG_weight_in_vec_7_val); ccs_rtl.weight_in_vec_0_rdy(ccs_rtl_SIG_weight_in_vec_0_rdy); ccs_rtl.weight_in_vec_1_rdy(ccs_rtl_SIG_weight_in_vec_1_rdy); ccs_rtl.weight_in_vec_2_rdy(ccs_rtl_SIG_weight_in_vec_2_rdy); ccs_rtl.weight_in_vec_3_rdy(ccs_rtl_SIG_weight_in_vec_3_rdy); ccs_rtl.weight_in_vec_4_rdy(ccs_rtl_SIG_weight_in_vec_4_rdy); ccs_rtl.weight_in_vec_5_rdy(ccs_rtl_SIG_weight_in_vec_5_rdy); ccs_rtl.weight_in_vec_6_rdy(ccs_rtl_SIG_weight_in_vec_6_rdy); ccs_rtl.weight_in_vec_7_rdy(ccs_rtl_SIG_weight_in_vec_7_rdy); ccs_rtl.weight_in_vec_0_msg(ccs_rtl_SIG_weight_in_vec_0_msg); ccs_rtl.weight_in_vec_1_msg(ccs_rtl_SIG_weight_in_vec_1_msg); ccs_rtl.weight_in_vec_2_msg(ccs_rtl_SIG_weight_in_vec_2_msg); ccs_rtl.weight_in_vec_3_msg(ccs_rtl_SIG_weight_in_vec_3_msg); ccs_rtl.weight_in_vec_4_msg(ccs_rtl_SIG_weight_in_vec_4_msg); ccs_rtl.weight_in_vec_5_msg(ccs_rtl_SIG_weight_in_vec_5_msg); ccs_rtl.weight_in_vec_6_msg(ccs_rtl_SIG_weight_in_vec_6_msg); ccs_rtl.weight_in_vec_7_msg(ccs_rtl_SIG_weight_in_vec_7_msg); ccs_rtl.accum_out_vec_0_val(ccs_rtl_SIG_accum_out_vec_0_val); ccs_rtl.accum_out_vec_1_val(ccs_rtl_SIG_accum_out_vec_1_val); ccs_rtl.accum_out_vec_2_val(ccs_rtl_SIG_accum_out_vec_2_val); ccs_rtl.accum_out_vec_3_val(ccs_rtl_SIG_accum_out_vec_3_val); ccs_rtl.accum_out_vec_4_val(ccs_rtl_SIG_accum_out_vec_4_val); ccs_rtl.accum_out_vec_5_val(ccs_rtl_SIG_accum_out_vec_5_val); ccs_rtl.accum_out_vec_6_val(ccs_rtl_SIG_accum_out_vec_6_val); ccs_rtl.accum_out_vec_7_val(ccs_rtl_SIG_accum_out_vec_7_val); ccs_rtl.accum_out_vec_0_rdy(ccs_rtl_SIG_accum_out_vec_0_rdy); ccs_rtl.accum_out_vec_1_rdy(ccs_rtl_SIG_accum_out_vec_1_rdy); ccs_rtl.accum_out_vec_2_rdy(ccs_rtl_SIG_accum_out_vec_2_rdy); ccs_rtl.accum_out_vec_3_rdy(ccs_rtl_SIG_accum_out_vec_3_rdy); ccs_rtl.accum_out_vec_4_rdy(ccs_rtl_SIG_accum_out_vec_4_rdy); ccs_rtl.accum_out_vec_5_rdy(ccs_rtl_SIG_accum_out_vec_5_rdy); ccs_rtl.accum_out_vec_6_rdy(ccs_rtl_SIG_accum_out_vec_6_rdy); ccs_rtl.accum_out_vec_7_rdy(ccs_rtl_SIG_accum_out_vec_7_rdy); ccs_rtl.accum_out_vec_0_msg(ccs_rtl_SIG_accum_out_vec_0_msg); ccs_rtl.accum_out_vec_1_msg(ccs_rtl_SIG_accum_out_vec_1_msg); ccs_rtl.accum_out_vec_2_msg(ccs_rtl_SIG_accum_out_vec_2_msg); ccs_rtl.accum_out_vec_3_msg(ccs_rtl_SIG_accum_out_vec_3_msg); ccs_rtl.accum_out_vec_4_msg(ccs_rtl_SIG_accum_out_vec_4_msg); ccs_rtl.accum_out_vec_5_msg(ccs_rtl_SIG_accum_out_vec_5_msg); ccs_rtl.accum_out_vec_6_msg(ccs_rtl_SIG_accum_out_vec_6_msg); ccs_rtl.accum_out_vec_7_msg(ccs_rtl_SIG_accum_out_vec_7_msg); // Register processes SC_METHOD(update_proc); sensitive << clk << rst << write_req.Connections::InBlocking_Ports_abs<InputSetup::WriteReq >::val << ccs_rtl_SIG_write_req_rdy << write_req.Connections::InBlocking<InputSetup::WriteReq, Connections::SYN_PORT >::msg << start.Connections::InBlocking_Ports_abs<ac_int<6, false > >::val << ccs_rtl_SIG_start_rdy << start.Connections::InBlocking<ac_int<6, false >, Connections::SYN_PORT >::msg << weight_in_vec[0].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[1].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[2].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[3].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[4].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[5].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[6].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[7].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << ccs_rtl_SIG_weight_in_vec_0_rdy << ccs_rtl_SIG_weight_in_vec_1_rdy << ccs_rtl_SIG_weight_in_vec_2_rdy << ccs_rtl_SIG_weight_in_vec_3_rdy << ccs_rtl_SIG_weight_in_vec_4_rdy << ccs_rtl_SIG_weight_in_vec_5_rdy << ccs_rtl_SIG_weight_in_vec_6_rdy << ccs_rtl_SIG_weight_in_vec_7_rdy << weight_in_vec[0].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[1].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[2].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[3].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[4].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[5].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[6].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[7].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << ccs_rtl_SIG_accum_out_vec_0_val << ccs_rtl_SIG_accum_out_vec_1_val << ccs_rtl_SIG_accum_out_vec_2_val << ccs_rtl_SIG_accum_out_vec_3_val << ccs_rtl_SIG_accum_out_vec_4_val << ccs_rtl_SIG_accum_out_vec_5_val << ccs_rtl_SIG_accum_out_vec_6_val << ccs_rtl_SIG_accum_out_vec_7_val << accum_out_vec[0].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[1].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[2].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[3].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[4].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[5].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[6].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[7].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << ccs_rtl_SIG_accum_out_vec_0_msg << ccs_rtl_SIG_accum_out_vec_1_msg << ccs_rtl_SIG_accum_out_vec_2_msg << ccs_rtl_SIG_accum_out_vec_3_msg << ccs_rtl_SIG_accum_out_vec_4_msg << ccs_rtl_SIG_accum_out_vec_5_msg << ccs_rtl_SIG_accum_out_vec_6_msg << ccs_rtl_SIG_accum_out_vec_7_msg; // Other constructor statements } ~sysc_sim_wrapper() { } // C++ class functions }; } // end namespace CCS_RTL // // ------------------------------------- // sysc_sim_wrapper // Represents a new SC_MODULE having the same interface as the original model SysTop_rtl // ------------------------------------- // // --------------------------------------------------------------- // Process: SC_METHOD update_proc // Static sensitivity: sensitive << clk << rst << write_req.Connections::InBlocking_Ports_abs<InputSetup::WriteReq >::val << ccs_rtl_SIG_write_req_rdy << write_req.Connections::InBlocking<InputSetup::WriteReq, Connections::SYN_PORT >::msg << start.Connections::InBlocking_Ports_abs<ac_int<6, false > >::val << ccs_rtl_SIG_start_rdy << start.Connections::InBlocking<ac_int<6, false >, Connections::SYN_PORT >::msg << weight_in_vec[0].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[1].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[2].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[3].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[4].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[5].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[6].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << weight_in_vec[7].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << ccs_rtl_SIG_weight_in_vec_0_rdy << ccs_rtl_SIG_weight_in_vec_1_rdy << ccs_rtl_SIG_weight_in_vec_2_rdy << ccs_rtl_SIG_weight_in_vec_3_rdy << ccs
_rtl_SIG_weight_in_vec_4_rdy << ccs_rtl_SIG_weight_in_vec_5_rdy << ccs_rtl_SIG_weight_in_vec_6_rdy << ccs_rtl_SIG_weight_in_vec_7_rdy << weight_in_vec[0].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[1].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[2].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[3].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[4].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[5].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[6].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << weight_in_vec[7].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << ccs_rtl_SIG_accum_out_vec_0_val << ccs_rtl_SIG_accum_out_vec_1_val << ccs_rtl_SIG_accum_out_vec_2_val << ccs_rtl_SIG_accum_out_vec_3_val << ccs_rtl_SIG_accum_out_vec_4_val << ccs_rtl_SIG_accum_out_vec_5_val << ccs_rtl_SIG_accum_out_vec_6_val << ccs_rtl_SIG_accum_out_vec_7_val << accum_out_vec[0].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[1].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[2].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[3].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[4].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[5].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[6].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << accum_out_vec[7].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy << ccs_rtl_SIG_accum_out_vec_0_msg << ccs_rtl_SIG_accum_out_vec_1_msg << ccs_rtl_SIG_accum_out_vec_2_msg << ccs_rtl_SIG_accum_out_vec_3_msg << ccs_rtl_SIG_accum_out_vec_4_msg << ccs_rtl_SIG_accum_out_vec_5_msg << ccs_rtl_SIG_accum_out_vec_6_msg << ccs_rtl_SIG_accum_out_vec_7_msg; void CCS_RTL::sysc_sim_wrapper::update_proc() { // none.sc_in field_key=clk:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-685:clk:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-685 sc_logic t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_685; // NPS - LV to hold field ccs_rtl_SIG_clk.write(clk.read()); // none.sc_in field_key=rst:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-686:rst:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-686 sc_logic t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_686; // NPS - LV to hold field type_to_vector(rst.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_686); // read orig port and type convert ccs_rtl_SIG_rst.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_686); // then write to RTL port // none.sc_in field_key=write_req:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-696:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-725 sc_logic t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_725; // NPS - LV to hold field type_to_vector(write_req.Connections::InBlocking_Ports_abs<InputSetup::WriteReq >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_725); // read orig port and type convert ccs_rtl_SIG_write_req_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_725); // then write to RTL port // none.sc_out field_key=write_req:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-696:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-735 bool d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_735; vector_to_type(ccs_rtl_SIG_write_req_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_735); write_req.Connections::InBlocking_Ports_abs<InputSetup::WriteReq >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_735); // none.sc_in field_key=write_req:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-696:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-745 sc_lv< 69 > t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_745; // NPS - LV to hold field type_to_vector(write_req.Connections::InBlocking<InputSetup::WriteReq, Connections::SYN_PORT >::msg.read(),69,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_745); // read orig port and type convert ccs_rtl_SIG_write_req_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_745); // then write to RTL port // none.sc_in field_key=start:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-755:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-782 sc_logic t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_782; // NPS - LV to hold field type_to_vector(start.Connections::InBlocking_Ports_abs<ac_int<6, false > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_782); // read orig port and type convert ccs_rtl_SIG_start_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_782); // then write to RTL port // none.sc_out field_key=start:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-755:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-792 bool d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_792; vector_to_type(ccs_rtl_SIG_start_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_792); start.Connections::InBlocking_Ports_abs<ac_int<6, false > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_792); // none.sc_in field_key=start:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-755:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-802 sc_lv< 6 > t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_802; // NPS - LV to hold field type_to_vector(start.Connections::InBlocking<ac_int<6, false >, Connections::SYN_PORT >::msg.read(),6,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_802); // read orig port and type convert ccs_rtl_SIG_start_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_802); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839 sc_logic t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839; // NPS - LV to hold field type_to_vector(weight_in_vec[0].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_0_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839 type_to_vector(weight_in_vec[1].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_1_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839 type_to_vector(weight_in_vec[2].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_2_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839 type_to_vector(weight_in_vec[3].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_3_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839 type_to_vector(weight_in_vec[4].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_4_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839 type_to_vector(weight_in_vec[5].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_5_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839 type_to_vector(weight_in_vec[6].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_6_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-839 type_to_vector(weight_in_vec[7].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_7_val.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_839); // then write to RTL port // none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849 bool d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849; vector_to_type(ccs_rtl_SIG_weight_in_vec_0_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); weight_in_vec[0].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); // none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849 vector_to_type(ccs_rtl_SIG_weight_in_vec_1_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); weight_in_vec[1].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); // none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849 vector_to_type(ccs_rtl_SIG_weight_in_vec_2_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); weight_in_vec[2].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); // none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849 vector_to_type(ccs_rtl_SIG_weight_in_vec_3_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); weight_in_vec[3].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); // none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849 vector_to_type(ccs_rtl_SIG_weight_in_vec_4_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); weight_in_vec[4].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); // none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849 vector_to_type(ccs_rtl_SIG_weight_in_vec_5_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); weight_in_vec[5].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); // none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849 vector_to_type(ccs_rtl_SIG_weight_in_vec_6_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); weight_in_vec[6].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); // none.sc_out field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-849 vector_to_type(ccs_rtl_SIG_weight_in_vec_7_rdy.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); weight_in_vec[7].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_849); // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859 sc_lv< 8 > t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859; // NPS - LV to hold field type_to_vector(weight_in_vec[0].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_0_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859 type_to_vector(weight_in_vec[1].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_1_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859 type_to_vector(weight_in_vec[2].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_2_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859 type_to_vector(weight_in_vec[3].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_3_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859 type_to_vector(weight_in_vec[4].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_4_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859 type_to_vector(weight_in_vec[5].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_5_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859 type_to_vector(weight_in_vec[6].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_6_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port // none.sc_in field_key=weight_in_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-812:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-859 type_to_vector(weight_in_vec[7].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_7_msg.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_859); // then write to RTL port // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884 bool d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884; vector_to_type(ccs_rtl_SIG_accum_out_vec_0_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); accum_out_vec[0].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884 vector_to_type(ccs_rtl_SIG_accum_out_vec_1_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); accum_out_vec[1].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884 vector_to_type(ccs_rtl_SIG_accum_out_vec_2_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); accum_out_vec[2].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884 vector_to_type(ccs_rtl_SIG_accum_out_vec_3_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); accum_out_vec[3].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884 vector_to_type(ccs_rtl_SIG_accum_out_vec_4_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); accum_out_vec[4].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884 vector_to_type(ccs_rtl_SIG_accum_out_vec_5_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); accum_out_vec[5].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884 vector_to_type(ccs_rtl_SIG_accum_out_vec_6_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); accum_out_vec[6].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:val:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-884 vector_to_type(ccs_rtl_SIG_accum_out_vec_7_val.read(), 1, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); accum_out_vec[7].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_884); // none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888 sc_logic t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888; // NPS - LV to hold field type_to_vector(accum_out_vec[0].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_0_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port // none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888 type_to_vector(accum_out_vec[1].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_1_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port // none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888 type_to_vector(accum_out_vec[2].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_2_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port // none.sc_in fi
eld_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888 type_to_vector(accum_out_vec[3].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_3_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port // none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888 type_to_vector(accum_out_vec[4].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_4_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port // none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888 type_to_vector(accum_out_vec[5].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_5_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port // none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888 type_to_vector(accum_out_vec[6].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_6_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port // none.sc_in field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:rdy:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-888 type_to_vector(accum_out_vec[7].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_7_rdy.write(t_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_888); // then write to RTL port // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892 sc_dt::sc_lv<32 > d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892; vector_to_type(ccs_rtl_SIG_accum_out_vec_0_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); accum_out_vec[0].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892 vector_to_type(ccs_rtl_SIG_accum_out_vec_1_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); accum_out_vec[1].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892 vector_to_type(ccs_rtl_SIG_accum_out_vec_2_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); accum_out_vec[2].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892 vector_to_type(ccs_rtl_SIG_accum_out_vec_3_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); accum_out_vec[3].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892 vector_to_type(ccs_rtl_SIG_accum_out_vec_4_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); accum_out_vec[4].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892 vector_to_type(ccs_rtl_SIG_accum_out_vec_5_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); accum_out_vec[5].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892 vector_to_type(ccs_rtl_SIG_accum_out_vec_6_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); accum_out_vec[6].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); // none.sc_out field_key=accum_out_vec:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-869:msg:6bfbc86a-4643-405d-8ac5-31fb9eb3828c-892 vector_to_type(ccs_rtl_SIG_accum_out_vec_7_msg.read(), 32, &d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); accum_out_vec[7].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_6bfbc86a_4643_405d_8ac5_31fb9eb3828c_892); } // Include original testbench file(s) #include "/home/billyk/cs148/hls/lab3/SysTop/../../../cmod/lab3/SysTop/testbench.cpp"
/* * Created on: 21. jun. 2019 * Author: Jonathan Horsted Schougaard */ #ifdef HW_COSIM //#define __GMP_WITHIN_CONFIGURE #endif #define DEBUG_SYSTEMC #define HLS_APPROX_TIME #define SC_INCLUDE_FX #include "hwcore/tb/pipes/tb_imagedatafix.h" #include <systemc.h> unsigned errors = 0; const char simulation_name[] = "tb_imagedatafix"; int sc_main(int argc, char *argv[]) { cout << "INFO: Elaborating " << simulation_name << endl; sc_core::sc_report_handler::set_actions("/IEEE_Std_1666/deprecated", sc_core::SC_DO_NOTHING); sc_report_handler::set_actions(SC_ID_LOGIC_X_TO_BOOL_, SC_LOG); sc_report_handler::set_actions(SC_ID_VECTOR_CONTAINS_LOGIC_VALUE_, SC_LOG); // sc_report_handler::set_actions( SC_ID_OBJECT_EXISTS_, SC_LOG); // sc_set_time_resolution(1,SC_PS); // sc_set_default_time_unit(1,SC_NS); // ModuleSingle modulesingle("modulesingle_i"); tb_top_imagedata_fix tb_01("tb_top_imagedata_fix"); cout << "INFO: Simulating " << simulation_name << endl; sc_time time_out(1000, SC_US); sc_start(time_out); cout << "INFO: end time is: " << sc_time_stamp().to_string() << ", and max time is: " << time_out.to_string() << std::endl << std::flush; sc_assert(sc_time_stamp() != time_out); cout << "INFO: Post-processing " << simulation_name << endl; cout << "INFO: Simulation " << simulation_name << " " << (errors ? "FAILED" : "PASSED") << " with " << errors << " errors" << std::endl; #ifdef __RTL_SIMULATION__ cout << "HW cosim done" << endl; #endif return errors ? 1 : 0; }
/* * Copyright (c) 2010 TIMA Laboratory * * This file is part of Rabbits. * * Rabbits 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. * * Rabbits is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Rabbits. If not, see <http://www.gnu.org/licenses/>. */ #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <signal.h> #include <system_init.h> #include <systemc.h> #include <abstract_noc.h> #include <interconnect_master.h> #include <../../qemu/qemu-0.9.1/qemu_systemc.h> #include <qemu_wrapper.h> #include <qemu_cpu_wrapper.h> #include <qemu_wrapper_cts.h> #include <interconnect.h> #include <sram_device.h> #include <dbf_device.h> #include <framebuffer_device.h> #include <timer_device.h> #include <tty_serial_device.h> #include <sem_device.h> #include <mem_device.h> #include <sl_block_device.h> #include <qemu_imported.h> #include <qemu_wrapper_cts.h> #ifndef O_BINARY #define O_BINARY 0 #endif unsigned long no_frames_to_simulate = 0; mem_device *ram = NULL; interconnect *onoc = NULL; slave_device *slaves[50]; int nslaves = 0; init_struct is; int sc_main (int argc, char ** argv) { int i; memset (&is, 0, sizeof (init_struct)); is.cpu_family = "arm"; is.cpu_model = NULL; is.kernel_filename = NULL; is.initrd_filename = NULL; is.no_cpus = 4; is.ramsize = 256 * 1024 * 1024; parse_cmdline (argc, argv, &is); if (check_init (&is) != 0) return 1; fb_reset_t fb_res_stat = { /* .fb_start = */ 0, /* .fb_w = */ 0, /* .fb_h = */ 0, /* .fb_mode = */ NONE, /* .fb_display_on_warp = */ 0, }; //slaves ram = new mem_device ("dynamic", is.ramsize + 0x1000); sram_device *sram = new sram_device ("sram", 0x800000); tty_serial_device *tty = new tty_serial_device ("tty"); sem_device *sem = new sem_device ("sem", 0x100000); fb_device *fb = new fb_device("fb", is.no_cpus, &fb_res_stat); dbf_device *dbf = new dbf_device("DBF", is.no_cpus + 1/* , nslaves + 1*/); sl_block_device *bl = new sl_block_device("block", is.no_cpus + 2, NULL, 1); timer_device *timers[1]; int ntimers = sizeof (timers) / sizeof (timer_device *); slaves[nslaves++] = ram; // 0 slaves[nslaves++] = sram; // 1 slaves[nslaves++] = fb->get_slave(); // 2 slaves[nslaves++] = tty; // 3 slaves[nslaves++] = sem; // 4 slaves[nslaves++] = bl->get_slave(); // 5 for (i = 0; i < ntimers; i++){ char buf[20]; sprintf (buf, "timer_%d", i); timers[i] = new timer_device (buf); slaves[nslaves++] = timers[i]; // 6 + i } int no_irqs = ntimers + 3; /* timers + TTY + FB + DBF */ int int_cpu_mask [] = {1, 1, 1, 1, 0, 0}; sc_signal<bool> *wires_irq_qemu = new sc_signal<bool>[no_irqs]; for (i = 0; i < ntimers; i++) timers[i]->irq(wires_irq_qemu[i]); tty->irq_line(wires_irq_qemu[ntimers]); fb->irq(wires_irq_qemu[ntimers + 1]); dbf->irq(wires_irq_qemu[ntimers + 2]); //interconnect onoc = new interconnect ("interconnect", is.no_cpus + 3, /* masters: CPUs + FB + DBF + BL*/ nslaves + 1); /* slaves: ... */ for (i = 0; i < nslaves; i++) onoc->connect_slave_64 (i, slaves[i]->get_port, slaves[i]->put_port); onoc->connect_slave_64(nslaves, dbf->get_port, dbf->put_port); arm_load_kernel (&is); //masters qemu_wrapper qemu1 ("QEMU1", 0, no_irqs, int_cpu_mask, is.no_cpus, is.cpu_family, is.cpu_model, is.ramsize); qemu1.add_map(0xA0000000, 0x20000000); // (base address, size) qemu1.set_base_address (QEMU_ADDR_BASE); for(i = 0; i < no_irqs; i++) qemu1.interrupt_ports[i] (wires_irq_qemu[i]); for(i = 0; i < is.no_cpus; i++) onoc->connect_master_64 (i, qemu1.get_cpu(i)->put_port, qemu1.get_cpu(i)->get_port); if(is.gdb_port > 0){ qemu1.m_qemu_import.gdb_srv_start_and_wait(qemu1.m_qemu_instance, is.gdb_port); //qemu1.set_unblocking_write (0); } /* Master : FrameBuffer */ onoc->connect_master_64(is.no_cpus, fb->get_master()->put_port, fb->get_master()->get_port); /* Master : H264 DBF */ onoc->connect_master_64(is.no_cpus + 1, dbf->master_put_port, dbf->master_get_port); /* Block device*/ sc_signal<bool> bl_irq_wire; bl->irq (bl_irq_wire); onoc->connect_master_64(is.no_cpus + 2, bl->get_master()->put_port, bl->get_master()->get_port); sc_start (); return 0; } void invalidate_address (unsigned long addr, int slave_id, unsigned long offset_slave, int src_id) { int i, first_node_id; unsigned long taddr; qemu_wrapper *qw; for (i = 0; i < qemu_wrapper::s_nwrappers; i++) { qw = qemu_wrapper::s_wrappers[i]; first_node_id = qw->m_cpus[0]->m_node_id; if (src_id >= first_node_id && src_id < first_node_id + qw->m_ncpu) { qw->invalidate_address (addr, src_id - first_node_id); } else { if (onoc->get_master (first_node_id)->get_liniar_address ( slave_id, offset_slave, taddr)) { qw->invalidate_address (taddr, -1); } } } } int systemc_load_image (const char *file, unsigned long ofs) { if (file == NULL) return -1; int fd, img_size, size; fd = open (file, O_RDONLY | O_BINARY); if (fd < 0) return -1; img_size = lseek (fd, 0, SEEK_END); if (img_size + ofs > ram->get_size ()) { printf ("%s - RAM size < %s size + %lx\n", __FUNCTION__, file, ofs); close(fd); exit (1); } lseek (fd, 0, SEEK_SET); size = img_size; if (read (fd, ram->get_mem () + ofs, size) != size) { printf ("Error reading file (%s) in function %s.\n", file, __FUNCTION__); close(fd); exit (1); } close (fd); return img_size; } unsigned char* systemc_get_sram_mem_addr () { return ram->get_mem (); } extern "C" { unsigned char dummy_for_invalid_address[256]; struct mem_exclusive_t {unsigned long addr; int cpus;} mem_exclusive[100]; int no_mem_exclusive = 0; #define idx_to_bit(idx) (1 << (idx)) void memory_mark_exclusive (int cpu, unsigned long addr) { mem_exclusive_t *entry; int i; addr &= 0xFFFFFFFC; for (i = 0; i < no_mem_exclusive; i++) { entry = &mem_exclusive[i]; if (entry->addr == addr) { entry->cpus |= idx_to_bit(cpu); return; } } entry = &mem_exclusive[no_mem_exclusive]; entry->addr = addr; entry->cpus = idx_to_bit(cpu); no_mem_exclusive++; } static int delete_entry(int i) { for (; i < no_mem_exclusive - 1; i++) { mem_exclusive[i].addr = mem_exclusive[i + 1].addr; mem_exclusive[i].cpus = mem_exclusive[i + 1].cpus; } no_mem_exclusive--; } int memory_test_exclusive (int cpu, unsigned long addr) { int i; addr &= 0xFFFFFFFC; for (i = 0; i < no_mem_exclusive; i++) { mem_exclusive_t *entry = &mem_exclusive[i]; if (entry->addr == addr) { if (entry->cpus & idx_to_bit(cpu)) { delete_entry(i); return 0; } break; } } return 1; } void memory_clear_exclusive (int cpu, unsigned long addr) { int i; addr &= 0xFFFFFFFC; for (i = 0; i < no_mem_exclusive; i++) { mem_exclusive_t *entry = &mem_exclusive[i]; if (entry->addr == addr) { delete_entry(i); return; } } } unsigned char *systemc_get_mem_addr (qemu_cpu_wrapper_t *qw, unsigned long addr) { int slave_id = onoc->get_master (qw->m_node_id)->get_slave_id_for_mem_addr (addr); if (slave_id == -1) return dummy_for_invalid_address; return slaves[slave_id]->get_mem () + addr; } } /* * Vim standard variables * vim:set ts=4 expandtab tw=80 cindent syntax=c: * * Emacs standard variables * Local Variables: * mode: c * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: nil * End: */
#ifndef IPS_FILTER_TLM_CPP #define IPS_FILTER_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 "ips_filter_tlm.hpp" #include "common_func.hpp" #include "important_defines.hpp" void ips_filter_tlm::do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address) { this->img_result = *(Filter<IPS_IN_TYPE_TB, IPS_OUT_TYPE_TB, IPS_FILTER_KERNEL_SIZE>::result_ptr); *data = (unsigned char) this->img_result; //memcpy(data, Filter<IPS_IN_TYPE_TB, IPS_OUT_TYPE_TB, IPS_FILTER_KERNEL_SIZE>::result_ptr, sizeof(IPS_OUT_TYPE_TB)); } void ips_filter_tlm::do_when_write_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address) { IPS_OUT_TYPE_TB* result = new IPS_OUT_TYPE_TB; IPS_IN_TYPE_TB* img_window = new IPS_IN_TYPE_TB[3 * 3]; //dbgprint("[DEBUG]: data: %0d, address %0d, data_length %0d, size of char %0d", *data, address, data_length, sizeof(char)); this->img_window[address] = (IPS_IN_TYPE_TB) *data; //dbgprint("[DEBUG]: img_window data: %0f", this->img_window[address]); if (address == 8) { filter(this->img_window, result); } } #endif // IPS_FILTER_TLM_CPP
/* * Created on: 21. jun. 2019 * Author: Jonathan Horsted Schougaard */ #ifdef HW_COSIM //#define __GMP_WITHIN_CONFIGURE #endif #define SC_INCLUDE_FX #include <systemc.h> #include "hwcore/tb/improc/tb_imfilter.h" unsigned errors = 0; const char simulation_name[] = "dma tester test"; int sc_main(int argc, char* argv[]) { cout << "INFO: Elaborating "<< simulation_name << endl; sc_core::sc_report_handler::set_actions( "/IEEE_Std_1666/deprecated", sc_core::SC_DO_NOTHING ); sc_report_handler::set_actions( SC_ID_LOGIC_X_TO_BOOL_, SC_LOG); sc_report_handler::set_actions( SC_ID_VECTOR_CONTAINS_LOGIC_VALUE_, SC_LOG); sc_report_handler::set_actions( SC_ID_OBJECT_EXISTS_, SC_LOG); //sc_set_time_resolution(1,SC_PS); //sc_set_default_time_unit(1,SC_NS); //ModuleSingle modulesingle("modulesingle_i"); TB_imfilter_top tb_01; cout << "INFO: Simulating "<< simulation_name << endl; sc_start(); cout << "INFO: Post-processing "<< simulation_name << endl; cout << "INFO: Simulation " << simulation_name << " " << (errors?"FAILED":"PASSED") << " with " << errors << " errors" << std::endl; #ifdef __RTL_SIMULATION__ cout << "HW cosim done" << endl; #endif return errors?1:0; }
#include <pthread.h> #include <systemc.h> #include "sc_main.h" #include "sc_run.h" //#include "sc_config.h" #include "sc_qt_adaptor.h" //#include "sc_rst.h" //#include "sc_clk.h" //#include "sc_mux.h" //#include "sc_tri.h" //#include "sc_terminals.h" //#include "sc_gates.h" //#include "sc_gates_pv.h" //#include "sc_reg.h" //#include "sc_arith.h" /* ????? what is this? template <bool CLKEDGE = DEFAULT_CLKEDGE, flexinterface_t FLEXINT = DEFAULT_FLEXINT> class U1block : public SyscFlexInt<CLKEDGE, FLEXINT> { public: typedef sc_lv<32> data_t; typedef sc_lv<1> sel_t; // --------------------- Ports --------------------- // Provided by base module scFlexModuleT // sc_in_clk clock{"clock"}; // Clock input (FLEXINT: custom active edge) // sc_in<rst_t> reset{"reset"}; // Asynchronous reset input (FLEXINT: possibly unmapped, custom active level) // sc_in<ena_t> enable{"enable"}; // Synchronous enable input (FLEXINT: possibly unmapped, custom active level) sc_out<data_t> q{"q"}; // Data output sc_in<data_t> load{"load"}; // Load value (when mux selection = 1, d = load) sc_in<data_t> incr{"incr"}; // Incr value (when mux selection = 0, d = q + incr) sc_in<sel_t> sel{"sel"}; // Mux selection value typedef SyscFlexInt<CLKEDGE, FLEXINT> BASE_MODULE; typedef U1block<CLKEDGE, FLEXINT> SC_CURRENT_USER_MODULE; private: SyscMux<2,1,1,,1,1> u3; SyscReg<32,CLKEDGE,FLEXINT> u2; SyscAdd<2,32> a1; sc_signal<sc_lv<32>> wire1{"u3.d0,a1.y"}; sc_signal<sc_lv<32>> wire2{"u3.y,u2.d"}; public: U1block(::sc_core::sc_module_name name): SyscFlexInt<CLKEDGE,FLEXINT>(name) , u3("u3"), u2("u2"), a1("a1") { u3.d[0]->bind(wire1); u3.d[1]->bind(load); u3.sel(sel); u3.y(wire2); a1.d[0]->bind(u2.q); a1.d[1]->bind(incr); a1.y(wire1); u2.d.bind(wire2); u2.reset.bind(BASE_MODULE::reset); u2.clock.bind(BASE_MODULE::clock); u2.q.bind(q); } }; */ /* * Create a separate thread to execute this code, the original systemc's main() code. * @code return sc_core::sc_elab_and_sim(argc, argv); @endcode */ void *scSimMain(void *args) { (void)args; scQtAdaptor ADAPTOR("QT<->SC_bridge"); sc_setRunResult(sc_core::sc_elab_and_sim(0, nullptr)); return nullptr; } int sc_main (int argc, char *argv[]) { return 0; } /* * Create design and run the simulation (void)argc; (void)argv; // Inputs //SyscIn<1> clk(1, 1, 0, SC_LOGIC_0, "clk"); sc_clock clk("clk"); //SyscIn<1> rst(4, 4, 0, SC_LOGIC_0, "rst"); sc_signal<sc_lv<1>> rst("rst"); //SyscIn<1> sel(2, 2, 0, SC_LOGIC_0, "sel"); sc_signal<sc_lv<1>> sel("sel"); //SyscIn<32> incr(4, 4, 0, SC_LOGIC_0, "incr"); sc_signal<sc_lv<32>> incr("incr"); //SyscIn<1> sel2(4, 4, 0, SC_LOGIC_0, "sel2"); sc_signal<sc_lv<1>> load("load"); //SyscIn<32> load(4, 4, 0, SC_LOGIC_0, "load"); sc_signal<sc_lv<32>> val("val"); // Outputs //SyscOut<32> y("y"); sc_signal<sc_lv<32>> y("y"); // Components SyscCnt<32, DEFAULT_CLKEDGE, RST_HIGH_NO_ENA> u4("u4"); SyscMux_pv<2,32,1> u5("u5"); U1block<true, RST_HIGH_NO_ENA> u1("u1"); // Additional wires sc_signal<sc_lv<32>> wire1("u5.d0,u4.q"); sc_signal<sc_lv<32>> wire2("u5.d1,u1.q"); // Wiring/binding u4.reset(rst); u4.clock(clk); u4.q(wire1); u5.map(prefix, index, wire); u5.sel(sel); u5.d[0](wire1); u5.d[1](wire2); u5.y(y); u1.sel(load); u1.incr(incr); u1.load(val); u1.reset(rst); u1.clock(clk); u1.q(wire2); sc_start(); // Run forever return 0; } */
/* * SysAttay testbench, for Harvard cs148/248 only */ #include "SysArray.h" #include <systemc.h> #include <mc_scverify.h> #include <nvhls_int.h> #include <vector> #define NVHLS_VERIFY_BLOCKS (SysArray) #include <nvhls_verify.h> using namespace::std; #include <testbench/nvhls_rand.h> // W/I/O dimensions const static int N = SysArray::N; const static int M = N*3; int ERROR = 0; vector<int> Count(N, 0); template<typename T> vector<vector<T>> GetMat(int rows, int cols) { vector<vector<T>> mat(rows, vector<T>(cols)); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { mat[i][j] = nvhls::get_rand<T::width>(); } } return mat; } template<typename T> void PrintMat(vector<vector<T>> mat) { int rows = (int) mat.size(); int cols = (int) mat[0].size(); for (int i = 0; i < rows; i++) { cout << "\t"; for (int j = 0; j < cols; j++) { cout << mat[i][j] << "\t"; } cout << endl; } cout << endl; } template<typename T, typename U> vector<vector<U>> MatMul(vector<vector<T>> mat_A, vector<vector<T>> mat_B) { // mat_A _N*_M // mat_B _M*_P // mat_C _N*_P int _N = (int) mat_A.size(); int _M = (int) mat_A[0].size(); int _P = (int) mat_B[0].size(); assert(_M == (int) mat_B.size()); vector<vector<U>> mat_C(_N, vector<U>(_P, 0)); for (int i = 0; i < _N; i++) { for (int j = 0; j < _P; j++) { mat_C[i][j] = 0; for (int k = 0; k < _M; k++) { mat_C[i][j] += mat_A[i][k]*mat_B[k][j]; } } } return mat_C; } SC_MODULE (Source) { Connections::Out<SysPE::InputType> act_in_vec[N]; Connections::Out<SysPE::InputType> weight_in_vec[N]; sc_in <bool> clk; sc_in <bool> rst; vector<vector<SysPE::InputType>> W_mat, I_mat; SC_CTOR(Source) { SC_THREAD(Run); sensitive << clk.pos(); async_reset_signal_is(rst, false); } void Run() { for (int i = 0; i < N; i++) { act_in_vec[i].Reset(); weight_in_vec[i].Reset(); } // Wait for initial reset wait(100.0, SC_NS); wait(); // Write Weight to PE, e.g. for 4*4 weight // w00 w10 w20 w30 // w01 w11 w21 w31 // w02 w12 w22 w32 // w03 w13 w23 w33 <- push this first (col N-1) cout << sc_time_stamp() << " " << name() << ": Start Loading Weight Matrix" << endl; for (int j = N-1; j >= 0; j--) { for (int i = 0; i < N; i++) { weight_in_vec[i].Push(W_mat[i][j]); } } cout << sc_time_stamp() << " " << name() << ": Finish Loading Weight Matrix" << endl; wait(N); cout << sc_time_stamp() << " " << name() << ": Start Sending Input Matrix" << endl; // Activation most follow Systolic Array Pattern // e.g. 4*6 Input matrix // a00 // a01 a10 // a02 a11 a20 // a03 a12 a21 a30 // a04 a13 a22 a31 // a05 a14 a23 a32 // a15 a24 a33 // a25 a34 // a35 vector<int> col(N, 0); for (int i = 0; i < N-1; i++) { for (int j = 0; j <= i; j++) { SysPE::InputType _act = I_mat[j][col[j]]; act_in_vec[j].Push(_act); col[j] += 1; } } for (int i = N-1; i < M; i++) { for (int j = 0; j < N; j++) { SysPE::InputType _act = I_mat[j][col[j]]; act_in_vec[j].Push(_act); col[j] += 1; } } for (int i = M; i < N+M-1; i++) { for (int j = i-M+1; j < N; j++) { SysPE::InputType _act = I_mat[j][col[j]]; act_in_vec[j].Push(_act); col[j] += 1; } } wait(); } }; SC_MODULE (Sink) { Connections::In<SysPE::AccumType> accum_out_vec[N]; sc_in <bool> clk; sc_in <bool> rst; vector<vector<SysPE::AccumType>> O_mat; SC_CTOR(Sink) { SC_THREAD(Run); sensitive << clk.pos(); async_reset_signal_is(rst, false); } void Run() { for (int i = 0; i < N; i++) { accum_out_vec[i].Reset(); } vector<bool> is_out(N, 0); while (1) { vector<SysPE::AccumType> out_vec(N, 0); for (int i = 0; i < N; i++) { SysPE::AccumType _out; is_out[i] = accum_out_vec[i].PopNB(_out); if (is_out[i]) { out_vec[i] = _out; SysPE::AccumType _out_ref = O_mat[i][Count[i]]; if (_out != _out_ref){ ERROR += 1; cout << "output incorrect" << endl; } Count[i] += 1; } } bool is_out_or = 0; for (int i = 0; i < N; i++) is_out_or |= is_out[i]; if (is_out_or) { cout << sc_time_stamp() << " " << name() << " accum_out_vec: "; cout << "\t"; for (int i = 0; i < N; i++) { if (is_out[i] == 1) cout << out_vec[i] << "\t"; else cout << "-\t"; } cout << endl; } wait(); } } }; SC_MODULE (testbench) { sc_clock clk; sc_signal<bool> rst; Connections::Combinational<SysPE::InputType> act_in_vec[N]; Connections::Combinational<SysPE::InputType> weight_in_vec[N]; Connections::Combinational<SysPE::AccumType> accum_out_vec[N]; NVHLS_DESIGN(SysArray) sa; Source src; Sink sink; SC_HAS_PROCESS(testbench); testbench(sc_module_name name) : sc_module(name), clk("clk", 1, SC_NS, 0.5,0,SC_NS,true), rst("rst"), sa("sa"), src("src"), sink("sink") { sa.clk(clk); sa.rst(rst); src.clk(clk); src.rst(rst); sink.clk(clk); sink.rst(rst); for (int i=0; i < N; i++) { sa.act_in_vec[i](act_in_vec[i]); sa.weight_in_vec[i](weight_in_vec[i]); sa.accum_out_vec[i](accum_out_vec[i]); src.act_in_vec[i](act_in_vec[i]); src.weight_in_vec[i](weight_in_vec[i]); sink.accum_out_vec[i](accum_out_vec[i]); } SC_THREAD(Run); } void Run() { rst = 1; wait(10.5, SC_NS); rst = 0; cout << "@" << sc_time_stamp() << " Asserting Reset " << endl ; wait(1, SC_NS); cout << "@" << sc_time_stamp() << " Deasserting Reset " << endl ; rst = 1; wait(1000, SC_NS); cout << "@" << sc_time_stamp() << " Stop " << endl ; cout << "Check Output Count" << endl; for (int i = 0; i < N; i++) { if (Count[i] != M) { ERROR += 1; cout << "Count incorrect" << endl; } } if (ERROR == 0) cout << "Implementation Correct :)" << endl; else cout << "Implementation Incorrect (:" << endl; sc_stop(); } }; int sc_main(int argc, char *argv[]) { nvhls::set_random_seed(); // Weight N*N // Input N*M // Output N*M vector<vector<SysPE::InputType>> W_mat = GetMat<SysPE::InputType>(N, N); vector<vector<SysPE::InputType>> I_mat = GetMat<SysPE::InputType>(N, M); vector<vector<SysPE::AccumType>> O_mat; O_mat = MatMul<SysPE::InputType, SysPE::AccumType>(W_mat, I_mat); cout << "Weight Matrix " << endl; PrintMat(W_mat); cout << "Input Matrix " << endl; PrintMat(I_mat); cout << "Reference Output Matrix " << endl; PrintMat(O_mat); testbench my_testbench("my_testbench"); my_testbench.src.W_mat = W_mat; my_testbench.src.I_mat = I_mat; my_testbench.sink.O_mat = O_mat; sc_start(); cout << "CMODEL PASS" << endl; return 0; };
//-------------------------------------------------------- //Testbench: Unification //By: Roger Morales Monge //Description: Simple TB for pixel unification modules //-------------------------------------------------------- #ifndef USING_TLM_TB_EN #define STB_IMAGE_IMPLEMENTATION #include "include/stb_image.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "include/stb_image_write.h" #include <systemc.h> #include <math.h> #ifdef IMG_UNIFICATE_PV_EN #include "unification_pv_model.hpp" #endif // IMG_UNIFICATE_PV_EN int sc_main(int, char*[]) { unsigned char pixel_x, pixel_y; unsigned char pixel_magnitude; int width, height, channels, pixel_count; unsigned char *img_x, *img_y, *img_unificated; //Ref Image pointer unsigned char *img_ref; int error_count; float error_med; img_unification_module unification_U1 ("unification_U1"); // Open VCD file sc_trace_file *wf = sc_create_vcd_trace_file("unification_U1"); wf->set_time_unit(1, SC_NS); // Dump the desired signals sc_trace(wf, pixel_x, "pixel_x"); sc_trace(wf, pixel_y, "pixel_y"); sc_trace(wf, pixel_magnitude, "pixel_magnitude"); // Load Image img_x = stbi_load("../../tools/datagen/src/imgs/car_sobel_x_result.jpg", &width, &height, &channels, 0); img_y = stbi_load("../../tools/datagen/src/imgs/car_sobel_y_result.jpg", &width, &height, &channels, 0); img_ref = stbi_load("../../tools/datagen/src/imgs/car_sobel_combined_result.jpg", &width, &height, &channels, 0); pixel_count = width * height * channels; //Allocate memory for output image img_unificated = (unsigned char *)(malloc(size_t(pixel_count))); if(img_unificated == NULL) { printf("Unable to allocate memory for the output image.\n"); exit(1); } printf("Loaded images X and Y with Width: %0d, Height: %0d, Channels %0d. Total pixel count: %0d", width, height, channels, pixel_count); sc_start(); cout << "@" << sc_time_stamp()<< endl; printf("Combined X and Y images...\n"); //Iterate over image unification_U1.unificate_img(img_x, img_y, img_unificated, pixel_count, channels); printf("Unification finished.\n"); //Compare with reference image error_count = 0; error_med = 0; for(unsigned char *ref = img_ref, *result = img_unificated; ref < img_ref + pixel_count && result< img_unificated + pixel_count; ref+=channels, result+=channels){ //printf("Pixel #%0d, Ref Value: %0d, Result Value: %0d\n", int(ref-img_ref), *ref, *result); error_count += (*ref != *result); error_med += abs(*ref - *result); } error_med /= pixel_count; printf("-----------------------------------\n"); printf("Comparison Results:\n"); printf("Error Count: %0d, Error Rate: %0.2f\n", error_count, (100*(error_count+0.0))/pixel_count); printf("Mean Error Distance: %0.2f\n", error_med); printf("-----------------------------------\n"); //FIXME: Add time measurement cout << "@" << sc_time_stamp() <<" Terminating simulation\n" << endl; //Write output image stbi_write_jpg("./car_unificated.jpg", width, height, channels, img_unificated, 100); sc_close_vcd_trace_file(wf); return 0;// Terminate simulation } #endif // #ifdef USING_TLM_TB_EN
/******************************************************************************** * 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_04_ANN_INPUTS 2 // Number of inputs #define cD_04_ANN_OUTPUTS 1 // Number of outputs //----------------------------------------------------------------------------- // Physical constants //----------------------------------------------------------------------------- static double cD_04_I_0 = 77.3 ; // [A] Nominal current static double cD_04_T_0 = 298.15 ; // [K] Ambient temperature static double cD_04_R_0 = 0.01 ; // [Ω] Data-sheet R_DS_On (Drain-Source resistance in the On State) static double cD_04_V_0 = 47.2 ; // [V] Nominal voltage static double cD_04_Alpha = 0.002 ; // [Ω/K] Temperature coefficient of Drain-Source resistance in the On State static double cD_04_ThermalConstant = 0.75 ; static double cD_04_Tau = 0.02 ; // [s] Sampling period //----------------------------------------------------------------------------- // Status descriptors //----------------------------------------------------------------------------- typedef struct cD_04_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_04_DEVICE; static cD_04_DEVICE cD_04_device; //----------------------------------------------------------------------------- // Mnemonics to access the array that contains the sampled data //----------------------------------------------------------------------------- #define cD_04_SAMPLE_LEN 3 // Array of SAMPLE_LEN elements #define cD_04_I_INDEX 0 // Current #define cD_04_V_INDEX 1 // Voltage #define cD_04_TIME_INDEX 2 // Time ///----------------------------------------------------------------------------- // Forward references //----------------------------------------------------------------------------- static int cD_04_initDescriptors(cD_04_DEVICE device) ; //static void getSample(int index, double sample[SAMPLE_LEN]) ; static void cD_04_cleanData(int index, double sample[cD_04_SAMPLE_LEN]) ; static double cD_04_extractFeatures(double tPrev, double iPrev, double iNow, double rPrev) ; static void cD_04_normalize(int index, double x[cD_04_ANN_INPUTS]) ; static double cD_04_degradationModel(double tNow) ; //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- int cD_04_initDescriptors(cD_04_DEVICE device) {HEPSY_S(cleanData_04_id) // for (int i = 0; i < NUM_DEV; i++) // { HEPSY_S(cleanData_04_id) device.t = cD_04_T_0 ; // Operating temperature = Ambient temperature HEPSY_S(cleanData_04_id) device.r = cD_04_R_0 ; // Operating R_DS_On = Data-sheet R_DS_On // printf("Init %d \n",i); // } HEPSY_S(cleanData_04_id) return( EXIT_SUCCESS ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void cD_04_cleanData(int index, double sample[cD_04_SAMPLE_LEN]) {HEPSY_S(cleanData_04_id) // the parameter "index" could be useful to retrieve the characteristics of the device HEPSY_S(cleanData_04_id) if ( sample[cD_04_I_INDEX] < 0 ) {HEPSY_S(cleanData_04_id) HEPSY_S(cleanData_04_id) sample[cD_04_I_INDEX] = 0 ; HEPSY_S(cleanData_04_id) } else if ( sample[cD_04_I_INDEX] > (2.0 * cD_04_I_0) ) {HEPSY_S(cleanData_04_id) HEPSY_S(cleanData_04_id) sample[cD_04_I_INDEX] = (2.0 * cD_04_I_0) ; // Postcondition: (0 <= sample[I_INDEX] <= 2.0*I_0) HEPSY_S(cleanData_04_id) } HEPSY_S(cleanData_04_id) if( sample[cD_04_V_INDEX] < 0 ) {HEPSY_S(cleanData_04_id) HEPSY_S(cleanData_04_id) sample[cD_04_V_INDEX] = 0 ; HEPSY_S(cleanData_04_id)} else if ( sample[cD_04_V_INDEX] > (2.0 * cD_04_V_0 ) ) {HEPSY_S(cleanData_04_id) HEPSY_S(cleanData_04_id) sample[cD_04_V_INDEX] = (2.0 * cD_04_V_0) ; // Postcondition: (0 <= sample[V_INDEX] <= 2.0*V_0) HEPSY_S(cleanData_04_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_04_extractFeatures(double tPrev, double iPrev, double iNow, double rPrev) {HEPSY_S(cleanData_04_id) HEPSY_S(cleanData_04_id) double t ; // Temperature HEPSY_S(cleanData_04_id) HEPSY_S(cleanData_04_id) double i = 0.5*(iPrev + iNow); // Average current // printf("cD_04_extractFeatures tPrev=%f\n",tPrev); HEPSY_S(cleanData_04_id) HEPSY_S(cleanData_04_id) HEPSY_S(cleanData_04_id) HEPSY_S(cleanData_04_id) HEPSY_S(cleanData_04_id) HEPSY_S(cleanData_04_id) HEPSY_S(cleanData_04_id) t = tPrev + // Previous temperature rPrev * (i * i) * cD_04_Tau - // Heat generated: P = I·R^2 cD_04_ThermalConstant * (tPrev - cD_04_T_0) * cD_04_Tau ; // Dissipation and heat capacity HEPSY_S(cleanData_04_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_04_degradationModel(double tNow) {HEPSY_S(cleanData_04_id) HEPSY_S(cleanData_04_id) double r ; //r = R_0 + Alpha * tNow ; HEPSY_S(cleanData_04_id) HEPSY_S(cleanData_04_id) HEPSY_S(cleanData_04_id) r = cD_04_R_0 * ( 2 - exp(-cD_04_Alpha*tNow) ); HEPSY_S(cleanData_04_id) return( r ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void cD_04_normalize(int index, double sample[cD_04_ANN_INPUTS]) { double i ; double v ; // Precondition: (0 <= sample[I_INDEX] <= 2*I_0) && (0 <= sample[V_INDEX] <= 2*V_0) i = sample[cD_04_I_INDEX] <= cD_04_I_0 ? 0.0 : 1.0; v = sample[cD_04_V_INDEX] <= cD_04_V_0 ? 0.0 : 1.0; // Postcondition: (i in {0.0, 1.0}) and (v in {0.0, 1.0}) sample[cD_04_I_INDEX] = i ; sample[cD_04_V_INDEX] = v ; } void mainsystem::cleanData_04_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_04_sample[cD_04_SAMPLE_LEN] ; double x[cD_04_ANN_INPUTS + cD_04_ANN_OUTPUTS] ; // NOTE: commented, should be changed param by ref... //cD_04_initDescriptors(cD_04_device); HEPSY_S(cleanData_04_id) cD_04_device.t = cD_04_T_0 ; // Operating temperature = Ambient temperature HEPSY_S(cleanData_04_id) cD_04_device.r = cD_04_R_0 ; // Operating R_DS_On = Data-sheet R_DS_On // ### added for time related dynamics //static double cD_04_Tau = 0.02 ; // [s] Sampling period HEPSY_S(cleanData_04_id) double cD_04_last_sample_time = 0; //implementation HEPSY_S(cleanData_04_id) while(1) {HEPSY_S(cleanData_04_id) // content HEPSY_S(cleanData_04_id) sampleTimCord_cleanData_xx_payload_var = sampleTimCord_cleanData_04_channel->read(); HEPSY_S(cleanData_04_id) dev = sampleTimCord_cleanData_xx_payload_var.dev; HEPSY_S(cleanData_04_id) step = sampleTimCord_cleanData_xx_payload_var.step; HEPSY_S(cleanData_04_id) ex_time = sampleTimCord_cleanData_xx_payload_var.ex_time; HEPSY_S(cleanData_04_id) sample_i = sampleTimCord_cleanData_xx_payload_var.sample_i; HEPSY_S(cleanData_04_id) sample_v = sampleTimCord_cleanData_xx_payload_var.sample_v; // cout << "cleanData_04 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_04_id) cD_04_sample[cD_04_I_INDEX] = sample_i; HEPSY_S(cleanData_04_id) cD_04_sample[cD_04_V_INDEX] = sample_v; HEPSY_S(cleanData_04_id) cD_04_sample[cD_04_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_04_id) cD_04_cleanData(dev, cD_04_sample) ; HEPSY_S(cleanData_04_id) cD_04_device.time_Ex = cD_04_sample[cD_04_TIME_INDEX] ; HEPSY_S(cleanData_04_id) cD_04_device.i = cD_04_sample[cD_04_I_INDEX] ; HEPSY_S(cleanData_04_id) cD_04_device.v = cD_04_sample[cD_04_V_INDEX] ; // ### added for time related dynamics //static double cD_04_Tau = 0.02 ; // [s] Sampling period HEPSY_S(cleanData_04_id) cD_04_Tau = ex_time - cD_04_last_sample_time; HEPSY_S(cleanData_04_id) cD_04_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_04_id) cD_04_device.t = cD_04_extractFeatures( cD_04_device.t, // Previous temperature cD_04_device.i, // Previous current cD_04_sample[cD_04_I_INDEX], // Current at this step cD_04_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_04_id) cD_04_device.r = cD_04_degradationModel(cD_04_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_04_id) x[0] = cD_04_device.i ; HEPSY_S(cleanData_04_id) x[1] = cD_04_device.v ; HEPSY_S(cleanData_04_id) cD_04_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_04_id) cleanData_xx_ann_xx_payload_var.dev = dev; HEPSY_S(cleanData_04_id) cleanData_xx_ann_xx_payload_var.step = step; HEPSY_S(cleanData_04_id) cleanData_xx_ann_xx_payload_var.ex_time = ex_time; HEPSY_S(cleanData_04_id) cleanData_xx_ann_xx_payload_var.device_i = cD_04_device.i; HEPSY_S(cleanData_04_id) cleanData_xx_ann_xx_payload_var.device_v = cD_04_device.v; HEPSY_S(cleanData_04_id) cleanData_xx_ann_xx_payload_var.device_t = cD_04_device.t; HEPSY_S(cleanData_04_id) cleanData_xx_ann_xx_payload_var.device_r = cD_04_device.r; HEPSY_S(cleanData_04_id) cleanData_xx_ann_xx_payload_var.x_0 = x[0]; HEPSY_S(cleanData_04_id) cleanData_xx_ann_xx_payload_var.x_1 = x[1]; HEPSY_S(cleanData_04_id) cleanData_xx_ann_xx_payload_var.x_2 = x[2]; HEPSY_S(cleanData_04_id) cleanData_04_ann_04_channel->write(cleanData_xx_ann_xx_payload_var); HEPSY_P(cleanData_04_id) } } //END
/* * @ASCK */ #include <systemc.h> SC_MODULE (Memory) { sc_in <bool> r_nw; sc_in <sc_uint<13>> addr; sc_in <sc_int<8>> data; sc_out <sc_int<8>> out; /* ** module global variables */ sc_int<8> mem[8192] = {0}; // 2^13 rows bool done = false; SC_CTOR (Memory){ SC_METHOD (process); sensitive << r_nw << addr << data; } void process () { if(done){ return; } if(addr.read() < 8192){ if(r_nw.read()){ out.write(mem[addr.read()]); } else{ mem[addr.read()] = data.read(); out.write(mem[addr.read()]); } } else{ out.write(0); } } };
// Copyright 2019 Glenn Ramalho - RFIDo Design // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // This code was based off the work from Espressif Systems covered by the // License: // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <systemc.h> #include "esp32-hal-log.h" #include "esp_log.h" #include <stdarg.h> #include <stdlib.h> int log_printf(const char *fmt, ...) { int size; char buffer[128]; va_list ap; va_start(ap, fmt); size = vsnprintf(buffer, 128, fmt, ap); va_end(ap); SC_REPORT_INFO("LOGP", buffer); return size; } int log_v(const char *fmt, ...) { int size; char buffer[128]; va_list ap; va_start(ap, fmt); size = vsnprintf(buffer, 128, fmt, ap); va_end(ap); SC_REPORT_INFO("LOGV", buffer); return size; } int isr_log_v(const char *fmt, ...) { int size; char buffer[128]; va_list ap; va_start(ap, fmt); size = vsnprintf(buffer, 128, fmt, ap); va_end(ap); SC_REPORT_INFO("LOGISRV", buffer); return size; } int log_i(const char *fmt, ...) { int size; char buffer[128]; va_list ap; va_start(ap, fmt); size = vsnprintf(buffer, 128, fmt, ap); va_end(ap); SC_REPORT_INFO("LOG", buffer); return size; } int isr_log_i(const char *fmt, ...) { int size; char buffer[128]; va_list ap; va_start(ap, fmt); size = vsnprintf(buffer, 128, fmt, ap); va_end(ap); SC_REPORT_INFO("LOGISR", buffer); return size; } int log_d(const char *fmt, ...) { int size; char buffer[128]; va_list ap; va_start(ap, fmt); size = vsnprintf(buffer, 128, fmt, ap); va_end(ap); SC_REPORT_INFO("LOGDEBUG", buffer); return size; } int isr_log_d(const char *fmt, ...) { int size; char buffer[128]; va_list ap; va_start(ap, fmt); size = vsnprintf(buffer, 128, fmt, ap); va_end(ap); SC_REPORT_INFO("LOGISRD", buffer); return size; } int log_w(const char *fmt, ...) { int size; char buffer[128]; va_list ap; va_start(ap, fmt); size = vsnprintf(buffer, 128, fmt, ap); va_end(ap); SC_REPORT_WARNING("LOG", buffer); return size; } int isr_log_w(const char *fmt, ...) { int size; char buffer[128]; va_list ap; va_start(ap, fmt); size = vsnprintf(buffer, 128, fmt, ap); va_end(ap); SC_REPORT_WARNING("LOGISR", buffer); return size; } int log_e(const char *fmt, ...) { int size; char buffer[128]; va_list ap; va_start(ap, fmt); size = vsnprintf(buffer, 128, fmt, ap); va_end(ap); SC_REPORT_WARNING("LOGERR", buffer); return size; } int isr_log_e(const char *fmt, ...) { int size; char buffer[128]; va_list ap; va_start(ap, fmt); size = vsnprintf(buffer, 128, fmt, ap); va_end(ap); SC_REPORT_WARNING("LOGISRERR", buffer); return size; } int log_n(const char *fmt, ...) { int size; char buffer[128]; va_list ap; va_start(ap, fmt); size = vsnprintf(buffer, 128, fmt, ap); va_end(ap); SC_REPORT_INFO("LOGNOTE", buffer); return size; } int isr_log_n(const char *fmt, ...) { int size; char buffer[128]; va_list ap; va_start(ap, fmt); size = vsnprintf(buffer, 128, fmt, ap); va_end(ap); SC_REPORT_INFO("LOGISRNOTE", buffer); return size; } esp_log_level_t esp_level; void esp_log_level_set(const char *tag, esp_log_level_t level) { esp_level = level; } uint32_t esp_log_timestamp() { double ts = sc_time_stamp().to_seconds(); return (uint32_t)(ts*1000); } uint32_t esp_log_early_timestamp() { double ts = sc_time_stamp().to_seconds(); return (uint32_t)(ts*1000); } void esp_log_write(esp_log_level_t level, const char *tag, const char * format, ...) { if (level <= esp_level) { int size; char buffer[128]; va_list ap; size = strlen(tag); strncpy(buffer, tag, 16); if (size > 16) size = 16; buffer[size] = ':'; va_start(ap, format); vsnprintf(buffer+size+1, 128 - size - 1, format, ap); va_end(ap); switch(level) { case ESP_LOG_ERROR: SC_REPORT_INFO("LOGERR", buffer); break; case ESP_LOG_WARN: SC_REPORT_INFO("LOGWARN", buffer); break; case ESP_LOG_INFO: SC_REPORT_INFO("LOGINFO", buffer); break; case ESP_LOG_DEBUG: SC_REPORT_INFO("LOGDEBUG", buffer); break; case ESP_LOG_VERBOSE: SC_REPORT_INFO("LOGVERB", buffer); break; default : SC_REPORT_INFO("LOGOTHER", buffer); break; } } }
#ifndef USING_TLM_TB_EN #define int64 systemc_int64 #define uint64 systemc_uint64 #include <systemc.h> #undef int64 #undef uint64 #define int64 opencv_int64 #define uint64 opencv_uint64 #include <opencv2/opencv.hpp> #undef int64 #undef uint64 #include "vga.hpp" // Image path #define IPS_IMG_PATH_TB "../../tools/datagen/src/imgs/car_rgb_noisy_image.jpg" // Main clock frequency in Hz - 25.175 MHz #define CLK_FREQ 25175000 // VGA settings #define H_ACTIVE 640 #define H_FP 16 #define H_SYNC_PULSE 96 #define H_BP 48 #define V_ACTIVE 480 #define V_FP 10 #define V_SYNC_PULSE 2 #define V_BP 33 // Compute the total number of pixels #define TOTAL_VERTICAL (H_ACTIVE + H_FP + H_SYNC_PULSE + H_BP) #define TOTAL_HORIZONTAL (V_ACTIVE + V_FP + V_SYNC_PULSE + V_BP) #define TOTAL_PIXELES (TOTAL_VERTICAL * TOTAL_HORIZONTAL) // Number of bits for ADC, DAC and VGA #define BITS 8 int sc_main(int, char*[]) { // Read image const std::string img_path = IPS_IMG_PATH_TB; cv::Mat read_img = cv::imread(img_path, cv::IMREAD_COLOR); // CV_8UC3 Type: 8-bit unsigned, 3 channels (e.g., for a color image) cv::Mat tx_img; read_img.convertTo(tx_img, CV_8UC3); cv::Mat rx_data(TOTAL_HORIZONTAL, TOTAL_VERTICAL, CV_8UC3); cv::Mat rx_img(tx_img.size(), CV_8UC3); #ifdef IPS_DEBUG_EN std::cout << "Loading image: " << img_path << std::endl; #endif // IPS_DEBUG_EN // Check if the image is loaded successfully if (tx_img.empty()) { std::cerr << "Error: Could not open or find the image!" << std::endl; exit(EXIT_FAILURE); } #ifdef IPS_DEBUG_EN std::cout << "TX image info: "; std::cout << "rows = " << tx_img.rows; std::cout << " cols = " << tx_img.cols; std::cout << " channels = " << tx_img.channels() << std::endl; std::cout << "RX data info: "; std::cout << "rows = " << rx_data.rows; std::cout << " cols = " << rx_data.cols; std::cout << " channels = " << rx_data.channels() << std::endl; std::cout << "RX image info: "; std::cout << "rows = " << rx_img.rows; std::cout << " cols = " << rx_img.cols; std::cout << " channels = " << rx_img.channels() << std::endl; #endif // IPS_DEBUG_EN // Compute the clock time in seconds const double CLK_TIME = 1.0 / static_cast<double>(CLK_FREQ); // Compute the total simulation based on the total amount of pixels in the // screen const double SIM_TIME = CLK_TIME * static_cast<double>(TOTAL_PIXELES); // Signals to use // -- Inputs sc_core::sc_clock clk("clk", CLK_TIME, sc_core::SC_SEC); sc_core::sc_signal<sc_uint<8> > s_tx_red; sc_core::sc_signal<sc_uint<8> > s_tx_green; sc_core::sc_signal<sc_uint<8> > s_tx_blue; // -- Outputs sc_core::sc_signal<bool> s_hsync; sc_core::sc_signal<bool> s_vsync; sc_core::sc_signal<unsigned int> s_h_count; sc_core::sc_signal<unsigned int> s_v_count; sc_core::sc_signal<sc_uint<8> > s_rx_red; sc_core::sc_signal<sc_uint<8> > s_rx_green; sc_core::sc_signal<sc_uint<8> > s_rx_blue; // VGA module instanciation and connections vga< BITS, H_ACTIVE, H_FP, H_SYNC_PULSE, H_BP, V_ACTIVE, V_FP, V_SYNC_PULSE, V_BP > ips_vga("ips_vga"); ips_vga.clk(clk); ips_vga.red(s_tx_red); ips_vga.green(s_tx_green); ips_vga.blue(s_tx_blue); ips_vga.o_hsync(s_hsync); ips_vga.o_vsync(s_vsync); ips_vga.o_h_count(s_h_count); ips_vga.o_v_count(s_v_count); ips_vga.o_red(s_rx_red); ips_vga.o_green(s_rx_green); ips_vga.o_blue(s_rx_blue); // Signals to dump #ifdef IPS_DUMP_EN sc_trace_file* wf = sc_create_vcd_trace_file("ips_vga"); sc_trace(wf, clk, "clk"); sc_trace(wf, s_tx_red, "tx_red"); sc_trace(wf, s_tx_green, "tx_green"); sc_trace(wf, s_tx_blue, "tx_blue"); sc_trace(wf, s_hsync, "hsync"); sc_trace(wf, s_vsync, "vsync"); sc_trace(wf, s_h_count, "h_count"); sc_trace(wf, s_v_count, "v_count"); sc_trace(wf, s_rx_red, "rx_red"); sc_trace(wf, s_rx_green, "rx_green"); sc_trace(wf, s_rx_blue, "rx_blue"); #endif // IPS_DUMP_EN // Start time std::cout << "@" << sc_time_stamp() << std::endl; double total_sim_time = 0.0; while (SIM_TIME > total_sim_time) { const int IMG_ROW = s_v_count.read() - (V_SYNC_PULSE + V_BP); const int IMG_COL = s_h_count.read() - (H_SYNC_PULSE + H_BP); #ifdef IPS_DEBUG_EN std::cout << "TX image: "; std::cout << "row = " << IMG_ROW; std::cout << " col = " << IMG_COL; #endif // IPS_DEBUG_EN if ((IMG_ROW < 0) || (IMG_COL < 0) || (IMG_ROW >= V_ACTIVE) || (IMG_COL >= H_ACTIVE)) { s_tx_red.write(0); s_tx_green.write(0); s_tx_blue.write(0); #ifdef IPS_DEBUG_EN std::cout << " dpixel = (0,0,0) " << std::endl; #endif // IPS_DEBUG_EN } else { cv::Vec3b pixel = tx_img.at<cv::Vec3b>(IMG_ROW, IMG_COL, 0); s_tx_red.write(static_cast<sc_uint<8> >(pixel[0])); s_tx_green.write(static_cast<sc_uint<8> >(pixel[1])); s_tx_blue.write(static_cast<sc_uint<8> >(pixel[2])); #ifdef IPS_DEBUG_EN std::cout << " ipixel = (" << static_cast<int>(pixel[0]) << "," << static_cast<int>(pixel[1]) << "," << static_cast<int>(pixel[2]) << ")" << std::endl; #endif // IPS_DEBUG_EN } total_sim_time += CLK_TIME; sc_start(CLK_TIME, sc_core::SC_SEC); if ((IMG_ROW < 0) || (IMG_COL < 0) || (IMG_ROW >= V_ACTIVE) || (IMG_COL >= H_ACTIVE)) { cv::Vec3b pixel(0, 0, 0); rx_data.at<cv::Vec3b>(s_v_count.read(), s_h_count.read()) = pixel; } else { cv::Vec3b pixel = cv::Vec3b(s_rx_red.read(), s_rx_green.read(), s_rx_blue.read()); rx_data.at<cv::Vec3b>(s_v_count.read(), s_h_count.read()) = pixel; rx_img.at<cv::Vec3b>(IMG_ROW, IMG_COL) = pixel; } } // End time std::cout << "@" << sc_time_stamp() << std::endl; #ifdef IPS_DUMP_EN sc_close_vcd_trace_file(wf); #endif // IPS_DUMP_EN #ifdef IPS_IMSHOW // Show the images in their respective windows cv::imshow("TX image", tx_img); cv::imshow("RX image", rx_img); // Wait for a key press indefinitely to keep the windows open cv::waitKey(0); #endif // IPS_IMSHOW return 0; } #endif // USING_TLM_TB_EN
/******************************************************************************* * gpio_mf.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Implements a SystemC model of a generic multi-function GPIO with * analog function. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "gpio_mf.h" #include "info.h" /********************* * Function: set_function() * inputs: new function * outputs: none * returns: none * globals: none * * Sets the function, can be GPIO or ANALOG. */ void gpio_mf::set_function(gpio_function_t newfunction) { /* We ignore unchanged function requests. */ if (newfunction == function) return; /* We also ignore illegal function requests. */ if (newfunction == GPIOMF_ANALOG) { PRINTF_WARN("GPIOMF", "%s cannot be set to ANALOG", name()) return; } /* To select a function there must be at least the fin or the fout * available. The fen is optional. Ideal would be to require all three * but there are some peripherals that need only one of these pins, * so to make life easier, we require at least a fin or a fout. */ if (newfunction >= GPIOMF_FUNCTION && (newfunction-1 >= fin.size() && newfunction-1 >= fout.size())) { PRINTF_WARN("GPIOMF", "%s cannot be set to FUNC%d", name(), newfunction) return; } /* When we change to the GPIO function, we set the driver high and set * the function accordingly. */ if (newfunction == GPIOMF_GPIO) { PRINTF_INFO("GPIOMF", "%s set to GPIO mode", name()) function = newfunction; driveok = true; /* set_val() handles the driver. */ gpio_base::set_val(pinval); } else { PRINTF_INFO("GPIOMF", "%s set to FUNC%d", name(), newfunction); function = newfunction; } /* And we set any notifications we need. */ updatefunc.notify(); updatereturn.notify(); } /********************* * Function: get_function() * inputs: none * outputs: none * returns: current function * globals: none * * Returns the current function. */ gpio_function_t gpio_mf::get_function() { return function; } /********************* * Function: set_val() * inputs: new value * outputs: none * returns: none * globals: none * * Changes the value to set onto the GPIO, if GPIO function is set. */ void gpio_mf::set_val(bool newval) { pinval = newval; if (function == GPIOMF_GPIO) gpio_base::set_val(newval); } /********************* * Thread: drive_return() * inputs: none * outputs: none * returns: none * globals: none * * Drives the return path from the pin onto the alternate functions. */ void gpio_mf::drive_return() { sc_logic pinsamp; bool retval; int func; /* We begin driving all returns to low. */ for (func = 0; func < fout.size(); func = func + 1) fout[func]->write(false); /* Now we go into the loop waiting for a return or a change in function. */ for(;;) { /* printf("<<%s>>: U:%d pin:%d:%c @%s\n", name(), updatereturn.triggered(), pin.event(), pin.read().to_char(), sc_time_stamp().to_string().c_str()); */ pinsamp = pin.read(); /* If the sampling value is Z or X and we have a function set, we * then issue a warning. We also do not warn at time 0s or we get some * dummy initialization warnings. */ if (sc_time_stamp() != sc_time(0, SC_NS) && (pinsamp == SC_LOGIC_X || pinsamp == SC_LOGIC_Z) && function != GPIOMF_ANALOG && function != GPIOMF_GPIO) { retval = false; PRINTF_WARN("GPIOMF", "can't return '%c' onto FUNC%d", pinsamp.to_char(), function) } else if (pinsamp == SC_LOGIC_1) retval = true; else retval = false; for (func = 0; func < fout.size(); func = func + 1) if (function == GPIOMF_ANALOG) fout[func]->write(false); else if (function == GPIOMF_GPIO) fout[func]->write(false); else if (func != function-1) fout[func]->write(false); else fout[func]->write(retval); wait(); } } /********************* * Thread: drive_func() * inputs: none * outputs: none * returns: none * globals: none * * Drives the value from an alternate function onto the pins. This does not * actually drive the value, it just places it in the correct variables so that * the drive() thread handles it. */ void gpio_mf::drive_func() { for(;;) { /* We only use this thread if we have an alternate function selected. */ if (function != GPIOMF_GPIO && function-1 < fin.size()) { /* We check if the fen is ok. If this function has no fen we default * it to enabled. */ if (function-1 < fen.size() || fen[function-1]->read() == true) driveok = true; else driveok = false; /* Note that we do not set the pin val, just call set_val to handle * the pin drive. */ gpio_base::set_val(fin[function-1]->read()); } /* We now wait for a change. If the function is no selected or if we * have an illegal function selected, we have to wait for a change * in the function selection. */ if (function == GPIOMF_GPIO || function-1 >= fin.size()) wait(updatefunc); /* If we have a valid function selected, we wait for either the * function or the fen to change. We also have to wait for a * function change. */ else if (fen.size() >= function-1) wait(updatefunc | fin[function-1]->value_changed_event()); else wait(updatefunc | fin[function-1]->value_changed_event() | fen[function-1]->value_changed_event()); } }
/******************************************************************************* * espintr.cpp -- Copyright 2020 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Implements a SystemC module for the ESP32 interrupt management. ******************************************************************************* * 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 "info.h" #include "espintr.h" #include "soc/soc.h" #include "esp_intr_alloc.h" #include "Arduino.h" void espintr::initialize() { int i; for (i = 0; i < ESPM_INTR_TABLE; i = i + 1) { table_pro[i] = -1; table_app[i] = -1; } for (i = 0; i < XCHAL_NUM_INTERRUPTS; i = i + 1) { handler_pro[i].fn = NULL; handler_pro[i].arg = NULL; handler_app[i].fn = NULL; handler_app[i].arg = NULL; } } void espintr::catcher() { uint32_t pro_lvl, app_lvl; while(true) { wait(); /* We collect all signals into one set of busses. */ pro_lvl = 0; app_lvl = 0; if (ledc_intr_i.read() && table_pro[ETS_LEDC_INTR_SOURCE] != -1) pro_lvl = pro_lvl | (1<<table_pro[ETS_LEDC_INTR_SOURCE]); if (ledc_intr_i.read() && table_app[ETS_LEDC_INTR_SOURCE] != -1) app_lvl = app_lvl | (1<<table_app[ETS_LEDC_INTR_SOURCE]); /* Once we are done we set the new values for raw and intr. */ raw_pro.write(pro_lvl); intr_pro.write(mask_pro.read() & pro_lvl); raw_app.write(app_lvl); intr_app.write(mask_pro.read() & app_lvl); } } int espintr::get_next(uint32_t edgemask, uint32_t now, uint32_t last) { /* Any bits that are edge triggered, we take the value for last. Any that * are not, we take the inverse of now forcing an edge trigger. */ uint32_t lm = last & edgemask | ~now & ~edgemask; /* Priority NMI */ if ((now & (1<<14))>0) return 14; /* Priority 5 */ if ((now & ~last & (1<<16))>0) return 16; /* Timer style */ if ((now & ~lm & (1<<26))>0) return 26; if ((now & ~lm & (1<<31))>0) return 31; /* Priority 4 */ if ((now & ~lm & (1<<24))>0) return 24; if ((now & ~lm & (1<<25))>0) return 25; if ((now & ~lm & (1<<28))>0) return 28; if ((now & ~lm & (1<<30))>0) return 30; /* Priority 3 */ if ((now & ~last & (1<<11))>0) return 11; /* Profiling */ if ((now & ~last & (1<<15))>0) return 15; /* Timer */ if ((now & ~lm & (1<<22))>0) return 22; if ((now & ~lm & (1<<23))>0) return 23; if ((now & ~lm & (1<<27))>0) return 27; if ((now & ~last & (1<<29))>0) return 29; /* Software */ /* Priority 2 */ if ((now & ~lm & (1<<19))>0) return 19; if ((now & ~lm & (1<<20))>0) return 20; if ((now & ~lm & (1<<21))>0) return 21; /* Priority 1 */ if ((now & ~lm & (1<<0))>0) return 0; if ((now & ~lm & (1<<1))>0) return 1; if ((now & ~lm & (1<<2))>0) return 2; if ((now & ~lm & (1<<3))>0) return 3; if ((now & ~lm & (1<<4))>0) return 4; if ((now & ~lm & (1<<5))>0) return 5; if ((now & ~last & (1<<6))>0) return 6; /* Timer */ if ((now & ~last & (1<<7))>0) return 7; /* Software */ if ((now & ~lm & (1<<8))>0) return 8; if ((now & ~lm & (1<<9))>0) return 9; if ((now & ~lm & (1<<10))>0) return 10; if ((now & ~lm & (1<<12))>0) return 12; if ((now & ~lm & (1<<13))>0) return 13; if ((now & ~lm & (1<<17))>0) return 17; if ((now & ~lm & (1<<18))>0) return 18; return -1; } void espintr::driver_app() { uint32_t last = 0; int nextintr; while(true) { wait(); nextintr = get_next(edge_interrupt_app.read(), intr_app.read(), last); last = intr_app.read(); if (nextintr >= 0 && handler_app[nextintr].fn != NULL) (*handler_pro[nextintr].fn)(handler_pro[nextintr].arg); } } void espintr::driver_pro() { uint32_t last = 0; int nextintr; while(true) { wait(); nextintr = get_next(edge_interrupt_pro.read(), intr_pro.read(), last); last = intr_pro.read(); if (nextintr >= 0 && handler_pro[nextintr].fn != NULL) (*handler_pro[nextintr].fn)(handler_pro[nextintr].arg); } } void espintr::maskupdate() { if (setunset) mask_pro.write(mask_pro.read() | newmask); else mask_pro.write(mask_pro.read() & ~newmask); if (setunset) mask_app.write(mask_app.read() | newmask); else mask_app.write(mask_app.read() & ~newmask); } void espintr::trace(sc_trace_file *tf) { sc_trace(tf, raw_app, raw_app.name()); sc_trace(tf, raw_pro, raw_pro.name()); sc_trace(tf, mask_app, mask_app.name()); sc_trace(tf, mask_pro, mask_pro.name()); sc_trace(tf, intr_app, intr_app.name()); sc_trace(tf, intr_pro, intr_pro.name()); }
/************************************************************************** * * * Catapult(R) Machine Learning Reference Design Library * * * * Software Version: 1.8 * * * * Release Date : Sun Jul 16 19:01:51 PDT 2023 * * Release Type : Production Release * * Release Build : 1.8.0 * * * * Copyright 2021 Siemens * * * ************************************************************************** * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * * implied. * * See the License for the specific language governing permissions and * * limitations under the License. * ************************************************************************** * * * The most recent version of this package is available at github. * * * *************************************************************************/ #include <systemc.h> #include "types.h" #include "sys_ram.h" #include "accel_if.h" #ifdef INCLUDE_UART #include "uart_if.h" #include "proc_fabric.h" #else #include "host_code_fabric.h" #endif #include "axi/axi4.h" #include "axi4_segment.h" #include "sysbus_axi_struct.h" class systemc_subsystem : public sc_module, public sysbus_axi { public: //== Ports sc_in<bool> clk; sc_in<bool> reset_bar; r_slave<> CCS_INIT_S1(r_cpu); w_slave<> CCS_INIT_S1(w_cpu); //== Local signals r_chan<> CCS_INIT_S1(r_acc_regs); w_chan<> CCS_INIT_S1(w_acc_regs); r_chan<> CCS_INIT_S1(r_acc_master); w_chan<> CCS_INIT_S1(w_acc_master); r_chan<> CCS_INIT_S1(r_memory); w_chan<> CCS_INIT_S1(w_memory); #ifdef INCLUDE_UART r_chan<> CCS_INIT_S1(r_uart); w_chan<> CCS_INIT_S1(w_uart); #endif //== Instances fabric CCS_INIT_S1(io_matrix); accel_if CCS_INIT_S1(go_fast); sys_ram CCS_INIT_S1(shared_memory); #ifdef INCLUDE_UART uart_if CCS_INIT_S1(uart); #endif //== Constructor SC_CTOR(systemc_subsystem) { io_matrix.clk (clk); io_matrix.rst_bar (reset_bar); io_matrix.r_mem (r_memory); io_matrix.w_mem (w_memory); io_matrix.r_reg (r_acc_regs); io_matrix.w_reg (w_acc_regs); io_matrix.r_cpu (r_cpu); io_matrix.w_cpu (w_cpu); io_matrix.r_acc (r_acc_master); io_matrix.w_acc (w_acc_master); #ifdef INCLUDE_UART io_matrix.r_uart (r_uart); io_matrix.w_uart (w_uart); #endif shared_memory.clk (clk); shared_memory.rst_bar (reset_bar); shared_memory.r_slave0 (r_memory); shared_memory.w_slave0 (w_memory); go_fast.clk (clk); go_fast.rst_bar (reset_bar); go_fast.r_reg_if (r_acc_regs); go_fast.w_reg_if (w_acc_regs); go_fast.r_mem_if (r_acc_master); go_fast.w_mem_if (w_acc_master); #ifdef INCLUDE_UART uart.clk (clk); uart.rst_bar (reset_bar); uart.r_uart_if (r_uart); uart.w_uart_if (w_uart); #endif } }; class systemc_subsystem_wrapper : public sc_module, public sysbus_axi { public: //== Ports sc_in <bool> clk; sc_in <bool> reset_bar; sc_in <sc_lv<44>> aw_msg_port; sc_in <bool> aw_valid_port; sc_out<bool> aw_ready_port; sc_in <sc_lv<37>> w_msg_port; sc_in <bool> w_valid_port; sc_out<bool> w_ready_port; sc_out<sc_lv<6>> b_msg_port; sc_out<bool> b_valid_port; sc_in <bool> b_ready_port; sc_in <sc_lv<44>> ar_msg_port; sc_in <bool> ar_valid_port; sc_out<bool> ar_ready_port; sc_out<sc_lv<39>> r_msg_port; sc_out<bool> r_valid_port; sc_in <bool> r_ready_port; sc_clock connections_clk; sc_event check_event; virtual void start_of_simulation() { Connections::get_sim_clk().add_clock_alias( connections_clk.posedge_event(), clk.posedge_event()); } void check_clock() { check_event.notify(2, SC_PS);} // Let SC and Vlog delta cycles settle. void check_event_method() { if (connections_clk.read() == clk.read()) return; CCS_LOG("clocks misaligned!:" << connections_clk.read() << " " << clk.read()); } systemc_subsystem CCS_INIT_S1(scs); SC_CTOR(systemc_subsystem_wrapper) : connections_clk("connections_clk", CLOCK_PERIOD, SC_NS, 0.5, 0, SC_NS, true) { SC_METHOD(check_clock); sensitive << connections_clk; sensitive << clk; SC_METHOD(check_event_method); sensitive << check_event; scs.clk(clk); scs.reset_bar(reset_bar); scs.w_cpu.aw.msg(aw_msg_port); scs.w_cpu.aw.val(aw_valid_port); scs.w_cpu.aw.rdy(aw_ready_port); scs.w_cpu.w.msg(w_msg_port); scs.w_cpu.w.val(w_valid_port); scs.w_cpu.w.rdy(w_ready_port); scs.w_cpu.b.msg(b_msg_port); scs.w_cpu.b.val(b_valid_port); scs.w_cpu.b.rdy(b_ready_port); scs.r_cpu.ar.msg(ar_msg_port); scs.r_cpu.ar.val(ar_valid_port); scs.r_cpu.ar.rdy(ar_ready_port); scs.r_cpu.r.msg(r_msg_port); scs.r_cpu.r.val(r_valid_port); scs.r_cpu.r.rdy(r_ready_port); } }; #ifdef QUESTA SC_MODULE_EXPORT(systemc_subsystem_wrapper); #endif
/******************************************************************************* * sc_main.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * The sc_main is the first function always called by the SystemC environment. * This one takes as arguments a test name and an option: * * testname.x [testnumber] [+waveform] * * testnumber - test to run, 0 for t0, 1 for t1, etc. Default = 0. * +waveform - generate VCD file for top level signals. * ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "HelloServertest.h" HelloServertest i_helloservertest("i_helloservertest"); int sc_main(int argc, char *argv[]) { int tn; bool wv = false; if (argc > 3) { SC_REPORT_ERROR("MAIN", "Too many arguments used in call"); return 1; } /* If no arguments are given, argc=1, there is no waveform and we run * test 0. */ else if (argc == 1) { tn = 0; wv = false; } /* If we have at least one argument, we check if it is the waveform command. * If it is, we set a tag. If we have two arguments, we assume the second * one is the test number. */ else if (strcmp(argv[1], "+waveform")==0) { wv = true; /* If two arguments were given (argc=3) we assume the second one is the * test name. If the testnumber was not given, we run test 0. */ if (argc == 3) tn = atoi(argv[2]); else tn = 0; } /* For the remaining cases, we check. If there are two arguments, the first * one must be the test number and the second one might be the waveform * option. If we see 2 arguments, we do that. If we do not, then we just * have a testcase number. */ else { if (argc == 3 && strcmp(argv[2], "+waveform")==0) wv = true; else wv = false; tn = atoi(argv[1]); } /* We start the wave tracing. */ sc_trace_file *tf = NULL; if (wv) { tf = sc_create_vcd_trace_file("waves"); i_helloservertest.trace(tf); } /* We need to connect the Arduino pin library to the gpios. */ i_helloservertest.i_esp.pininit(); /* Set the test number */ i_helloservertest.tn = tn; /* And run the simulation. */ sc_start(); if (wv) sc_close_vcd_trace_file(tf); exit(0); }
//**************************************************************************************** // MIT License //**************************************************************************************** // Copyright (c) 2012-2020 University of Bremen, Germany. // Copyright (c) 2015-2020 DFKI GmbH Bremen, Germany. // Copyright (c) 2020 Johannes Kepler University Linz, Austria. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //**************************************************************************************** #include <crave/SystemC.hpp> #include <crave/ConstrainedRandom.hpp> #include <systemc.h> #include <boost/timer.hpp> using crave::rand_obj; using crave::randv; using sc_dt::sc_bv; using sc_dt::sc_uint; struct ALU16 : public rand_obj { randv<sc_bv<2> > op; randv<sc_uint<16> > a, b; ALU16(rand_obj* parent = 0) : rand_obj(parent), op(this), a(this), b(this) { constraint((op() != 0x0) || (65535 >= a() + b())); constraint((op() != 0x1) || ((65535 >= a() - b()) && (b() <= a()))); constraint((op() != 0x2) || (65535 >= a() * b())); constraint((op() != 0x3) || (b() != 0)); } friend std::ostream& operator<<(std::ostream& o, ALU16 const& alu) { o << alu.op << ' ' << alu.a << ' ' << alu.b; return o; } }; int sc_main(int argc, char** argv) { crave::init("crave.cfg"); boost::timer timer; ALU16 c; CHECK(c.next()); std::cout << "first: " << timer.elapsed() << "\n"; for (int i = 0; i < 1000; ++i) { CHECK(c.next()); } std::cout << "complete: " << timer.elapsed() << "\n"; return 0; }
#include <crave/SystemC.hpp> #include <crave/ConstrainedRandom.hpp> #include <systemc.h> #include <boost/timer.hpp> using crave::rand_obj; using crave::randv; using sc_dt::sc_bv; using sc_dt::sc_uint; struct ALU24 : public rand_obj { randv< sc_bv<2> > op ; randv< sc_uint<24> > a, b ; ALU24() : op(this), a(this), b(this) { constraint ( (op() != 0x0) || ( 16777215 >= a() + b() ) ); constraint ( (op() != 0x1) || ((16777215 >= a() - b()) && (b() <= a()) ) ); constraint ( (op() != 0x2) || ( 16777215 >= a() * b() ) ); constraint ( (op() != 0x3) || ( b() != 0 ) ); } friend std::ostream & operator<< (std::ostream & o, ALU24 const & alu) { o << alu.op << ' ' << alu.a << ' ' << alu.b ; return o; } }; int sc_main (int argc, char** argv) { boost::timer timer; ALU24 c; c.next(); std::cout << "first: " << timer.elapsed() << "\n"; for (int i=0; i<1000; ++i) { c.next(); } std::cout << "complete: " << timer.elapsed() << "\n"; return 0; }
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** simple_fifo.cpp -- Simple SystemC 2.0 producer/consumer example. From "An Introduction to System Level Modeling in SystemC 2.0". By Stuart Swan, Cadence Design Systems. Available at www.accellera.org Original Author: Stuart Swan, Cadence Design Systems, 2001-06-18 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include <systemc.h> class write_if : virtual public sc_interface { public: virtual void write(char) = 0; virtual void reset() = 0; }; class read_if : virtual public sc_interface { public: virtual void read(char &) = 0; virtual int num_available() = 0; }; class fifo : public sc_channel, public write_if, public read_if { public: fifo(sc_module_name name) : sc_channel(name), num_elements(0), first(0) {} void write(char c) { if (num_elements == max) wait(read_event); data[(first + num_elements) % max] = c; ++ num_elements; write_event.notify(); } void read(char &c){ if (num_elements == 0) wait(write_event); c = data[first]; -- num_elements; first = (first + 1) % max; read_event.notify(); } void reset() { num_elements = first = 0; } int num_available() { return num_elements;} private: enum e { max = 10 }; char data[max]; int num_elements, first; sc_event write_event, read_event; }; class producer : public sc_module { public: sc_port<write_if> out; producer(sc_module_name name) : sc_module(name) { SC_THREAD(main); } void main() { const char *str = "Visit www.accellera.org and see what SystemC can do for you today!\n"; while (*str) out->write(*str++); } }; class consumer : public sc_module { public: sc_port<read_if> in; consumer(sc_module_name name) : sc_module(name) { SC_THREAD(main); } void main() { char c; cout << endl << endl; while (true) { in->read(c); cout << c << flush; if (in->num_available() == 1) cout << "<1>" << flush; if (in->num_available() == 9) cout << "<9>" << flush; } } }; class top : public sc_module { public: fifo *fifo_inst; producer *prod_inst; consumer *cons_inst; top(sc_module_name name) : sc_module(name) { fifo_inst = new fifo("Fifo1"); prod_inst = new producer("Producer1"); prod_inst->out(*fifo_inst); cons_inst = new consumer("Consumer1"); cons_inst->in(*fifo_inst); } }; int sc_main (int, char *[]) { top top1("Top1"); sc_start(); return 0; }
/******************************************************************************** * 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_01_ANN_INPUTS 2 // Number of inputs #define cD_01_ANN_OUTPUTS 1 // Number of outputs //----------------------------------------------------------------------------- // Physical constants //----------------------------------------------------------------------------- static double cD_01_I_0 = 77.3 ; // [A] Nominal current static double cD_01_T_0 = 298.15 ; // [K] Ambient temperature static double cD_01_R_0 = 0.01 ; // [Ω] Data-sheet R_DS_On (Drain-Source resistance in the On State) static double cD_01_V_0 = 47.2 ; // [V] Nominal voltage static double cD_01_Alpha = 0.002 ; // [Ω/K] Temperature coefficient of Drain-Source resistance in the On State static double cD_01_ThermalConstant = 0.75 ; static double cD_01_Tau = 0.02 ; // [s] Sampling period //----------------------------------------------------------------------------- // Status descriptors //----------------------------------------------------------------------------- typedef struct cD_01_DEVICE // Descriptor of the state of the device { double t ; // Operating temperature double r ; // Operating Drain-Source resistance in the On State double i ; // Operating current double v ; // Operating voltage double time_Ex ; int fault ; } cD_01_DEVICE ; static cD_01_DEVICE cD_01_device; //----------------------------------------------------------------------------- // Mnemonics to access the array that contains the sampled data //----------------------------------------------------------------------------- #define cD_01_SAMPLE_LEN 3 // Array of SAMPLE_LEN elements #define cD_01_I_INDEX 0 // Current #define cD_01_V_INDEX 1 // Voltage #define cD_01_TIME_INDEX 2 // Time ///----------------------------------------------------------------------------- // Forward references //----------------------------------------------------------------------------- static int cD_01_initDescriptors(cD_01_DEVICE device) ; //static void getSample(int index, double sample[SAMPLE_LEN]) ; static void cD_01_cleanData(int index, double sample[cD_01_SAMPLE_LEN]) ; static double cD_01_extractFeatures(double tPrev, double iPrev, double iNow, double rPrev) ; static void cD_01_normalize(int index, double x[cD_01_ANN_INPUTS]) ; static double cD_01_degradationModel(double tNow) ; //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- int cD_01_initDescriptors(cD_01_DEVICE device) { // for (int i = 0; i < NUM_DEV; i++) // { device.t = cD_01_T_0 ; // Operating temperature = Ambient temperature device.r = cD_01_R_0 ; // Operating R_DS_On = Data-sheet R_DS_On // printf("Init %d \n",i); // } return( EXIT_SUCCESS ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void cD_01_cleanData(int index, double sample[cD_01_SAMPLE_LEN]) { // the parameter "index" could be useful to retrieve the characteristics of the device if ( sample[cD_01_I_INDEX] < 0 ) sample[cD_01_I_INDEX] = 0 ; else if ( sample[cD_01_I_INDEX] > (2.0 * cD_01_I_0) ) sample[cD_01_I_INDEX] = (2.0 * cD_01_I_0) ; // Postcondition: (0 <= sample[I_INDEX] <= 2.0*I_0) if ( sample[cD_01_V_INDEX] < 0 ) sample[cD_01_V_INDEX] = 0 ; else if ( sample[cD_01_V_INDEX] > (2.0 * cD_01_V_0 ) ) sample[cD_01_V_INDEX] = (2.0 * cD_01_V_0) ; // Postcondition: (0 <= sample[V_INDEX] <= 2.0*V_0) } //----------------------------------------------------------------------------- // Input: // - tPrev = temperature at previous step // - iPrev = current at previous step // - iNow = current at this step // - rPrev = resistance at the previous step // Return: // - The new temperature // Very simple model: // - one constant for dissipation and heat capacity // - temperature considered constant during the step //----------------------------------------------------------------------------- double cD_01_extractFeatures(double tPrev, double iPrev, double iNow, double rPrev) { double t ; // Temperature double i = 0.5*(iPrev + iNow); // Average current //printf("cD_01_extractFeatures tPrev=%f\n",tPrev); t = tPrev + // Previous temperature rPrev * (i * i) * cD_01_Tau - // Heat generated: P = I·R^2 cD_01_ThermalConstant * (tPrev - cD_01_T_0) * cD_01_Tau ; // Dissipation and heat capacity return( t ); } //----------------------------------------------------------------------------- // Input: // - tNow: temperature at this step // Return: // - the resistance // The model isn't realistic because the even the simpler law is exponential //----------------------------------------------------------------------------- double cD_01_degradationModel(double tNow) { double r ; //r = R_0 + Alpha * tNow ; r = cD_01_R_0 * ( 2 - exp(-cD_01_Alpha*tNow) ); return( r ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void cD_01_normalize(int index, double sample[cD_01_ANN_INPUTS]) { double i ; double v ; // Precondition: (0 <= sample[I_INDEX] <= 2*I_0) && (0 <= sample[V_INDEX] <= 2*V_0) i = sample[cD_01_I_INDEX] <= cD_01_I_0 ? 0.0 : 1.0; v = sample[cD_01_V_INDEX] <= cD_01_V_0 ? 0.0 : 1.0; // Postcondition: (i in {0.0, 1.0}) and (v in {0.0, 1.0}) sample[cD_01_I_INDEX] = i ; sample[cD_01_V_INDEX] = v ; } void mainsystem::cleanData_01_main() { // datatype for channels sampleTimCord_cleanData_xx_payload sampleTimCord_cleanData_xx_payload_var; cleanData_xx_ann_xx_payload cleanData_xx_ann_xx_payload_var; //device var uint8_t dev; //step var uint16_t step; // ex_time (for extractFeatures...) double ex_time; //samples i and v double sample_i; double sample_v; //var for samples, to re-use cleanData() double cD_01_sample[cD_01_SAMPLE_LEN] ; double x[cD_01_ANN_INPUTS + cD_01_ANN_OUTPUTS] ; // NOTE: commented, should be changed param by ref... //cD_01_initDescriptors(cD_01_device); cD_01_device.t = cD_01_T_0 ; // Operating temperature = Ambient temperature cD_01_device.r = cD_01_R_0 ; // Operating R_DS_On = Data-sheet R_DS_On // ### added for time related dynamics //static double cD_01_Tau = 0.02 ; // [s] Sampling period double cD_01_last_sample_time = 0; //implementation HEPSY_S(cleanData_01_id) while(1) {HEPSY_S(cleanData_01_id) // content sampleTimCord_cleanData_xx_payload_var = sampleTimCord_cleanData_01_channel->read(); dev = sampleTimCord_cleanData_xx_payload_var.dev; step = sampleTimCord_cleanData_xx_payload_var.step; ex_time = sampleTimCord_cleanData_xx_payload_var.ex_time; sample_i = sampleTimCord_cleanData_xx_payload_var.sample_i; sample_v = sampleTimCord_cleanData_xx_payload_var.sample_v; // cout << "cleanData_01 rcv \t dev: " << dev // <<"\t step: " << step // <<"\t time_ex:" << ex_time // <<"\t i:" << sample_i // <<"\t v:" << sample_v // << endl; // reconstruct sample cD_01_sample[cD_01_I_INDEX] = sample_i; cD_01_sample[cD_01_V_INDEX] = sample_v; cD_01_sample[cD_01_TIME_INDEX] = ex_time; // ### C L E A N D A T A (0 <= I <= 2.0*I_0) and (0 <= V <= 2.0*V_0) cD_01_cleanData(dev, cD_01_sample) ; cD_01_device.time_Ex = cD_01_sample[cD_01_TIME_INDEX] ; cD_01_device.i = cD_01_sample[cD_01_I_INDEX] ; cD_01_device.v = cD_01_sample[cD_01_V_INDEX] ; // ### added for time related dynamics //static double cD_01_Tau = 0.02 ; // [s] Sampling period cD_01_Tau = ex_time - cD_01_last_sample_time; cD_01_last_sample_time = ex_time; // ### F E A T U R E S E X T R A C T I O N (compute the temperature) cD_01_device.t = cD_01_extractFeatures( cD_01_device.t, // Previous temperature cD_01_device.i, // Previous current cD_01_sample[cD_01_I_INDEX], // Current at this step cD_01_device.r) ; // Previous resistance // ### D E G R A D A T I O N M O D E L (compute R_DS_On) cD_01_device.r = cD_01_degradationModel(cD_01_device.t) ; // ### N O R M A L I Z E: (x[0] in {0.0, 1.0}) and (x[1] in {0.0, 1.0}) x[0] = cD_01_device.i ; x[1] = cD_01_device.v ; cD_01_normalize(dev, x) ; // // ### P R E D I C T (simple XOR) // if ( annRun(index, x) != EXIT_SUCCESS ){ //prepare out data payload cleanData_xx_ann_xx_payload_var.dev = dev; cleanData_xx_ann_xx_payload_var.step = step; cleanData_xx_ann_xx_payload_var.ex_time = ex_time; cleanData_xx_ann_xx_payload_var.device_i = cD_01_device.i; cleanData_xx_ann_xx_payload_var.device_v = cD_01_device.v; cleanData_xx_ann_xx_payload_var.device_t = cD_01_device.t; cleanData_xx_ann_xx_payload_var.device_r = cD_01_device.r; cleanData_xx_ann_xx_payload_var.x_0 = x[0]; cleanData_xx_ann_xx_payload_var.x_1 = x[1]; cleanData_xx_ann_xx_payload_var.x_2 = x[2]; cleanData_01_ann_01_channel->write(cleanData_xx_ann_xx_payload_var); HEPSY_P(cleanData_01_id) } } //END
#include <systemc.h> #include <string> #include "fetch.h" #include "testbench.h" int sc_main(int argv, char* argc[]) { sc_time PERIOD(10,SC_NS); sc_time DELAY(10,SC_NS); sc_clock clock("clock",PERIOD,0.5,DELAY,true); fetch ft("fetch"); testbench tb("tb"); sc_signal< sc_uint<14> > instruction_sg; sc_signal<bool> connection_sg; ft.instruction(instruction_sg); ft.clk(clock); ft.connection(connection_sg); tb.instruction(instruction_sg); tb.clk(clock); tb.connection(connection_sg); sc_start(); 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. *****************************************************************************/ /***************************************************************************** stimulus.cpp -- Original Author: Rocco Jonack, 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 "stimulus.h" void stimulus::entry() { cycle++; // sending some reset values if (cycle<4) { reset.write(true); input_valid.write(false); } else { reset.write(false); input_valid.write( false ); // sending normal mode values if (cycle%10==0) { input_valid.write(true); sample.write( (int)send_value1 ); cout << "Stimuli : " << (int)send_value1 << " at time " /* << sc_time_stamp() << endl; */ << sc_time_stamp().to_double() << endl; send_value1++; }; } }
/***************************************************************************** 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. *****************************************************************************/ /***************************************************************************** stimulus.cpp -- Original Author: Rocco Jonack, 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 "stimulus.h" void stimulus::entry() { cycle++; // sending some reset values if (cycle<4) { reset.write(true); input_valid.write(false); } else { reset.write(false); input_valid.write( false ); // sending normal mode values if (cycle%10==0) { input_valid.write(true); sample.write( (int)send_value1 ); cout << "Stimuli : " << (int)send_value1 << " at time " /* << sc_time_stamp() << endl; */ << sc_time_stamp().to_double() << endl; send_value1++; }; } }
#include <systemc.h> // // Every HW component class has to be derived from :class:`hwt.hwModule.HwModule` class // // .. hwt-autodoc:: // SC_MODULE(Showcase0) { // ports sc_in<sc_uint<32>> a; sc_in<sc_int<32>> b; sc_out<sc_uint<32>> c; sc_in_clk clk; sc_out<sc_uint<1>> cmp_0; sc_out<sc_uint<1>> cmp_1; sc_out<sc_uint<1>> cmp_2; sc_out<sc_uint<1>> cmp_3; sc_out<sc_uint<1>> cmp_4; sc_out<sc_uint<1>> cmp_5; sc_out<sc_uint<32>> contOut; sc_in<sc_uint<32>> d; sc_in<sc_uint<1>> e; sc_out<sc_uint<1>> f; sc_out<sc_uint<16>> fitted; sc_out<sc_uint<8>> g; sc_out<sc_uint<8>> h; sc_in<sc_uint<2>> i; sc_out<sc_uint<8>> j; sc_out<sc_uint<32>> k; sc_out<sc_uint<1>> out; sc_out<sc_uint<1>> output; sc_in<sc_uint<1>> rst_n; sc_out<sc_uint<8>> sc_signal_0; // component instances // internal signals sc_uint<32> const_private_signal = sc_uint<32>("0x0000007B"); sc_int<8> fallingEdgeRam[4]; sc_uint<1> r = sc_uint<1>("0b0"); sc_uint<2> r_0 = sc_uint<2>("0b00"); sc_uint<2> r_1 = sc_uint<2>("0b00"); sc_signal<sc_uint<1>> r_next; sc_signal<sc_uint<2>> r_next_0; sc_signal<sc_uint<2>> r_next_1; sc_uint<8> rom[4] = {sc_uint<8>("0x00"), sc_uint<8>("0x01"), sc_uint<8>("0x02"), sc_uint<8>("0x03"), }; void assig_process_c() { c.write(static_cast<sc_uint<32>>(a.read() + static_cast<sc_uint<32>>(b.read()))); } void assig_process_cmp_0() { cmp_0.write(a.read() < sc_uint<32>("0x00000004")); } void assig_process_cmp_1() { cmp_1.write(a.read() > sc_uint<32>("0x00000004")); } void assig_process_cmp_2() { cmp_2.write(b.read() <= sc_int<32>("0x00000004")); } void assig_process_cmp_3() { cmp_3.write(b.read() >= sc_int<32>("0x00000004")); } void assig_process_cmp_4() { cmp_4.write(b.read() != sc_int<32>("0x00000004")); } void assig_process_cmp_5() { cmp_5.write(b.read() == sc_int<32>("0x00000004")); } void assig_process_contOut() { contOut.write(static_cast<sc_uint<32>>(const_private_signal)); } void assig_process_f() { f.write(r); } void assig_process_fallingEdgeRam() { sc_signal<sc_uint<32>> tmpConcat_0; tmpConcat_0.write((sc_uint<24>("0x000000"), static_cast<sc_uint<8>>(static_cast<sc_uint<8>>(fallingEdgeRam[r_1])), )); { (fallingEdgeRam[r_1]).write(static_cast<sc_int<8>>(a.read().range(sc_int<32>("0x00000008"), sc_int<32>("0x00000000")))); k = tmpConcat_0.read(); } } void assig_process_fitted() { fitted.write(static_cast<sc_uint<16>>(a.read().range(sc_int<32>("0x00000010"), sc_int<32>("0x00000000")))); } void assig_process_g() { sc_signal<sc_uint<2>> tmpConcat_1; sc_signal<sc_uint<8>> tmpConcat_0; tmpConcat_1.write((a.read()[sc_int<32>("0x00000001")] & b.read()[sc_int<32>("0x00000001")], a.read()[sc_int<32>("0x00000000")] ^ b.read()[sc_int<32>("0x00000000")] | a.read()[sc_int<32>("0x00000001")], )); tmpConcat_0.write((tmpConcat_1.read(), static_cast<sc_uint<6>>(a.read().range(sc_int<32>("0x00000006"), sc_int<32>("0x00000000"))), )); g.write(tmpConcat_0.read()); } void assig_process_h() { if (a.read()[sc_int<32>("0x00000002")] == sc_uint<1>("0b1")) if (r == sc_uint<1>("0b1")) h.write(sc_uint<8>("0x00")); else if (a.read()[sc_int<32>("0x00000001")] == sc_uint<1>("0b1")) h.write(sc_uint<8>("0x01")); else h.write(sc_uint<8>("0x02")); } void assig_process_j() { j = static_cast<sc_uint<8>>(rom[r_1]); } void assig_process_out() { out.write(sc_uint<1>("0b0")); } void assig_process_output() { output.write(sc_uint<1>("0bX")); } void assig_process_r() { if (rst_n.read() == sc_uint<1>("0b0")) { r_1 = sc_uint<2>("0b00"); r_0 = sc_uint<2>("0b00"); r = sc_uint<1>("0b0"); } else { r_1 = r_next_1.read(); r_0 = r_next_0.read(); r = r_next.read(); } } void assig_process_r_next() { r_next_0.write(i.read()); } void assig_process_r_next_0() { r_next_1.write(r_0); } void assig_process_r_next_1() { if (r == sc_uint<1>("0b0")) r_next.write(e.read()); else r_next.write(r); } void assig_process_sc_signal_0() { switch(a.read()) { case sc_uint<32>("0x00000001"): { sc_signal_0.write(sc_uint<8>("0x00")); break; } case sc_uint<32>("0x00000002"): { sc_signal_0.write(sc_uint<8>("0x01")); break; } case sc_uint<32>("0x00000003"): { sc_signal_0.write(sc_uint<8>("0x03")); break; } default: sc_signal_0.write(sc_uint<8>("0x04")); } } SC_CTOR(Showcase0) { SC_METHOD(assig_process_c); sensitive << a << b; SC_METHOD(assig_process_cmp_0); sensitive << a; SC_METHOD(assig_process_cmp_1); sensitive << a; SC_METHOD(assig_process_cmp_2); sensitive << b; SC_METHOD(assig_process_cmp_3); sensitive << b; SC_METHOD(assig_process_cmp_4); sensitive << b; SC_METHOD(assig_process_cmp_5); sensitive << b; assig_process_contOut(); SC_METHOD(assig_process_f); sensitive << r; SC_METHOD(assig_process_fallingEdgeRam); sensitive << clk.neg(); SC_METHOD(assig_process_fitted); sensitive << a; SC_METHOD(assig_process_g); sensitive << a << b; SC_METHOD(assig_process_h); sensitive << a << r; SC_METHOD(assig_process_j); sensitive << clk.pos(); assig_process_out(); assig_process_output(); SC_METHOD(assig_process_r); sensitive << clk.pos(); SC_METHOD(assig_process_r_next); sensitive << i; SC_METHOD(assig_process_r_next_0); sensitive << r_0; SC_METHOD(assig_process_r_next_1); sensitive << e << r; SC_METHOD(assig_process_sc_signal_0); sensitive << a; // connect ports } };
// nand gate // Luciano Sobral <[email protected]> // this sample should fail #include <systemc.h> SC_MODULE(nand_gate) { sc_inout<bool> a; sc_inout<bool> b; sc_out<bool> c; void nand_process(void) { and_process(); // c = a and b c = !c.read(); // c = not c } void and_process ( void ) { c = a.read() && b.read(); } void test_process(void) { assert( c.read() == ( a.read() && b.read() ) ); } SC_CTOR(nand_gate) { } }; int sc_main( int argc, char * argv[] ) { sc_signal<bool> s1; sc_signal<bool> s2; sc_signal<bool> s3; s1.write(true); s2.write(false); s3.write(false); nand_gate gate("nand_gate"); gate.a(s1); gate.b(s2); gate.c(s3); gate.nand_process(); gate.test_process(); return 0; }
// nand gate // Luciano Sobral <[email protected]> // this sample should fail #include <systemc.h> SC_MODULE(nand_gate) { sc_inout<bool> a; sc_inout<bool> b; sc_out<bool> c; void nand_process(void) { and_process(); // c = a and b c = !c.read(); // c = not c } void and_process ( void ) { c = a.read() && b.read(); } void test_process(void) { assert( c.read() == ( a.read() && b.read() ) ); } SC_CTOR(nand_gate) { } }; int sc_main( int argc, char * argv[] ) { sc_signal<bool> s1; sc_signal<bool> s2; sc_signal<bool> s3; s1.write(true); s2.write(false); s3.write(false); nand_gate gate("nand_gate"); gate.a(s1); gate.b(s2); gate.c(s3); gate.nand_process(); gate.test_process(); return 0; }
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** rsa.cpp -- An implementation of the RSA public-key cipher. The following implementation is based on the one given in Cormen et al., Inroduction to Algorithms, 1991. I'll refer to this book as CLR because of its authors. This implementation shows the usage of arbitrary precision types of SystemC. That is, these types in SystemC can be used to implement algorithmic examples regarding arbitrary precision integers. The algorithms used are not the most efficient ones; however, they are intended for explanatory purposes, so they are simple and perform their job correctly. Below, NBITS shows the maximum number of bits in n, the variable that is a part of both the public and secret keys, P and S, respectively. NBITS can be made larger at the expense of longer running time. For example, CLR mentions that the RSA cipher uses large primes that contain approximately 100 decimal digits. This means that NBITS should be set to approximately 560. Some background knowledge: A prime number p > 1 is an integer that has only two divisiors, 1 and p itself. For example, 2, 3, 5, 7, and 11 are all primes. If p is not a prime number, it is called a composite number. If we are given two primes p and q, it is easy to find their product p * q; however, if we are given a number m which happens to be the product of two primes p and q that we do not know, it is very difficult to find p and q if m is very large, i.e., it is very difficult to factor m. The RSA public-key cryptosystem is based on this fact. Internally, we use the Miller-Rabin randomized primality test to deal with primes. More information can be obtained from pp. 831-836 in CLR, the first edition. Original Author: Ali Dasdan, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include <stdlib.h> #include <sys/types.h> #include <time.h> #include <stdlib.h> // drand48, srand48 #include "systemc.h" #define DEBUG_SYSTEMC // #undef this to disable assertions. // NBITS is the number of bits in n of public and secret keys P and // S. HALF_NBITS is the number of bits in p and q, which are the prime // factors of n. #define NBITS 250 #define HALF_NBITS ( NBITS / 2 ) // +2 is for the format specifier '0b' to make the string binary. #define STR_SIZE ( NBITS + 2 ) #define HALF_STR_SIZE ( HALF_NBITS + 2 ) typedef sc_bigint<NBITS> bigint; // Return the absolute value of x. inline bigint abs_val( const sc_signed& x ) { return ( x < 0 ? -x : x ); } // Initialize the random number generator. If seed == -1, the // generator will be initialized with the system time. If not, it will // be initialized with the given seed. This way, an experiment with // random numbers becomes reproducible. inline long randomize( int seed ) { long in_seed; // time_t is long. in_seed = ( seed <= 0 ? static_cast<long>(time( 0 )) : seed ); srand( ( unsigned ) in_seed ); return in_seed; } // Flip a coin with probability p. inline bool flip( double p ) { // rand() produces an integer between 0 and RAND_MAX so // rand() / RAND_MAX is a number between 0 and 1, // which is required to compare with p. return ( rand() < ( int ) ( p * RAND_MAX ) ); } // Randomly generate a bit string with nbits bits. str has a length // of nbits + 1. This function is used to generate random messages to // process. inline void rand_bitstr( char *str, int nbits ) { assert( nbits >= 4 ); str[ 0 ] = '0'; str[ 1 ] = 'b'; str[ 2 ] = '0'; // Sign for positive numbers. for ( int i = 3; i < nbits; ++i ) str[ i ] = ( flip( 0.5 ) == true ? '1' : '0' ); str[ nbits ] = '\0'; } // Generate "111..111" with nbits bits for masking. // str has a length of nbits + 1. inline void max_bitstr( char *str, int nbits ) { assert( nbits >= 4 ); str[ 0 ] = '0'; str[ 1 ] = 'b'; str[ 2 ] = '0'; // Sign for positive numbers. for ( int i = 3; i < nbits; ++i ) str[ i ] = '1'; str[ nbits ] = '\0'; } // Return a positive remainder. inline bigint ret_pos( const bigint& x, const bigint& n ) { if ( x < 0 ) return x + n; return x; } // Compute the greatest common divisor ( gcd ) of a and b. This is // Euclid's algorithm. This algorithm is at least 2,300 years old! The // non-recursive version of this algorithm is not as elegant. bigint gcd( const bigint& a, const bigint& b ) { if ( b == 0 ) return a; return gcd( b, a % b ); } // Compute d, x, and y such that d = gcd( a, b ) = ax + by. x and y can // be zero or negative. This algorithm is also Euclid's algorithm but // it is extended to also find x and y. Recall that the existence of x // and y is guaranteed by Euclid's algorithm. void euclid( const bigint& a, const bigint& b, bigint& d, bigint& x, bigint& y ) { if ( b != 0 ) { euclid( b, a % b, d, x, y ); bigint tmp = x; x = y; y = tmp - ( a / b ) * y; } else { d = a; x = 1; y = 0; } } // Return d = a^b % n, where ^ represents exponentiation. inline bigint modular_exp( const bigint& a, const bigint& b, const bigint& n ) { bigint d = 1; for ( int i = b.length() - 1; i >= 0; --i ) { d = ( d * d ) % n; if ( b[ i ] ) d = ( d * a ) % n; } return ret_pos( d, n ); } // Return the multiplicative inverse of a, modulo n, when a and n are // relatively prime. Recall that x is a multiplicative inverse of a, // modulo n, if a * x = 1 ( mod n ). inline bigint inverse( const bigint& a, const bigint& n ) { bigint d, x, y; euclid( a, n, d, x, y ); assert( d == 1 ); x %= n; return ret_pos( x, n ); } // Find a small odd integer a that is relatively prime to n. I do not // know an efficient algorithm to do that but the loop below seems to // work; it usually iterates a few times. Recall that a is relatively // prime to n if their only common divisor is 1, i.e., gcd( a, n ) == // 1. inline bigint find_rel_prime( const bigint& n ) { bigint a = 3; while ( true ) { if ( gcd( a, n ) == 1 ) break; a += 2; #ifdef DEBUG_SYSTEMC assert( a < n ); #endif } return a; } // Return true if and only if a is a witness to the compositeness of // n, i.e., a can be used to prove that n is composite. inline bool witness( const bigint& a, const bigint& n ) { bigint n_minus1 = n - 1; bigint x; bigint d = 1; // Compute d = a^( n-1 ) % n. for ( int i = n.length() - 1; i >= 0; --i ) { // Sun's SC5 bug when compiling optimized version // makes the wrong assignment if abs_val() is inlined //x = (sc_signed)d<0?-(sc_signed)d:(sc_signed)d;//abs_val( d ); if(d<0) { x = -d; assert(x==-d); } else { x = d; assert(x==d); } d = ( d * d ) % n; // x is a nontrivial square root of 1 modulo n ==> n is composite. if ( ( abs_val( d ) == 1 ) && ( x != 1 ) && ( x != n_minus1 ) ) return true; if ( n_minus1[ i ] ) d = ( d * a ) % n; } // d = a^( n-1 ) % n != 1 ==> n is composite. if ( abs_val( d ) != 1 ) return true; return false; } // Check to see if n has any small divisors. For small numbers, we do // not have to run the Miller-Rabin primality test. We define "small" // to be less than 1023. You can change it if necessary. inline bool div_test( const bigint& n ) { int limit; if ( n < 1023 ) limit = n.to_int() - 2; else limit = 1023; for ( int i = 3; i <= limit; i += 2 ) { if ( n % i == 0 ) return false; // n is composite. } return true; // n may be prime. } // Return true if n is almost surely prime, return false if n is // definitely composite. This test, called the Miller-Rabin primality // test, errs with probaility at most 2^(-s). CLR suggests s = 50 for // any imaginable application, and s = 3 if we are trying to find // large primes by applying miller_rabin to randomly chosen large // integers. Even though we are doing the latter here, we will still // choose s = 50. The probability of failure is at most // 0.00000000000000088817, a pretty small number. inline bool miller_rabin( const bigint& n ) { if ( n <= 2 ) return false; if ( ! div_test( n ) ) return false; char str[ STR_SIZE + 1 ]; int s = 50; for ( int j = 1; j <= s; ++j ) { // Choose a random number. rand_bitstr( str, STR_SIZE ); // Set a to the chosen number. bigint a = str; // Make sure that a is in [ 1, n - 1 ]. a = ( a % ( n - 1 ) ) + 1; // Check to see if a is a witness. if ( witness( a, n ) ) return false; // n is definitely composite. } return true; // n is almost surely prime. } // Return a randomly generated, large prime number using the // Miller-Rabin primality test. inline bigint find_prime( const bigint& r ) { char p_str[ HALF_STR_SIZE + 1 ]; rand_bitstr( p_str, HALF_STR_SIZE ); p_str[ HALF_STR_SIZE - 1 ] = '1'; // Force p to be an odd number. bigint p = p_str; #ifdef DEBUG_SYSTEMC assert( ( p > 0 ) && ( p % 2 == 1 ) ); #endif // p is randomly determined. Now, we'll look for a prime in the // vicinity of p. By the prime number theorem, executing the // following loop approximately ln ( 2^NBITS ) iterations should // find a prime. #ifdef DEBUG_SYSTEMC // A very large counter to check against infinite loops. sc_bigint<NBITS> niter = 0; #endif #if defined(SC_BIGINT_CONFIG_HOLLOW) // Remove when we fix hollow support!! while ( ! miller_rabin( p ) ) { p = ( p + 2 ) % r; #else size_t increment; for ( increment = 0; increment < 100000 && !miller_rabin( p ); ++increment ) { p = ( p + 2 ) % r; #endif #ifdef DEBUG_SYSTEMC assert( ++niter > 0 ); #endif } return p; } // Encode or cipher the message in msg using the RSA public key P=( e, n ). inline bigint cipher( const bigint& msg, const bigint& e, const bigint& n ) { return modular_exp( msg, e, n ); } // Dencode or decipher the message in msg using the RSA secret key S=( d, n ). inline bigint decipher( const bigint& msg, const bigint& d, const bigint& n ) { return modular_exp( msg, d, n ); } // The RSA cipher. inline void rsa( int seed ) { // Generate all 1's in r. char r_str[ HALF_STR_SIZE + 1 ]; max_bitstr( r_str, HALF_STR_SIZE ); bigint r = r_str; #ifdef DEBUG_SYSTEMC assert( r > 0 ); #endif // Initialize the random number generator. cout << "\nRandom number generator seed = " << randomize( seed ) << endl; cout << endl; // Find two large primes p and q. bigint p = find_prime( r ); bigint q = find_prime( r ); #ifdef DEBUG_SYSTEMC assert( ( p > 0 ) && ( q > 0 ) ); #endif // Compute n and ( p - 1 ) * ( q - 1 ) = m. bigint n = p * q; bigint m = ( p - 1 ) * ( q - 1 ); #ifdef DEBUG_SYSTEMC assert( ( n > 0 ) && ( m > 0 ) ); #endif // Find a small odd integer e that is relatively prime to m. bigint e = find_rel_prime( m ); #ifdef DEBUG_SYSTEMC assert( e > 0 ); #endif // Find the multiplicative inverse d of e, modulo m. bigint d = inverse( e, m ); #ifdef DEBUG_SYSTEMC assert( d > 0 ); #endif // Output public and secret keys. cout << "RSA public key P: P=( e, n )" << endl; cout << "e = " << e << endl; cout << "n = " << n << endl; cout << endl; cout << "RSA secret key S: S=( d, n )" << endl; cout << "d = " << d << endl; cout << "n = " << n << endl; cout << endl; // Cipher and decipher a randomly generated message msg. char msg_str[ STR_SIZE + 1 ]; rand_bitstr( msg_str, STR_SIZE ); bigint msg = msg_str; msg %= n; // Make sure msg is smaller than n. If larger, this part // will be a block of the input message. #ifdef DEBUG_SYSTEMC assert( msg > 0 ); #endif cout << "Message to be ciphered = " << endl; cout << msg << endl; bigint msg2 = cipher( msg, e, n ); cout << "\nCiphered message = " << endl; cout << msg2 << endl; msg2 = decipher( msg2, d, n ); cout << "\nDeciphered message = " << endl; cout << msg2 << endl; // Make sure that the original message is recovered. if ( msg == msg2 ) { cout << "\nNote that the original message == the deciphered message, " << endl; cout << "showing that this algorithm and implementation work correctly.\n" << endl; } else { // This case is unlikely. cout << "\nNote that the original message != the deciphered message, " << endl; cout << "showing that this implementation works incorrectly.\n" << endl; } return; } int sc_main( int argc, char *argv[] ) { if ( argc <= 1 ) rsa( -1 ); else rsa( atoi( argv[ 1 ] ) ); return 0; } // End of file
/****************************************************************************** * * * Copyright (C) 2022 MachineWare GmbH * * All Rights Reserved * * * * This is work is licensed under the terms described in the LICENSE file * * found in the root directory of this source tree. * * * ******************************************************************************/ #include "vcml/core/thctl.h" #include "vcml/core/systemc.h" namespace vcml { struct thctl { thread::id sysc_thread; atomic<thread::id> curr_owner; mutex sysc_mutex; atomic<int> nwaiting; condition_variable_any cvar; thctl(); ~thctl(); bool is_sysc_thread() const; bool is_in_critical() const; void notify(); void block(); void enter_critical(); void exit_critical(); void suspend(); void flush(); void set_sysc_thread(thread::id id); static thctl& instance(); }; thctl::thctl(): sysc_thread(std::this_thread::get_id()), curr_owner(sysc_thread), sysc_mutex(), nwaiting(0), cvar() { sysc_mutex.lock(); } thctl::~thctl() { sysc_mutex.unlock(); notify(); } bool thctl::is_sysc_thread() const { return std::this_thread::get_id() == sysc_thread; } bool thctl::is_in_critical() const { return std::this_thread::get_id() == curr_owner; } void thctl::notify() { cvar.notify_all(); } void thctl::block() { VCML_ERROR_ON(is_sysc_thread(), "cannot block SystemC thread"); lock_guard<mutex> l(sysc_mutex); } void thctl::enter_critical() { if (is_sysc_thread()) VCML_ERROR("SystemC thread must not enter critical sections"); if (is_in_critical()) VCML_ERROR("thread already in critical section"); if (!sim_running()) return; int prev = nwaiting++; if (!sysc_mutex.try_lock()) { if (prev == 0) on_next_update([]() -> void { thctl_suspend(); }); sysc_mutex.lock(); } curr_owner = std::this_thread::get_id(); } void thctl::exit_critical() { if (curr_owner != std::this_thread::get_id()) VCML_ERROR("thread not in critical section"); if (nwaiting <= 0) VCML_ERROR("no thread in critical section"); if (!sim_running()) return; curr_owner = thread::id(); sysc_mutex.unlock(); if (--nwaiting == 0) notify(); } void thctl::suspend() { VCML_ERROR_ON(!is_sysc_thread(), "this is not the SystemC thread"); VCML_ERROR_ON(!is_in_critical(), "thread not in critical section"); do { cvar.wait(sysc_mutex); } while (nwaiting > 0); curr_owner = sysc_thread; } void thctl::flush() { if (nwaiting > 0) suspend(); } void thctl::set_sysc_thread(thread::id id) { sysc_thread = id; } thctl& thctl::instance() { static thctl singleton; return singleton; } // need to make sure thctl gets created on the main (aka SystemC) thread thctl& g_thctl = thctl::instance(); bool thctl_is_sysc_thread() { return thctl::instance().is_sysc_thread(); } bool thctl_is_in_critical() { return thctl::instance().is_in_critical(); } void thctl_notify() { thctl::instance().notify(); } void thctl_block() { thctl::instance().block(); } void thctl_enter_critical() { thctl::instance().enter_critical(); } void thctl_exit_critical() { thctl::instance().exit_critical(); } void thctl_suspend() { thctl::instance().suspend(); } void thctl_flush() { thctl::instance().flush(); } void thctl_set_sysc_thread(thread::id id) { thctl::instance().set_sysc_thread(id); } } // namespace vcml
#include <systemc.h> SC_MODULE (hello) { // module named hello SC_CTOR (hello) { //constructor phase, which is empty in this case } void say_hello() { std::cout << "Hello World!" << std::endl; } }; int sc_main(int argc, char* argv[]) { hello h("hello"); h.say_hello(); return 0; }
#include <systemc.h> #include <i2c_controller_tb.h> #include <i2c_controller.h> #include <i2c_slave_controller.h> int sc_main(int argc, char* argv[]) { sc_signal<bool> rst; sc_signal<sc_uint<7>> addr; sc_signal<sc_uint<8>> data_in; sc_signal<bool> enable; sc_signal<bool> rw; sc_signal<sc_lv<8>> data_out; sc_signal<bool> ready; sc_signal<sc_logic, SC_MANY_WRITERS> i2c_sda; sc_signal<sc_logic> i2c_scl; sc_signal<sc_logic> scl; sc_signal<sc_logic> sda; sc_trace_file *f_trace; i2c_controller_tb tb("tb"); f_trace = sc_create_vcd_trace_file("waveforms"); f_trace->set_time_unit(1.0, SC_PS); sc_trace(f_trace, *tb.clk, "clk"); sc_trace(f_trace, tb.rst, "rst"); sc_trace(f_trace, tb.master->i2c_sda, "sda"); sc_trace(f_trace, tb.ready, "ready"); sc_trace(f_trace, tb.master->i2c_scl, "scl"); sc_trace(f_trace, tb.addr, "addr"); sc_trace(f_trace, tb.rw, "rw"); sc_trace(f_trace, tb.enable, "enable"); sc_trace(f_trace, tb.master->i2c_clk, "i2c_clk"); sc_trace(f_trace, tb.master->i2c_scl_enable, "i2c_scl_enable"); sc_trace(f_trace, tb.master->sda_out, "sda_out"); sc_trace(f_trace, tb.master->counter, "counter"); sc_trace(f_trace, tb.master->write_enable, "write_enable"); sc_trace(f_trace, tb.master->saved_data, "saved_data"); sc_trace(f_trace, tb.master->data_from_slave, "data_from_slave"); sc_trace(f_trace, tb.slave->data_in, "slave_data_in"); sc_trace(f_trace, tb.slave->data_out, "slave_data_out"); sc_trace(f_trace, tb.slave->start, "slave_start"); sc_trace(f_trace, tb.slave->write_enable, "slave_we"); sc_trace(f_trace, tb.slave->addr, "slave_addr"); sc_trace(f_trace, tb.slave->sda, "slave_sda"); sc_trace(f_trace, tb.slave->scl, "slave_scl"); sc_start(3000, SC_NS); sc_stop(); sc_close_vcd_trace_file(f_trace); return 0; }
#include <crave/SystemC.hpp> #include <crave/ConstrainedRandom.hpp> #include <systemc.h> #include <boost/timer.hpp> using crave::rand_obj; using crave::randv; using sc_dt::sc_bv; using sc_dt::sc_uint; struct ALU24 : public rand_obj { randv< sc_bv<2> > op ; randv< sc_uint<24> > a, b ; ALU24() : op(this), a(this), b(this) { constraint ( (op() != 0x0) || ( 16777215 >= a() + b() ) ); constraint ( (op() != 0x1) || ((16777215 >= a() - b()) && (b() <= a()) ) ); constraint ( (op() != 0x2) || ( 16777215 >= a() * b() ) ); constraint ( (op() != 0x3) || ( b() != 0 ) ); } friend std::ostream & operator<< (std::ostream & o, ALU24 const & alu) { o << alu.op << ' ' << alu.a << ' ' << alu.b ; return o; } }; int sc_main (int argc, char** argv) { boost::timer timer; ALU24 c; c.next(); std::cout << "first: " << timer.elapsed() << "\n"; for (int i=0; i<1000; ++i) { c.next(); } std::cout << "complete: " << timer.elapsed() << "\n"; return 0; }
/** #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; } //---------------------------------------
/* * @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; } } };
/******************************************************************************* * gpio_mf.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Implements a SystemC model of a generic multi-function GPIO with * analog function. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "gpio_mf.h" #include "info.h" /********************* * Function: set_function() * inputs: new function * outputs: none * returns: none * globals: none * * Sets the function, can be GPIO or ANALOG. */ void gpio_mf::set_function(gpio_function_t newfunction) { /* We ignore unchanged function requests. */ if (newfunction == function) return; /* We also ignore illegal function requests. */ if (newfunction == GPIOMF_ANALOG) { PRINTF_WARN("GPIOMF", "%s cannot be set to ANALOG", name()) return; } /* To select a function there must be at least the fin or the fout * available. The fen is optional. Ideal would be to require all three * but there are some peripherals that need only one of these pins, * so to make life easier, we require at least a fin or a fout. */ if (newfunction >= GPIOMF_FUNCTION && (newfunction-1 >= fin.size() && newfunction-1 >= fout.size())) { PRINTF_WARN("GPIOMF", "%s cannot be set to FUNC%d", name(), newfunction) return; } /* When we change to the GPIO function, we set the driver high and set * the function accordingly. */ if (newfunction == GPIOMF_GPIO) { PRINTF_INFO("GPIOMF", "%s set to GPIO mode", name()) function = newfunction; driveok = true; /* set_val() handles the driver. */ gpio_base::set_val(pinval); } else { PRINTF_INFO("GPIOMF", "%s set to FUNC%d", name(), newfunction); function = newfunction; } /* And we set any notifications we need. */ updatefunc.notify(); updatereturn.notify(); } /********************* * Function: get_function() * inputs: none * outputs: none * returns: current function * globals: none * * Returns the current function. */ gpio_function_t gpio_mf::get_function() { return function; } /********************* * Function: set_val() * inputs: new value * outputs: none * returns: none * globals: none * * Changes the value to set onto the GPIO, if GPIO function is set. */ void gpio_mf::set_val(bool newval) { pinval = newval; if (function == GPIOMF_GPIO) gpio_base::set_val(newval); } /********************* * Thread: drive_return() * inputs: none * outputs: none * returns: none * globals: none * * Drives the return path from the pin onto the alternate functions. */ void gpio_mf::drive_return() { sc_logic pinsamp; bool retval; int func; /* We begin driving all returns to low. */ for (func = 0; func < fout.size(); func = func + 1) fout[func]->write(false); /* Now we go into the loop waiting for a return or a change in function. */ for(;;) { /* printf("<<%s>>: U:%d pin:%d:%c @%s\n", name(), updatereturn.triggered(), pin.event(), pin.read().to_char(), sc_time_stamp().to_string().c_str()); */ pinsamp = pin.read(); /* If the sampling value is Z or X and we have a function set, we * then issue a warning. We also do not warn at time 0s or we get some * dummy initialization warnings. */ if (sc_time_stamp() != sc_time(0, SC_NS) && (pinsamp == SC_LOGIC_X || pinsamp == SC_LOGIC_Z) && function != GPIOMF_ANALOG && function != GPIOMF_GPIO) { retval = false; PRINTF_WARN("GPIOMF", "can't return '%c' onto FUNC%d", pinsamp.to_char(), function) } else if (pinsamp == SC_LOGIC_1) retval = true; else retval = false; for (func = 0; func < fout.size(); func = func + 1) if (function == GPIOMF_ANALOG) fout[func]->write(false); else if (function == GPIOMF_GPIO) fout[func]->write(false); else if (func != function-1) fout[func]->write(false); else fout[func]->write(retval); wait(); } } /********************* * Thread: drive_func() * inputs: none * outputs: none * returns: none * globals: none * * Drives the value from an alternate function onto the pins. This does not * actually drive the value, it just places it in the correct variables so that * the drive() thread handles it. */ void gpio_mf::drive_func() { for(;;) { /* We only use this thread if we have an alternate function selected. */ if (function != GPIOMF_GPIO && function-1 < fin.size()) { /* We check if the fen is ok. If this function has no fen we default * it to enabled. */ if (function-1 < fen.size() || fen[function-1]->read() == true) driveok = true; else driveok = false; /* Note that we do not set the pin val, just call set_val to handle * the pin drive. */ gpio_base::set_val(fin[function-1]->read()); } /* We now wait for a change. If the function is no selected or if we * have an illegal function selected, we have to wait for a change * in the function selection. */ if (function == GPIOMF_GPIO || function-1 >= fin.size()) wait(updatefunc); /* If we have a valid function selected, we wait for either the * function or the fen to change. We also have to wait for a * function change. */ else if (fen.size() >= function-1) wait(updatefunc | fin[function-1]->value_changed_event()); else wait(updatefunc | fin[function-1]->value_changed_event() | fen[function-1]->value_changed_event()); } }
/***************************************************************************** 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(); }; }
#include "sc_run.h" #include <systemc.h> static int scThreadResult = 0; static sc_thread_run_t *scThreadRun = nullptr; int sc_getRunResultFromUI(void) { return scThreadResult; } void sc_setRunFromUI(sc_thread_run_t *theRun) { scThreadRun = theRun; } void sc_setRunResult(int theResult) {scThreadResult = theResult; } void sc_setReportFromSC(std::vector<std::string> &rep) { //cout << "DEBUG: sc_setReportFromSC()" << endl; scThreadRun->report = rep; } void sc_setHierarchyFromSC(std::vector<std::string> &hier) { //cout << "DEBUG: sc_setHierarchyFromSC()" << endl; scThreadRun->hierarchy = hier; } void sc_NotifyUIFromSC(int newState) { //cout << "DEBUG: sc_NotifyUIFromSC()" << endl; scThreadRun->state = newState; if (pthread_cond_signal(&scThreadRun->condvar) != 0) { cout << "sc_NotifyUIFromSC() ERROR: Internal error pthread_cond_signal()" << endl; return; } //cout << "DEBUG: SC cond signal start" << endl; if (pthread_mutex_unlock(&scThreadRun->condvar_mutex) != 0) { cout << "sc_NotifyUIFromSC() ERROR: Internal error pthread_mutex_unlock()" << endl; } //cout << "DEBUG: SC mutex unlock" << endl; } int sc_waitStateChange(void) { //cout << "DEBUG: sc_waitStateChange()" << endl; if (scThreadRun == nullptr) { cout << "sc_waitUiState() ERROR: Internal error scThreadRun is NULL" << endl; // Non MT-safe change of state return SC_ST_COMMAND_EXIT; } if (pthread_mutex_lock(&scThreadRun->condvar_mutex) != 0) { cout << "sc_waitUiState() ERROR: Internal error pthread_mutex_lock()" << endl; // Non MT-safe change of state scThreadRun->state = SC_ST_RESPONSE_ABORTED; return SC_ST_COMMAND_EXIT; } //cout << "DEBUG: SC mutex lock" << endl; while (scThreadRun->state >= SC_ST_MINRESPONSE) { //cout << "DEBUG: SC cond wait start" << endl; if (pthread_cond_wait(&scThreadRun->condvar, &scThreadRun->condvar_mutex) != 0) { cout << "sc_waitUiState() ERROR: Internal error pthread_cond_wait()" << endl; // Non thread-safe change of state sc_NotifyUIFromSC(SC_ST_RESPONSE_ABORTED); return SC_ST_COMMAND_EXIT; } //cout << "DEBUG: SC cond wait end" << endl; } if (scThreadRun->state == SC_ST_COMMAND_EXIT) { //cout << "DEBUG: sc_waitStateChange() gonna stop" << endl; sc_stop(); sc_NotifyUIFromSC(SC_ST_RESPONSE_FINISHED); } return scThreadRun->state; } int sc_StartTransactionFromUI() { //cout << "DEBUG: sc_StartTransactionFromUI()" << endl; if (scThreadRun == nullptr) { cout << "sc_StartTransactionFromUI() ERROR: Internal error scThreadRun is NULL" << endl; return 0; } if (pthread_mutex_lock(&scThreadRun->condvar_mutex) != 0) { cout << "sc_StartTransactionFromUI() ERROR: Internal error pthread_mutex_lock()" << endl; return 0; } //cout << "DEBUG: GUI mutex lock" << endl; return 1; } int sc_NotifyTransactionFromUI() { //cout << "DEBUG: sc_NotifyTransactionFromUI()" << endl; if (scThreadRun == nullptr) { cout << "sc_NotifyTransactionFromUI() ERROR: Internal error scThreadRun is NULL" << endl; return 0; } if (pthread_cond_signal(&scThreadRun->condvar) != 0) { cout << "sc_NotifyTransactionFromUI() ERROR: Internal error pthread_cond_signal()" << endl; return 0; } //cout << "DEBUG: GUI cond signal start" << endl; return 1; } int sc_EndTransactionFromUI() { //cout << "DEBUG: sc_EndTransactionFromUI()" << endl; if (scThreadRun == nullptr) { cout << "sc_EndTransactionFromUI() ERROR: Internal error scThreadRun is NULL" << endl; return 0; } if (pthread_mutex_unlock(&scThreadRun->condvar_mutex) != 0) { cout << "sc_EndTransactionFromUI() ERROR: Internal error pthread_mutex_unlock()" << endl; return 0; } //cout << "DEBUG: GUI mutex unlock" << endl; return 1; } int sc_waitStateChangeFromUI(void) { //cout << "DEBUG: sc_waitStateChangeFromUI()" << endl; if (scThreadRun == nullptr) { cout << "sc_waitStateChangeFromUI() ERROR: Internal error scThreadRun is NULL" << endl; return 0; } while (scThreadRun->state <= SC_ST_MAXCOMMAND) { //cout << "DEBUG: GUI cond wait start" << endl; if (pthread_cond_wait(&scThreadRun->condvar, &scThreadRun->condvar_mutex) != 0) { cout << "sc_waitStateChangeFromUI() ERROR: Internal error pthread_cond_wait()" << endl; return 0; } //cout << "DEBUG: GUI cond wait end" << endl; } return 1; } int sc_NewStateFromUI(int newState) { //cout << "DEBUG: sc_NewStateFromUI() start" << endl; if (!sc_StartTransactionFromUI()) { cout << "DEBUG: sc_NewStateFromUI() abort (1)" << endl; return 0; } scThreadRun->state = newState; if (!sc_NotifyTransactionFromUI() || !sc_EndTransactionFromUI()) { cout << "DEBUG: sc_NewStateFromUI() abort (2)" << endl; return 0; } //cout << "DEBUG: sc_NewStateFromUI() end" << endl; return 1; } std::vector<std::string> sc_getHierarchyFromUI() { std::vector<std::string> hier; //cout << "DEBUG: sc_getHierarchyFromUI() start" << endl; if (sc_NewStateFromUI(SC_ST_COMMAND_RUN)) { if (sc_StartTransactionFromUI()) { if (sc_waitStateChangeFromUI()) { hier = scThreadRun->hierarchy; sc_EndTransactionFromUI(); } } } //cout << "DEBUG: sc_getHierarchyFromUI() end" << endl; return hier; } void sc_setTraceListFromUI(std::vector<std::string> &tl) { //cout << "DEBUG: sc_setTraceListFromUI() start" << endl; if (sc_StartTransactionFromUI()) { scThreadRun->tracelist = tl; sc_EndTransactionFromUI(); } //cout << "DEBUG: sc_setTraceListFromUI() end" << endl; } std::vector<std::string> sc_getReportFromUI() { std::vector<std::string> rep; //cout << "DEBUG: sc_getReportFromUI() start" << endl; if (sc_StartTransactionFromUI()) { rep = scThreadRun->report; sc_EndTransactionFromUI(); } //cout << "DEBUG: sc_getReportFromUI() end" << endl; return rep; }
#include "systemc.h" #include "systemperl.h" #include "verilated_vcd_c.h" #include "env_memory.h" #include "tv_responder.h" #include "Vtv80s.h" #include "VT16450.h" #include "SpTraceVcd.h" #include <unistd.h> #include "z80_decoder.h" #include "di_mux.h" extern char *optarg; extern int optind, opterr, optopt; #define FILENAME_SZ 80 int sc_main(int argc, char *argv[]) { bool dumping = false; bool memfile = false; int index; char dumpfile_name[FILENAME_SZ]; char mem_src_name[FILENAME_SZ]; VerilatedVcdC *tfp; z80_decoder dec0 ("dec0"); sc_clock clk("clk125", 8, SC_NS, 0.5); sc_signal<bool> reset_n; sc_signal<bool> wait_n; sc_signal<bool> int_n; sc_signal<bool> nmi_n; sc_signal<bool> busrq_n; sc_signal<bool> m1_n; sc_signal<bool> mreq_n; sc_signal<bool> iorq_n; sc_signal<bool> rd_n; sc_signal<bool> wr_n; sc_signal<bool> rfsh_n; sc_signal<bool> halt_n; sc_signal<bool> busak_n; sc_signal<uint32_t> di; sc_signal<uint32_t> di_mem; sc_signal<uint32_t> di_resp; sc_signal<uint32_t> di_uart; sc_signal<uint32_t> dout; sc_signal<uint32_t> addr; sc_signal<bool> uart_cs_n, serial, cts_n, dsr_n, ri_n, dcd_n; sc_signal<bool> baudout, uart_int; while ( (index = getopt(argc, argv, "d:i:k")) != -1) { printf ("DEBUG: getopt optind=%d index=%d char=%c\n", optind, index, (char) index); if (index == 'd') { strncpy (dumpfile_name, optarg, FILENAME_SZ); dumping = true; printf ("VCD dump enabled to %s\n", dumpfile_name); } else if (index == 'i') { strncpy (mem_src_name, optarg, FILENAME_SZ); memfile = true; } else if (index == 'k') { printf ("Z80 Instruction decode enabled\n"); dec0.en_decode = true; } } Vtv80s tv80s ("tv80s"); tv80s.A (addr); tv80s.reset_n (reset_n); tv80s.clk (clk); tv80s.wait_n (wait_n); tv80s.int_n (int_n); tv80s.nmi_n (nmi_n); tv80s.busrq_n (busrq_n); tv80s.m1_n (m1_n); tv80s.mreq_n (mreq_n); tv80s.iorq_n (iorq_n); tv80s.rd_n (rd_n); tv80s.wr_n (wr_n); tv80s.rfsh_n (rfsh_n); tv80s.halt_n (halt_n); tv80s.busak_n (busak_n); tv80s.di (di); tv80s.dout (dout); di_mux di_mux0("di_mux0"); di_mux0.mreq_n (mreq_n); di_mux0.iorq_n (iorq_n); di_mux0.addr (addr); di_mux0.di (di); di_mux0.di_mem (di_mem); di_mux0.di_uart (di_uart); di_mux0.di_resp (di_resp); di_mux0.uart_cs_n (uart_cs_n); env_memory env_memory0("env_memory0"); env_memory0.clk (clk); env_memory0.wr_data (dout); env_memory0.rd_data (di_mem); env_memory0.mreq_n (mreq_n); env_memory0.rd_n (rd_n); env_memory0.wr_n (wr_n); env_memory0.addr (addr); env_memory0.reset_n (reset_n); tv_responder tv_resp0("tv_resp0"); tv_resp0.clk (clk); tv_resp0.reset_n (reset_n); tv_resp0.wait_n (wait_n); tv_resp0.int_n (int_n); tv_resp0.nmi_n (nmi_n); tv_resp0.busak_n (busak_n); tv_resp0.busrq_n (busrq_n); tv_resp0.m1_n (m1_n); tv_resp0.mreq_n (mreq_n); tv_resp0.iorq_n (iorq_n); tv_resp0.rd_n (rd_n); tv_resp0.wr_n (wr_n); tv_resp0.addr (addr); tv_resp0.di_resp (di_resp); tv_resp0.dout (dout); tv_resp0.halt_n (halt_n); dec0.clk (clk); dec0.m1_n (m1_n); dec0.addr (addr); dec0.mreq_n (mreq_n); dec0.rd_n (rd_n); dec0.wait_n (wait_n); dec0.di (di); dec0.reset_n (reset_n); VT16450 t16450 ("t16450"); t16450.reset_n (reset_n); t16450.clk (clk); t16450.rclk (clk); t16450.cs_n (uart_cs_n); t16450.rd_n (rd_n); t16450.wr_n (wr_n); t16450.addr (addr); t16450.wr_data (dout); t16450.rd_data (di_uart); t16450.sin (serial); t16450.cts_n (cts_n); t16450.dsr_n (dsr_n); t16450.ri_n (ri_n); t16450.dcd_n (dcd_n); t16450.sout (serial); t16450.rts_n (cts_n); t16450.dtr_n (dsr_n); t16450.out1_n (ri_n); t16450.out2_n (dcd_n); t16450.baudout (baudout); t16450.intr (uart_int); // create dumpfile /* sc_trace_file *trace_file; trace_file = sc_create_vcd_trace_file("sc_tv80_env"); sc_trace (trace_file, clk, "clk"); sc_trace (trace_file, reset_n, "reset_n"); sc_trace (trace_file, wait_n, "wait_n"); sc_trace (trace_file, int_n, "int_n"); sc_trace (trace_file, nmi_n, "nmi_n"); sc_trace (trace_file, busrq_n, "busrq_n"); sc_trace (trace_file, m1_n, "m1_n"); sc_trace (trace_file, mreq_n, "mreq_n"); sc_trace (trace_file, iorq_n, "iorq_n"); sc_trace (trace_file, rd_n, "rd_n"); sc_trace (trace_file, wr_n, "wr_n"); sc_trace (trace_file, halt_n, "halt_n"); sc_trace (trace_file, busak_n, "busak_n"); sc_trace (trace_file, di, "di"); sc_trace (trace_file, dout, "dout"); sc_trace (trace_file, addr, "addr"); */ // Start Verilator traces if (dumping) { Verilated::traceEverOn(true); tfp = new VerilatedVcdC; tv80s.trace (tfp, 99); tfp->open (dumpfile_name); } // check for command line argument if (memfile) { printf ("Loading IHEX file %s\n", mem_src_name); env_memory0.load_ihex (mem_src_name); } // set reset to 0 before sim start reset_n.write (0); sc_start(); /* sc_close_vcd_trace_file (trace_file); */ if (dumping) tfp->close(); return 0; }
// -*- mode: C++; c-file-style: "cc-mode" -*- //************************************************************************* // DESCRIPTION: Verilator: Emit Makefile // // Code available from: https://verilator.org // //************************************************************************* // // Copyright 2004-2022 by Wilson Snyder. This program is free software; you // can redistribute it and/or modify it under the terms of either the GNU // Lesser General Public License Version 3 or the Perl Artistic License // Version 2.0. // SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0 // //************************************************************************* #include "config_build.h" #include "verilatedos.h" #include "V3EmitMk.h" #include "V3EmitCBase.h" #include "V3Global.h" #include "V3HierBlock.h" #include "V3Os.h" VL_DEFINE_DEBUG_FUNCTIONS; //###################################################################### // Emit statements and math operators class EmitMk final { public: // METHODS void putMakeClassEntry(V3OutMkFile& of, const string& name) { of.puts("\t" + V3Os::filenameNonDirExt(name) + " \\\n"); } void emitClassMake() { // Generate the makefile V3OutMkFile of(v3Global.opt.makeDir() + "/" + v3Global.opt.prefix() + "_classes.mk"); of.putsHeader(); of.puts("# DESCR" "IPTION: Verilator output: Make include file with class lists\n"); of.puts("#\n"); of.puts("# This file lists generated Verilated files, for including " "in higher level makefiles.\n"); of.puts("# See " + v3Global.opt.prefix() + ".mk" + " for the caller.\n"); of.puts("\n### Switches...\n"); of.puts("# C11 constructs required? 0/1 (always on now)\n"); of.puts("VM_C11 = 1\n"); of.puts("# Timing enabled? 0/1\n"); of.puts("VM_TIMING = "); of.puts(v3Global.usesTiming() ? "1" : "0"); of.puts("\n"); of.puts("# Coverage output mode? 0/1 (from --coverage)\n"); of.puts("VM_COVERAGE = "); of.puts(v3Global.opt.coverage() ? "1" : "0"); of.puts("\n"); of.puts("# Parallel builds? 0/1 (from --output-split)\n"); of.puts("VM_PARALLEL_BUILDS = "); of.puts(v3Global.useParallelBuild() ? "1" : "0"); of.puts("\n"); of.puts("# Threaded output mode? 0/1/N threads (from --threads)\n"); of.puts("VM_THREADS = "); of.puts(cvtToStr(v3Global.opt.threads())); of.puts("\n"); of.puts("# Tracing output mode? 0/1 (from --trace/--trace-fst)\n"); of.puts("VM_TRACE = "); of.puts(v3Global.opt.trace() ? "1" : "0"); of.puts("\n"); of.puts("# Tracing output mode in VCD format? 0/1 (from --trace)\n"); of.puts("VM_TRACE_VCD = "); of.puts(v3Global.opt.trace() && v3Global.opt.traceFormat().vcd() ? "1" : "0"); of.puts("\n"); of.puts("# Tracing output mode in FST format? 0/1 (from --trace-fst)\n"); of.puts("VM_TRACE_FST = "); of.puts(v3Global.opt.trace() && v3Global.opt.traceFormat().fst() ? "1" : "0"); of.puts("\n"); of.puts("\n### Object file lists...\n"); for (int support = 0; support < 3; ++support) { for (const bool& slow : {false, true}) { if (support == 2) { of.puts("# Global classes, need linked once per executable"); } else if (support) { of.puts("# Generated support classes"); } else { of.puts("# Generated module classes"); } if (slow) { of.puts(", non-fast-path, compile with low/medium optimization\n"); } else { of.puts(", fast-path, compile with highest optimization\n"); } of.puts(support == 2 ? "VM_GLOBAL" : support == 1 ? "VM_SUPPORT" : "VM_CLASSES"); of.puts(slow ? "_SLOW" : "_FAST"); of.puts(" += \\\n"); if (support == 2 && v3Global.opt.hierChild()) { // Do nothing because VM_GLOBAL is necessary per executable. Top module will // have them. } else if (support == 2 && !slow) { putMakeClassEntry(of, "verilated.cpp"); if (v3Global.dpi()) putMakeClassEntry(of, "verilated_dpi.cpp"); if (v3Global.opt.vpi()) putMakeClassEntry(of, "verilated_vpi.cpp"); if (v3Global.opt.savable()) putMakeClassEntry(of, "verilated_save.cpp"); if (v3Global.opt.coverage()) putMakeClassEntry(of, "verilated_cov.cpp"); if (v3Global.opt.trace()) { putMakeClassEntry(of, v3Global.opt.traceSourceBase() + "_c.cpp"); if (v3Global.opt.systemC()) { putMakeClassEntry(of, v3Global.opt.traceSourceLang() + ".cpp"); } } if (v3Global.usesTiming()) putMakeClassEntry(of, "verilated_timing.cpp"); if (v3Global.opt.threads()) putMakeClassEntry(of, "verilated_threads.cpp"); if (v3Global.opt.usesProfiler()) { putMakeClassEntry(of, "verilated_profiler.cpp"); } } else if (support == 2 && slow) { } else { for (AstNodeFile* nodep = v3Global.rootp()->filesp(); nodep; nodep = VN_AS(nodep->nextp(), NodeFile)) { const AstCFile* const cfilep = VN_CAST(nodep, CFile); if (cfilep && cfilep->source() && cfilep->slow() == (slow != 0) && cfilep->support() == (support != 0)) { putMakeClassEntry(of, cfilep->name()); } } } of.puts("\n"); } } of.puts("\n"); of.putsHeader(); } void emitOverallMake() { // Generate the makefile V3OutMkFile of(v3Global.opt.makeDir() + "/" + v3Global.opt.prefix() + ".mk"); of.putsHeader(); of.puts("# DESCR" "IPTION: Verilator output: " "Makefile for building Verilated archive or executable\n"); of.puts("#\n"); of.puts("# Execute this makefile from the object directory:\n"); of.puts("# make -f " + v3Global.opt.prefix() + ".mk" + "\n"); of.puts("\n"); if (v3Global.opt.exe()) { of.puts("default: " + v3Global.opt.exeName() + "\n"); } else if (!v3Global.opt.libCreate().empty()) { of.puts("default: lib" + v3Global.opt.libCreate() + "\n"); } else { of.puts("default: " + v3Global.opt.prefix() + "__ALL.a\n"); } of.puts("\n### Constants...\n"); of.puts("# Perl executable (from $PERL)\n"); of.puts("PERL = " + V3Options::getenvPERL() + "\n"); of.puts("# Path to Verilator kit (from $VERILATOR_ROOT)\n"); of.puts("VERILATOR_ROOT = " + V3Options::getenvVERILATOR_ROOT() + "\n"); of.puts("# SystemC include directory with systemc.h (from $SYSTEMC_INCLUDE)\n"); of.puts(string("SYSTEMC_INCLUDE ?= ") + V3Options::getenvSYSTEMC_INCLUDE() + "\n"); of.puts("# SystemC library directory with libsystemc.a (from $SYSTEMC_LIBDIR)\n"); of.puts(string("SYSTEMC_LIBDIR ?= ") + V3Options::getenvSYSTEMC_LIBDIR() + "\n"); // Only check it if we really need the value if (v3Global.opt.systemC() && !V3Options::systemCFound()) { v3fatal("Need $SYSTEMC_INCLUDE in environment or when Verilator configured,\n" "and need $SYSTEMC_LIBDIR in environment or when Verilator configured\n" "Probably System-C isn't installed, see http://www.systemc.org\n"); } of.puts("\n### Switches...\n"); of.puts("# C++ code coverage 0/1 (from --prof-c)\n"); of.puts(string("VM_PROFC = ") + ((v3Global.opt.profC()) ? "1" : "0") + "\n"); of.puts("# SystemC output mode? 0/1 (from --sc)\n"); of.puts(string("VM_SC = ") + ((v3Global.opt.systemC()) ? "1" : "0") + "\n"); of.puts("# Legacy or SystemC output mode? 0/1 (from --sc)\n"); of.puts(string("VM_SP_OR_SC = $(VM_SC)\n")); of.puts("# Deprecated\n"); of.puts(string("VM_PCLI = ") + (v3Global.opt.systemC() ? "0" : "1") + "\n"); of.puts( "# Deprecated: SystemC architecture to find link library path (from $SYSTEMC_ARCH)\n"); of.puts(string("VM_SC_TARGET_ARCH = ") + V3Options::getenvSYSTEMC_ARCH() + "\n"); of.puts("\n### Vars...\n"); of.puts("# Design prefix (from --prefix)\n"); of.puts(string("VM_PREFIX = ") + v3Global.opt.prefix() + "\n"); of.puts("# Module prefix (from --prefix)\n"); of.puts(string("VM_MODPREFIX = ") + v3Global.opt.modPrefix() + "\n"); of.puts("# User CFLAGS (from -CFLAGS on Verilator command line)\n"); of.puts("VM_USER_CFLAGS = \\\n"); if (!v3Global.opt.libCreate().empty()) of.puts("\t-fPIC \\\n"); const V3StringList& cFlags = v3Global.opt.cFlags(); for (const string& i : cFlags) of.puts("\t" + i + " \\\n"); of.puts("\n"); of.puts("# User LDLIBS (from -LDFLAGS on Verilator command line)\n"); of.puts("VM_USER_LDLIBS = \\\n"); const V3StringList& ldLibs = v3Global.opt.ldLibs(); for (const string& i : ldLibs) of.puts("\t" + i + " \\\n"); of.puts("\n"); V3StringSet dirs; of.puts("# User .cpp files (from .cpp's on Verilator command line)\n"); of.puts("VM_USER_CLASSES = \\\n"); const V3StringSet& cppFiles = v3Global.opt.cppFiles(); for (const auto& cppfile : cppFiles) { of.puts("\t" + V3Os::filenameNonExt(cppfile) + " \\\n"); const string dir = V3Os::filenameDir(cppfile); dirs.insert(dir); } of.puts("\n"); of.puts("# User .cpp directories (from .cpp's on Verilator command line)\n"); of.puts("VM_USER_DIR = \\\n"); for (const auto& i : dirs) of.puts("\t" + i + " \\\n"); of.puts("\n"); of.puts("\n### Default rules...\n"); of.puts("# Include list of all generated classes\n"); of.puts("include " + v3Global.opt.prefix() + "_classes.mk\n"); if (v3Global.opt.hierTop()) { of.puts("# Include rules for hierarchical blocks\n"); of.puts("include " + v3Global.opt.prefix() + "_hier.mk\n"); } of.puts("# Include global rules\n"); of.puts("include $(VERILATOR_ROOT)/include/verilated.mk\n"); if (v3Global.opt.exe()) { of.puts("\n### Executable rules... (from --exe)\n"); of.puts("VPATH += $(VM_USER_DIR)\n"); of.puts("\n"); for (const string& cppfile : cppFiles) { const string basename = V3Os::filenameNonExt(cppfile); // NOLINTNEXTLINE(performance-inefficient-string-concatenation) of.puts(basename + ".o: " + cppfile + "\n"); of.puts("\t$(OBJCACHE) $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(OPT_FAST) -c -o $@ $<\n"); } of.puts("\n### Link rules... (from --exe)\n"); of.puts(v3Global.opt.exeName() + ": $(VK_USER_OBJS) $(VK_GLOBAL_OBJS) $(VM_PREFIX)__ALL.a $(VM_HIER_LIBS)\n"); of.puts("\t$(LINK) $(LDFLAGS) $^ $(LOADLIBES) $(LDLIBS) $(LIBS) $(SC_LIBS) -o $@\n"); of.puts("\n"); } if (!v3Global.opt.libCreate().empty()) { const string libCreateDeps = "$(VK_OBJS) $(VK_USER_OBJS) $(VK_GLOBAL_OBJS) " + v3Global.opt.libCreate() + ".o $(VM_HIER_LIBS)"; of.puts("\n### Library rules from --lib-create\n"); // The rule to create .a is defined in verilated.mk, so just define dependency here. of.puts(v3Global.opt.libCreateName(false) + ": " + libCreateDeps + "\n"); of.puts("\n"); if (v3Global.opt.hierChild()) { // Hierarchical child does not need .so because hierTop() will create .so from .a of.puts("lib" + v3Global.opt.libCreate() + ": " + v3Global.opt.libCreateName(false) + "\n"); } else { of.puts(v3Global.opt.libCreateName(true) + ": " + libCreateDeps + "\n"); // Linker on mac emits an error if all symbols are not found here, // but some symbols that are referred as "DPI-C" can not be found at this moment. // So add dynamic_lookup of.puts("ifeq ($(shell uname -s),Darwin)\n"); of.puts("\t$(OBJCACHE) $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(OPT_FAST) -undefined " "dynamic_lookup -shared -flat_namespace -o $@ $^\n"); of.puts("else\n"); of.puts( "\t$(OBJCACHE) $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(OPT_FAST) -shared -o $@ $^\n"); of.puts("endif\n"); of.puts("\n"); of.puts("lib" + v3Global.opt.libCreate() + ": " + v3Global.opt.libCreateName(false) + " " + v3Global.opt.libCreateName(true) + "\n"); } } of.puts("\n"); of.putsHeader(); } explicit EmitMk() { emitClassMake(); emitOverallMake(); } virtual ~EmitMk() = default; }; //###################################################################### class EmitMkHierVerilation final { const V3HierBlockPlan* const m_planp; const string m_makefile; // path of this makefile void emitCommonOpts(V3OutMkFile& of) const { const string cwd = V3Os::filenameRealPath("."); of.puts("# Verilation of hierarchical blocks are executed in this directory\n"); of.puts("VM_HIER_RUN_DIR := " + cwd + "\n"); of.puts("# Common options for hierarchical blocks\n"); const string fullpath_bin = V3Os::filenameRealPath(v3Global.opt.buildDepBin()); const string verilator_wrapper = V3Os::filenameDir(fullpath_bin) + "/verilator"; of.puts("VM_HIER_VERILATOR := " + verilator_wrapper + "\n"); of.puts("VM_HIER_INPUT_FILES := \\\n"); const V3StringList& vFiles = v3Global.opt.vFiles(); for (const string& i : vFiles) of.puts("\t" + V3Os::filenameRealPath(i) + " \\\n"); of.puts("\n"); const V3StringSet& libraryFiles = v3Global.opt.libraryFiles(); of.puts("VM_HIER_VERILOG_LIBS := \\\n"); for (const string& i : libraryFiles) { of.puts("\t" + V3Os::filenameRealPath(i) + " \\\n"); } of.puts("\n"); } void emitLaunchVerilator(V3OutMkFile& of, const string& argsFile) const { of.puts("\t@$(MAKE) -C $(VM_HIER_RUN_DIR) -f " + m_makefile + " hier_launch_verilator \\\n"); of.puts("\t\tVM_HIER_LAUNCH_VERILATOR_ARGSFILE=\"" + argsFile + "\"\n"); } void emit(V3OutMkFile& of) const { of.puts("# Hierarchical Verilation -*- Makefile -*-\n"); of.puts("# DESCR" "IPTION: Verilator output: Makefile for hierarchical verilatrion\n"); of.puts("#\n"); of.puts("# The main makefile " + v3Global.opt.prefix() + ".mk calls this makefile\n"); of.puts("\n"); of.puts("ifndef VM_HIER_VERILATION_INCLUDED\n"); of.puts("VM_HIER_VERILATION_INCLUDED = 1\n\n"); of.puts(".SUFFIXES:\n"); of.puts(".PHONY: hier_build hier_verilation hier_launch_verilator\n"); of.puts("# Libraries of hierarchical blocks\n"); of.puts("VM_HIER_LIBS := \\\n"); const V3HierBlockPlan::HierVector blocks = m_planp->hierBlocksSorted(); // leaf comes first // List in order of leaf-last order so that linker can resolve dependency for (auto& block : vlstd::reverse_view(blocks)) { of.puts("\t" + block->hierLib(true) + " \\\n"); } of.puts("\n"); // Build hierarchical libraries as soon as possible to get maximum parallelism of.puts("hier_build: $(VM_HIER_LIBS) " + v3Global.opt.prefix() + ".mk\n"); of.puts("\t$(MAKE) -f " + v3Global.opt.prefix() + ".mk\n"); of.puts("hier_verilation: " + v3Global.opt.prefix() + ".mk\n"); emitCommonOpts(of); // Instead of direct execute of "cd $(VM_HIER_RUN_DIR) && $(VM_HIER_VERILATOR)", // call via make to get message of "Entering directory" and "Leaving directory". // This will make some editors and IDEs happy when viewing a logfile. of.puts("# VM_HIER_LAUNCH_VERILATOR_ARGSFILE must be passed as a command argument\n"); of.puts("hier_launch_verilator:\n"); of.puts("\t$(VM_HIER_VERILATOR) -f $(VM_HIER_LAUNCH_VERILATOR_ARGSFILE)\n"); // Top level module { const string argsFile = v3Global.hierPlanp()->topCommandArgsFileName(false); of.puts("\n# Verilate the top module\n"); of.puts(v3Global.opt.prefix() + ".mk: $(VM_HIER_INPUT_FILES) $(VM_HIER_VERILOG_LIBS) "); of.puts(V3Os::filenameNonDir(argsFile) + " "); for (const auto& itr : *m_planp) of.puts(itr.second->hierWrapper(true) + " "); of.puts("\n"); emitLaunchVerilator(of, argsFile); } // Rules to process hierarchical blocks of.puts("\n# Verilate hierarchical blocks\n"); for (const V3HierBlock* const blockp : m_planp->hierBlocksSorted()) { const string prefix = blockp->hierPrefix(); const string argsFile = blockp->commandArgsFileName(false); of.puts(blockp->hierGenerated(true)); of.puts(": $(VM_HIER_INPUT_FILES) $(VM_HIER_VERILOG_LIBS) "); of.puts(V3Os::filenameNonDir(argsFile) + " "); const V3HierBlock::HierBlockSet& children = blockp->children(); for (V3HierBlock::HierBlockSet::const_iterator child = children.begin(); child != children.end(); ++child) { of.puts((*child)->hierWrapper(true) + " "); } of.puts("\n"); emitLaunchVerilator(of, argsFile); // Rule to build lib*.a of.puts(blockp->hierLib(true)); of.puts(": "); of.puts(blockp->hierMk(true)); of.puts(" "); for (V3HierBlock::HierBlockSet::const_iterator child = children.begin(); child != children.end(); ++child) { of.puts((*child)->hierLib(true)); of.puts(" "); } of.puts("\n\t$(MAKE) -f " + blockp->hierMk(false) + " -C " + prefix); of.puts(" VM_PREFIX=" + prefix); of.puts("\n\n"); } of.puts("endif # Guard\n"); } public: explicit EmitMkHierVerilation(const V3HierBlockPlan* planp) : m_planp{planp} , m_makefile{v3Global.opt.makeDir() + "/" + v3Global.opt.prefix() + "_hier.mk"} { V3OutMkFile of(m_makefile); emit(of); } }; //###################################################################### // Gate class functions void V3EmitMk::emitmk() { UINFO(2, __FUNCTION__ << ": " << endl); const EmitMk emitter; } void V3EmitMk::emitHierVerilation(const V3HierBlockPlan* planp) { UINFO(2, __FUNCTION__ << ": " << endl); EmitMkHierVerilation{planp}; }
//This is simple Producer/Consumer example //For more examples check //http://www.asic-world.com/systemc/ //must include to use the systemc library #include "systemc.h" #include "pc.h" #include "headers.h" void Example::producerThread(){ cout << sc_time_stamp() << ": Initializing producerThread\n"; int x; //a time variable sc_time time = sc_time(3, SC_MS); //loop that runs 10 times for(int i = 0; i < 5; i++){ wait(time); x = producer(); cout << sc_time_stamp() << ": producerThread writing " << x << " to the fifo\n"; fifo.write(x); //note that write on fifo blocks once the fifo is full } } void Example::consumerThread(){ cout << "\t \t \t \t \t " << sc_time_stamp() << ": Initializing consumerThread\n"; int x; //a time variable sc_time time = sc_time(5, SC_MS); //loop that runs 10 times for(int i = 0; i < 5; i++){ fifo.read(x); consumer(x); cout << "\t \t \t \t \t " << sc_time_stamp() << ": consumerThread has read " << x << " from the fifo\n"; //take time to consume wait(time); } exit(0); }