text
stringlengths
41
20k
/******************************************************************************* * gnmux.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This is a simple gnmux for GN logic use in testbenches. ******************************************************************************* * 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 "gnmux.h" void gnmux::drivey_th() { for(;;) { // If the selector is invalid, we drive nothing. We will hang here until // something changes. if (pinS.read() < 0 || pinS.read() >= pin.size()) { pinY.write(def); wait(pinS.value_changed_event()); } // If it is valid, we drive the output with the input level. else { pinY.write(pin[pinS.read()]->read()); // We now wait until a change in the input or the selector. wait(pinS.value_changed_event() | pin[pinS.read()]->value_changed_event()); } } }
/* * @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; } } };
#ifndef TLM_QUEUE_CPP #define TLM_QUEUE_CPP #include <systemc.h> #include "tlm.h" #include "tlm_utils/simple_initiator_socket.h" #include "tlm_utils/simple_target_socket.h" #include "tlm_utils/peq_with_cb_and_phase.h" #include "common_func.hpp" #include "img_generic_extension.hpp" typedef struct tlm_item{ tlm::tlm_generic_payload *transaction; tlm::tlm_phase phase; sc_time delay; } tlm_item_t; template<unsigned int QUEUE_DEPTH> struct tlm_queue : sc_module { tlm_item_t tlm_item_queue[QUEUE_DEPTH]; unsigned int tlm_queue_ptr; bool is_full; bool is_empty; sc_event item_pushed_e; sc_event item_popped_e; SC_CTOR(tlm_queue): is_full(false), is_empty(true), tlm_queue_ptr(0) { // for (unsigned int i=0; i < QUEUE_DEPTH; i++){ // tlm_item_queue[i]; // } //SC_THREAD(tlm_queue_thread); } void push(tlm::tlm_generic_payload *trans, tlm::tlm_phase& phase, sc_time& delay) { if (is_full) { printf("[FULL] Waiting for queue to pop..\n"); wait(item_popped_e); } img_generic_extension* img_ext; (*trans).get_extension(img_ext); printf("[PUSH] pushing transaction %0d to queue index %0d\n", img_ext->transaction_number, tlm_queue_ptr); tlm_item_queue[tlm_queue_ptr].transaction = trans; tlm_item_queue[tlm_queue_ptr].phase = phase; tlm_item_queue[tlm_queue_ptr].delay = delay; tlm_queue_ptr++; is_full = (QUEUE_DEPTH <= tlm_queue_ptr); item_pushed_e.notify(); } void pop(tlm::tlm_generic_payload *trans, tlm::tlm_phase& phase, sc_time& delay) { if (is_empty) { printf("[EMPTY] Waiting for queue to push..\n"); wait(item_pushed_e); } trans = tlm_item_queue[tlm_queue_ptr].transaction; phase = tlm_item_queue[tlm_queue_ptr].phase; delay = tlm_item_queue[tlm_queue_ptr].delay; img_generic_extension* img_ext; (*trans).get_extension(img_ext); printf("[PULL] pushing transaction %0d to queue index %0d\n", img_ext->transaction_number, tlm_queue_ptr); // //tlm_queue_ptr--; // is_empty = (0 == tlm_queue_ptr); // item_popped_e.notify(); } }; #endif //TLM_QUEUE_CPP
/******************************************************************************* * cd4067.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This is a simple model for the CD4067 Analog Mux. ******************************************************************************* * 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 "cd4067.h" int cd4067::get_selector() { return (((d.read())?1:0) << 3) | (((c.read())?1:0) << 2) | (((b.read())?1:0) << 1) | ((a.read())?1:0); } void cd4067::process_th() { int line; bool channel_is_driver = false; x.write(GN_LOGIC_Z); for(line = 0; line < channel.size(); line = line + 1) channel[line]->write(GN_LOGIC_Z); sel = get_selector(); bool recheck = false; while(true) { /* If the recheck is high, this means the selector changed and we need * to refigure out who is driving. */ if (recheck) { /* We wait a time stamp and redo the driving. */ wait(1, SC_NS); recheck = false; /* In these cases, we just keep everyone at Z. */ if (inh.read() || sel >= channel.size()) continue; /* We check who is the driver and drive the other. If they are both * being driven, we drive X everywhere. */ if (x.read() == GN_LOGIC_Z) { channel_is_driver = true; x.write(channel[sel]->read()); } else if (channel[sel]->read()==GN_LOGIC_Z) { channel_is_driver = false; channel[sel]->write(x.read()); } else { PRINTF_WARN("TEST", "Two drivers on MUX"); channel[sel]->write(GN_LOGIC_X); x.write(GN_LOGIC_X); } continue; } /* We wait for one either a change in the selector or a change in * either side of the mux. If the selector is pointing to an illegal * value, we then just wait for a change in the selector. */ if (sel >= channel.size()) wait(a->default_event() | b->default_event() | c->default_event() | d->default_event() | inh->default_event()); else wait(channel[sel]->default_event() | a->default_event() | b->default_event() | c->default_event() | d->default_event() | inh->default_event() | x->default_event()); bool sel_triggered = a->value_changed_event().triggered() || b->value_changed_event().triggered() || c->value_changed_event().triggered() || d->value_changed_event().triggered(); if (debug) { /* If the sel is illegal, we only can process the selector. */ if (sel >= channel.size()) printf("%s: sel = %d, triggers: sel %c, inh %c, x %c\n", name(), sel, (sel_triggered)?'t':'f', (inh->value_changed_event().triggered())?'t':'f', (x->value_changed_event().triggered())?'t':'f'); else printf( "%s: sel = %d, triggers: channel %c, sel %c, inh %c, x %c\n", name(), sel, (channel[sel]->value_changed_event().triggered())?'t':'f', (sel_triggered)?'t':'f', (inh->value_changed_event().triggered())?'t':'f', (x->value_changed_event().triggered())?'t':'f'); } /* If inh went high we shut it all off, it does not matter who triggered * what. */ if (inh.read() == GN_LOGIC_1) { x.write(GN_LOGIC_Z); if (sel < channel.size()) channel[sel]->write(GN_LOGIC_Z); channel_is_driver = false; } /* If inh came back, we then need to resolve. */ else if (inh.value_changed_event().triggered()) { /* No need to drive Z if it is already. */ recheck = true; channel_is_driver = false; } /* Now we check the selector. If it changed, we need to drive Z and * recheck. This is because it is difficult to check every single * driver in a signal to find out what is going on. */ else if (sel_triggered) { int newsel = get_selector(); /* We now drive Z everywhere. */ if (sel < channel.size()) channel[sel]->write(GN_LOGIC_Z); x.write(GN_LOGIC_Z); channel_is_driver = false; /* And we update the selector variable. */ sel = newsel; /* And if the new selector is valid, we do a recheck. */ if (sel < channel.size()) recheck = true; } /* If the selector is not valid, we just ignore any activity on either * side as there can't be any change. We simply drive Z everywhere. * Note: this path is a safety one, it is probably never called. */ else if (sel >= channel.size()) { channel_is_driver = false; x.write(GN_LOGIC_Z); } /* When we update a output pin, there is always a reflection. If both * sides have the same value, this probably was a reflection, so we * can dump it. */ else if (x.read() == channel[sel]->read()) continue; /* We have an analog mux. In a real mux system, we would do a fight * between the sides and eventually settle to something. This is a * digital simulator though, so we need a simplification. If I get a * driver on one side, we drive that value on the other. */ else if (channel[sel]->value_changed_event().triggered() && (channel_is_driver || x.read() == GN_LOGIC_Z)) { channel_is_driver = true; x.write(channel[sel]->read()); } else if (x.default_event().triggered() && (!channel_is_driver || channel[sel]->read() == GN_LOGIC_Z)) { channel_is_driver = false; channel[sel]->write(x.read()); } /* If there are drivers on both sides, we need to put X on both sides. * Note: the current model will not leave this state unless there is * an inh or sel change. */ else { PRINTF_WARN("TEST", "Two drivers on MUX"); channel[sel]->write(GN_LOGIC_X); x.write(GN_LOGIC_X); } } } void cd4067::trace(sc_trace_file *tf) { sc_trace(tf, x, x.name()); sc_trace(tf, a, a.name()); sc_trace(tf, b, b.name()); sc_trace(tf, c, c.name()); sc_trace(tf, d, d.name()); sc_trace(tf, inh, inh.name()); }
/******************************************************************************* * cchanflash.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Implements a SystemC module for an integer wide UART protocol. It should * eventually be replaced with a real QSPI interface, but for now this works * for the ESPMOD project. ******************************************************************************* * 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 <vector> #include "cchanflash.h" #define SECADDR(range, addr) (secstart[range]+(((addr)-rangestart[range])>>12)) #define PAGEADDRINSEC(range, addr) ((secstart[range]<<4)+((addr)>>8)) #define PAGEADDR(range, addr) \ ((secstart[range]<<4)+(((addr)-(rangestart[range]))>>8)) #define ADDRINPAGE(range, addr) (((addr)-(rangestart[range]) & 0xfc)>>2) int cchanflash::getrange(unsigned int addr) { unsigned int r; /* We need to scan the memory for the address o see if it is valid. */ for(r = 0; r < rangestart.size(); r = r + 1) { /* The address ranges are in order, so if the current address is before * the current range, then there is no legal range. */ if (addr < rangestart[r]) return -1; /* Now we check the ending address. If it is in this range, we return * the addres range. */ if (addr <= rangeend[r]) return r; } /* And if we do not find it, we return -1. */ return -1; } bool cchanflash::checkaddr(unsigned int addr) { /* If the range is valid, we return true. */ return getrange(addr) >= 0; } bool cchanflash::preerase(unsigned int addr, unsigned int endaddr) { unsigned int i; unsigned int startsec, endsec; /* We need to find out what address range we are talking about. Only one * range can be erased at a time. */ int r = getrange(addr); if (r < 0) { PRINTF_ERROR("SCFLASH", "Starting address %x is not in a valid range", addr); return false; } if (endaddr > rangeend[r]) { PRINTF_ERROR("SCFLASH", "Erasing must be done to one range at a time."); return false; } startsec = SECADDR(r, addr); endsec = SECADDR(r, endaddr); for(i = startsec; i < endsec; i = i + 1) secs[i] = ERS; return true; } bool cchanflash::preload(unsigned int addr, void* data, unsigned int size) { int r; unsigned int startsec, endsec, sec; /* First we make sure the starting and ending addresses are valid. */ r = getrange(addr); if (r < 0) { PRINTF_ERROR("SCFLASH", "Access to illegal address %0x", addr); return false; } if (size + addr - 1> rangeend[r]) { PRINTF_ERROR("SCFLASH", "Access to illegal address %0x", addr + size -1); return false; } /* Now, we can deal with the data. We start by marking the set sectors. * For the preloading function we do not do all the checking if the secotr * is already programmed or erased. We just assume it is ok as this is for * preloading data for a test. */ startsec = SECADDR(r, addr); endsec = SECADDR(r, addr + size - 1); for(sec = startsec; sec <= endsec; sec = sec + 1) { secs[sec] = PROG; } /* Now we program the data. Note that there could be something already * there. If there is we get rid of it. */ unsigned int adinsec; unsigned int byteaddr; /* We do 64 words at a time. */ unsigned int endaddr = addr - rangestart[r] + size - 1; unsigned int pagesize; unsigned int fromaddr = 0; unsigned int pageend; unsigned int writeend; /* We now scan one page at a time. */ for(adinsec = addr - rangestart[r]; adinsec <= endaddr; adinsec = adinsec + 256) { /* Writes must be contained within a page. So first we need to find * out if this write will be within this page or not. */ pageend = adinsec | 0x0ffU; /* Now we find out if this write will go all the way to the end of the * page or not. */ if (endaddr >= pageend) writeend = pageend; else writeend = endaddr; /* We now set the size of the field. Anything beyond the string we chop * off. Therefore we will resize the field so that the page end position * fits. Any new spaces we fill with blanks, 0xffffffff. */ pagesize = (writeend % 256) + 1; pgm[PAGEADDRINSEC(r, adinsec)].resize(pagesize, 0xffffffff); /* And we copy in the data, one word at a time. We cycle from the * current address in this page all the way till the end of this * page. */ for (byteaddr = adinsec % 256; byteaddr < writeend % 256; byteaddr = byteaddr + 4) { pgm[PAGEADDRINSEC(r, adinsec)][byteaddr>>2] = ((unsigned int *)data)[fromaddr>>2]; // Each time we transfered a word, we increment the from address. fromaddr = fromaddr + 4; } } return true; } void cchanflash::addrange(unsigned int _rangestart, unsigned int _rangeend) { int r; /* This function can only be called before the rangeinit(). */ if (secs != NULL) { PRINTF_ERROR("SCFLASH", "addrange can only be called before rangeinit"); return; } if (_rangeend <= _rangestart) { PRINTF_ERROR("SCFLASH", "range from %x to %x is invalid", _rangestart, _rangeend); return; } for (r = 0; r < (int)rangestart.size(); r = r + 1) { if (_rangestart >= rangestart[r] && _rangestart <= rangeend[r] || _rangeend >= rangestart[r] && _rangeend <= rangeend[r] || _rangestart < rangestart[r] && _rangeend > rangeend[r]) { PRINTF_ERROR("SCFLASH", "No range overlaps are allowed"); } } /* Now that we know they are ok, we can insert them in order. */ for(r = 0; r < (int)rangestart.size() && _rangestart > rangestart[r]; r=r+1); if (r == (int)rangestart.size()) { rangestart.push_back(_rangestart); rangeend.push_back(_rangeend); } else { rangestart.insert(rangestart.begin()+r, _rangestart); rangeend.insert(rangeend.begin()+r, _rangeend); } } void cchanflash::rangeinit() { int r, sec, seccnt, thissecsize; /* There must be at least one region declared to call this function. */ if (rangestart.size() == 0 || rangeend.size() == 0) { PRINTF_ERROR("SCFLASH", "At least one range needs to be defined before calling rangeinit()"); return; } else if (rangestart.size() != rangeend.size()) { PRINTF_ERROR("SCFLASH", "There should be the same number of range ends and range starts."); return; } /* We need to calculate the starting sector for each range and also the * total number of sectors. */ seccnt = 0; thissecsize = 0; secstart.resize(rangestart.size()); for(r = 0; r < (int)rangestart.size(); r = r + 1) { /* We set the current range to start just after the previous one * finished. */ secstart[r] = seccnt; /* Now that we computed the sec starting position, we can calculate the * size of this range. We will need to do this to get the total size and * also the starting address of the next range. */ thissecsize = (rangeend[r]+1-rangestart[r])/4096; seccnt = seccnt + thissecsize; } /* We can now create the space. There should be at least one sector. */ if (seccnt == 0) { PRINTF_ERROR("SCFLASH", "There should at least one sector defined."); return; } /* We can now create the ranges and put them in place. */ secs = new secstate_t[seccnt]; if (secs == NULL) { PRINTF_FATAL("SCFLASH", "Could not allocate space for the sectors"); return; } for (sec = 0; sec < seccnt; sec = sec + 1) secs[sec] = UNK; /* The data is set to all blank. */ pgm = new std::vector<int>[seccnt*16]; if (pgm == NULL) { PRINTF_FATAL("SCFLASH", "Could not allocate space for the memory model"); return; } } void cchanflash::flash(void) { std::string msg(""); unsigned int addr, size, pos; uint32_t data; char recv; int range; printf("Running Flash Thread\n"); /* We check the secs pointer. If it is null, the memory has not been * initialized. */ if (secs == NULL) { PRINTF_ERROR("SCFLASH", "The CCHAN flash needs valid ranges added and initialized before using."); } while(1) { msg = ""; do { recv = i_uflash.from.read(); msg += recv; } while(recv != '\n'); printf("Flash got message %s", msg.c_str()); /* ERASE */ if (msg.find("e:") == 0) { /* We parse the message */ sscanf(msg.c_str(), "e:%x", &addr); addr = addr * 4096; /* convert sector to address. */ /* We forbid erasures to dangerous locations. */ range = getrange(addr); if (range < 0) { PRINTF_ERROR("SCFLASH", "Access to illegal address %0x", addr); i_uflash.to.write('\1'); } else { /* And we do a delay for the erasure. */ wait(20, SC_MS); /* Assuming it worked, we label the sector as erased. */ secs[SECADDR(range,addr)] = ERS; int pgstart = PAGEADDR(range,addr); int pgend = pgstart+15; int pg; for (pg = pgstart; pg <= pgend; pg = pg + 1) pgm[pg].resize(0); /* And we return success. */ i_uflash.to.write('\0'); } } /* PROGRAM */ else if (msg.find("w:") == 0) { /* We parse the message */ sscanf(msg.c_str(), "w:%x %u", &addr, &size); /* We forbid erasures to dangerous locations. */ range = getrange(addr); if (range < 0) { PRINTF_ERROR("SCFLASH", "Access to illegal address %0x", addr); i_uflash.to.write('\1'); } /* Writing to a never used sector can be bad. */ else if (secs[SECADDR(range, addr)] == UNK) { PRINTF_ERROR("SCFLASH", "Access to unititialized address %0x", addr); i_uflash.to.write('\1'); } /* We do not support size 0 or large messages. */ else if (size < 1 || size > 64) { PRINTF_ERROR("SCFLASH", "Illegal Size %d", size); i_uflash.to.write('\1'); } else if (((addr + size*4 - 1) & 0xffffff00) != (addr & 0xffffff00)) { PRINTF_ERROR("SCFLASH", "Write crossing 256byte page boundary: start = %x end = %x", addr, addr + size*4 - 1); i_uflash.to.write('\1'); } /* Command is valid. */ else { /* It should begin with "d:" */ if (i_uflash.from.read() != 'd' || i_uflash.from.read() != ':') { while(i_uflash.from.read() != '\n') ; SC_REPORT_ERROR("SCFLASH", "Data message expected!"); i_uflash.to.write('\1'); } else { /* The request is valid, so we store it. We simulate * the write time. */ wait(20, SC_US); /* We define the page is programmed. */ secs[SECADDR(range, addr)] = PROG; /* If the current position is too small to store the new page, * we extend it. For this we get the address within the page * and add the size. We always start a record from the address * zero. */ int pageaddr = PAGEADDR(range, addr); int addrinpage = ADDRINPAGE(range, addr); if (addrinpage + size > pgm[pageaddr].size()) pgm[pageaddr].resize(addrinpage + size); /* Now we store the data sent. */ for(pos = 0; pos < size; pos = pos + 1) { data = (0x000000ffU & i_uflash.from.read()); data = data | ((0x000000ffU & i_uflash.from.read()) << 8); data = data | ((0x000000ffU & i_uflash.from.read()) << 16); data = data | ((0x000000ffU & i_uflash.from.read()) << 24); pgm[pageaddr][pos+addrinpage] = data; } while(i_uflash.from.read() != '\n') ; i_uflash.to.write('\0'); } } } /* READ */ else { /* We parse the message */ sscanf(msg.c_str(), "r:%x %u", &addr, &size); /* We forbid accesses to dangerous locations. */ range = getrange(addr); if (range < 0) { PRINTF_ERROR("SCFLASH", "Access to illegal address %0x", addr); i_uflash.to.write('\1'); } /* We do not ban reads to unused locations as the firmware does * this to test the flash. We instead return different results. */ else { int secaddr = SECADDR(range, addr); int pageaddr = PAGEADDR(range, addr); wait(200, SC_NS); printf("Got Flash Read %x %u @%s\n", addr, size, sc_time_stamp().to_string().c_str()); /* Unknown: return random data. */ if (secs[secaddr] == UNK) { for(pos = 0; pos < size; pos = pos + 1) { i_uflash.to.write((char)rand()); i_uflash.to.write((char)rand()); i_uflash.to.write((char)rand()); i_uflash.to.write((char)rand()); } } /* Erased: return FFFF. */ else if (secs[secaddr] == ERS || pgm[pageaddr].size() == 0) { for(pos = 0; pos < size; pos = pos + 1) { i_uflash.to.write((char)(0xff)); i_uflash.to.write((char)(0xff)); i_uflash.to.write((char)(0xff)); i_uflash.to.write((char)(0xff)); } } /* Programmed: return the data programmed. */ else { pos = (addr>>2) & 0x3f; /* offset addr */ unsigned int end = size + pos - 1; unsigned int endsto = pgm[pageaddr].size()-1; /* If the starting pos is before the size (end of the * message) we put as much as we can. */ for(; pos <= ((end>endsto)?endsto:end); pos = pos + 1) { data = pgm[pageaddr][pos]; i_uflash.to.write((char)(data & 0xff)); i_uflash.to.write((char)((data>>8) & 0xff)); i_uflash.to.write((char)((data>>16) & 0xff)); i_uflash.to.write((char)((data>>24) & 0xff)); } /* If we have not given all the data, we fill the rest with * ff */ for(; pos <= end; pos = pos + 1) { i_uflash.to.write((char)(0xff)); i_uflash.to.write((char)(0xff)); i_uflash.to.write((char)(0xff)); i_uflash.to.write((char)(0xff)); } } i_uflash.to.write('\0'); /* Return success */ } } } }
#include <systemc.h> #include <unordered_set> #include <array> #include <string> namespace acs { typedef int Building; typedef int Person; #define NUM_DOORS 6 #define NUM_PERSONS 4 #define NUM_BUILDINGS 4 #define NO_PERSON (-1) #define DEFAULT_BUILDING 0 #define TIMEOUT_RED 5 #define TIMEOUT_GREEN 20 #define TIME_UNIT SC_SEC /* Default number of steps in the simulation */ #define NUM_STEPS 20 /* The authentication datatbase */ class Users { private: static std::unordered_set<Building> aut[NUM_PERSONS]; static Building sit[NUM_PERSONS]; public: Users() { for (Person p= 0; p< NUM_PERSONS; p++) { aut[p]= std::unordered_set<Building>(); sit[p]= DEFAULT_BUILDING; } } static bool admitted(Person p, Building b) { return (aut[p].count(b) > 0); } static void set_sit(Person p, Building b) { sit[p]= b; } static Building get_sit(Person b) { return sit[b]; } static void add_aut(Person p, Building b) { aut[p].insert(b); } }; std::unordered_set<Building> Users::aut[NUM_PERSONS]; Building Users::sit[NUM_PERSONS]; std::string log_time() { return "["+ sc_time_stamp().to_string()+ "] "; } /* An LED, which can be turned on and off. */ SC_MODULE(LED) { sc_in<bool> in; sc_in<bool> in2; SC_CTOR(LED) { SC_METHOD(blink); sensitive << in; } void blink() { if (in.read()) cout << log_time() << "LED "<< name() << ": ON\n"; else cout << log_time() << "LED "<< name() << ": OFF\n"; } }; /* The gate, implementing the block Door */ SC_MODULE(Gate) { sc_in<Person> card; // Turnstile interface: sc_in<bool> passed; sc_out<bool> unlock; // Two lights for green and red: sc_out<bool> green; sc_out<bool> red; public: // Better: make it private, include values as constructor args. Building org; Building dest; private: Person dap= NO_PERSON; // Person currently passing public: SC_CTOR(Gate) { dap= NO_PERSON; SC_THREAD(operate); } void accept() { cout << log_time() << "Person " << dap << " accepted.\n"; green.write(true); unlock.write(true); } void pass_thru() { cout << log_time() << "Person " << dap << " has gone to " << dest << "\n"; Users::set_sit(dap, dest); green.write(false); unlock.write(false); dap= NO_PERSON; } void off_grn() { green.write(false); unlock.write(false); dap= NO_PERSON; } void refuse() { cout << log_time() << "Person " << dap << " refused.\n"; red.write(true); dap= NO_PERSON; } void off_red() { red.write(false); dap= NO_PERSON; } void operate() { while (true) { wait(card.value_changed_event()); dap= card.read(); if (Users::admitted(dap, dest)) { accept(); wait(sc_time(TIMEOUT_GREEN, TIME_UNIT), passed.posedge_event()); if (passed.read()) pass_thru(); else off_grn(); } else { refuse(); wait(TIMEOUT_RED, TIME_UNIT); off_red(); } } } }; bool pick_bool() { return rand() % 2 == 0; } /* The turnstile has an input to be unlocked, and an output * indicating wether someone has passed. */ SC_MODULE(turnstile) { sc_in<bool> unlock; sc_out<bool> passed; SC_CTOR(turnstile) { SC_THREAD(operate); // sensitive << unlock; } void operate() { int t; bool b; while (true) { wait (unlock.posedge_event()); cout << log_time() << "Turnstile " << name() << " unlocked.\n"; /* Wait random amount of time... */ wait(rand() % (TIMEOUT_GREEN/2)+ TIMEOUT_GREEN/2, TIME_UNIT); b= pick_bool(); cout << log_time() << "Turnstile " << name () << (b ? ": somebody " : ": nobody ") << "passed.\n"; passed.write(b); } } }; /* A complete door consists of a gate (controller), two LEDs, and a turnstile */ SC_MODULE(Door) { sc_out<Person> card; private: sc_signal<bool> green_sig; sc_signal<bool> red_sig; sc_signal<bool> unlock_sig; sc_signal<bool> pass_sig; sc_signal<Person> card_sig; LED grn; LED red; turnstile ts; Gate gc; public: SC_CTOR(Door) : grn("Green"), red("Red"), ts("TS"), gc("GC") { gc.red(red_sig); red.in(red_sig); gc.green(green_sig); grn.in(green_sig); gc.card(card_sig); card(card_sig); gc.unlock(unlock_sig); ts.unlock(unlock_sig); gc.passed(pass_sig); ts.passed(pass_sig); // SC_METHOD(operate); // sensitive >> card; } void setOrgDest(int org, int dest) { gc.org= org; gc.dest= dest; } void operate() { approach(card.read()); } void approach(Person p) { cout << log_time() << "Person "<< p << " approaching door " << name() << "\n"; card.write(p); } }; SC_MODULE(testGen) { Door *doors[NUM_DOORS]; int num_steps; SC_CTOR(testGen) { doors[0] = new Door("DoorA"); doors[1] = new Door("DoorB"); doors[2] = new Door("DoorC"); doors[3] = new Door("DoorD"); doors[4] = new Door("DoorE"); doors[5] = new Door("DoorF"); /* Connect doors */ doors[0]->setOrgDest(1, 2); doors[1]->setOrgDest(2, 1); doors[2]->setOrgDest(2, 3); doors[3]->setOrgDest(3, 4); doors[4]->setOrgDest(4, 3); doors[5]->setOrgDest(4, 1); SC_THREAD(driver); } void driver() { Person p; Building b; int c; for (int i= 0; i< num_steps; i++) { cout << log_time() << "#### New simulation step ################\n"; p= rand() % NUM_PERSONS; c= rand() % NUM_DOORS; // cout << "Person "<< p<< " approaching door "<< c << "\n"; doors[c]->approach(p); wait(20, SC_SEC); cout << log_time() << "Person "<< p<< " now in building "<< Users::get_sit(p) << "\n"; } } }; int sc_main(int argc, char* argv[]) { int steps= NUM_STEPS; Building permissions[NUM_PERSONS][NUM_BUILDINGS]= { {1, 2, 3, 4}, {1, 2}, {2, 3}, {1, 2, 4}, }; if (argc > 1) { std::stringstream s; s << argv[1]; s >> steps; } /* Initialize controller */ for (Person p= 0; p< NUM_PERSONS; p++) for (Building b= 0; b< NUM_BUILDINGS; b++) { if (permissions[p][b]) Users::add_aut(p, permissions[p][b]); } testGen tg("TestGen"); tg.num_steps= steps; /* Run the test */ cout << "Starting.\n"; sc_start(); return 0; } }
/******************************************************************************* * panic.cpp -- Copyright 2019 Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This file replaces the run time error functions from the ESP32 with * equivalents that will kill the model and print a message on the screen. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file was based off the work covered by the license below: * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <systemc.h> #include "info.h" #include <stdlib.h> #include <esp_system.h> #include <freertos/FreeRTOS.h> #include <freertos/task.h> /* Note: The linker script will put everything in this file in IRAM/DRAM, so it also works with flash cache disabled. */ void __attribute__((weak)) vApplicationStackOverflowHook( TaskHandle_t xTask, signed char *pcTaskName ) { printf("***ERROR*** A stack overflow in task "); printf((char *)pcTaskName); printf(" has been detected.\r\n"); espm_abort(); } /* These two weak stubs for esp_reset_reason_{get,set}_hint are used when * the application does not call esp_reset_reason() function, and * reset_reason.c is not linked into the output file. */ void __attribute__((weak)) esp_reset_reason_set_hint(esp_reset_reason_t hint) { } esp_reset_reason_t __attribute__((weak)) esp_reset_reason_get_hint(void) { return ESP_RST_UNKNOWN; } static inline void invoke_abort() { SC_REPORT_FATAL("PANIC", "Abort Called"); } /* Renamed to espm_abort to not conflict with the system abort(). */ void espm_abort() { printf("abort() was called\n"); /* Calling code might have set other reset reason hint (such as Task WDT), * don't overwrite that. */ if (esp_reset_reason_get_hint() == ESP_RST_UNKNOWN) { esp_reset_reason_set_hint(ESP_RST_PANIC); } invoke_abort(); } /* This disables all the watchdogs for when we call the gdbstub. */ static void esp_panic_dig_reset() { SC_REPORT_FATAL("PANIC", "Panic Dig Reset"); } void esp_set_breakpoint_if_jtag(void *fn) { PRINTF_INFO("PANIC", "Set breakpoint %p", fn); } esp_err_t esp_set_watchpoint(int no, void *adr, int size, int flags) { if (no < 0 || no > 1) { return ESP_ERR_INVALID_ARG; } if (flags & (~0xC0000000)) { return ESP_ERR_INVALID_ARG; } PRINTF_INFO("PANIC", "Setting watchpoint %d addr=%p size=%d flags=%x", no, adr, size, flags); return ESP_OK; } void esp_clear_watchpoint(int no) { PRINTF_INFO("PANIC", "Clearing watchpoint %d", no); } static void esp_error_check_failed_print(const char *msg, esp_err_t rc, const char *file, int line, const char *function, const char *expression) { printf("%s failed: esp_err_t 0x%x", msg, rc); } void _esp_error_check_failed_without_abort(esp_err_t rc, const char *file, int line, const char *function, const char *expression) { esp_error_check_failed_print("ESP_ERROR_CHECK_WITHOUT_ABORT", rc, file, line, function, expression); } void _esp_error_check_failed(esp_err_t rc, const char *file, int line, const char *function, const char *expression) { esp_error_check_failed_print("ESP_ERROR_CHECK", rc, file, line, function, expression); invoke_abort(); }
// #include <QApplication> #include "mainwindow.h" #include "qapplication.h" #include <QVBoxLayout> #include <QHBoxLayout> #include <QSplitter> #include <QPushButton> #include <systemc.h> #include <pthread.h> #include <QList> #include <iostream> #include "scqt_worker.h" // -------------- From "How do I create a pause/wait function using Qt?" ----- // -------------- https://stackoverflow.com/questions/3752742/how-do-i-create-a-pause-wait-function-using-qt ----- // -------------- answered Mar 24, 2017 at 15:18 by dvntehn00bz ----------------- #include <QEventLoop> #include <QTimer> inline void delay(int millisecondsWait) { QEventLoop loop; QTimer t; t.connect(&t, &QTimer::timeout, &loop, &QEventLoop::quit); t.start(millisecondsWait); loop.exec(); } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , m_scqtThread(nullptr) , m_scqtWorker(nullptr) , ui(new Ui::MainWindow) { connect(this, &MainWindow::Message, this, &MainWindow::onMessage); // setupUi(); ui->setupUi(this); setupSim(); SVGs = new SVG_Viewer(NULL); SVGs->getScene()->addItem (SVGs->getTxt()); ui->graphicsView->setScene(SVGs->getScene()); ui->graphicsView->show(); QObject::connect(ui->verticalSlider, SIGNAL( valueChanged(int) ), SVGs, SLOT(on_verticalSlider_valueChanged(int))); } MainWindow::~MainWindow() { } /* SVG rendering is updated in this function (each time the "clock" button is pressed). * A first mode where lists are initialized: case where 'logMessage.contains("Report received: 0 s") * This involves a search for correspondences between systemC components and SVG file elements. * * Another mode where rendering is updated according to the string generated by systemC: case where logMessage.contains("Report received") * SVG element list values are updated according to the values (after the '=' sign) contained in the strDom string array */ void MainWindow::onMessage(QString const &msg_origin, QString const &msg_level, QString const &msg) { QString logMessage(msg_level); // QStringList strDom; // QList<QDomElement> listElem; QDomElement elem; logMessage.append(" msg (").append(msg_origin).append(") :: ").append(msg); // logConsole->append(logMessage); ui->textBrowser->append(logMessage); if(logMessage.contains("Report received: 0 s")) { ui->textBrowser->append("Report received time 0 : findDomelements related to SVG file and value processing"); *(SVGs->getStrDom()) = logMessage.split(", "); /* Loading hierarchy elements (string) */ // *(SVGs->getPrior_value()) = *(SVGs->getStrDom()); /* Visual console of hierarchy elements (character string) */ for(int i = 0 ; i< (SVGs->getStrDom())->length() ; i++) { ui->textBrowser->append((SVGs->getStrDom())->at(i)); } SVGs->getStrDom()->removeFirst(); // Deleting the first element corresponding to a systemC message /* DOM loading based on string array elements */ ui->textBrowser->append(""); ui->textBrowser->append("Find elements!"); for(int i = 0 ; i<(SVGs->getStrDom())->length() ; i++) { elem = findDomElement("svg30:layer1:STROKES:"+ ((SVGs->getStrDom())->at(i).split("=").at(0)), *(SVGs->getDom())); if(!(elem).isNull()) { SVGs->getPrior_value()->append((SVGs->getStrDom())->at(i)); SVGs->getIndex_elem()->append(i); SVGs->getListElem()->append(elem); // Add element only when non-zero } } /* Visual for all SVG elements found */ std::cout<<std::endl; std::cout<<"Display found elements and its index value!"<<std::endl; for(int i = 0 ; i<SVGs->getListElem()->length() ; i++) { // ui->textBrowser->append(SVGs->getListElem()->at(i).attribute("id")); // ui->textBrowser->append((SVGs->getIndex_elem()->at(i))); std::cout<<"el:"<<SVGs->getListElem()->at(i).attribute("id").toStdString()<<" ; index:"<<(SVGs->getIndex_elem()->at(i))<<std::endl; } } else if(logMessage.contains("Report received")) { *(SVGs->getStrDom()) = logMessage.split(", "); /* Loading hierarchy elements (string) */ SVGs->getStrDom()->removeFirst(); // Deleting the first element corresponding to a systemC message ui->textBrowser->append("Report received time > 0 : only value processing"); // setTextDomElementSim((QDomElement*)&(SVGs->getListElem()->at(12)), (SVGs->getStrDom())->at(12).split("=").at(1)); /* Updating values */ for(int i=0 ; i<SVGs->getIndex_elem()->length() ; i++) { // std::cout<<"12:"<<SVGs->getListElem()->at(i).attribute("id").toStdString()<<std::endl; setTextDomElementSim((SVGs->getListElem()->at(i)), (SVGs->getStrDom())->at(SVGs->getIndex_elem()->at(i)).split("=").at(1)); } /* Scans all elements of the strDom, listElem and prior_value lists to detect a change in value, thus changing the color of the thread (red). */ for(int i=0 ; i<SVGs->getIndex_elem()->length() ; i++) { if((SVGs->getPrior_value()->at(i)) != ((SVGs->getStrDom())->at(SVGs->getIndex_elem()->at(i)))) { std::cout<<"12:"<<(SVGs->getPrior_value()->at(i)).toStdString()<<std::endl; setColorDomElement((SVGs->getListElem()->at(i)), "ff0000"); } } /* Update priority_value */ for(int i=0 ; i<SVGs->getIndex_elem()->length() ; i++) { std::cout<<"actual:"<<((SVGs->getStrDom())->at(SVGs->getIndex_elem()->at(i))).toStdString()<<" ; prior:"<<(SVGs->getPrior_value()->at(i)).toStdString()<<std::endl; (SVGs->getPrior_value())->replace(i, (SVGs->getStrDom())->at(SVGs->getIndex_elem()->at(i))); } SVGs->refresh(); } } //void MainWindow::onResetClicked(bool checked) //{ // (void)checked; // _sendMessage("DEBUG", "Reset clicked"); //} void MainWindow::on_pushButton_clicked(bool checked) { (void)checked; _sendMessage("DEBUG", "Reset clicked"); } //void MainWindow::onClockClicked(bool checked) //{ // (void)checked; // _sendMessage("DEBUG", "Clock clicked"); // if (m_scqtWorker != nullptr) { // emit setNewState(SC_ST_COMMAND_RUN); // emit requestReport(); // } //} void MainWindow::on_pushButton_3_clicked(bool checked) { (void)checked; _sendMessage("DEBUG", "Clock clicked"); if (m_scqtWorker != nullptr) { emit setNewState(SC_ST_COMMAND_RUN); emit requestReport(); } } void MainWindow::on_pushButton_2_clicked(bool checked) { (void)checked; _sendMessage("DEBUG", "Exit clicked, terminating program"); if (m_scqtWorker != nullptr) { emit setNewState(SC_ST_COMMAND_EXIT); } delay(1000); QApplication::quit(); } void MainWindow::newHierarchy(QStringList hier) { QString debugMsg("Hierarchy received:"); for (qsizetype i=0; i<hier.size(); i++) { if (i == 0) { debugMsg.append(" "); } else { debugMsg.append(", "); } debugMsg.append(hier.at(i)); } _sendMessage("DEBUG", debugMsg); } void MainWindow::newReport(QStringList rep) { QString debugMsg("Report received:"); for (qsizetype i=0; i<rep.size(); i++) { if (i == 0) { debugMsg.append(" "); } else { debugMsg.append(", "); } debugMsg.append(rep.at(i)); } _sendMessage("DEBUG", debugMsg); } void MainWindow::_sendMessage(QString const &msg_level, QString const &msg) { emit Message("GUI", msg_level, msg); // emit Message("DEBUG", msg_level, msg_upper); } void MainWindow::setupUi() { QGridLayout *gridLayout = new QGridLayout; QPushButton *btnReset; QPushButton *btnClock; QPushButton *btnExit; QWidget *cWidget = new QWidget(); setCentralWidget(cWidget); centralWidget()->setLayout(gridLayout); btnReset = new QPushButton("Reset"); connect(btnReset, &QPushButton::clicked, this, &MainWindow::on_pushButton_clicked); btnClock = new QPushButton("Clock"); connect(btnClock, &QPushButton::clicked, this, &MainWindow::on_pushButton_3_clicked); btnExit = new QPushButton("Exit"); connect(btnExit, &QPushButton::clicked, this, &MainWindow::on_pushButton_2_clicked); // logConsole = new QTextBrowser(); // Layout grid // First row: <Reset> ...splitter... <Clock> // Second row: < logConsole > // Third row: <Exit> gridLayout->addWidget(btnReset, 0, 0); gridLayout->addWidget(new QSplitter(Qt::Horizontal), 0, 1); gridLayout->addWidget(btnClock, 0, 2); // gridLayout->addWidget(logConsole, 2, 0, 1, 3); // Span the three columns gridLayout->addWidget(btnExit, 3, 0); setWindowTitle("SystemC Test"); } void MainWindow::setupSim() { m_scqtThread = new QThread; m_scqtWorker = new scQtWorker; m_scqtWorker->moveToThread(m_scqtThread); // Prepare config parameters m_ConfigParams.rst_act_level = false; // Reset: low-level active m_ConfigParams.rst_act_microsteps = 20; // Reset active for 25 usteps (2.5 clock periods) m_ConfigParams.clk_act_edge = false; // Clock: falling-edge sensitive m_ConfigParams.ena_act_level = true; // Enable: high-level active m_ConfigParams.clk_period = sc_time(10, SC_NS); // CLock period: 10 ns m_ConfigParams.clk_semiperiod_microsteps = 4; m_ConfigParams.microstep = m_ConfigParams.clk_period/m_ConfigParams.clk_semiperiod_microsteps; m_scqtWorker->setConfigParameters(m_ConfigParams); connect(m_scqtThread, &QThread::started, m_scqtWorker, &scQtWorker::doStart); connect(m_scqtWorker, &scQtWorker::Message, this, &MainWindow::onMessage); connect(this, &MainWindow::setNewState, m_scqtWorker, &scQtWorker::setNewState); connect(this, &MainWindow::requestHierarchy, m_scqtWorker, &scQtWorker::getHierarchy); connect(this, &MainWindow::requestReport, m_scqtWorker, &scQtWorker::getReport); connect(this, &MainWindow::setTraceList, m_scqtWorker, &scQtWorker::setTraceList); connect(m_scqtWorker, &scQtWorker::signalHierarchy, this, &MainWindow::newHierarchy); connect(m_scqtWorker, &scQtWorker::signalReport, this, &MainWindow::newReport); m_scqtThread->start(); emit setNewState(SC_ST_COMMAND_RUN); emit requestHierarchy(); } void MainWindow::Refresh() { ui->graphicsView->update(); } void MainWindow::on_checkBox_clicked(bool checked) { std::cout<<"clicked"<<std::endl; if(checked) { for(int i=0 ; i<SVGs->getIndex_elem()->length() ; i++) { // showDomElementSim(SVGs->getListElem()->at(i)); setStyleAttrDomElementSim(SVGs->getListElem()->at(i), "display:inline"); } } else { for(int i=0 ; i<SVGs->getIndex_elem()->length() ; i++) { // hideDomElementSim(SVGs->getListElem()->at(i)); setStyleAttrDomElementSim(SVGs->getListElem()->at(i), "display:none"); } } SVGs->refresh(); } /* * Not used for this simulation */ void MainWindow::on_actionExit_triggered() { } /* Function called when user clicks on 'file' > 'Open Source * */ void MainWindow::on_actionOpen_source_triggered() { /* The files displayed in the dialog box are only those whose extension is set in the 2nd parameter (txt and asm). */ QString link = WinSelectFile.getOpenFileName(this, tr("Select Source file)"), "C:/", tr("Assembler Files (*.asm *.txt)")); std::cout<<link.toStdString()<<std::endl; QFile asmf(link); asmf.open(QIODevice::ReadOnly); /* The contents of the file go into this Widget */ ui->TextEditor->setPlainText(asmf.readAll()); }
#ifndef MEMORY_TLM_CPP #define MEMORY_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 "memory_tlm.hpp" #include "common_func.hpp" #include "address_map.hpp" void memory_tlm::do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address) { sc_uint<8> local_data[8]; int max_data_length = (data_length > 8) ? 8 : data_length; for (int i = 0; i < max_data_length; i++) { local_data[i] = *(mem_array + address - MEMORY_ADDRESS_LO + i); } for (int i = max_data_length; i < 8; i++) { local_data[i] = 0; } mem_data = (local_data[7], local_data[6], local_data[5], local_data[4], local_data[3], local_data[2], local_data[1], local_data[0]); mem_address = address - MEMORY_ADDRESS_LO; mem_we = 0; memcpy(data, (mem_array + address - MEMORY_ADDRESS_LO), data_length); } void memory_tlm::do_when_write_transaction(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address) { sc_uint<8> local_data[8]; int max_data_length = (data_length > 8) ? 8 : data_length; for (int i = 0; i < max_data_length; i++) { local_data[i] = *(data + i); } for (int i = max_data_length; i < 8; i++) { local_data[i] = 0; } mem_data = (local_data[7], local_data[6], local_data[5], local_data[4], local_data[3], local_data[2], local_data[1], local_data[0]); mem_address = address - MEMORY_ADDRESS_LO; mem_we = 1; memcpy((mem_array + address - MEMORY_ADDRESS_LO), data, data_length); } void memory_tlm::backdoor_write(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address) { memcpy((mem_array + address - MEMORY_ADDRESS_LO), data, data_length); } void memory_tlm::backdoor_read(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address) { data = new unsigned char[data_length]; memcpy(data, (mem_array + address - MEMORY_ADDRESS_LO), data_length); } #endif // MEMORY_TLM_CPP
/* Copyright (c) 2015 Convey Computer Corporation * * This file is part of the OpenHT toolset located at: * * https://github.com/TonyBrewer/OpenHT * * Use and distribution licensed under the BSD 3-clause license. * See the LICENSE file for the complete license text. */ // Generate fixtures for each module in input vex file // #include "stdafx.h" #include "Design.h" struct CPort { CPort(string name, bool bIndexed, int highBit, int lowBit, int portIdx) : m_name(name), m_bIndexed(bIndexed), m_highBit(highBit), m_lowBit(lowBit), m_portIdx(portIdx) {} string m_name; bool m_bIndexed; int m_highBit; int m_lowBit; int m_portIdx; }; struct CPortList { string m_clock; vector<CPort> m_inputs; vector<CPort> m_outputs; }; void CDesign::GenFixture(const string &verilogFileName) { static const basic_string <char>::size_type npos = -1; string testDir = "VexTest"; MkDir(testDir); GenVexTestRunAll(testDir + "/RunAll"); GenFixtureCommon(testDir + "/Common"); MkDir(testDir + "/Modules"); string primFileName = verilogFileName; size_t periodPos = primFileName.find_last_of("."); if (periodPos != npos) primFileName.erase(periodPos); size_t slashPos = primFileName.find_last_of("/\\"); if (slashPos != npos) primFileName.erase(0, slashPos+1); ModuleMap_Iter moduleIter; for (moduleIter = m_moduleMap.begin(); moduleIter != m_moduleMap.end(); moduleIter++) { CModule *pModule = &moduleIter->second; if (pModule->m_bPrim) continue; GenFixtureModule(testDir + "/Modules/" + pModule->m_name.c_str(), primFileName, pModule); } } void CDesign::GenVexTestRunAll(const string &runAllFile) { FILE *fp = fopen(runAllFile.c_str(), "wb"); if (!fp) { printf("Could not open '%s' for writing\n", runAllFile.c_str()); exit(1); } fprintf(fp, "#!/bin/tcsh\n"); fprintf(fp, "cd Common\n"); fprintf(fp, "g++ VcdDiff.cpp -o VcdDiff\n"); fprintf(fp, "cd ..\n"); fprintf(fp, "cd Modules\n"); fprintf(fp, "foreach i (*)\n"); fprintf(fp, "cd $i\n"); fprintf(fp, "./RunTest $i\n"); fprintf(fp, "cd ..\n"); fprintf(fp, "end\n"); fclose(fp); } void CDesign::GenFixtureCommon(const string &commonDir) { MkDir(commonDir); GenFixtureCommonRandomH(commonDir + "/Random.h"); GenFixtureCommonRandomCpp(commonDir + "/Random.cpp"); GenFixtureCommonVcdDiff(commonDir + "/VcdDiff.cpp"); } void CDesign::GenFixtureCommonRandomH(const string &randomHFile) { FILE *fp = fopen(randomHFile.c_str(), "w"); if (!fp) { printf("Could not open '%s' for writing\n", randomHFile.c_str()); exit(1); } fprintf(fp, "// Random.h: Header for random number generator\n"); fprintf(fp, "//\n"); fprintf(fp, "//////////////////////////////////////////////////////////////////////\n"); fprintf(fp, "\n"); fprintf(fp, "#pragma once\n"); fprintf(fp, "\n"); fprintf(fp, "class CRandom;\n"); fprintf(fp, "\n"); fprintf(fp, "class CRndGen\n"); fprintf(fp, "{\n"); fprintf(fp, "public:\n"); fprintf(fp, " CRndGen(uint32_t init=1);\n"); fprintf(fp, " virtual ~CRndGen();\n"); fprintf(fp, "\n"); fprintf(fp, " uint32_t AsUint32();\n"); fprintf(fp, " uint64_t AsUint64() { return ((uint64_t)AsUint32() << 32) | AsUint32(); }\n"); fprintf(fp, " int64_t AsSint64() { return (int64_t)(((uint64_t)AsUint32() << 32) | AsUint32()); }\n"); fprintf(fp, " double AsDouble();\n"); fprintf(fp, " float AsFloat();\n"); fprintf(fp, " uint32_t GetSeed() { return initialSeed; }\n"); fprintf(fp, " void Seed(uint32_t init);\n"); fprintf(fp, "\n"); fprintf(fp, "private:\n"); fprintf(fp, " void ResetRndGen();\n"); fprintf(fp, "\n"); fprintf(fp, "private:\n"); fprintf(fp, " union PrivateDoubleType { // used to access doubles as unsigneds\n"); fprintf(fp, " double d;\n"); fprintf(fp, " uint32_t u[2];\n"); fprintf(fp, " };\n"); fprintf(fp, " PrivateDoubleType doubleMantissa;\n"); fprintf(fp, "\n"); fprintf(fp, " union PrivateFloatType { // used to access floats as unsigneds\n"); fprintf(fp, " float f;\n"); fprintf(fp, " uint32_t u;\n"); fprintf(fp, " };\n"); fprintf(fp, " PrivateFloatType floatMantissa;\n"); fprintf(fp, "\n"); fprintf(fp, " // struct defines a knot of the circular queue\n"); fprintf(fp, " // used by the lagged Fibonacci algorithm\n"); fprintf(fp, " struct Vknot {\n"); fprintf(fp, " Vknot() { v = 0; vnext = 0; }\n"); fprintf(fp, " uint32_t v;\n"); fprintf(fp, " Vknot *vnext;\n"); fprintf(fp, " } m_Vknot[97];\n"); fprintf(fp, " uint32_t initialSeed; // start value of initialization routine\n"); fprintf(fp, " uint32_t Xn; // generated value\n"); fprintf(fp, " uint32_t cn, Vn; // temporary values\n"); fprintf(fp, " Vknot *V33, *V97, *Vanker; // some pointers to the queue\n"); fprintf(fp, "};\n"); fprintf(fp, "\n"); fprintf(fp, "class CRandom\n"); fprintf(fp, "{\n"); fprintf(fp, " friend class CRndGen;\n"); fprintf(fp, "public:\n"); fprintf(fp, " CRandom() {}\n"); fprintf(fp, " // ~CRandom() {};\n"); fprintf(fp, " void Seed(uint32_t init) { m_rndGen.Seed(init); }\n"); fprintf(fp, "\n"); fprintf(fp, " bool RndBool() { return (m_rndGen.AsUint32() & 1) == 1; }\n"); fprintf(fp, "\n"); fprintf(fp, " int32_t RndSint32() { return m_rndGen.AsUint32(); }\n"); fprintf(fp, "\n"); fprintf(fp, " uint32_t RndUint32() { return m_rndGen.AsUint32(); }\n"); fprintf(fp, "\n"); fprintf(fp, " uint32_t RndUint32(uint32_t low, uint32_t high)\n"); fprintf(fp, " { return (m_rndGen.AsUint32() %% (high-low+1)) + low; }\n"); fprintf(fp, "\n"); fprintf(fp, " uint64_t RndSint64(int64_t low, int64_t high)\n"); fprintf(fp, " { return (m_rndGen.AsUint64() %% (high-low+1)) + low; }\n"); fprintf(fp, "\n"); fprintf(fp, " uint32_t RndSint32(int32_t low,int32_t high)\n"); fprintf(fp, " { return (m_rndGen.AsUint32() %% (high-low+1)) + low; }\n"); fprintf(fp, "\n"); fprintf(fp, " uint64_t RndUint64() { return m_rndGen.AsUint64(); }\n"); fprintf(fp, "\n"); fprintf(fp, " uint64_t RndUint64(uint64_t low, uint64_t high)\n"); fprintf(fp, " { return (m_rndGen.AsUint64() %% (high-low+1)) + low; }\n"); fprintf(fp, "\n"); fprintf(fp, " double RndUniform(double pLow=0.0, double pHigh=1.0)\n"); fprintf(fp, " { return pLow + (pHigh - pLow) * m_rndGen.AsDouble(); }\n"); fprintf(fp, "\n"); fprintf(fp, " float RndUniform(float pLow, float pHigh=1.0)\n"); fprintf(fp, " { return pLow + (pHigh - pLow) * m_rndGen.AsFloat(); }\n"); fprintf(fp, "\n"); fprintf(fp, " double RndPercent() { return RndUniform(0.0, 99.999999999); }\n"); fprintf(fp, "\n"); fprintf(fp, " // double RndNegExp(double mean)\n"); fprintf(fp, " // { return(-mean * log(m_rndGen.AsDouble())); }\n"); fprintf(fp, "\n"); fprintf(fp, "private:\n"); fprintf(fp, " CRndGen m_rndGen;\n"); fprintf(fp, "};\n"); fclose(fp); } void CDesign::GenFixtureCommonRandomCpp(const string &randomCppFile) { FILE *fp = fopen(randomCppFile.c_str(), "w"); if (!fp) { printf("Could not open '%s' for writing\n", randomCppFile.c_str()); exit(1); } fprintf(fp, "// Random.cpp: Random number generator for fixture\n"); fprintf(fp, "//\n"); fprintf(fp, "//////////////////////////////////////////////////////////////////////\n"); fprintf(fp, "\n"); fprintf(fp, "#include <stdint.h>\n"); fprintf(fp, "#include \"Random.h\"\n"); fprintf(fp, "\n"); fprintf(fp, "//////////////////////////////////////////////////////////////////////\n"); fprintf(fp, "// Construction/Destruction\n"); fprintf(fp, "//////////////////////////////////////////////////////////////////////\n"); fprintf(fp, "\n"); fprintf(fp, "CRndGen::CRndGen(uint32_t init)\n"); fprintf(fp, "{\n"); fprintf(fp, " // create a 97 element circular queue\n"); fprintf(fp, " Vknot *Vhilf;\n"); fprintf(fp, " Vanker = V97 = Vhilf = &m_Vknot[0];\n"); fprintf(fp, "\n"); fprintf(fp, " for(int16_t i=96; i>0; i-- ) {\n"); fprintf(fp, " Vhilf->vnext = &m_Vknot[i];\n"); fprintf(fp, " Vhilf = Vhilf->vnext;\n"); fprintf(fp, " if (i == 33)\n"); fprintf(fp, " V33 = Vhilf;\n"); fprintf(fp, " }\n"); fprintf(fp, "\n"); fprintf(fp, " Vhilf->vnext = Vanker;\n"); fprintf(fp, "\n"); fprintf(fp, " initialSeed = init;\n"); fprintf(fp, "\n"); fprintf(fp, " ResetRndGen();\n"); fprintf(fp, "\n"); fprintf(fp, " // initialize mantissa to all ones\n"); fprintf(fp, " doubleMantissa.d = 1.0;\n"); fprintf(fp, " doubleMantissa.u[0] ^= 0xffffffff;\n"); fprintf(fp, " doubleMantissa.u[1] ^= 0x3fffffff;\n"); fprintf(fp, "\n"); fprintf(fp, " // initialize mantissa to all ones\n"); fprintf(fp, " floatMantissa.f = 1.0;\n"); fprintf(fp, " floatMantissa.u ^= 0x3fffffff;\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); fprintf(fp, "CRndGen::~CRndGen()\n"); fprintf(fp, "{\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); fprintf(fp, "void\n"); fprintf(fp, "CRndGen::Seed(uint32_t init)\n"); fprintf(fp, "{\n"); fprintf(fp, " initialSeed = init;\n"); fprintf(fp, "\n"); fprintf(fp, " ResetRndGen();\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); fprintf(fp, "void\n"); fprintf(fp, "CRndGen::ResetRndGen()\n"); fprintf(fp, "{\n"); fprintf(fp, " // initialise FIBOG like RANMAR (or IMAV)\n"); fprintf(fp, " Vknot *Vhilf = V97;\n"); fprintf(fp, "\n"); fprintf(fp, " int32_t ijkl = 54217137;\n"); fprintf(fp, " if (initialSeed >0 && initialSeed <= 0x7fffffff) ijkl = initialSeed;\n"); fprintf(fp, " int32_t ij = ijkl / 30082;\n"); fprintf(fp, " int32_t kl = ijkl - 30082 * ij;\n"); fprintf(fp, " int32_t i = (ij/177) %% 177 + 2;\n"); fprintf(fp, " int32_t j = ij %% 177 + 2;\n"); fprintf(fp, " int32_t k = (kl/169) %% 178 + 1;\n"); fprintf(fp, " int32_t l = kl %% 169;\n"); fprintf(fp, " int32_t s, t;\n"); fprintf(fp, " for(int32_t ii=0; ii<97; ii++) {\n"); fprintf(fp, " s = 0; t = 0x80000000;\n"); fprintf(fp, " for(int32_t jj=0; jj<32; jj++) {\n"); fprintf(fp, " int32_t m = (((i * j) %% 179) * k) %% 179;\n"); fprintf(fp, " i = j; j = k; k = m;\n"); fprintf(fp, " l = (53 * l + 1) %% 169;\n"); fprintf(fp, " if ((l * m) %% 64 >= 32) s = s + t;\n"); fprintf(fp, " t /= 2;\n"); fprintf(fp, " }\n"); fprintf(fp, "\n"); fprintf(fp, " Vhilf->v = s;\n"); fprintf(fp, " Vhilf = Vhilf->vnext;\n"); fprintf(fp, " }\n"); fprintf(fp, "\n"); fprintf(fp, " cn = 15362436;\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); fprintf(fp, "uint32_t\n"); fprintf(fp, "CRndGen::AsUint32()\n"); fprintf(fp, "{\n"); fprintf(fp, " Vn = (V97->v - V33->v) & 0xffffffff; // (x & 2^32) might be faster \n"); fprintf(fp, " cn = (cn + 362436069) & 0xffffffff; // than (x ^32)\n"); fprintf(fp, " Xn = (Vn - cn) & 0xffffffff;\n"); fprintf(fp, "\n"); fprintf(fp, " V97->v = Vn;\n"); fprintf(fp, " V97 = V97->vnext;\n"); fprintf(fp, " V33 = V33->vnext;\n"); fprintf(fp, "\n"); fprintf(fp, " return Xn;\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); fprintf(fp, "double\n"); fprintf(fp, "CRndGen::AsDouble()\n"); fprintf(fp, "{\n"); fprintf(fp, " PrivateDoubleType result;\n"); fprintf(fp, " result.d = 1.0;\n"); fprintf(fp, " result.u[1] |= (AsUint32() & doubleMantissa.u[1]);\n"); fprintf(fp, " result.u[0] |= (AsUint32() & doubleMantissa.u[0]);\n"); fprintf(fp, " result.d -= 1.0;\n"); fprintf(fp, " return( result.d );\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); fprintf(fp, "float\n"); fprintf(fp, "CRndGen::AsFloat()\n"); fprintf(fp, "{\n"); fprintf(fp, " PrivateFloatType result;\n"); fprintf(fp, " result.f = 1.0;\n"); fprintf(fp, " result.u |= (AsUint32() & floatMantissa.u);\n"); fprintf(fp, " result.f -= 1.0;\n"); fprintf(fp, " return( result.f );\n"); fprintf(fp, "}\n"); fclose(fp); } void CDesign::GenFixtureCommonVcdDiff(const string &vcdDiffFile) { FILE *fp = fopen(vcdDiffFile.c_str(), "w"); if (!fp) { printf("Could not open '%s' for writing\n", vcdDiffFile.c_str()); exit(1); } fprintf(fp, "#include <stdio.h>\n"); fprintf(fp, "#include <stdlib.h>\n"); fprintf(fp, "#include <stdint.h>\n"); fprintf(fp, "\n"); fprintf(fp, "#include <string>\n"); fprintf(fp, "#include <vector>\n"); fprintf(fp, "#include <map>\n"); fprintf(fp, "\n"); fprintf(fp, "using namespace std;\n"); fprintf(fp, "\n"); fprintf(fp, "struct CSignal {\n"); fprintf(fp, " CSignal(string name, int width) : m_name(name), m_width(width) {}\n"); fprintf(fp, "\n"); fprintf(fp, " string m_name;\n"); fprintf(fp, " int m_width;\n"); fprintf(fp, " string m_value;\n"); fprintf(fp, "};\n"); fprintf(fp, "\n"); fprintf(fp, "typedef map<string, int> SigIdMap;\n"); fprintf(fp, "typedef pair <string, int> SigIdPair;\n"); fprintf(fp, "\n"); fprintf(fp, "void GetSignals(FILE *fp, vector<CSignal> &sv, SigIdMap &hv);\n"); fprintf(fp, "bool AdvTime(int cmpTime, int &curTime, char *line, FILE *fp, vector<CSignal> &sv, SigIdMap &hv);\n"); fprintf(fp, "bool UpdateSignal(char *line, vector<CSignal> &sv, SigIdMap &hv);\n"); fprintf(fp, "void GetCmpList(vector<int> &cmpList, vector<CSignal> &sv1, vector<CSignal> &sv2);\n"); fprintf(fp, "void CmpSignals(int cmpTime, vector<int> &cmpList, vector<CSignal> &sv1, vector<CSignal> &sv2);\n"); fprintf(fp, "\n"); fprintf(fp, "string moduleName;\n"); fprintf(fp, "\n"); fprintf(fp, "int main(int argc, char **argv)\n"); fprintf(fp, "{\n"); fprintf(fp, " if (argc != 4) {\n"); fprintf(fp, " fprintf(stderr, \"VcdDiff ModuleName VcdFile1 VcdFile2\\n\");\n"); fprintf(fp, " exit(1);\n"); fprintf(fp, " }\n"); fprintf(fp, "\n"); fprintf(fp, " moduleName = argv[1];\n"); fprintf(fp, "\n"); fprintf(fp, " int argIdx = 2;\n"); fprintf(fp, "\n"); fprintf(fp, " FILE *fp1 = fopen(argv[argIdx], \"r\");\n"); fprintf(fp, " if (!fp1) {\n"); fprintf(fp, " printf(\"%%s: Could not open '%%s' for reading\\n\", moduleName.c_str(), argv[argIdx]);\n"); fprintf(fp, " exit(1);\n"); fprintf(fp, " }\n"); fprintf(fp, " argIdx += 1;\n"); fprintf(fp, "\n"); fprintf(fp, " FILE *fp2 = fopen(argv[argIdx], \"r\");\n"); fprintf(fp, " if (!fp2) {\n"); fprintf(fp, " printf(\"%%s: Could not open '%%s' for reading\\n\", moduleName.c_str(), argv[argIdx]);\n"); fprintf(fp, " exit(1);\n"); fprintf(fp, " }\n"); fprintf(fp, " argIdx += 1;\n"); fprintf(fp, "\n"); fprintf(fp, " vector<CSignal> sv1;\n"); fprintf(fp, " SigIdMap hm1;\n"); fprintf(fp, " GetSignals(fp1, sv1, hm1);\n"); fprintf(fp, "\n"); fprintf(fp, " vector<CSignal> sv2;\n"); fprintf(fp, " SigIdMap hm2;\n"); fprintf(fp, " GetSignals(fp2, sv2, hm2);\n"); fprintf(fp, "\n"); fprintf(fp, " vector<int> cmpList;\n"); fprintf(fp, " GetCmpList(cmpList, sv1, sv2);\n"); fprintf(fp, "\n"); fprintf(fp, " // now start comparing\n"); fprintf(fp, " int curTime1 = 0;\n"); fprintf(fp, " int curTime2 = 0;\n"); fprintf(fp, " char line1[256] = { '\\0' };\n"); fprintf(fp, " char line2[256] = { '\\0' };\n"); fprintf(fp, "\n"); fprintf(fp, " int cmpTime = 168000;\n"); fprintf(fp, " for (;;) {\n"); fprintf(fp, " if (!AdvTime(cmpTime, curTime1, line1, fp1, sv1, hm1) || !AdvTime(cmpTime, curTime2, line2, fp2, sv2, hm2))\n"); fprintf(fp, " break;\n"); fprintf(fp, "\n"); fprintf(fp, " // compare signal values\n"); fprintf(fp, " CmpSignals(cmpTime, cmpList, sv1, sv2);\n"); fprintf(fp, "\n"); fprintf(fp, " cmpTime += 8000;\n"); fprintf(fp, "\n"); fprintf(fp, " if (!AdvTime(cmpTime, curTime1, line1, fp1, sv1, hm1) || !AdvTime(cmpTime, curTime2, line2, fp2, sv2, hm2))\n"); fprintf(fp, " break;\n"); fprintf(fp, "\n"); fprintf(fp, " CmpSignals(cmpTime, cmpList, sv1, sv2);\n"); fprintf(fp, "\n"); fprintf(fp, " cmpTime += 2000;\n"); fprintf(fp, " }\n"); fprintf(fp, "\n"); fprintf(fp, " printf(\"%%s: Test Passed - final time %%d\\n\", argv[1], curTime1);\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); fprintf(fp, "void GetSignals(FILE *fp, vector<CSignal> &sv, SigIdMap &hm)\n"); fprintf(fp, "{\n"); fprintf(fp, " char line[256];\n"); fprintf(fp, " char *lp;\n"); fprintf(fp, " while (lp = fgets(line, 256, fp)) {\n"); fprintf(fp, " if (strncmp(lp, \"$scope\", 6) == 0)\n"); fprintf(fp, " break;\n"); fprintf(fp, " }\n"); fprintf(fp, "\n"); fprintf(fp, " for (int sigIdx = 0; lp = fgets(line, 256, fp); sigIdx += 1) {\n"); fprintf(fp, " if (strncmp(lp, \"$var\", 4) != 0)\n"); fprintf(fp, " break;\n"); fprintf(fp, "\n"); fprintf(fp, " char typeStr[32];\n"); fprintf(fp, " int width;\n"); fprintf(fp, " char idStr[32];\n"); fprintf(fp, " char nameStr[128];\n"); fprintf(fp, " char endStr[32];\n"); fprintf(fp, "\n"); fprintf(fp, " if (sscanf(line, \"$var %%s %%d %%s %%s %%s\", typeStr, &width, idStr, nameStr, endStr) != 5) {\n"); fprintf(fp, " printf(\"%%s: Unknown $var format: %%s\", moduleName.c_str(), line);\n"); fprintf(fp, " exit(1);\n"); fprintf(fp, " }\n"); fprintf(fp, "\n"); fprintf(fp, " sv.push_back(CSignal(nameStr, width));\n"); fprintf(fp, " hm.insert( SigIdPair(idStr, sigIdx) );\n"); fprintf(fp, " }\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); fprintf(fp, "bool AdvTime(int advTime, int &curTime, char *line, FILE *fp, vector<CSignal> &sv, SigIdMap &hv)\n"); fprintf(fp, "{\n"); fprintf(fp, " char *lp;\n"); fprintf(fp, " for (;;) {\n"); fprintf(fp, " if (strncmp(line, \"$dumpvars\", 9) == 0) {\n"); fprintf(fp, " while ((lp = fgets(line, 256, fp)) && UpdateSignal(line, sv, hv));\n"); fprintf(fp, " if (lp == 0) return false;\n"); fprintf(fp, " if (strncmp(line, \"$end\", 4) != 0) {\n"); fprintf(fp, " printf(\"%%s: Unknown line format\\n\", moduleName.c_str());\n"); fprintf(fp, " exit(1);\n"); fprintf(fp, " }\n"); fprintf(fp, " } else if (line[0] == '#') {\n"); fprintf(fp, " sscanf(line, \"#%%d\", &curTime);\n"); fprintf(fp, " if (curTime == 195100)\n"); fprintf(fp, " bool stop = true;\n"); fprintf(fp, " if (curTime >= advTime)\n"); fprintf(fp, " return true;\n"); fprintf(fp, " while ((lp = fgets(line, 256, fp)) && UpdateSignal(line, sv, hv));\n"); fprintf(fp, " if (!lp) return false;\n"); fprintf(fp, " continue;\n"); fprintf(fp, " } else if (strncmp(line, \"$comment\", 8) == 0) {\n"); fprintf(fp, " while (fgets(line, 256, fp) && strncmp(line, \"$end\", 4) != 0);\n"); fprintf(fp, " } else if (strncmp(line, \"$end\", 4) != 0 && line[0] != '\\n' && line[0] != '\\r' && line[0] != '\\0') {\n"); fprintf(fp, " printf(\"%%s: Unknown line format\\n\", moduleName.c_str());\n"); fprintf(fp, " exit(1);\n"); fprintf(fp, " }\n"); fprintf(fp, "\n"); fprintf(fp, " fgets(line, 256, fp);\n"); fprintf(fp, " };\n"); fprintf(fp, "\n"); fprintf(fp, " return true;\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); fprintf(fp, "bool UpdateSignal(char *line, vector<CSignal> &sv, SigIdMap &hm)\n"); fprintf(fp, "{\n"); fprintf(fp, " char *lp = line;\n"); fprintf(fp, " char num[256];\n"); fprintf(fp, " char *np = num;\n"); fprintf(fp, " char id[256];\n"); fprintf(fp, " char *ip = id;\n"); fprintf(fp, " SigIdMap :: const_iterator hmIter;\n"); fprintf(fp, "\n"); fprintf(fp, " if (*lp == 'b' || *lp == '1' || *lp == '0' || *lp == 'x' || *lp == 'z') {\n"); fprintf(fp, " // binary\n"); fprintf(fp, " if (*lp == 'b') lp += 1;\n"); fprintf(fp, "\n"); fprintf(fp, " // skip leading zeros\n"); fprintf(fp, " if (*lp == '0') {\n"); fprintf(fp, " while (*lp == '0') lp += 1;\n"); fprintf(fp, " if (*lp != '1' && *lp != 'z' && *lp != 'x')\n"); fprintf(fp, " lp -= 1;\n"); fprintf(fp, " }\n"); fprintf(fp, " while (*lp == '0' || *lp == '1' || *lp == 'z' || *lp == 'x')\n"); fprintf(fp, " *np++ = *lp++;\n"); fprintf(fp, " *np = '\\0';\n"); fprintf(fp, " } else \n"); fprintf(fp, " return false;\n"); fprintf(fp, "\n"); fprintf(fp, " while (*lp == ' ') lp += 1;\n"); fprintf(fp, "\n"); fprintf(fp, " while (*lp != '\\n' && *lp != '\\r' && *lp != ' ' && *lp != '\\0')\n"); fprintf(fp, " *ip++ = *lp++;\n"); fprintf(fp, " *ip = '\\0';\n"); fprintf(fp, "\n"); fprintf(fp, " hmIter = hm.find( id );\n"); fprintf(fp, "\n"); fprintf(fp, " if (hmIter == hm.end()) {\n"); fprintf(fp, " printf(\"%%s: Did not find Id String\\n\", moduleName.c_str());\n"); fprintf(fp, " exit(1);\n"); fprintf(fp, " }\n"); fprintf(fp, "\n"); fprintf(fp, " int sigIdx = hmIter-
>second;\n"); fprintf(fp, "\n"); fprintf(fp, " sv[sigIdx].m_value = num;\n"); fprintf(fp, "\n"); fprintf(fp, " return true;\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); fprintf(fp, "void GetCmpList(vector<int> &cmpList, vector<CSignal> &sv1, vector<CSignal> &sv2)\n"); fprintf(fp, "{\n"); fprintf(fp, " for (size_t i = 0; i < sv1.size(); i += 1)\n"); fprintf(fp, " for (size_t j = 0; j < sv2.size(); j += 1)\n"); fprintf(fp, " if (sv1[i].m_name == sv2[j].m_name) {\n"); fprintf(fp, " cmpList.push_back(j);\n"); fprintf(fp, " break;\n"); fprintf(fp, " }\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); fprintf(fp, "void CmpSignals(int cmpTime, vector<int> &cmpList, vector<CSignal> &sv1, vector<CSignal> &sv2)\n"); fprintf(fp, "{\n"); fprintf(fp, " for (size_t i = 0; i < cmpList.size(); i += 1)\n"); fprintf(fp, " if (sv1[i].m_value != sv2[cmpList[i]].m_value) {\n"); fprintf(fp, " printf(\"%%s: Trace mismatch found at time %%d, signal %%s\\n\", moduleName.c_str(), cmpTime, sv1[i].m_name.c_str());\n"); fprintf(fp, " exit(1);\n"); fprintf(fp, " }\n"); fprintf(fp, "}\n"); fclose(fp); } void CDesign::GenFixtureModule(const string &modDir, const string &primFileName, CModule *pModule) { MkDir(modDir); CPortList portList; GetModulePorts(pModule, portList); GenFixtureModuleRunTest(modDir + "/RunTest", pModule); GenFixtureModuleSystemC(modDir + "/SystemC", primFileName, pModule, portList); GenFixtureModuleVerilog(modDir + "/Verilog", primFileName, pModule, portList); } void CDesign::GetModulePorts(CModule *pModule, CPortList &portList) { SignalMap_Iter sigIter; for (sigIter = pModule->m_signalMap.begin(); sigIter != pModule->m_signalMap.end(); sigIter++) { CSignal *pSignal = sigIter->second; if (pSignal->m_sigType == sig_input) { if (pSignal->m_name == "ck" || pSignal->m_name == "clk") portList.m_clock = pSignal->m_name; else portList.m_inputs.push_back(CPort(pSignal->m_name, pSignal->m_bIndexed, pSignal->m_upperIdx, pSignal->m_lowerIdx, pSignal->m_portIdx)); } } for (sigIter = pModule->m_signalMap.begin(); sigIter != pModule->m_signalMap.end(); sigIter++) { CSignal *pSignal = sigIter->second; if (pSignal->m_sigType == sig_output) portList.m_outputs.push_back(CPort(pSignal->m_name, pSignal->m_bIndexed, pSignal->m_upperIdx, pSignal->m_lowerIdx, pSignal->m_portIdx)); } } void CDesign::GenFixtureModuleRunTest(const string &runTestFile, CModule *pModule) { FILE *fp = fopen(runTestFile.c_str(), "wb"); if (!fp) { printf("Could not open '%s' for writing\n", runTestFile.c_str()); exit(1); } fprintf(fp, "#!/bin/sh\n"); fprintf(fp, "cd Verilog; ./Verilog.script >& Verilog.log; cd ..\n"); fprintf(fp, "cd SystemC; ./SystemC.script >& SystemC.log; cd ..\n"); fprintf(fp, "../../Common/VcdDiff %s SystemC/SystemC.vcd Verilog/Verilog.vcd | tee RunTest.out\n", pModule->m_name.c_str()); fclose(fp); } void CDesign::GenFixtureModuleSystemC(const string &systemcDir, const string &primFileName, CModule *pModule, CPortList &portList) { MkDir(systemcDir); GenFixtureModuleSystemCScript(systemcDir + "/SystemC.script"); GenFixtureModuleSystemCMainCpp(systemcDir + "/Main.cpp", primFileName, pModule, portList); } void CDesign::GenFixtureModuleSystemCScript(const string &systemcScript) { FILE *fp = fopen(systemcScript.c_str(), "wb"); if (!fp) { printf("Could not open '%s' for writing\n", systemcScript.c_str()); exit(1); } fprintf(fp, "#!/bin/sh\n"); fprintf(fp, "g++ -m64 -I ~/SystemC/systemc-2.2.0/src ../../../Common/Random.cpp Main.cpp ~/SystemC/systemc-2.2.0/lib-linux64/libsystemc.a -o systemc_sim\n"); fprintf(fp, "\n"); fprintf(fp, "./systemc_sim\n"); fclose(fp); } void CDesign::GenFixtureModuleSystemCMainCpp(const string &mainCppFile, const string &primFileName, CModule *pModule, CPortList &portList) { FILE *fp = fopen(mainCppFile.c_str(), "wb"); if (!fp) { printf("Could not open '%s' for writing\n", mainCppFile.c_str()); exit(1); } fprintf(fp, "#include <stdio.h>\n"); fprintf(fp, "#include <stdlib.h>\n"); fprintf(fp, "#include <stdint.h>\n"); fprintf(fp, "\n"); fprintf(fp, "#include <SystemC.h>\n"); fprintf(fp, "#include \"../../../Common/Random.h\"\n"); fprintf(fp, "\n"); fprintf(fp, "CRandom cnyRnd;\n"); fprintf(fp, "\n"); fprintf(fp, "sc_trace_file * scVcdFp = sc_create_vcd_trace_file(\"SystemC\");\n"); fprintf(fp, "\n"); fprintf(fp, "#include \"../../../%s.h\"\n", primFileName.c_str()); fprintf(fp, "\n"); fprintf(fp, "int\n"); fprintf(fp, "sc_main(int argc, char *argv[])\n"); fprintf(fp, "{\n"); if (portList.m_clock.size() > 0) fprintf(fp, " sc_uint<1> %s;\n", portList.m_clock.c_str()); for (size_t i = 0; i < portList.m_inputs.size(); i += 1) fprintf(fp, " sc_uint<%d> %s;\n", portList.m_inputs[i].m_highBit - portList.m_inputs[i].m_lowBit + 1, portList.m_inputs[i].m_name.c_str()); for (size_t i = 0; i < portList.m_outputs.size(); i += 1) fprintf(fp, " sc_uint<%d> %s;\n", portList.m_outputs[i].m_highBit - portList.m_outputs[i].m_lowBit + 1, portList.m_outputs[i].m_name.c_str()); fprintf(fp, "\n"); if (portList.m_clock.size() > 0) fprintf(fp, " sc_trace(scVcdFp, %s, \"%s\");\n", portList.m_clock.c_str(), portList.m_clock.c_str()); for (size_t i = 0; i < portList.m_inputs.size(); i += 1) fprintf(fp, " sc_trace(scVcdFp, %s, \"%s\");\n", portList.m_inputs[i].m_name.c_str(), portList.m_inputs[i].m_name.c_str()); for (size_t i = 0; i < portList.m_outputs.size(); i += 1) fprintf(fp, " sc_trace(scVcdFp, %s, \"%s\");\n", portList.m_outputs[i].m_name.c_str(), portList.m_outputs[i].m_name.c_str()); fprintf(fp, "\n"); fprintf(fp, " for (int testCnt = 0; testCnt < 10000; testCnt += 1) {\n"); fprintf(fp, "\n"); fprintf(fp, " sc_start(sc_time(2.5, SC_NS));\n"); fprintf(fp, "\n"); for (size_t i = 0; i < portList.m_inputs.size(); i += 1) fprintf(fp, " %s = cnyRnd.RndUint64();\n", portList.m_inputs[i].m_name.c_str()); fprintf(fp, "\n"); if (portList.m_clock.size() > 0) { fprintf(fp, " sc_start(sc_time(2.5, SC_NS));\n"); fprintf(fp, "\n"); fprintf(fp, " ck = 1;\n"); fprintf(fp, "\n"); } fprintf(fp, " %s(", pModule->m_name.c_str()); size_t portCnt = portList.m_inputs.size() + portList.m_outputs.size(); char *pSeparater = " "; for (size_t i = 0; i < portCnt; i += 1) { bool bFound = false; for (size_t j = 0; j < portList.m_inputs.size() && !bFound; j += 1) { if ((int)i == portList.m_inputs[j].m_portIdx) { bFound = true; fprintf(fp, "%s%s", pSeparater, portList.m_inputs[j].m_name.c_str()); } } for (size_t j = 0; j < portList.m_outputs.size() && !bFound; j += 1) { if ((int)i == portList.m_outputs[j].m_portIdx) { bFound = true; fprintf(fp, "%s%s", pSeparater, portList.m_outputs[j].m_name.c_str()); } } pSeparater = ", "; } fprintf(fp, " );\n"); fprintf(fp, "\n"); if (portList.m_clock.size() > 0) fprintf(fp, " sc_start(sc_time(5, SC_NS));\n"); else fprintf(fp, " sc_start(sc_time(7.5, SC_NS));\n"); if (portList.m_clock.size() > 0) fprintf(fp, " ck = 0;\n"); fprintf(fp, "\n"); fprintf(fp, " }\n"); fprintf(fp, "\n"); fprintf(fp, " return 0;\n"); fprintf(fp, "}\n"); fclose(fp); } void CDesign::GenFixtureModuleVerilog(const string &verilogDir, const string &primFileName, CModule *pModule, CPortList &portList) { MkDir(verilogDir); GenFixtureModuleVerilogScript(verilogDir + "/Verilog.script", primFileName); GenFixtureModuleVerilogSimvCmds(verilogDir + "/simv.cmds"); GenFixtureModuleVerilogPliTab(verilogDir + "/pli.tab"); GenFixtureModuleVerilogFixtureV(verilogDir + "/Fixture.v", pModule, portList); GenFixtureModuleVerilogMainCpp(verilogDir + "/Main.cpp", pModule, portList); } void CDesign::GenFixtureModuleVerilogScript(const string &vcsScriptDir, const string &primFileName) { FILE *fp = fopen(vcsScriptDir.c_str(), "wb"); if (!fp) { printf("Could not open '%s' for writing\n", vcsScriptDir.c_str()); exit(1); } fprintf(fp, "#!/bin/sh\n"); fprintf(fp, "vcs Fixture.v ../../../%s.v Main.cpp ../../../Common/Random.cpp " "-debug -P pli.tab +acc+3 +libext+.v +v2k -y /hw/tools/xilinx/13.2/ISE/verilog/src/unisims " "/hw/tools/xilinx/13.2/ISE/verilog/src/glbl.v -cpp /usr/bin/c++\n", primFileName.c_str() ); fprintf(fp, "\n"); fprintf(fp, "./simv -ucli -do simv.cmds\n"); fclose(fp); } void CDesign::GenFixtureModuleVerilogSimvCmds(const string &simvCmdsFile) { FILE *fp = fopen(simvCmdsFile.c_str(), "wb"); if (!fp) { printf("Could not open '%s' for writing\n", simvCmdsFile.c_str()); exit(1); } fprintf(fp, "run 10000000\n"); fprintf(fp, "exit\n"); fclose(fp); } void CDesign::GenFixtureModuleVerilogPliTab(const string &pliTabDir) { FILE *fp = fopen(pliTabDir.c_str(), "w"); if (!fp) { printf("Could not open '%s' for writing\n", pliTabDir.c_str()); exit(1); } fprintf(fp, "$Fixture size=0 call=InitFixture acc=rw,wn:*\n"); fclose(fp); } void CDesign::GenFixtureModuleVerilogFixtureV(const string &fixtureVFile, CModule *pModule, CPortList &portList) { FILE *fp = fopen(fixtureVFile.c_str(), "w"); if (!fp) { printf("Could not open '%s' for writing\n", fixtureVFile.c_str()); exit(1); } fprintf(fp, "`timescale 1ns / 1ps\n"); fprintf(fp, "\n"); fprintf(fp, "module Fixture ( );\n"); fprintf(fp, "\n"); if (portList.m_clock.size() > 0) fprintf(fp, " reg %s;\n", portList.m_clock.c_str()); fprintf(fp, " reg [1:0] phase;\n"); char widthStr[32]; for (size_t i = 0; i < portList.m_inputs.size(); i += 1) { bool bWidth = portList.m_inputs[i].m_bIndexed; if (bWidth && portList.m_inputs[i].m_highBit > 31) { for (int lowBit = 0; lowBit < portList.m_inputs[i].m_highBit; lowBit += 32) { int highBit = lowBit+31 < portList.m_inputs[i].m_highBit ? lowBit+31 : portList.m_inputs[i].m_highBit; sprintf(widthStr, "[%d:%d]", highBit, lowBit); fprintf(fp, " wire %-8s %s_%d_%d;\n", widthStr, portList.m_inputs[i].m_name.c_str(), highBit, lowBit); } } sprintf(widthStr, bWidth ? "[%d:%d]" : "", portList.m_inputs[i].m_highBit, portList.m_inputs[i].m_lowBit); fprintf(fp, " wire %-8s %s;\n", widthStr, portList.m_inputs[i].m_name.c_str()); } for (size_t i = 0; i < portList.m_outputs.size(); i += 1) { bool bWidth = portList.m_outputs[i].m_bIndexed; sprintf(widthStr, bWidth ? "[%d:%d]" : "", portList.m_outputs[i].m_highBit, portList.m_outputs[i].m_lowBit); fprintf(fp, " wire %-8s %s;\n", widthStr, portList.m_outputs[i].m_name.c_str()); } fprintf(fp, "\n"); for (size_t i = 0; i < portList.m_inputs.size(); i += 1) { bool bWidth = portList.m_inputs[i].m_bIndexed; if (bWidth && portList.m_inputs[i].m_highBit > 31) { fprintf(fp, " assign %s = { %s_%d_%d", portList.m_inputs[i].m_name.c_str(), portList.m_inputs[i].m_name.c_str(), portList.m_inputs[i].m_highBit, portList.m_inputs[i].m_highBit & ~0x1f /* ul */); for (int lowBit = (portList.m_inputs[i].m_highBit & ~0x1ful)-32; lowBit >= 0; lowBit -= 32) fprintf(fp, ", %s_%d_%d", portList.m_inputs[i].m_name.c_str(), lowBit+31, lowBit); fprintf(fp, " };\n"); } } fprintf(fp, "\n"); fprintf(fp, " initial begin\n"); fprintf(fp, " $dumpfile(\"Verilog.vcd\");\n"); if (portList.m_clock.size() > 0) fprintf(fp, " $dumpvars(0, %s);\n", portList.m_clock.c_str()); for (size_t i = 0; i < portList.m_inputs.size(); i += 1) fprintf(fp, " $dumpvars(0, %s);\n", portList.m_inputs[i].m_name.c_str()); for (size_t i = 0; i < portList.m_outputs.size(); i += 1) fprintf(fp, " $dumpvars(0, %s);\n", portList.m_outputs[i].m_name.c_str()); fprintf(fp, " end\n"); fprintf(fp, "\n"); fprintf(fp, " initial begin\n"); if (portList.m_clock.size() > 0) fprintf(fp, " %s = 0;\n", portList.m_clock.c_str()); fprintf(fp, " phase = 0;\n"); fprintf(fp, " end\n"); fprintf(fp, "\n"); fprintf(fp, " always begin\n"); fprintf(fp, " #2.5 phase = phase + 1;\n"); fprintf(fp, " end\n"); fprintf(fp, "\n"); if (portList.m_clock.size() > 0) { fprintf(fp, " always begin\n"); fprintf(fp, " #5 %s = ~%s;\n", portList.m_clock.c_str(), portList.m_clock.c_str()); fprintf(fp, " end\n"); fprintf(fp, "\n"); } fprintf(fp, " initial $Fixture (\n"); fprintf(fp, " phase"); char *pSeparater = ",\n"; for (size_t i = 0; i < portList.m_inputs.size(); i += 1) { bool bWidth = portList.m_inputs[i].m_bIndexed; if (bWidth && portList.m_inputs[i].m_highBit > 31) { for (int lowBit = 0; lowBit < portList.m_inputs[i].m_highBit; lowBit += 32) { int highBit = lowBit+31 < portList.m_inputs[i].m_highBit ? lowBit+31 : portList.m_inputs[i].m_highBit; fprintf(fp, "%s %s_%d_%d", pSeparater, portList.m_inputs[i].m_name.c_str(), highBit, lowBit); } } else fprintf(fp, "%s %s", pSeparater, portList.m_inputs[i].m_name.c_str()); } fprintf(fp, "\n );\n"); fprintf(fp, "\n"); fprintf(fp, " %s dut(\n", pModule->m_name.c_str()); pSeparater = ""; if (portList.m_clock.size() > 0) { fprintf(fp, " .%s(%s)", portList.m_clock.c_str(), portList.m_clock.c_str()); pSeparater = ",\n"; } for (size_t i = 0; i < portList.m_inputs.size(); i += 1) { fprintf(fp, "%s .%s(%s)", pSeparater, portList.m_inputs[i].m_name.c_str(), portList.m_inputs[i].m_name.c_str()); pSeparater = ",\n"; } for (size_t i = 0; i < portList.m_outputs.size(); i += 1) { fprintf(fp, "%s .%s(%s)", pSeparater, portList.m_outputs[i].m_name.c_str(), portList.m_outputs[i].m_name.c_str()); pSeparater = ",\n"; } fprintf(fp, "\n );\n"); fprintf(fp, "\n"); fprintf(fp, "endmodule\n"); fclose(fp); } void CDesign::GenFixtureModuleVerilogMainCpp(const string &mainCppFile, CModule *pModule, CPortList &portList) { FILE *fp = fopen(mainCppFile.c_str(), "w"); if (!fp) { printf("Could not open '%s' for writing\n", mainCppFile.c_str()); exit(1); } fprintf(fp, "#include <stdint.h>\n"); fprintf(fp, "#include <stdlib.h>\n"); fprintf(fp, "#include <stdio.h>\n"); fprintf(fp, "#include <ctype.h>\n"); fprintf(fp, "#include \"../../../Common/Random.h\"\n"); fprintf(fp, "\n"); fprintf(fp, "CRandom cnyRnd;\n"); fprintf(fp, "\n"); fprintf(fp, "#include \"acc_user.h\"\n"); fprintf(fp, "extern \"C\" int InitFixture();\n"); fprintf(fp, "extern \"C\" int Fixture();\n"); fprintf(fp, "\n"); fprintf(fp, "struct CHandles {\n"); fprintf(fp, " handle m_phase;\n"); for (size_t i = 0; i < portList.m_inputs.size(); i += 1) { bool bWidth = portList.m_inputs[i].m_bIndexed; if (bWidth && portList.m_inputs[i].m_highBit > 31) { for (int lowBit = 0; lowBit < portList.m_inputs[i].m_highBit; lowBit += 32) { int highBit = lowBit+31 < portList.m_inputs[i].m_highBit ? lowBit+31 : portList.m_inputs[i].m_highBit; fprintf(fp, " handle m_%s_%d_%d;\n", portList.m_inputs[i].m_name.c_str(), highBit, lowBit); } } else fprintf(fp, " handle m_%s;\n", portList.m_inputs[i].m_name.c_str()); } fprintf(fp, "} sig;\n"); fprintf(fp, "\n"); fprintf(fp, "void SetSigValue(handle sig, uint32_t value) {\n"); fprintf(fp, " s_setval_value value_s;\n"); fprintf(fp, " value_s.format = accIntVal;\n"); fprintf(fp, " value_s.value.integer = value;\n"); fprintf(fp, "\n"); fprintf(fp, " s_setval_delay delay_s;\n"); fprintf(fp, " delay_s.model = accNoDelay;\n"); fprintf(fp, " delay_s.time.type = accTime;\n"); fprintf(fp, " delay_s.time.low = 0;\n"); fprintf(fp, " delay_s.time.high = 0;\n"); fprintf(fp, "\n"); fprintf(fp, " acc_set_value(sig, &value_s, &delay_s);\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); fprintf(fp, "uint32_t GetSigValue(handle sig, char *pName) {\n"); fprintf(fp, " p_acc_value pAccValue;\n"); fprintf(fp, " const char *pNum = acc_fetch_value(sig, \"%%x\", pAccValue);\n"); fprintf(fp, " const char *pNum2 = pNum;\n"); fprintf(fp, "\n"); fprintf(fp, " uint32_t value = 0;\n"); fprintf(fp, " while (isdigit(*pNum) || tolower(*pNum) >= 'a' && tolower(*pNum) <= 'f')\n"); fprintf(fp, " value = value * 16 + (isdigit(*pNum) ? (*pNum++ - '0') : (tolower(*pNum++) - 'a' + 10));\n"); fprintf(fp, "\n"); fprintf(fp, " if (*pNum != '\\0')\n"); fprintf(fp, " printf(\" Signal '%%s' had value '%%s'\\n\", pName, pNum2);\n"); fprintf(fp, "\n"); fprintf(fp, " return value;\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); for (size_t i = 0; i < portList.m_inputs.size(); i += 1) { fprintf(fp, "void SetSig_%s(uint64_t %s) { ", portList.m_inputs[i].m_name.c_str(), portList.m_inputs[i].m_name.c_str()); bool bWidth = portList.m_inputs[i].m_bIndexed; if (bWidth && portList.m_inputs[i].m_highBit > 31) { for (int lowBit = 0; lowBit < portList.m_inputs[i].m_highBit; lowBit += 32) { int highBit = lowBit+31 < portList.m_inputs[i].m_highBit ? lowBit+31 : portList.m_inputs[i].m_highBit; fprintf(fp, "SetSigValue(sig.m_%s_%d_%d, (%s >> %d) & 0xffffffff); ", portList.m_inputs[i].m_name.c_str(), highBit, lowBit, portList.m_inputs[i].m_name.c_str(), lowBit); } } else fprintf(fp, "SetSigValue(sig.m_%s, %s); ", portList.m_inputs[i].m_name.c_str(), portList.m_inputs[i].m_name.c_str()); fprintf(fp, "}\n"); } fprintf(fp, "\n"); fprintf(fp, "uint32_t GetSig_phase() { return GetSigValue(sig.m_phase, \"phase\"); }\n"); fprintf(fp, "\n"); fprintf(fp, "int InitFixture() {\n"); fprintf(fp, " acc_initialize();\n"); fprintf(fp, " int i = 1;\n"); fprintf(fp, " sig.m_phase = acc_handle_tfarg(i++);\n"); for (size_t i = 0; i < portList.m_inputs.size(); i += 1) { bool bWidth = portList.m_inputs[i].m_bIndexed; if (bWidth && portList.m_inputs[i].m_highBit > 31) { for (int lowBit = 0; lowBit < portList.m_inputs[i].m_highBit; lowBit += 32) { int highBit = lowBit+31 < portList.m_inputs[i].m_highBit ? lowBit+31 : portList.m_inputs[i].m_highBit; fprintf(fp, " sig.m_%s_%d_%d = acc_handle_tfarg(i++);\n", portList.m_inputs[i].m_name.c_str(), highBit, lowBit); } } else fprintf(fp, " sig.m_%s = acc_handle_tfarg(i++);\n", portList.m_inputs[i].m_name.c_str()); } fprintf(fp, "\n"); fprintf(fp, " acc_vcl_add(sig.m_phase, ::Fixture, null, vcl_verilog_logic);\n"); fprintf(fp, " acc_close();\n"); fprintf(fp, "\n"); fprintf(fp, " return 0;\n"); fprintf(fp, "}\n"); fprintf(fp, "\n"); fprintf(fp, "int clkCnt = 0;\n"); fprintf(fp, "\n"); fprintf(fp, "int Fixture() {\n"); fprintf(fp, " if (GetSig_phase() != 1)\n"); fprintf(fp, " return 0;\n"); fprintf(fp, "\n"); fprintf(fp, " if (++clkCnt == 10000)\n"); fprintf(fp, " exit(0);\n"); fprintf(fp, "\n"); for (size_t i = 0; i < portList.m_inputs.size(); i += 1) fprintf(fp, " uint64_t %s = cnyRnd.RndUint64();\n", portList.m_inputs[i].m_name.c_str()); fprintf(fp, "\n"); for (size_t i = 0; i < portList.m_inputs.size(); i += 1) fprintf(fp, " SetSig_%s(%s);\n", portList.m_inputs[i].m_name.c_str(), portList.m_inputs[i].m_name.c_str()); fprintf(fp, "\n"); fprintf(fp, " return 0;\n"); fprintf(fp, "}\n"); fclose(fp); } void CDesign::MkDir(const string &newDir) { #ifdef _WIN32 int err = mkdir(newDir.c_str()); #else int err = mkdir(newDir.c_str(), 0x755); #endif if (err != 0) { int errnum; #ifdef _WIN32 _get_errno(&errnum); #else errnum = errno; #endif if (errnum == EEXIST) { printf(" Directory for test fixture already exists: %s\n", newDir.c_str()); printf(" Remove directory to proceed with test fixture generation\n"); } else printf(" Unable to create directory: %s", newDir.c_str()); exit(1); } }
/******************************************************************************* * 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 "Blinktest.h" Blinktest i_Blinktest("i_blinktest"); 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_Blinktest.trace(tf); } /* We need to connect the Arduino pin library to the gpios. */ i_Blinktest.i_esp.pininit(); /* Set the test number */ i_Blinktest.tn = tn; /* And run the simulation. */ sc_start(); if (wv) sc_close_vcd_trace_file(tf); exit(0); }
/******************************************************************************* * netcon.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Simple block that connects two sc_signals, one being bool and one being * sc_signal_resolved. ******************************************************************************* * 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 "netcon.h" #include "info.h" void netcon_rvtobool::transport() { for(;;) { wait(); if (a.read() == SC_LOGIC_0) b.write(false); else if (a.read() == SC_LOGIC_1) b.write(true); else { /* We only warn if we are not at time 0 or we get some dummy * warnings. */ if (sc_time_stamp() != sc_time(0, SC_NS)) { PRINTF_WARN("NETCON", "Assigning %c to signal %s", a.read().to_char(), name()); } b.write(false); } } } void netcon_booltorv::transport() { b.write(SC_LOGIC_0); for(;;) { wait(); if (a.read() == false) b.write(SC_LOGIC_0); else b.write(SC_LOGIC_1); } } void netcon_mixtobool::transport() { for(;;) { wait(); if (a.read() == SC_LOGIC_0) b.write(false); else if (a.read() == SC_LOGIC_1) b.write(true); else { /* We only warn if we are not at time 0 or we get some dummy * warnings. */ if (sc_time_stamp() != sc_time(0, SC_NS)) { PRINTF_WARN("NETCON", "Assigning %c to signal %s", a.read().to_char(), name()); } b.write(false); } } } void netcon_booltomix::transport() { b.write(GN_LOGIC_0); for(;;) { wait(); if (a.read() == false) b.write(GN_LOGIC_0); else b.write(GN_LOGIC_1); } } void netcon_mixtorv::transport() { for(;;) { wait(); b.write(a.read().logic); } } void netcon_rvtomix::transport() { b.write(GN_LOGIC_X); for(;;) { wait(); b.write(gn_mixed(a.read())); } } void netcon_mixtoana::transport() { b.write(0.0); for(;;) { wait(); b.write(a.read().lvl); } } void netcon_anatomix::transport() { b.write(GN_LOGIC_X); for(;;) { wait(); b.write(gn_mixed(a.read())); } }
/* * @ASCK */ #include <systemc.h> SC_MODULE (WB) { sc_in_clk clk; sc_in <sc_int<8>> prev_alu_result; sc_in <sc_int<8>> prev_mem_result; sc_in <bool> prev_WbMux; sc_in <bool> prev_regWrite; sc_in <sc_uint<3>> prev_rd; sc_out <sc_int<8>> next_alu_result; sc_out <sc_int<8>> next_mem_result; sc_out <bool> next_WbMux; sc_out <bool> next_regWrite; sc_out <sc_uint<3>> next_rd; /* ** module global variables */ SC_CTOR (WB){ SC_THREAD (process); sensitive << clk.pos(); } void process () { while(true){ wait(); if(now_is_call){ wait(micro_acc_ev); } next_alu_result.write(prev_alu_result.read()); next_mem_result.write(prev_mem_result.read()); next_WbMux.write(prev_WbMux.read()); next_regWrite.write(prev_regWrite); next_rd.write(prev_rd.read()); } } };
/* * @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); } } };
/***************************************************************************** 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. (contributors@amiq.com) 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(); }; }
/* * @ASCK */ #include <systemc.h> SC_MODULE (Mux3) { sc_in <bool> sel; sc_in <sc_uint<3>> in0; sc_in <sc_uint<3>> in1; sc_out <sc_uint<3>> out; /* ** module global variables */ SC_CTOR (Mux3){ SC_METHOD (process); sensitive << in0 << in1 << sel; } void process () { if(!sel.read()){ out.write(in0.read()); } else{ out.write(in1.read()); } } };
/* * @ASCK */ #include <systemc.h> SC_MODULE (IR) { sc_in <sc_uint<14>> addr; sc_out <sc_uint<20>> inst; /* ** module global variables */ sc_uint<20> mem[819]; // 819 rows and 819*20=16380 bits = (16KB - 4bits) ~= 16KB int instNum = 50; sc_uint<20> instruction[50] = { // 0b01234567890123456789 0b00000000000000000000, 0b00100000000000000111, // transfer (r0 <- 7): 7 0b00010010010000000000, // inc (r1++): 1 //stall for achieving the correct register data - sub 0b11110000000000000000, //stall 0b11110000000000000000, //stall 0b11110000000000000000, //stall 0b00000110000010000010, // sub (r3 <-r0 - r1): 6 0b11110000000000000000, //stall 0b11110000000000000000, //stall 0b11110000000000000000, //stall 0b00011000110010000001, // addc (r4 <- r3 + r1 + 1): 8 0b11110000000000000000, //stall 0b11110000000000000000, //stall 0b11110000000000000000, //stall 0b00001001000000101001, // shiftR (r4 >> 2): 2 0b01010000000000000101, // stroe (mem[5] <= r0) : 7 0b01001010000000000101, // load (r5 <= mem[5]) : 7 0b01100000000000000000, // do accelerator 0b01000100000000010100, // load (r2 <= mem[20]) : 17 => 0x11 0b11110000000000000000, //nop 0b11110000000000000000, //nop 0b11110000000000000000, //nop 0b11110000000000000000, //nop 0b11110000000000000000, //nop 0b11110000000000000000 //nop }; SC_CTOR (IR){ SC_METHOD (process); sensitive << addr; for(int i=0; i<instNum; i++){ mem[i] = instruction[i]; } // filling out other rows with a nop opcode for(int i=instNum; i<819; i++){ mem[i] = 0b11110000000000000000; } } void process () { if(addr.read() < 819){ inst.write(mem[addr.read()]); } else{ inst.write(0); } } };
/******************************************************************************* * tb_gpio.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Testbench for the GPIO models. ******************************************************************************* * 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 "tb_gpio.h" #include "info.h" void tb_gpio::expect(const char *name, bool a, sc_logic v) { if (a != v) PRINTF_WARN("TEST", "Expected %s to be %c but got %c", name, v.to_char(), (a)?'1':'0') else PRINTF_INFO("TEST", "SUCCESS: got %s to be %c", name, v.to_char()); } void tb_gpio::expect(const char *name, sc_logic a, sc_logic v) { if (a != v) PRINTF_WARN("TEST", "Expected %s to be %c but got %c", name, v.to_char(), a.to_char()) else PRINTF_INFO("TEST", "SUCCESS: got %s to be %c", name, v.to_char()); } void tb_gpio::expect(const char *name, gn_mixed a, sc_logic v) { if (a != v) PRINTF_WARN("TEST", "Expected %s to be %c but got %c", name, v.to_char(), a.to_char()) else PRINTF_INFO("TEST", "SUCCESS: got %s to be %c", name, v.to_char()); } void tb_gpio::expectfunc(const char *name, int a, int v) { if (a != v) PRINTF_WARN("TEST", "Expected %s to be Function %d but got %c",name,v,a) else PRINTF_INFO("TEST", "SUCCESS: got %s to be Function %d", name, v); } void tb_gpio::t0(void) { wait(SC_ZERO_TIME); /* We start off checking the pins. */ expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_Z); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_Z); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_Z); expect(pin3.name(), pin3.read(), SC_LOGIC_Z); expectfunc(i_gpio.name(), i_gpio.get_function(), GPIOMF_GPIO); expectfunc(i_gpio_mix.name(), i_gpio_mix.get_function(), GPIOMF_GPIO); expectfunc(i_gpio_mfmix.name(), i_gpio_mfmix.get_function(), GPIOMF_GPIO); expectfunc(i_gpio_mf.name(), i_gpio_mf.get_function(), GPIOMF_GPIO); /* We now change the GPIOs to be Output and check the outputs. */ wait(10, SC_NS); printf("\n\n**** Changing GPIOs to Output ****\n"); i_gpio.set_dir(GPIODIR_OUTPUT); i_gpio_mix.set_dir(GPIODIR_OUTPUT); i_gpio_mfmix.set_dir(GPIODIR_OUTPUT); i_gpio_mf.set_dir(GPIODIR_OUTPUT); wait(SC_ZERO_TIME); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_0); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_0); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_0); expect(pin3.name(), pin3.read(), SC_LOGIC_0); /* We drive something and check it. */ wait(10, SC_NS); i_gpio.set_val(true); i_gpio_mix.set_val(true); i_gpio_mfmix.set_val(true); i_gpio_mf.set_val(true); wait(SC_ZERO_TIME); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_1); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_1); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_1); expect(pin3.name(), pin3.read(), SC_LOGIC_1); /* We change them to WPU or OD and recheck it. */ printf("\n\n**** Checking weak pull-up/OD ****\n"); i_gpio.set_wpu(); i_gpio_mix.set_od(); i_gpio_mfmix.set_wpu(); i_gpio_mf.set_wpu(); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_Z); /* WPU but looks like Z */ expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_Z); /* OD */ expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_1); /* WPU */ expect(pin3.name(), pin3.read(), SC_LOGIC_Z); /* WPU but looks like Z */ /* And we go low. */ i_gpio.set_val(false); i_gpio_mix.set_val(false); i_gpio_mfmix.set_val(false); i_gpio_mf.set_val(false); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_0); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_0); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_0); expect(pin3.name(), pin3.read(), SC_LOGIC_0); /* Now we switch the OD and WPU pins and try it again. */ printf("\n\n**** Switching weak pull-up and OD ****\n"); i_gpio.set_val(true); i_gpio_mix.set_val(true); i_gpio_mfmix.set_val(true); i_gpio_mf.set_val(true); i_gpio.clr_wpu(); i_gpio.set_od(); i_gpio_mix.clr_od(); i_gpio_mix.set_wpu(); i_gpio_mfmix.clr_wpu(); i_gpio_mfmix.set_od(); i_gpio_mf.clr_wpu(); i_gpio_mf.set_od(); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_Z); /* OD */ expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_1); /* WPU */ expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_Z); /* OD */ expect(pin3.name(), pin3.read(), SC_LOGIC_Z); /* OD */ /* And we go low again. */ i_gpio.set_val(false); i_gpio_mix.set_val(false); i_gpio_mfmix.set_val(false); i_gpio_mf.set_val(false); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_0); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_0); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_0); expect(pin3.name(), pin3.read(), SC_LOGIC_0); /* Now we go with a weak pull-down. */ printf("\n\n**** Checking weak pull-down ****\n"); i_gpio.set_wpd(); i_gpio.clr_od(); i_gpio_mix.set_wpd(); i_gpio_mix.clr_wpu(); i_gpio_mfmix.set_wpd(); i_gpio_mfmix.clr_od(); i_gpio_mf.set_wpd(); i_gpio_mf.clr_od(); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_Z); /* WPD but looks like Z */ expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_0); /* WPD */ expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_0); /* WPD */ expect(pin3.name(), pin3.read(), SC_LOGIC_Z); /* WPD but looks like Z */ /* And we raise the signals. */ i_gpio.set_val(true); i_gpio_mix.set_val(true); i_gpio_mfmix.set_val(true); i_gpio_mf.set_val(true); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_1); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_1); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_1); expect(pin3.name(), pin3.read(), SC_LOGIC_1); /* Now we go with a weak pull-down. */ i_gpio.set_val(false); i_gpio_mix.set_val(false); i_gpio_mfmix.set_val(false); i_gpio_mf.set_val(false); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_Z); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_0); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_0); expect(pin3.name(), pin3.read(), SC_LOGIC_Z); /* And we shut off the pull downs. */ i_gpio.clr_wpd(); i_gpio_mix.clr_wpd(); i_gpio_mfmix.clr_wpd(); i_gpio_mf.clr_wpd(); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_0); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_0); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_0); expect(pin3.name(), pin3.read(), SC_LOGIC_0); /* Now we go to GPIO In */ printf("\n\n**** Changing GPIOs to Input ****\n"); pin1.write(SC_LOGIC_1); pin_a1.write(SC_LOGIC_0); pin_a2.write(SC_LOGIC_1); pin3.write(SC_LOGIC_0); i_gpio.set_dir(GPIODIR_INPUT); i_gpio_mix.set_dir(GPIODIR_INPUT); i_gpio_mfmix.set_dir(GPIODIR_INPUT); i_gpio_mf.set_dir(GPIODIR_INPUT); wait(10, SC_NS); expect(i_gpio.name(), i_gpio.get_val(), SC_LOGIC_1); expect(i_gpio_mix.name(), i_gpio_mix.get_val(), SC_LOGIC_0); expect(i_gpio_mfmix.name(), i_gpio_mfmix.get_val(), SC_LOGIC_1); expect(i_gpio_mf.name(), i_gpio_mf.get_val(), SC_LOGIC_0); pin1.write(SC_LOGIC_0); pin_a1.write(SC_LOGIC_1); pin_a2.write(SC_LOGIC_0); pin3.write(SC_LOGIC_1); wait(10, SC_NS); expect(pin1.name(), i_gpio.get_val(), SC_LOGIC_0); expect(pin_a1.name(), i_gpio_mix.get_val(), SC_LOGIC_1); expect(pin_a2.name(), i_gpio_mfmix.get_val(), SC_LOGIC_0); expect(pin3.name(), i_gpio_mf.get_val(), SC_LOGIC_1); /* These one should still be low as the function was not selected. */ expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); /* Now we change values. */ printf("\n\n**** Changing GPIOs to I/O ****\n"); pin1.write(SC_LOGIC_1); pin_a1.write(SC_LOGIC_0); pin_a2.write(SC_LOGIC_1); pin3.write(SC_LOGIC_0); i_gpio.set_dir(GPIODIR_INOUT); i_gpio.set_val(true); i_gpio_mix.set_dir(GPIODIR_INOUT); i_gpio_mix.set_val(true); i_gpio_mfmix.set_dir(GPIODIR_INOUT); i_gpio_mfmix.set_val(true); i_gpio_mf.set_dir(GPIODIR_INOUT); i_gpio_mf.set_val(true); wait(10, SC_NS); expect(pin1.name(), pin1, SC_LOGIC_1); expect(pin_a1.name(), pin_a1, SC_LOGIC_X); expect(pin_a2.name(), pin_a2, SC_LOGIC_1); /* It was high. */ expect(pin3.name(), pin3, SC_LOGIC_X); pin1.write(SC_LOGIC_Z); pin_a1.write(SC_LOGIC_Z); pin_a2.write(SC_LOGIC_Z); pin3.write(SC_LOGIC_Z); wait(10, SC_NS); expect(pin1.name(), pin1, sc_logic(i_gpio.get_val())); expect(pin_a1.name(), pin_a1, sc_logic(i_gpio.get_val())); expect(pin_a2.name(), pin_a2, sc_logic(i_gpio.get_val())); expect(pin3.name(), pin3, sc_logic(i_gpio.get_val())); /* Now we change the modes. */ printf("\n\n**** Function ANALOG ****\n"); i_gpio_mix.set_function(GPIOMF_ANALOG); i_gpio_mfmix.set_function(GPIOMF_ANALOG); wait(10, SC_NS); expect(pin1.name(), pin1, sc_logic(i_gpio.get_val())); expect(pin_a1.name(), pin_a1, SC_LOGIC_Z); expect(pin_a2.name(), pin_a2, SC_LOGIC_Z); expect(f1out.name(), f1out, SC_LOGIC_0); expect(f2out.name(), f2out, SC_LOGIC_0); printf("\n\n**** Funtion GPIO ****\n"); /* We drive all functions high and the internal values low and check * that the pins follow signal. */ i_gpio_mfmix.set_function(GPIOMF_GPIO); i_gpio_mfmix.set_dir(GPIODIR_INOUT); i_gpio_mfmix.set_val(false); i_gpio_mf.set_function(GPIOMF_GPIO); i_gpio_mf.set_dir(GPIODIR_INOUT); i_gpio_mf.set_val(false); f1in.write(true); f1en.write(true); f2in.write(true); f2en.write(true); f3in.write(true); f3en.write(true); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_0); expect(f1out.name(), f1out, SC_LOGIC_0); expect(f2out.name(), f2out, SC_LOGIC_0); expect(pin3.name(), pin3, SC_LOGIC_0); expect(f3out.name(), f3out, SC_LOGIC_0); /* We toggle a bit more the pins */ f2in.write(false); f2en.write(true); f3in.write(false); f3en.write(true); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_0); expect(f1out.name(), f1out, SC_LOGIC_0); expect(f2out.name(), f2out, SC_LOGIC_0); expect(pin3.name(), pin3, SC_LOGIC_0); expect(f3out.name(), f3out, SC_LOGIC_0); printf("\n\n**** Funtion 1 ****\n"); /* We now switch to function 1 and check that the functions are passed * through. */ i_gpio_mfmix.set_function(1); i_gpio_mf.set_function(1); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_1); expect(f1out.name(), f1out, SC_LOGIC_1); expect(f2out.name(), f2out, SC_LOGIC_0); expect(pin3.name(), pin3, SC_LOGIC_0); expect(f3out.name(), f3out, SC_LOGIC_0); f2in.write(true); f2en.write(true); f3in.write(true); f3en.write(true); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_1); expect(f1out.name(), f1out, SC_LOGIC_1); expect(f2out.name(), f2out, SC_LOGIC_0); expect(f3out.name(), f3out, SC_LOGIC_1); f2in.write(false); f2en.write(true); f3in.write(true); f3en.write(false); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_1); expect(pin3.name(), pin3, SC_LOGIC_Z); expect(f1out.name(), f1out, SC_LOGIC_1); expect(f2out.name(), f2out, SC_LOGIC_0); expect(f3out.name(), f3out, SC_LOGIC_0); /* Z can't be put on wire f3out.*/ printf("\n\n**** Funtion 2 ****\n"); i_gpio_mfmix.set_function(2); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_0); expect(f1out.name(), f1out, SC_LOGIC_0); expect(f2out.name(), f2out, SC_LOGIC_0); f2in.write(true); f2en.write(false); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_Z); expect(f1out.name(), f1out, SC_LOGIC_0); expect(f2out.name(), f2out, SC_LOGIC_0); f2in.write(true); f2en.write(true); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_1); expect(f1out.name(), f1out, SC_LOGIC_0); expect(f2out.name(), f2out, SC_LOGIC_1); } void tb_gpio::testbench(void) { /* Now we check the test case and run the correct TB. */ PRINTF_INFO("TEST", "Starting Testbench Test%d", tn); if (tn == 0) t0(); else SC_REPORT_FATAL("TEST", "Test number too large."); sc_stop(); } void tb_gpio::trace(sc_trace_file *tf) { sc_trace(tf, pin1, pin1.name()); sc_trace(tf, pin_a1, pin_a1.name()); sc_trace(tf, pin_a2, pin_a2.name()); sc_trace(tf, pin3, pin3.name()); sc_trace(tf, f1in, f1in.name()); sc_trace(tf, f1en, f1en.name()); sc_trace(tf, f1out, f1out.name()); sc_trace(tf, f2in, f2in.name()); sc_trace(tf, f2en, f2en.name()); sc_trace(tf, f2out, f2out.name()); sc_trace(tf, f3in, f3in.name()); sc_trace(tf, f3en, f3en.name()); sc_trace(tf, f3out, f3out.name()); }
/* * @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; } } };
#include <systemc.h> #include "Memory.h" using namespace std; void Memory::execute() { // Initialize memory to some predefined contents. for (int i=0; i<MEM_SIZE; i++) _data[i] = i + 0xff000; port_Stall = true; for (;;) { wait(); int addr = port_Addr % MEM_SIZE; if (port_Read) { // Read word from memory. int data = _data[addr]; port_RData = data; port_Stall = false; // Always ready. #if defined(PRINT_WHILE_RUN) cout << sc_time_stamp() << "\tMemory: Done read request. Addr = " << showbase << hex << addr << ", Data = " << showbase << hex << data << endl; #endif // Hold data until read cleared. do { wait(); } while (port_Read); port_RData = 0; } else if (port_Write) { // Write a word to memory. int data = port_WData; //int be = port_BE; port_Stall = true; #if defined(PRINT_WHILE_RUN) cout << sc_time_stamp() << "\tMemory: Started write request. Addr = " << showbase << hex << addr << ", Data = " << showbase << hex << data << endl; #endif wait(10); port_Stall = false; _data[addr] = data; // TODO: byte enable #if defined(PRINT_WHILE_RUN) cout << sc_time_stamp() << "\tMemory: Finished write request. Addr = " << showbase << hex << addr << endl; #endif // Wait until write cleared. do { wait(); } while (port_Write); } } }
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** display.cpp -- Original Author: Rocco Jonack, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation: Teodor Vasilache and Dragos Dospinescu, AMIQ Consulting s.r.l. (contributors@amiq.com) Date: 2018-Feb-20 Description of Modification: Included the FC4SC library in order to collect functional coverage data and generate a coverage database. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include <systemc.h> #include "display.h" #include "fc4sc.hpp" void display::entry(){ // Reading Data when valid if high tmp1 = result.read(); cout << "Display : " << tmp1 << " " /* << " at time " << sc_time_stamp() << endl; */ << " at time " << sc_time_stamp().to_double() << endl; i++; // sample the data this->out_cg.sample(result, output_data_ready); if(i == 24) { cout << "Simulation of " << i << " items finished" /* << " at time " << sc_time_stamp() << endl; */ << " at time " << sc_time_stamp().to_double() << endl; // generate the coverage database from the collected data fc4sc::global::coverage_save("coverage_results.xml"); sc_stop(); }; } // EOF
/* * @ASCK */ #include <systemc.h> SC_MODULE (PC) { sc_in <bool> clk; sc_in <sc_uint<14>> prev_addr; sc_out <sc_uint<14>> next_addr; /* ** module global variables */ SC_CTOR (PC){ SC_METHOD (process); sensitive << clk.pos(); } void process () { next_addr.write(prev_addr.read()); } };
#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> //here we create a module called hello_world SC_MODULE(hello_world) { private int meaning_of_life; // easter egg //SC_CTOR -- systemC constructor SC_CTOR(hello_world) { meaning_of_life=42; } void say_hello() { cout << "Hello Systemc-2.3.1!\n"; } void open_magic_box() { cout << meaning_of_life << endl; } }; int sc_main(int argc, char* argv[]) { hello_world hello("HELLO"); hello.say_hello(); hello.open_magic_box(); return(0); }
/******************************************************************************* * pn532_base.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 "pn532_base.h" #include "info.h" void pn532_base::pushack() { to.write(0x00); to.write(0x00); to.write(0xFF); to.write(0x00); to.write(0xFF); to.write(0x00); } void pn532_base::pushsyntaxerr() { to.write(0x00); to.write(0x00); to.write(0xFF); to.write(0x01); to.write(0xFF); to.write(0x7F); to.write(0x81); to.write(0x00); } void pn532_base::pushpreamble(int len, bool hosttopn, int cmd, unsigned char *c) { to.write(0x00); to.write(0x00); to.write(0xFF); to.write(len); to.write(0x100-len); /* Now we clear the checksum as we begin with the TFI. */ *c = 0; pushandcalc((hosttopn)?0xd4:0xd5, c); pushandcalc(cmd, c); } void pn532_base::setcardnotpresent() { mif.tags = 0; mif.sens_res = 0x0000; mif.sel_res = 0; mif.uidLength = 0; mif.uidValue = 0x0000; } void pn532_base::setcardpresent(uint32_t uid) { mif.tags = 1; mif.sens_res = 0x5522; mif.sel_res = 0; mif.uidLength = 4; mif.uidValue = uid; std::map<int, data_block_t>::iterator i; for(i = mif.mem.begin(); i != mif.mem.end(); i++) i->second.authenticated = false; mif.lastincmd = 0x0; mif.bn = 0x0; } void pn532_base::mifset(int pos, const char *value) { int i; bool fillzero; fillzero = false; for (i = 0; i < 15; i = i + 1) { if (!fillzero) { mif.mem[pos].data[i] = value[i]; if (value[i] == '\0') fillzero = true; } else mif.mem[pos].data[i] = 0; } } void pn532_base::mifsetn(int pos, const uint8_t *value, int len) { int i; bool fillzero; fillzero = false; for (i = 0; i < 15; i = i + 1) { if (!fillzero) { mif.mem[pos].data[i] = value[i]; if (i == len-1) fillzero = true; } else mif.mem[pos].data[i] = 0; } } void pn532_base::start_of_simulation() { /* We begin setting the card as non-present. */ setcardnotpresent(); mif.mxrtypassiveactivation = 0xff; /* And we initialize the device to off and no IRQ. */ opstate.write(OPOFF); } pn532_base::resp_t pn532_base::pushresp() { unsigned char cksum = 0; /* Now we can start processing the commands. */ if (mif.cmd == 0x4a && !mif.cmdbad) { /* If we got a card, we return the data on it. */ if (mif.tags > 0) { /* Calculate size. */ int len = 1 + 1 + mif.tags * (1+2+1+1+mif.uidLength) + 1; int i; /* Preamble */ pushpreamble(len, false, 0x4B, &cksum); /* Packet */ pushandcalc(mif.tags, &cksum);/* NbTg */ for(i = 1; i <= mif.tags; i = i + 1) { pushandcalc(i, &cksum); /* Tag no. */ pushandcalc(mif.sens_res>>8, &cksum);/* sens res upper */ pushandcalc(mif.sens_res&0xff, &cksum);/* sens res lower */ pushandcalc(mif.sel_res, &cksum); /* sel res */ pushandcalc(mif.uidLength, &cksum); /* NFCID Len */ } /* NFCID */ pushandcalc(mif.uidValue>>24, &cksum); pushandcalc((mif.uidValue&0xff0000)>>16, &cksum); pushandcalc((mif.uidValue&0xff00)>>8, &cksum); pushandcalc(mif.uidValue&0xff, &cksum); to.write(0x100-cksum); /* DCS */ to.write(0x00); /* ZERO */ /* If there is no card, and it is configured to infinite retries, we need * to try again. */ } else if (mif.retries == 0xff) { return RESP_RETRY; /* If we had a number of retries set, we then decrement the count and * retry. */ } else if (mif.retries > 0) { mif.retries = mif.retries - 1; return RESP_RETRY; /* If we are out of retries, we can then return an empty frame. */ } else { /* If no target came in, we return an empty list. */ /* Preamble */ pushpreamble(0x3, false, 0x4B, &cksum); /* Packet */ pushandcalc(0, &cksum); /* NbTg */ to.write(0x100-cksum); /* DCS */ to.write(0x00); /* ZERO */ } } /* SAMConfiguration command */ else if (mif.cmd == 0x14 && !mif.cmdbad) { pushpreamble(0x2, false, 0x15, &cksum); to.write(0x100-cksum); /* DCS */ to.write(0x00); /* ZERO */ } /* Get Firmware Version. */ else if (mif.cmd == 0x02 && !mif.cmdbad) { pushpreamble(0x06, false, 0x3, &cksum); /* Firmware Version, we just pick something cool from * one of the examples. */ pushandcalc(0x32, &cksum); /* IC */ pushandcalc(0x01, &cksum); /* Firmware Version */ pushandcalc(0x06, &cksum); /* Revision */ pushandcalc(0x07, &cksum); /* Support */ to.write(0x100-cksum); /* DCS */ to.write(0x00); /* ZERO */ } /* InDataExchange Command */ else if (mif.cmd == 0x40) { /* We don't process the actual MiFare commands, we just return that it * was authenticated ok. */ /* We return the data. If the command is bad, we return a failure and * some random junk. */ if (mif.cmdbad) { PRINTF_INFO("MIFARE", "Command Rejected"); pushpreamble(0x06, false, 0x41, &cksum); pushandcalc(0x55, &cksum); /* BAD */ pushandcalc(mif.lastincmd, &cksum); pushandcalc(0x02, &cksum); pushandcalc(0x03, &cksum); } else if (mif.lastincmd == 0x60) { PRINTF_INFO("MIFARE", "Block 0x%02x Authenticated", mif.bn); pushpreamble(0x06, false, 0x41, &cksum); pushandcalc(0x00, &cksum); /* OK */ pushandcalc(mif.lastincmd, &cksum); pushandcalc(0x02, &cksum); pushandcalc(0x03, &cksum); } else if (mif.lastincmd == 0xA0) { PRINTF_INFO("MIFARE", "Write to block 0x%02x", mif.bn); pushpreamble(0x06, false, 0x41, &cksum); pushandcalc(0x00, &cksum); /* OK */ pushandcalc(mif.lastincmd, &cksum); pushandcalc(0x02, &cksum); pushandcalc(0x03, &cksum); } else if (mif.lastincmd == 0x30) { PRINTF_INFO("MIFARE", "Read from block 0x%02x", mif.bn); int p; pushpreamble(21, false, 0x41, &cksum); pushandcalc(0x00, &cksum); /* OK */ p = 0; while (p < 16) { pushandcalc(mif.mem[mif.bn].data[p], &cksum); p = p + 1; } pushandcalc(0x90, &cksum); pushandcalc(0x00, &cksum); } else { PRINTF_INFO("MIFARE", "Other Command"); pushpreamble(0x06, false, 0x41, &cksum); pushandcalc(0x00, &cksum); /* OK */ pushandcalc(mif.lastincmd, &cksum); pushandcalc(0x02, &cksum); pushandcalc(0x03, &cksum); } to.write(0x100-cksum); /* DCS */ to.write(0x00); /* ZERO */ } else { /* For unknown commands we just return a syntax error. */ pushsyntaxerr(); } /* We also clear the command so we do not keep on sending it back. */ mif.cmd = 0; return RESP_OK; } void pn532_base::resp_th() { while(true) { /* We first wait for a command to come in. */ wait(newcommand_ev | ack_ev); /* Anytime we get a new command, we need to dump what we were doing before * and start it. So, we move the state back to OPACK to issue the new ACK. */ if (newcommand_ev.triggered()) { ack_ev.notify(200, SC_US); opstate.write(OPACK); /* For other times, we just process whatever command came in. */ } else switch (opstate.read()) { /* The manual was not clear what happens if the host does not read * the ACK. There are three possible options: * - it gets merged with the next command * - it gets overwitten * - the command does not start until the ACK was read * I am then assuming the third is the one. */ case OPACK: /* We dump any previous possible data in the to FIFO, like a * previous unread response, and we push the ACK. Then we wait * for it to be read out. */ flush_to(); pushack(); opstate.write(OPACKRDOUT); break; /* After the ACK has been read out, we do a delay. Some commands have * a predelay too. */ case OPACKRDOUT: if (mif.predelay != 0) { ack_ev.notify(sc_time(mif.predelay, SC_MS)); opstate.write(OPPREDELAY); } else { ack_ev.notify(sc_time(mif.delay, SC_MS)); opstate.write(OPBUSY); } break; case OPPREDELAY: ack_ev.notify(sc_time(mif.delay, SC_MS)); opstate.write(OPBUSY); break; /* Then we send the response. */ case OPBUSY: flush_to(); /* We try to push a response. If there is a retry request, we * reissue the delay and do it again. */ if (RESP_RETRY == pushresp()) ack_ev.notify(sc_time(mif.delay, SC_MS)); /* If the response was ok, we go to the READOUT state. */ else opstate.write(OPREADOUT); break; case OPREADOUT: opstate.write(OPIDLE); default: ; } } } void pn532_base::process_th() { unsigned char cksum = 0; unsigned char msg; enum {IDLE, UNLOCK1, UNLOCK2, UNLOCK3, UNLOCK4, UNLOCK5, PD0, PDN, DCS, LOCK} pn532state; while(true) { msg = grab(&cksum); switch(pn532state) { case IDLE: if (msg == 0x0) pn532state = UNLOCK1; else { PRINTF_WARN("PN532", "Warning: got an illegal preamble."); pn532state = IDLE; } break; case UNLOCK1: if (msg == 0x0) pn532state = UNLOCK2; else { PRINTF_WARN("PN532","Warning: got an illegal preamble, byte 2."); pn532state = IDLE; } break; case UNLOCK2: /* The first 0x0 can be as long as the customer wants, so we * discard any extra 0x0 received. */ if (msg == 0x0) pn532state = UNLOCK2; else if (msg == 0xff) pn532state = UNLOCK3; else { PRINTF_WARN("PN532","Warning: got an illegal preamble, byte 3."); pn532state = IDLE; } break; case UNLOCK3: /* And we collect the length of the next command. */ mif.len = msg; pn532state = UNLOCK4; break; case UNLOCK4: /* Anytime we go to the UNLOCK5 (TFI state) we clear the cksum. */ cksum = 0; /* Now we check the LCS, it should be the complement of the LEN. */ if (0x100 - mif.len != msg) { PRINTF_WARN("PN532", "Warning: got illegal LCS."); } pn532state = UNLOCK5; break; case UNLOCK5: { unsigned char tfi = msg; if (tfi != 0xD4) { PRINTF_WARN("PN532", "Warning: got illegal TFI %02x", tfi); pn532state = IDLE; } mif.len = mif.len - 1; pn532state = PD0; break; } case PD0: if (pn532state == PD0) mif.cmd = msg; mif.len = mif.len - 1; if (mif.len == 0) pn532state = DCS; else pn532state = PDN; /* We dump any previous command in the fifo. */ while(to.num_available() != 0) { cksum = cksum + to.read(); } break; case PDN: /* Some packages have a packet. If it has one we take it in to the * right places. Any remaining bytes or packets in unsupported * messages are pitched. */ mif.len = mif.len - 1; mif.cmdbad = false; /* SAM command */ if (mif.cmd == 0x14) { mif.mode = msg; if (mif.len<2) { mif.cmdbad = true; } else { mif.timeout=grab(&cksum); mif.len = mif.len-1; mif.useirq=grab(&cksum); mif.len = mif.len-1; } } /* InDataExchange */ else if (mif.cmd == 0x40) { /* For the InDataExchange command we are talking to the card. * This varies a lot according to the card, and it can get * quite complex. We are trying to do something simple here, * so all we do is check for a few commands. */ /* We first get the header. */ if (mif.len < 2) mif.cmdbad = true; else { /* msg has the Target No. */ mif.lastincmd = grab(&cksum); mif.len = mif.len - 1; /* cmd */ mif.bn = grab(&cksum); mif.len = mif.len - 1; /* Block No. */ /* Authenticate */ if (mif.lastincmd == 0x60 && mif.len >= 10) { mif.mem[mif.bn].authenticated = true; /* Write */ } else if (mif.lastincmd == 0xA0 && mif.len >= 16 && mif.mem[mif.bn].authenticated) { int p; p = 0; while (p < 16) { mif.mem[mif.bn].data[p] = grab(&cksum); mif.len = mif.len - 1; p = p + 1; } /* Read */ } else if (mif.lastincmd == 0x30 && mif.mem[mif.bn].authenticated) { ; /* Other commands we simply return a good as we do not know * what to do. */ } else { mif.cmdbad = false; } } } else if (mif.cmd == 0x32) { int cfgitem = msg; int cfg[3]; switch (cfgitem) { case 0x1: cfg[0] = grab(&cksum); mif.len = mif.len - 1; PRINTF_INFO("PN532", "Accepted RFConfiguration [0x1]=%02x", cfg[0]); break; case 0x2: cfg[0] = grab(&cksum); mif.len = mif.len - 1; cfg[1] = grab(&cksum); mif.len = mif.len - 1; cfg[2] = grab(&cksum); mif.len = mif.len - 1; PRINTF_INFO("PN532", "Accepted RFConfiguration [0x2]=RFU: %02x", cfg[0]); PRINTF_INFO("PN532", "Accepted RFConfiguration [0x2]=fATR_RES_Timeout: %02x", cfg[1]); PRINTF_INFO("PN532", "Accepted RFConfiguration [0x2]=fRetryTimeout: %02x", cfg[2]); break; case 0x4: cfg[0] = grab(&cksum); mif.len = mif.len - 1; PRINTF_INFO("PN532", "Accepted RFConfiguration [0x4]=MxRetryCOM: %02x", cfg[0]); break; case 0x5: cfg[0] = grab(&cksum); mif.len = mif.len - 1; cfg[1] = grab(&cksum); mif.len = mif.len - 1; cfg[2] = grab(&cksum); mif.len = mif.len - 1; PRINTF_INFO("PN532", "Accepted RFConfiguration [0x5]=MxRtyATR: %02x",cfg[0]); PRINTF_INFO("PN532", "Accepted RFConfiguration [0x5]=MxRtyPSL: %02x", cfg[1]); PRINTF_INFO("PN532", "Accepted RFConfiguration [0x5]=MxRtyPassiveActivation: %02x", cfg[2]); mif.mxrtypassiveactivation = cfg[2]; break; } if (mif.len<1) { mif.cmdbad = true; } else { mif.brty = grab(&cksum); mif.len = mif.len - 1; } /* brty=00 only supports 1 or 2 targets. */ if (mif.maxtg > 2 || mif.maxtg <= 0) mif.cmdbad = true; if (mif.brty != 0x00) mif.cmdbad = true; /* we only support 00*/ } else if (mif.cmd == 0x4a) { mif.maxtg = msg; if (mif.len<1) { mif.cmdbad = true; } else { mif.brty = grab(&cksum); mif.len = mif.len - 1; } /* brty=00 only supports 1 or 2 targets. */ if (mif.maxtg > 2 || mif.maxtg <= 0) mif.cmdbad = true; if (mif.brty != 0x00) mif.cmdbad = true; /* we only support 00*/ } /* We flush out the rest of the payload. */ while (mif.len > 0) { pn532state = DCS; int i = grab(&cksum); PRINTF_INFO("I", "%02x", i); mif.len = mif.len - 1; } /* And we go to the DCS. */ pn532state = DCS; break; case DCS: { /* We now check the DCS. Note that the DCS was added, so we should * see zero. If it is wrong, we need to backtrack to get the * expected value. */ if (cksum != 0) { PRINTF_WARN("PN532", "Got the DCS to be %02x when expected %02x", msg, 0x100 - (0xff & (cksum - msg))); } pn532state = LOCK; break; } case LOCK: /* We check the command to make sure it is a LOCK. */ if (msg != 0x00) { PRINTF_WARN("PN532", "Relock did not match!"); } /* And we return to idle. */ pn532state = IDLE; /* Now we can execute the command. */ if (mif.cmd == 0x4a) { PRINTF_INFO("PN532", "Accepted Inlist Passive Target"); /* We put then the response in the buffer */ mif.predelay = 5; mif.delay = 200; /* We set the retries to the maximum set and notify the process * to begin. */ mif.retries = mif.mxrtypassiveactivation; newcommand_ev.notify(); } else if (mif.cmd == 0x14) { PRINTF_INFO("PN532", "Accepted SAM configuration command"); /* We put then the response in the buffer */ mif.predelay = 5; mif.delay = 20; newcommand_ev.notify(); } else if (mif.cmd == 0x02) { PRINTF_INFO("PN532", "Accepted getVersion com
mand"); mif.predelay = 2; mif.delay = 20; newcommand_ev.notify(); } else if (mif.cmd == 0x40) { PRINTF_INFO("PN532", "Accepted InDataExchange command"); mif.predelay = 0; mif.delay = 1; newcommand_ev.notify(); } else if (mif.cmd == 0x32) { mif.predelay = 0; mif.delay = 1; newcommand_ev.notify(); } else { /* Illegal commands also are processed as commands, so an * ACK is returned, just the data packet has a syntax error. */ mif.predelay = 0; mif.delay = 1; PRINTF_INFO("PN532", "Accepted Unknown command"); newcommand_ev.notify(); } } pnstate.write(pn532state); } } /* For the IRQ manage, we initialize the thread taking the pin high. Then, when * the TO fifo changes, we will take it either high or low. */ void pn532_base::irqmanage_th() { bool wasempty = true; irq.write(GN_LOGIC_1); while(1) { wait(to.data_written_event() | to.data_read_event()); if (to.num_available() == 0 && !wasempty) { irq.write(GN_LOGIC_1); /* If the read_th was waiting to read data, we then wake it up to * go to the next state. */ if (opstate.read() == OPACKRDOUT || opstate.read() == OPREADOUT) ack_ev.notify(); } else irq.write(GN_LOGIC_0); wasempty = to.num_available() == 0; } } void pn532_base::trace(sc_trace_file *tf) { sc_trace(tf, opstate, opstate.name()); sc_trace(tf, ack_ev, ack_ev.name()); sc_trace(tf, newcommand_ev, newcommand_ev.name()); sc_trace(tf, pnstate, pnstate.name()); sc_trace(tf, intoken, intoken.name()); sc_trace(tf, outtoken, outtoken.name()); sc_trace(tf, irq, irq.name()); }
/** * Murac Auxilliary Architecture integration framework * Author: Brandon Hamilton <brandon.hamilton@gmail.com> */ #include <systemc.h> #include <dlfcn.h> #include <fcntl.h> #include <sys/mman.h> #include "muracAA.hpp" typedef int (*murac_init_func)(BusInterface*); typedef int (*murac_exec_func)(unsigned long int); using std::cout; using std::endl; using std::dec; using std::hex; SC_HAS_PROCESS( muracAA ); muracAAInterupt::muracAAInterupt(const char *name, muracAA *aa): m_aa(aa), m_name(name) { } void muracAAInterupt::write(const int &value) { if (value == 1) { m_aa->onBrArch(value); } } /** * Constructor */ muracAA::muracAA( sc_core::sc_module_name name) : sc_module( name ), brarch("brarch", this) { } int muracAA::loadLibrary(const char *library) { cout << "Loading murac library: " << library << endl; void* handle = dlopen(library, RTLD_NOW | RTLD_GLOBAL); if (!handle) { cout << dlerror() << endl; return -1; } dlerror(); cout << "Initializing murac library: " << library << endl; murac_init_func m_init = (murac_init_func) dlsym(handle, "murac_init"); int result = m_init(this); return result; } int muracAA::invokePluginSimulation(const char* path, unsigned long int ptr) { char *error; void* handle = dlopen(path, RTLD_LAZY | RTLD_GLOBAL); if (!handle) { cout << dlerror() << endl; return -1; } dlerror(); murac_exec_func m_exec = (murac_exec_func) dlsym(handle, "murac_execute"); if ((error = dlerror()) != NULL) { fprintf(stderr, "%s\n", error); return -1; } int result = -1; sc_process_handle h = sc_spawn(&result, sc_bind(m_exec, ptr) ); wait(h.terminated_event()); //dlclose(handle); return result; } /** * Handle the BrArch interrupt from the PA */ void muracAA::onBrArch(const int &value) { cout << "@" << sc_time_stamp() << " onBrArch" << endl; int ret = -1; int fd; unsigned long int pc = 0; unsigned int instruction_size = 0; unsigned long int ptr = 0; unsigned char* fmap; char *tmp_file_name = strdup("/tmp/murac_AA_XXXXXX"); if (busRead(MURAC_PC_ADDRESS, (unsigned char*) &pc, 4) < 0) { cout << "@" << sc_time_stamp() << " Memory read error !" << endl; goto trigger_return_interrupt; } cout << "@" << sc_time_stamp() << " PC: 0x" << hex << pc << endl; if (busRead(MURAC_PC_ADDRESS + 4, (unsigned char*) &instruction_size, 4) < 0) { cout << "@" << sc_time_stamp() << " Memory read error !" << endl; goto trigger_return_interrupt; } cout << "@" << sc_time_stamp() << " Instruction size: " << dec << instruction_size << endl; if (busRead(MURAC_PC_ADDRESS + 8, (unsigned char*) &ptr, 4) < 0) { cout << "@" << sc_time_stamp() << " Memory read error !" << endl; goto trigger_return_interrupt; } cout << "@" << sc_time_stamp() << " Ptr : " << hex << ptr << dec << endl; cout << "@" << sc_time_stamp() << " Reading embedded AA simulation file " << endl; fd = mkostemp (tmp_file_name, O_RDWR | O_CREAT | O_TRUNC); if (fd == -1) { cout << "Error: Cannot open temporary file for writing." << endl; goto trigger_return_interrupt; } ret = lseek(fd, instruction_size-1, SEEK_SET); if (ret == -1) { close(fd); cout << "Error: Cannot call lseek() on temporary file." << endl; goto trigger_return_interrupt; } ret = ::write(fd, "", 1); if (ret != 1) { close(fd); cout << "Error: Error writing last byte of the temporary file." << endl; goto trigger_return_interrupt; } fmap = (unsigned char*) mmap(0, instruction_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (fmap == MAP_FAILED) { close(fd); cout << "Error: Error mmapping the temporary file." << endl; goto trigger_return_interrupt; } // Write the file if (busRead(pc, fmap, instruction_size) < 0) { cout << "@" << sc_time_stamp() << " Memory read error !" << endl; munmap(fmap, instruction_size); close(fd); goto trigger_return_interrupt; } if (munmap(fmap, instruction_size) == -1) { close(fd); cout << "Error: Error un-mmapping the temporary file." << endl; goto trigger_return_interrupt; } close(fd); cout << "@" << sc_time_stamp() << " Running murac AA simulation " << endl; ret = invokePluginSimulation(tmp_file_name, ptr); cout << "@" << sc_time_stamp() << " Simulation result = " << ret << endl; remove(tmp_file_name); trigger_return_interrupt: free(tmp_file_name); cout << "@" << sc_time_stamp() << " Returning to PA " << endl; // Trigger interrupt for return to PA intRetArch.write(1); intRetArch.write(0); } /** * Read from the bus */ int muracAA::busRead (unsigned long int addr, unsigned char rdata[], int dataLen) { bus_payload.set_read (); bus_payload.set_address ((sc_dt::uint64) addr); bus_payload.set_byte_enable_length ((const unsigned int) dataLen); bus_payload.set_byte_enable_ptr (0); bus_payload.set_data_length ((const unsigned int) dataLen); bus_payload.set_data_ptr ((unsigned char *) rdata); busTransfer(bus_payload); return bus_payload.is_response_ok () ? 0 : -1; } /** * Write to the bus */ int muracAA::busWrite (unsigned long int addr, unsigned char wdata[], int dataLen) { bus_payload.set_write (); bus_payload.set_address ((sc_dt::uint64) addr); bus_payload.set_byte_enable_length ((const unsigned int) dataLen); bus_payload.set_byte_enable_ptr (0); bus_payload.set_data_length ((const unsigned int) dataLen); bus_payload.set_data_ptr ((unsigned char *) wdata); busTransfer(bus_payload); return bus_payload.is_response_ok () ? 0 : -1; } /** * Initiate bus transfer */ void muracAA::busTransfer( tlm::tlm_generic_payload &trans ) { sc_core::sc_time dummyDelay = sc_core::SC_ZERO_TIME; aa_bus->b_transport( trans, dummyDelay ); } int muracAA::read(unsigned long int addr, unsigned char*data, unsigned int len) { return busRead(addr, data, len); } int muracAA::write(unsigned long int addr, unsigned char*data, unsigned int len) { return busWrite(addr, data, len); }
/******************************************************************************* * panic.cpp -- Copyright 2019 Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This file replaces the run time error functions from the ESP32 with * equivalents that will kill the model and print a message on the screen. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file was based off the work covered by the license below: * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <systemc.h> #include "info.h" #include <stdlib.h> #include <esp_system.h> #include <freertos/FreeRTOS.h> #include <freertos/task.h> /* Note: The linker script will put everything in this file in IRAM/DRAM, so it also works with flash cache disabled. */ void __attribute__((weak)) vApplicationStackOverflowHook( TaskHandle_t xTask, signed char *pcTaskName ) { printf("***ERROR*** A stack overflow in task "); printf((char *)pcTaskName); printf(" has been detected.\r\n"); espm_abort(); } /* These two weak stubs for esp_reset_reason_{get,set}_hint are used when * the application does not call esp_reset_reason() function, and * reset_reason.c is not linked into the output file. */ void __attribute__((weak)) esp_reset_reason_set_hint(esp_reset_reason_t hint) { } esp_reset_reason_t __attribute__((weak)) esp_reset_reason_get_hint(void) { return ESP_RST_UNKNOWN; } static inline void invoke_abort() { SC_REPORT_FATAL("PANIC", "Abort Called"); } /* Renamed to espm_abort to not conflict with the system abort(). */ void espm_abort() { printf("abort() was called\n"); /* Calling code might have set other reset reason hint (such as Task WDT), * don't overwrite that. */ if (esp_reset_reason_get_hint() == ESP_RST_UNKNOWN) { esp_reset_reason_set_hint(ESP_RST_PANIC); } invoke_abort(); } /* This disables all the watchdogs for when we call the gdbstub. */ static void esp_panic_dig_reset() { SC_REPORT_FATAL("PANIC", "Panic Dig Reset"); } void esp_set_breakpoint_if_jtag(void *fn) { PRINTF_INFO("PANIC", "Set breakpoint %p", fn); } esp_err_t esp_set_watchpoint(int no, void *adr, int size, int flags) { if (no < 0 || no > 1) { return ESP_ERR_INVALID_ARG; } if (flags & (~0xC0000000)) { return ESP_ERR_INVALID_ARG; } PRINTF_INFO("PANIC", "Setting watchpoint %d addr=%p size=%d flags=%x", no, adr, size, flags); return ESP_OK; } void esp_clear_watchpoint(int no) { PRINTF_INFO("PANIC", "Clearing watchpoint %d", no); } static void esp_error_check_failed_print(const char *msg, esp_err_t rc, const char *file, int line, const char *function, const char *expression) { printf("%s failed: esp_err_t 0x%x", msg, rc); } void _esp_error_check_failed_without_abort(esp_err_t rc, const char *file, int line, const char *function, const char *expression) { esp_error_check_failed_print("ESP_ERROR_CHECK_WITHOUT_ABORT", rc, file, line, function, expression); } void _esp_error_check_failed(esp_err_t rc, const char *file, int line, const char *function, const char *expression) { esp_error_check_failed_print("ESP_ERROR_CHECK", rc, file, line, function, expression); invoke_abort(); }
/******************************************************************************* * task.cpp -- Copyright 2019 Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This file reimplements the freertos tasks to get them to compile under the * ESPMOD SystemC model. The tasks were rewrittent to spawn SC dynamic * threads. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file was based off the work covered by the license below: * FreeRTOS V8.2.0 - Copyright (C) 2015 Real Time Engineers Ltd. * All rights reserved * * FreeRTOS is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License (version 2) as published by the * Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception. * * FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. Full license text is available on the following * link: http://www.freertos.org/a00114.html */ #define SC_INCLUDE_DYNAMIC_PROCESSES #include <systemc.h> #include "FreeRTOS.h" #include "task.h" void vTaskDelay( const TickType_t xTicksToDelay ) { /* We set the portTICK_RATE_MS to 1, so the value should be the * number in lilliseconds. Perhaps we should change this later. */ wait(xTicksToDelay, SC_MS); } BaseType_t xTaskCreatePinnedToCore( TaskFunction_t pvTaskCode, const char * const pcName, const uint32_t usStackDepth, void * const pvParameters, UBaseType_t uxPriority, TaskHandle_t * const pvCreatedTask, const BaseType_t xCoreID) { sc_spawn(sc_bind(pvTaskCode, pvParameters)); return pdTRUE; } void vTaskDelete( TaskHandle_t xTaskToDelete ) { }
#include <Gemmini.h> #include <systemc.h> #include <ac_int.h> #include <ac_std_float.h> #include <cfenv> template<class To, class From> To _bit_cast(const From& src) noexcept { To dst; std:: memcpy(&dst, &src, sizeof(To)); return dst; } sc_biguint<8> Gemmini::ScaleInputType(sc_biguint<8> input,sc_biguint<32> scale){ // Bit-cast scale to float ac_ieee_float32 scale_ac_float = _bit_cast<float, uint32_t>(scale.to_uint()); // Convert input to float ac_ieee_float32 input_ac_float(_bit_cast<int8_t,uint8_t>(input.to_uint())); // Perform multiply auto result_ac_float = input_ac_float * scale_ac_float; // Cast to int with rounding to the nearest even number // TODO: Make clamping programmatic with generated gemmini bitwidths // TODO: Use custom types corresponding to the gemmini configuration auto result_float = result_ac_float.to_float(); auto result_int = static_cast<int64_t>(std::nearbyint(result_float)); int8_t result_clamped = result_int > INT8_MAX ? INT8_MAX : (result_int < INT8_MIN ? INT8_MIN : result_int); // Bit-cast back to sc_biguint8 uint8_t result_uint = _bit_cast<uint8_t, int8_t>(result_clamped); sc_biguint<8> to_return(result_uint); return to_return; } sc_biguint<8> Gemmini::ScaleAccType(sc_biguint<32> input,sc_biguint<32> scale){ // bitcast scale to float ac_ieee_float32 scale_ac_float = _bit_cast<float, uint32_t>(scale.to_uint()); // Cast scale and input to 64 bit floats ac_ieee_float64 scale_ac_float64(scale_ac_float); ac_ieee_float64 input_float64(_bit_cast<int32_t,uint32_t>(input.to_uint())); // Perform multiply ac_ieee_float64 result_float64 = scale_ac_float64 * input_float64; // Cast to int with rounding to the nearest integer auto result_double = result_float64.to_double(); auto result_rounded = std::nearbyint(result_double); auto result_clamped = result_rounded > INT8_MAX ? INT8_MAX : (result_rounded < INT8_MIN ? INT8_MIN : result_rounded); auto result_int = static_cast<int8_t>(result_clamped); // Cast back to sc_biguint sc_biguint<8> out(result_int); return out; }
/************************************************************************** * * * Catapult(R) MatchLib Toolkit Example Design Library * * * * Software Version: 2.2 * * * * Release Date : Thu Aug 22 21:10:31 PDT 2024 * * Release Type : Production Release * * Release Build : 2.2.0 * * * * Copyright 2020 Siemens * * * ************************************************************************** * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * * implied. * * See the License for the specific language governing permissions and * * limitations under the License. * ************************************************************************** * * * The most recent version of this package is available at github. * * * *************************************************************************/ #include <systemc.h> #include "dut.h" #include <mc_scverify.h> using namespace::std; class Top : public sc_module { public: CCS_DESIGN(dut) CCS_INIT_S1(dut1); sc_clock clk; SC_SIG(bool, rst_bar); Connections::Combinational<dut::T> CCS_INIT_S1(out1); Connections::Combinational<dut::T> CCS_INIT_S1(in1); int matlab_input; bool matlab_input_valid; int matlab_output; bool matlab_output_valid; SC_CTOR(Top) : clk("clk", 1, SC_NS, 0.5,0,SC_NS,true) { sc_object_tracer<sc_clock> trace_clk(clk); dut1.clk(clk); dut1.rst_bar(rst_bar); dut1.out1(out1); dut1.in1(in1); SC_CTHREAD(reset, clk); SC_THREAD(stim); sensitive << clk.posedge_event(); async_reset_signal_is(rst_bar, false); SC_THREAD(resp); sensitive << clk.posedge_event(); async_reset_signal_is(rst_bar, false); } void stim() { CCS_LOG("Stimulus started"); in1.ResetWrite(); wait(); int i1 = 0; while (1) { #ifdef EXTERNAL_TESTBENCH if (matlab_input_valid) { in1.Push(matlab_input); matlab_input_valid = 0; } else { wait(); } #else in1.Push(i1++); if (i1 > 10) sc_stop(); #endif } } void resp() { out1.ResetRead(); wait(); while (1) { #ifdef EXTERNAL_TESTBENCH matlab_output = out1.Pop(); matlab_output_valid = 1; std::cout << "calling sc_pause()\n"; sc_pause(); #else CCS_LOG("See: " << out1.Pop()); #endif } } void reset() { rst_bar.write(0); wait(5); rst_bar.write(1); wait(); } }; Top *top_ptr{0}; // sc_main instantiates the SC hierarchy but does not run the simulation - that is handled elsewhere int sc_main(int argc, char **argv) { sc_report_handler::set_actions("/IEEE_Std_1666/deprecated", SC_DO_NOTHING); sc_report_handler::set_actions(SC_ERROR, SC_DISPLAY); // This function instantiates the design hiearchy including the testbench. sc_trace_file *trace_file_ptr = sc_trace_static::setup_trace_file("trace"); top_ptr = new Top("top"); trace_hierarchy(top_ptr, trace_file_ptr); #ifndef EXTERNAL_TESTBENCH sc_start(); #endif return 0; } #ifdef EXTERNAL_TESTBENCH // This class represents the SC simulator to Python or Matlab Mex class sc_simulator { public: sc_simulator() { sc_elab_and_sim(0, 0); } // This function represents the python or Matlab Mex function that would be called repeatedly // to process one (or more) data inputs and return one (or more) data outputs int process_one_sample(int in1) { top_ptr->matlab_input = in1; top_ptr->matlab_input_valid = true; std::cout << "calling sc_start()\n"; sc_start(); // This returns when sc_pause is called above return top_ptr->matlab_output; } }; // Python does not have a native C++ interface, so we export regular C functions to Python extern "C" { sc_simulator* sc_simulator_new() { return new sc_simulator(); } int process_one_sample(sc_simulator* sim, int in1) { return sim->process_one_sample(in1); } } #endif
#include <systemc.h> class sc_clockx : sc_module, sc_interface { public: sc_event edge; sc_event change; bool val; bool _val; int delta; private: int period; SC_HAS_PROCESS(sc_clockx); void run(void) { int tmp = period/2; edge.notify(SC_ZERO_TIME); change.notify(SC_ZERO_TIME); while(true) { wait(tmp, SC_NS); edge.notify(SC_ZERO_TIME); change.notify(SC_ZERO_TIME); val = !val; } } public: sc_clockx(sc_module_name name, int periodparam): sc_module(name) { SC_THREAD(run); period = periodparam; val = true; _val = true; } bool read() { return val; } void write(bool newval) { _val = newval; if (!(_val == val)) request_update(); } void update() { if (!(_val == val)) { val = _val; change.notify(SC_ZERO_TIME); delta = sc_delta_count(); } } };
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** in_class_initialization.cpp : Showcase for in-class initialization macros Original Author: Roman I. Popov, Intel *****************************************************************************/ #include <systemc.h> #ifdef USE_PIMPL_ADDER #include "adder_int_5_pimpl.h" #else #include "adder.h" #endif const int TEST_SIZE = 10; template <typename T, int N_INPUTS> struct adder_tester : sc_module { sc_in<bool> SC_NAMED(clock); sc_in<bool> SC_NAMED(reset); sc_in<T> SC_NAMED(res); sc_vector<sc_out<T>> SC_NAMED(din, N_INPUTS); SC_CTOR(adder_tester){} private: // In-class initialization of SC_CTHREAD, second parameter is clock edge, // third parameter is arbitrary initialization code SC_CTHREAD_IMP(adder_tester_cthread, clock.pos(), { async_reset_signal_is(reset, true); } ) { wait(); for (int ii = 0; ii < TEST_SIZE; ++ii) { T ref_res = 0; for (int jj = 0; jj < N_INPUTS; ++jj) { T input = ii + jj; ref_res += input; din[jj] = input; } wait(); cout << "RES: " << res << " REFERENCE: " << ref_res << "\n"; sc_assert(res == ref_res); } sc_stop(); } }; template <typename T, int N_INPUTS> struct testbench : sc_module { sc_clock SC_NAMED(clock, 10, SC_NS); sc_signal<bool> SC_NAMED(reset); sc_signal<T> SC_NAMED(res); sc_vector<sc_signal<T>> SC_NAMED(din, N_INPUTS); SC_CTOR(testbench) {} private: // SC_NAMED_WITH_INIT allows to specify arbitrary initialization code after member declaration // for example you can bind module ports here adder_tester<T, N_INPUTS> SC_NAMED_WITH_INIT(tester_inst) { tester_inst.clock(clock); tester_inst.reset(reset); tester_inst.res(res); tester_inst.din(din); } #ifdef USE_PIMPL_ADDER adder_int_5_pimpl SC_NAMED_WITH_INIT(adder_inst) #else adder<T, N_INPUTS> SC_NAMED_WITH_INIT(adder_inst) #endif { adder_inst.res(res); adder_inst.din(din); } SC_THREAD_IMP(reset_thread, sensitive << clock.posedge_event();) { reset = 1; wait(); reset = 0; } }; int sc_main(int argc, char **argv) { testbench<int, 5> SC_NAMED(tb_inst); sc_start(); return 0; }
//This the top level structural host module //PS, dont forget to link systemc, stdc++, and m #include <systemc.h> #include "fir.h" #include "tb.h" SC_MODULE( SYSTEM ) { //module declarations //Done by doing module_name Pointer_to_instance i.e. name *iname; tb *tb0; fir *fir0; //signal declarations sc_signal<bool> rst_sig; sc_signal< sc_int<16> > inp_sig; sc_signal< sc_int<16> > outp_sig; sc_clock clk_sig; sc_signal<bool> inp_sig_vld; sc_signal<bool> inp_sig_rdy; sc_signal<bool> outp_sig_vld; sc_signal<bool> outp_sig_rdy; //module instance signal connections //There are three arguements //The first is a character pointer string and can be anything you want //The second is the number of units long the clock signal is //The third arguement is a sc_time_unit //SC_US is microsecond units //SC_NS is nanoseconds units //SC_PS is picoseconds units //This is a copy constructor the the clock class will generate a repetitive clock signal SC_CTOR( SYSTEM ) : clk_sig ("clk_sig_name", 10, SC_NS) { //Since these are SC_MODULES we need to pass the a charcter pointer string tb0 = new tb("tb0"); fir0 = new fir("fir0"); //Since these are pointers (new allocates memory and returns a pointer to the first // location in that memory) we can use the arrow style derefferencing operator to // specify a particular port and then bind it to a signal with parenthesis tb0->clk( clk_sig ); tb0->rst( rst_sig ); tb0->inp( inp_sig ); tb0->outp( outp_sig ); fir0->clk( clk_sig ); fir0->rst( rst_sig ); fir0->inp( inp_sig ); fir0->outp( outp_sig ); tb0->inp_sig_vld( inp_sig_vld ); tb0->inp_sig_rdy( inp_sig_rdy ); tb0->outp_sig_vld( outp_sig_vld ); tb0->outp_sig_rdy( outp_sig_rdy ); fir0->inp_sig_vld( inp_sig_vld ); fir0->inp_sig_rdy( inp_sig_rdy ); fir0->outp_sig_vld( outp_sig_vld ); fir0->outp_sig_rdy( outp_sig_rdy ); } //Destructor ~SYSTEM() { //free the memory up from the functions that are no longer needed delete tb0; delete fir0; } }; //Module declaration just like we did in main for fir and tb but we just assign at //instantiation time NULL, could have done this above as well SYSTEM *top = NULL; //Make it int in case the compiler requires it int sc_main( int argc, char *argv[]) { top = new SYSTEM( "top" ); sc_start(); return 0; } /* This is what you need to ad to your make file to auto check results GOLD_DIR = ./golden GOLD_FILE = $(GOLD_DIR)/ref_output.dat cmp_result: @echo "*******************************************************" @if diff -w $(GOLD_FILE) ./output.dat; then \ echo "SIMULAITON PASSED"; \ else \ echo "SIMULATION FAILED"; \ fi @echo "*******************************************************" */ /* * sc_time represents anything in systemc that can be measured in time units * */
/***************************************************************************** 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. *****************************************************************************/ /***************************************************************************** forkjoin.cpp -- Demo fork/join and dynamic thread creation Original Author: Stuart Swan, Cadence Design Systems, Inc., 2002-10-22 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Andy Goodrich, Forte Design Systems, 19 Aug 2003 Description of Modification: Modified to use 2.1 dynamic process support. *****************************************************************************/ #include <systemc.h> int test_function(double d) { cout << endl << "Test_function sees " << d << endl; return int(d); } void void_function(double d) { cout << endl << "void_function sees " << d << endl; } int ref_function(const double& d) { cout << endl << "ref_function sees " << d << endl; return int(d); } class top : public sc_module { public: top(sc_module_name name) : sc_module(name) { SC_THREAD(main); } void main() { int r; sc_event e1, e2, e3, e4; cout << endl; e1.notify(100, SC_NS); // Spawn several threads that co-operatively execute in round robin order SC_FORK sc_spawn(&r, sc_bind(&top::round_robin, this, "1", sc_ref(e1), sc_ref(e2), 3), "1") , sc_spawn(&r, sc_bind(&top::round_robin, this, "2", sc_ref(e2), sc_ref(e3), 3), "2") , sc_spawn(&r, sc_bind(&top::round_robin, this, "3", sc_ref(e3), sc_ref(e4), 3), "3") , sc_spawn(&r, sc_bind(&top::round_robin, this, "4", sc_ref(e4), sc_ref(e1), 3), "4") , SC_JOIN cout << "Returned int is " << r << endl; cout << endl << endl; // Test that threads in thread pool are successfully reused ... for (int i = 0 ; i < 10; i++) sc_spawn(&r, sc_bind(&top::wait_and_end, this, i)); wait(20, SC_NS); // Show how to use sc_spawn_options sc_spawn_options o; o.set_stack_size(0); // Demo of a function rather than method call, & use return value ... wait( sc_spawn(&r, sc_bind(&test_function, 3.14159)).terminated_event()); cout << "Returned int is " << r << endl; sc_process_handle handle1 = sc_spawn(sc_bind(&void_function, 1.2345)); wait(handle1.terminated_event()); double d = 9.8765; wait( sc_spawn(&r, sc_bind(&ref_function, sc_cref(d))).terminated_event() ); cout << "Returned int is " << r << endl; cout << endl << "Done." << endl; } int round_robin(const char *str, sc_event& receive, sc_event& send, int cnt) { while (--cnt >= 0) { wait(receive); cout << "Round robin thread " << str << " at time " << sc_time_stamp() << endl; wait(10, SC_NS); send.notify(); } return 0; } int wait_and_end(int i) { wait( i + 1, SC_NS); cout << "Thread " << i << " ending." << endl; return 0; } }; 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: vittoriano.muttillo@guest.univaq.it * * marco.santic@guest.univaq.it * * luigi.pomante@univaq.it * * * ******************************************************************************** * This code has been developed from an HEPSYCODE model used as demonstrator by * * University of L'Aquila. * *******************************************************************************/ #include <systemc.h> #include "../mainsystem.h" #include <math.h> #define cD_03_ANN_INPUTS 2 // Number of inputs #define cD_03_ANN_OUTPUTS 1 // Number of outputs //----------------------------------------------------------------------------- // Physical constants //----------------------------------------------------------------------------- static double cD_03_I_0 = 77.3 ; // [A] Nominal current static double cD_03_T_0 = 298.15 ; // [K] Ambient temperature static double cD_03_R_0 = 0.01 ; // [Ω] Data-sheet R_DS_On (Drain-Source resistance in the On State) static double cD_03_V_0 = 47.2 ; // [V] Nominal voltage static double cD_03_Alpha = 0.002 ; // [Ω/K] Temperature coefficient of Drain-Source resistance in the On State static double cD_03_ThermalConstant = 0.75 ; static double cD_03_Tau = 0.02 ; // [s] Sampling period //----------------------------------------------------------------------------- // Status descriptors //----------------------------------------------------------------------------- typedef struct cD_03_DEVICE // Descriptor of the state of the device { double t ; // Operating temperature double r ; // Operating Drain-Source resistance in the On State double i ; // Operating current double v ; // Operating voltage double time_Ex ; int fault ; } cD_03_DEVICE ; static cD_03_DEVICE cD_03_device; //----------------------------------------------------------------------------- // Mnemonics to access the array that contains the sampled data //----------------------------------------------------------------------------- #define cD_03_SAMPLE_LEN 3 // Array of SAMPLE_LEN elements #define cD_03_I_INDEX 0 // Current #define cD_03_V_INDEX 1 // Voltage #define cD_03_TIME_INDEX 2 // Time ///----------------------------------------------------------------------------- // Forward references //----------------------------------------------------------------------------- static int cD_03_initDescriptors(cD_03_DEVICE device) ; //static void getSample(int index, double sample[SAMPLE_LEN]) ; static void cD_03_cleanData(int index, double sample[cD_03_SAMPLE_LEN]) ; static double cD_03_extractFeatures(double tPrev, double iPrev, double iNow, double rPrev) ; static void cD_03_normalize(int index, double x[cD_03_ANN_INPUTS]) ; static double cD_03_degradationModel(double tNow) ; //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- int cD_03_initDescriptors(cD_03_DEVICE device) {HEPSY_S(cleanData_03_id) // for (int i = 0; i < NUM_DEV; i++) // { HEPSY_S(cleanData_03_id) device.t = cD_03_T_0 ; // Operating temperature = Ambient temperature HEPSY_S(cleanData_03_id) device.r = cD_03_R_0 ; // Operating R_DS_On = Data-sheet R_DS_On // printf("Init %d \n",i); // } HEPSY_S(cleanData_03_id) return( EXIT_SUCCESS ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void cD_03_cleanData(int index, double sample[cD_03_SAMPLE_LEN]) {HEPSY_S(cleanData_03_id) // the parameter "index" could be useful to retrieve the characteristics of the device HEPSY_S(cleanData_03_id) if ( sample[cD_03_I_INDEX] < 0 ) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) sample[cD_03_I_INDEX] = 0 ; HEPSY_S(cleanData_03_id)} else if ( sample[cD_03_I_INDEX] > (2.0 * cD_03_I_0) ) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) sample[cD_03_I_INDEX] = (2.0 * cD_03_I_0) ; // Postcondition: (0 <= sample[I_INDEX] <= 2.0*I_0) HEPSY_S(cleanData_03_id)} HEPSY_S(cleanData_03_id) if ( sample[cD_03_V_INDEX] < 0 ) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) sample[cD_03_V_INDEX] = 0 ; HEPSY_S(cleanData_03_id)} else if ( sample[cD_03_V_INDEX] > (2.0 * cD_03_V_0 ) ) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) sample[cD_03_V_INDEX] = (2.0 * cD_03_V_0) ; // Postcondition: (0 <= sample[V_INDEX] <= 2.0*V_0) HEPSY_S(cleanData_03_id)} } //----------------------------------------------------------------------------- // Input: // - tPrev = temperature at previous step // - iPrev = current at previous step // - iNow = current at this step // - rPrev = resistance at the previous step // Return: // - The new temperature // Very simple model: // - one constant for dissipation and heat capacity // - temperature considered constant during the step //----------------------------------------------------------------------------- double cD_03_extractFeatures(double tPrev, double iPrev, double iNow, double rPrev) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) double t ; // Temperature HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) double i = 0.5*(iPrev + iNow); // Average current // printf("cD_03_extractFeatures tPrev=%f\n",tPrev); HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) t = tPrev + // Previous temperature rPrev * (i * i) * cD_03_Tau - // Heat generated: P = I·R^2 cD_03_ThermalConstant * (tPrev - cD_03_T_0) * cD_03_Tau ; // Dissipation and heat capacity HEPSY_S(cleanData_03_id) return( t ); } //----------------------------------------------------------------------------- // Input: // - tNow: temperature at this step // Return: // - the resistance // The model isn't realistic because the even the simpler law is exponential //----------------------------------------------------------------------------- double cD_03_degradationModel(double tNow) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) double r ; //r = R_0 + Alpha * tNow ; HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) r = cD_03_R_0 * ( 2 - exp(-cD_03_Alpha*tNow) ); HEPSY_S(cleanData_03_id) return( r ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void cD_03_normalize(int index, double sample[cD_03_ANN_INPUTS]) {HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) double i ; double v ; // Precondition: (0 <= sample[I_INDEX] <= 2*I_0) && (0 <= sample[V_INDEX] <= 2*V_0) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) i = sample[cD_03_I_INDEX] <= cD_03_I_0 ? 0.0 : 1.0; HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) HEPSY_S(cleanData_03_id) v = sample[cD_03_V_INDEX] <= cD_03_V_0 ? 0.0 : 1.0; HEPSY_S(cleanData_03_id) // Postcondition: (i in {0.0, 1.0}) and (v in {0.0, 1.0}) HEPSY_S(cleanData_03_id) sample[cD_03_I_INDEX] = i ; HEPSY_S(cleanData_03_id) sample[cD_03_V_INDEX] = v ; } void mainsystem::cleanData_03_main() { // datatype for channels sampleTimCord_cleanData_xx_payload sampleTimCord_cleanData_xx_payload_var; cleanData_xx_ann_xx_payload cleanData_xx_ann_xx_payload_var; //device var uint8_t dev; //step var uint16_t step; // ex_time (for extractFeatures...) double ex_time; //samples i and v double sample_i; double sample_v; //var for samples, to re-use cleanData() double cD_03_sample[cD_03_SAMPLE_LEN] ; double x[cD_03_ANN_INPUTS + cD_03_ANN_OUTPUTS] ; // NOTE: commented, should be changed param by ref... //cD_03_initDescriptors(cD_03_device); HEPSY_S(cleanData_03_id) cD_03_device.t = cD_03_T_0 ; // Operating temperature = Ambient temperature HEPSY_S(cleanData_03_id) cD_03_device.r = cD_03_R_0 ; // Operating R_DS_On = Data-sheet R_DS_On // ### added for time related dynamics //static double cD_03_Tau = 0.02 ; // [s] Sampling period HEPSY_S(cleanData_03_id) double cD_03_last_sample_time = 0; //implementation HEPSY_S(cleanData_03_id) while(1) {HEPSY_S(cleanData_03_id) // content HEPSY_S(cleanData_03_id) sampleTimCord_cleanData_xx_payload_var = sampleTimCord_cleanData_03_channel->read(); HEPSY_S(cleanData_03_id) dev = sampleTimCord_cleanData_xx_payload_var.dev; HEPSY_S(cleanData_03_id) step = sampleTimCord_cleanData_xx_payload_var.step; HEPSY_S(cleanData_03_id) ex_time = sampleTimCord_cleanData_xx_payload_var.ex_time; HEPSY_S(cleanData_03_id) sample_i = sampleTimCord_cleanData_xx_payload_var.sample_i; HEPSY_S(cleanData_03_id) sample_v = sampleTimCord_cleanData_xx_payload_var.sample_v; // cout << "cleanData_03 rcv \t dev: " << dev // <<"\t step: " << step // <<"\t time_ex:" << ex_time // <<"\t i:" << sample_i // <<"\t v:" << sample_v // << endl; // reconstruct sample HEPSY_S(cleanData_03_id) cD_03_sample[cD_03_I_INDEX] = sample_i; HEPSY_S(cleanData_03_id) cD_03_sample[cD_03_V_INDEX] = sample_v; HEPSY_S(cleanData_03_id) cD_03_sample[cD_03_TIME_INDEX] = ex_time; // ### C L E A N D A T A (0 <= I <= 2.0*I_0) and (0 <= V <= 2.0*V_0) HEPSY_S(cleanData_03_id) cD_03_cleanData(dev, cD_03_sample) ; HEPSY_S(cleanData_03_id) cD_03_device.time_Ex = cD_03_sample[cD_03_TIME_INDEX] ; HEPSY_S(cleanData_03_id) cD_03_device.i = cD_03_sample[cD_03_I_INDEX] ; HEPSY_S(cleanData_03_id) cD_03_device.v = cD_03_sample[cD_03_V_INDEX] ; // ### added for time related dynamics //static double cD_03_Tau = 0.02 ; // [s] Sampling period HEPSY_S(cleanData_03_id) cD_03_Tau = ex_time - cD_03_last_sample_time; HEPSY_S(cleanData_03_id) cD_03_last_sample_time = ex_time; // ### F E A T U R E S E X T R A C T I O N (compute the temperature) HEPSY_S(cleanData_03_id) cD_03_device.t = cD_03_extractFeatures( cD_03_device.t, // Previous temperature cD_03_device.i, // Previous current cD_03_sample[cD_03_I_INDEX], // Current at this step cD_03_device.r) ; // Previous resistance // ### D E G R A D A T I O N M O D E L (compute R_DS_On) HEPSY_S(cleanData_03_id) cD_03_device.r = cD_03_degradationModel(cD_03_device.t) ; // ### N O R M A L I Z E: (x[0] in {0.0, 1.0}) and (x[1] in {0.0, 1.0}) HEPSY_S(cleanData_03_id) x[0] = cD_03_device.i ; HEPSY_S(cleanData_03_id) x[1] = cD_03_device.v ; HEPSY_S(cleanData_03_id) cD_03_normalize(dev, x) ; // // ### P R E D I C T (simple XOR) // if ( annRun(index, x) != EXIT_SUCCESS ){ //prepare out data payload HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.dev = dev; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.step = step; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.ex_time = ex_time; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.device_i = cD_03_device.i; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.device_v = cD_03_device.v; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.device_t = cD_03_device.t; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.device_r = cD_03_device.r; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.x_0 = x[0]; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.x_1 = x[1]; HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.x_2 = x[2]; HEPSY_S(cleanData_03_id) cleanData_03_ann_03_channel->write(cleanData_xx_ann_xx_payload_var); HEPSY_P(cleanData_03_id) } } //END
/******************************************************************************** * University of L'Aquila - HEPSYCODE Source Code License * * * * * * (c) 2018-2019 Centre of Excellence DEWS All rights reserved * ******************************************************************************** * <one line to give the program's name and a brief idea of what it does.> * * Copyright (C) 2022 Vittoriano Muttillo, Luigi Pomante * * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * ******************************************************************************** * * * Created on: 09/May/2023 * * Authors: Vittoriano Muttillo, Marco Santic, Luigi Pomante * * * * email: vittoriano.muttillo@guest.univaq.it * * marco.santic@guest.univaq.it * * luigi.pomante@univaq.it * * * ******************************************************************************** * This code has been developed from an HEPSYCODE model used as demonstrator by * * University of L'Aquila. * *******************************************************************************/ #include "display.h" #include <systemc.h> void display::main() { int i = 1; system_display_payload system_display_payload_var; /* //implementation while(1) { system_display_payload_var = system_display_port_in->read(); cout << "Display-" << i << "\t at time \t" << sc_time_stamp().to_seconds() << endl; i++; } */ //implementation while(i <= 100) { system_display_payload_var = system_display_port_in->read(); cout << "Display-" << i <<": \t" << "\t at time \t" << sc_time_stamp().to_seconds() << endl; i++; } sc_stop(); }
/***************************************************************************** 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 <pvs@circuitsutra.com> * @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
/* * @ASCK */ #include <systemc.h> SC_MODULE (ID) { sc_in_clk clk; sc_in <sc_int<8>> prev_A; sc_in <sc_int<8>> prev_B; sc_in <sc_int<13>> prev_Imm; sc_in <sc_uint<3>> prev_Sa; sc_in <sc_uint<5>> prev_AluOp; sc_in <bool> prev_r; sc_in <bool> prev_w; sc_in <bool> prev_AluMux; sc_in <bool> prev_WbMux; sc_in <bool> prev_call; sc_in <bool> prev_regWrite; sc_in <sc_uint<3>> prev_rd; sc_out <sc_int<8>> next_A; sc_out <sc_int<8>> next_B; sc_out <sc_int<13>> next_Imm; sc_out <sc_uint<3>> next_Sa; sc_out <sc_uint<5>> next_AluOp; sc_out <bool> next_r; sc_out <bool> next_w; sc_out <bool> next_AluMux; sc_out <bool> next_WbMux; sc_out <bool> next_call; sc_out <bool> next_regWrite; sc_out <sc_uint<3>> next_rd; /* ** module global variables */ SC_CTOR (ID){ SC_THREAD (process); sensitive << clk.pos(); } void process () { while(true){ wait(); if(now_is_call){ wait(micro_acc_ev); } next_A.write(prev_A.read()); next_B.write(prev_B.read()); next_Imm.write(prev_Imm.read()); next_Sa.write(prev_Sa.read()); next_AluOp.write(prev_AluOp.read()); next_AluMux.write(prev_AluMux.read()); next_r.write(prev_r.read()); next_w.write(prev_w.read()); next_WbMux.write(prev_WbMux.read()); next_call.write(prev_call.read()); next_regWrite.write(prev_regWrite); next_rd.write(prev_rd.read()); } } };
/** #define meta ... prInt32f("%s\n", meta); **/ /* All rights reserved to Alireza Poshtkohi (c) 1999-2023. Email: arp@poshtkohi.info 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; } //---------------------------------------
#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 }
// //------------------------------------------------------------// // Copyright 2009-2012 Mentor Graphics Corporation // // All Rights Reserved Worldwid // // // // Licensed under the Apache License, Version 2.0 (the // // "License"); you may not use this file except in // // compliance with the License. You may obtain a copy of // // the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in // // writing, software distributed under the License is // // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // // CONDITIONS OF ANY KIND, either express or implied. See // // the License for the specific language governing // // permissions and limitations under the License. // //------------------------------------------------------------// #ifndef PACKET_H #define PACKET_H #include <vector> using std::vector; #include <systemc.h> #include <tlm.h> using namespace sc_core; class packet { public: short cmd; int addr; vector<char> data; }; //------------------------------------------------------------------------------ // Begin UVMC-specific code #include "uvmc.h" using namespace uvmc; UVMC_UTILS_3 (packet,cmd,addr,data) #endif // PACKET_H
/******************************************************************************* * gpio_mfmix.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_mfmix.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_mfmix::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 && !anaok) { PRINTF_WARN("GPIOMFMIX", "%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("GPIOMFMIX", "%s set to GPIO mode", name()) function = newfunction; driveok = true; /* set_val() handles the driver. */ gpio_base::set_val(pinval); } /* Analog drives the pin to nothing. */ else if (newfunction == GPIOMF_ANALOG) { /* This set_mode is an elegance thing, it might not be necessary. */ set_mode(GPIOMODE_NONE); PRINTF_INFO("GPIOMFMIX", "%s set to ANALOG", name()) function = GPIOMF_ANALOG; driveok = false; } /* And with the multi function we let the drive_func handle the settings. */ else { PRINTF_INFO("GPIOMFMIX", "%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_mfmix::get_function() { return function; } /********************* * Thread: drive_return() * inputs: none * outputs: none * returns: none * globals: none * * Drives the return path from the pin onto the alternate functions. */ void gpio_mfmix::drive_return() { gn_mixed 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 (pinsamp.logic.to_char() == 'X') printf(">%s : %s : %d/%d %c-\n", name(), sc_time_stamp().to_string().c_str(), pin.default_event().triggered(), updatereturn.triggered(), pinsamp.to_char()); /* 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 == GN_LOGIC_A || pinsamp == GN_LOGIC_X || pinsamp == GN_LOGIC_Z) && function != GPIOMF_ANALOG && function != GPIOMF_GPIO) { retval = false; PRINTF_WARN("GPIOMFMIX", "can't return '%c' onto FUNC%d", pinsamp.to_char(), function) } else if (pinsamp == GN_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_mfmix::drive_func() { for(;;) { /* We only use this thread if we have an alternate function selected. */ if (function != GPIOMF_GPIO && function != GPIOMF_ANALOG && 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_ANALOG || 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()); } }
#ifndef PACKET_GENERATOR_TLM_CPP #define PACKET_GENERATOR_TLM_CPP #include <systemc.h> using namespace sc_core; using namespace sc_dt; using namespace std; #include <tlm.h> #include <tlm_utils/simple_initiator_socket.h> #include <tlm_utils/simple_target_socket.h> #include <tlm_utils/peq_with_cb_and_phase.h> #include "packetGenerator_tlm.hpp" #include "common_func.hpp" #include "address_map.hpp" void packetGenerator_tlm::do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address){ dbgimgtarmodprint(use_prints, "Called do_when_read_transaction with an address %016llX and length %d", address, data_length); if ((address >= IMG_OUTPUT_SIZE + IMG_OUTPUT_SIZE_SIZE + IMG_OUTPUT_DONE_SIZE) && (address < IMG_OUTPUT_SIZE + IMG_OUTPUT_SIZE_SIZE + IMG_OUTPUT_DONE_SIZE + IMG_OUTPUT_STATUS_SIZE)) { if (packetGenerator::tmp_data_out_valid == true) { *data = 1; dbgimgtarmodprint(true, "Ethernet module still sending data, remaining bytes to send %0d", actual_data_length); } else { *data = 0; } } else { *data = 0; } } void packetGenerator_tlm::do_when_write_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address) { dbgimgtarmodprint(use_prints, "Called do_when_write_transaction with an address %016llX and length %d", address, data_length); if (address < IMG_OUTPUT_SIZE) { memcpy(tmp_data + address, data, data_length); } else if ((address >= IMG_OUTPUT_SIZE) && (address < IMG_OUTPUT_SIZE + IMG_OUTPUT_SIZE_SIZE)) { unsigned char *data_length_ptr = (unsigned char *)&tmp_data_length; memcpy(data_length_ptr + address - IMG_OUTPUT_SIZE, data, data_length); dbgimgtarmodprint(true, "Current data_length %0d", tmp_data_length); } else if ((address >= IMG_OUTPUT_SIZE + IMG_OUTPUT_SIZE_SIZE) && (address < IMG_OUTPUT_SIZE + IMG_OUTPUT_SIZE_SIZE + IMG_OUTPUT_DONE_SIZE) && (*data == 1)) { if (tmp_data_length == 0) { *(tmp_data) = 0; tmp_data_length = 1; } dbgimgtarmodprint(true, "Preparing to send %0d bytes", tmp_data_length); fill_data(tmp_data, (int)tmp_data_length); tmp_data_length = 0; } } //Backdoor write/read for debug purposes void packetGenerator_tlm::backdoor_write(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address) { sc_dt::uint64 local_address = address - IMG_OUTPUT_ADDRESS_LO; memcpy((tmp_data + local_address), data, data_length); for (int i = 0; (i < 10) && (local_address + i < IMG_OUTPUT_SIZE); i++) { dbgimgtarmodprint(true, "Backdoor Writing: %0d\n", *(tmp_data + local_address + i)); } } void packetGenerator_tlm::backdoor_read(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address) { sc_dt::uint64 local_address = address - IMG_OUTPUT_ADDRESS_LO; data = new unsigned char[data_length]; memcpy(data, (tmp_data + local_address), data_length); for (int i = 0; (i < 10) && (local_address + i < IMG_OUTPUT_SIZE); i++) { dbgimgtarmodprint(true, "Backdoor Reading: %0d\n", *(tmp_data + local_address + i)); } } #endif // PACKET_GENERATOR_TLM_CPP
#include <memory> #include <systemc.h> #include "sc_top.h" int sc_main(int argc, char* argv[]) { if (false && argc && argv) {} Verilated::debug(0); Verilated::randReset(2); Verilated::commandArgs(argc, argv); ios::sync_with_stdio(); const std::unique_ptr<sc_top> u_sc_top{new sc_top("sc_top")}; sc_start(); cout << "done, time = " << sc_time_stamp() << endl; return 0; } #ifdef VL_USER_STOP void vl_stop(const char *filename, int linenum, const char *hier) VL_MT_UNSAFE { sc_stop(); cout << "call vl_stop" << endl; } #endif
/******************************************************************************* * 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(); } }
/******************************************************************************* * tb_gpio.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Testbench for the GPIO models. ******************************************************************************* * 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 "tb_gpio.h" #include "info.h" void tb_gpio::expect(const char *name, bool a, sc_logic v) { if (a != v) PRINTF_WARN("TEST", "Expected %s to be %c but got %c", name, v.to_char(), (a)?'1':'0') else PRINTF_INFO("TEST", "SUCCESS: got %s to be %c", name, v.to_char()); } void tb_gpio::expect(const char *name, sc_logic a, sc_logic v) { if (a != v) PRINTF_WARN("TEST", "Expected %s to be %c but got %c", name, v.to_char(), a.to_char()) else PRINTF_INFO("TEST", "SUCCESS: got %s to be %c", name, v.to_char()); } void tb_gpio::expect(const char *name, gn_mixed a, sc_logic v) { if (a != v) PRINTF_WARN("TEST", "Expected %s to be %c but got %c", name, v.to_char(), a.to_char()) else PRINTF_INFO("TEST", "SUCCESS: got %s to be %c", name, v.to_char()); } void tb_gpio::expectfunc(const char *name, int a, int v) { if (a != v) PRINTF_WARN("TEST", "Expected %s to be Function %d but got %c",name,v,a) else PRINTF_INFO("TEST", "SUCCESS: got %s to be Function %d", name, v); } void tb_gpio::t0(void) { wait(SC_ZERO_TIME); /* We start off checking the pins. */ expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_Z); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_Z); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_Z); expect(pin3.name(), pin3.read(), SC_LOGIC_Z); expectfunc(i_gpio.name(), i_gpio.get_function(), GPIOMF_GPIO); expectfunc(i_gpio_mix.name(), i_gpio_mix.get_function(), GPIOMF_GPIO); expectfunc(i_gpio_mfmix.name(), i_gpio_mfmix.get_function(), GPIOMF_GPIO); expectfunc(i_gpio_mf.name(), i_gpio_mf.get_function(), GPIOMF_GPIO); /* We now change the GPIOs to be Output and check the outputs. */ wait(10, SC_NS); printf("\n\n**** Changing GPIOs to Output ****\n"); i_gpio.set_dir(GPIODIR_OUTPUT); i_gpio_mix.set_dir(GPIODIR_OUTPUT); i_gpio_mfmix.set_dir(GPIODIR_OUTPUT); i_gpio_mf.set_dir(GPIODIR_OUTPUT); wait(SC_ZERO_TIME); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_0); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_0); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_0); expect(pin3.name(), pin3.read(), SC_LOGIC_0); /* We drive something and check it. */ wait(10, SC_NS); i_gpio.set_val(true); i_gpio_mix.set_val(true); i_gpio_mfmix.set_val(true); i_gpio_mf.set_val(true); wait(SC_ZERO_TIME); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_1); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_1); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_1); expect(pin3.name(), pin3.read(), SC_LOGIC_1); /* We change them to WPU or OD and recheck it. */ printf("\n\n**** Checking weak pull-up/OD ****\n"); i_gpio.set_wpu(); i_gpio_mix.set_od(); i_gpio_mfmix.set_wpu(); i_gpio_mf.set_wpu(); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_Z); /* WPU but looks like Z */ expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_Z); /* OD */ expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_1); /* WPU */ expect(pin3.name(), pin3.read(), SC_LOGIC_Z); /* WPU but looks like Z */ /* And we go low. */ i_gpio.set_val(false); i_gpio_mix.set_val(false); i_gpio_mfmix.set_val(false); i_gpio_mf.set_val(false); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_0); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_0); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_0); expect(pin3.name(), pin3.read(), SC_LOGIC_0); /* Now we switch the OD and WPU pins and try it again. */ printf("\n\n**** Switching weak pull-up and OD ****\n"); i_gpio.set_val(true); i_gpio_mix.set_val(true); i_gpio_mfmix.set_val(true); i_gpio_mf.set_val(true); i_gpio.clr_wpu(); i_gpio.set_od(); i_gpio_mix.clr_od(); i_gpio_mix.set_wpu(); i_gpio_mfmix.clr_wpu(); i_gpio_mfmix.set_od(); i_gpio_mf.clr_wpu(); i_gpio_mf.set_od(); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_Z); /* OD */ expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_1); /* WPU */ expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_Z); /* OD */ expect(pin3.name(), pin3.read(), SC_LOGIC_Z); /* OD */ /* And we go low again. */ i_gpio.set_val(false); i_gpio_mix.set_val(false); i_gpio_mfmix.set_val(false); i_gpio_mf.set_val(false); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_0); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_0); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_0); expect(pin3.name(), pin3.read(), SC_LOGIC_0); /* Now we go with a weak pull-down. */ printf("\n\n**** Checking weak pull-down ****\n"); i_gpio.set_wpd(); i_gpio.clr_od(); i_gpio_mix.set_wpd(); i_gpio_mix.clr_wpu(); i_gpio_mfmix.set_wpd(); i_gpio_mfmix.clr_od(); i_gpio_mf.set_wpd(); i_gpio_mf.clr_od(); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_Z); /* WPD but looks like Z */ expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_0); /* WPD */ expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_0); /* WPD */ expect(pin3.name(), pin3.read(), SC_LOGIC_Z); /* WPD but looks like Z */ /* And we raise the signals. */ i_gpio.set_val(true); i_gpio_mix.set_val(true); i_gpio_mfmix.set_val(true); i_gpio_mf.set_val(true); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_1); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_1); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_1); expect(pin3.name(), pin3.read(), SC_LOGIC_1); /* Now we go with a weak pull-down. */ i_gpio.set_val(false); i_gpio_mix.set_val(false); i_gpio_mfmix.set_val(false); i_gpio_mf.set_val(false); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_Z); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_0); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_0); expect(pin3.name(), pin3.read(), SC_LOGIC_Z); /* And we shut off the pull downs. */ i_gpio.clr_wpd(); i_gpio_mix.clr_wpd(); i_gpio_mfmix.clr_wpd(); i_gpio_mf.clr_wpd(); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_0); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_0); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_0); expect(pin3.name(), pin3.read(), SC_LOGIC_0); /* Now we go to GPIO In */ printf("\n\n**** Changing GPIOs to Input ****\n"); pin1.write(SC_LOGIC_1); pin_a1.write(SC_LOGIC_0); pin_a2.write(SC_LOGIC_1); pin3.write(SC_LOGIC_0); i_gpio.set_dir(GPIODIR_INPUT); i_gpio_mix.set_dir(GPIODIR_INPUT); i_gpio_mfmix.set_dir(GPIODIR_INPUT); i_gpio_mf.set_dir(GPIODIR_INPUT); wait(10, SC_NS); expect(i_gpio.name(), i_gpio.get_val(), SC_LOGIC_1); expect(i_gpio_mix.name(), i_gpio_mix.get_val(), SC_LOGIC_0); expect(i_gpio_mfmix.name(), i_gpio_mfmix.get_val(), SC_LOGIC_1); expect(i_gpio_mf.name(), i_gpio_mf.get_val(), SC_LOGIC_0); pin1.write(SC_LOGIC_0); pin_a1.write(SC_LOGIC_1); pin_a2.write(SC_LOGIC_0); pin3.write(SC_LOGIC_1); wait(10, SC_NS); expect(pin1.name(), i_gpio.get_val(), SC_LOGIC_0); expect(pin_a1.name(), i_gpio_mix.get_val(), SC_LOGIC_1); expect(pin_a2.name(), i_gpio_mfmix.get_val(), SC_LOGIC_0); expect(pin3.name(), i_gpio_mf.get_val(), SC_LOGIC_1); /* These one should still be low as the function was not selected. */ expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); /* Now we change values. */ printf("\n\n**** Changing GPIOs to I/O ****\n"); pin1.write(SC_LOGIC_1); pin_a1.write(SC_LOGIC_0); pin_a2.write(SC_LOGIC_1); pin3.write(SC_LOGIC_0); i_gpio.set_dir(GPIODIR_INOUT); i_gpio.set_val(true); i_gpio_mix.set_dir(GPIODIR_INOUT); i_gpio_mix.set_val(true); i_gpio_mfmix.set_dir(GPIODIR_INOUT); i_gpio_mfmix.set_val(true); i_gpio_mf.set_dir(GPIODIR_INOUT); i_gpio_mf.set_val(true); wait(10, SC_NS); expect(pin1.name(), pin1, SC_LOGIC_1); expect(pin_a1.name(), pin_a1, SC_LOGIC_X); expect(pin_a2.name(), pin_a2, SC_LOGIC_1); /* It was high. */ expect(pin3.name(), pin3, SC_LOGIC_X); pin1.write(SC_LOGIC_Z); pin_a1.write(SC_LOGIC_Z); pin_a2.write(SC_LOGIC_Z); pin3.write(SC_LOGIC_Z); wait(10, SC_NS); expect(pin1.name(), pin1, sc_logic(i_gpio.get_val())); expect(pin_a1.name(), pin_a1, sc_logic(i_gpio.get_val())); expect(pin_a2.name(), pin_a2, sc_logic(i_gpio.get_val())); expect(pin3.name(), pin3, sc_logic(i_gpio.get_val())); /* Now we change the modes. */ printf("\n\n**** Function ANALOG ****\n"); i_gpio_mix.set_function(GPIOMF_ANALOG); i_gpio_mfmix.set_function(GPIOMF_ANALOG); wait(10, SC_NS); expect(pin1.name(), pin1, sc_logic(i_gpio.get_val())); expect(pin_a1.name(), pin_a1, SC_LOGIC_Z); expect(pin_a2.name(), pin_a2, SC_LOGIC_Z); expect(f1out.name(), f1out, SC_LOGIC_0); expect(f2out.name(), f2out, SC_LOGIC_0); printf("\n\n**** Funtion GPIO ****\n"); /* We drive all functions high and the internal values low and check * that the pins follow signal. */ i_gpio_mfmix.set_function(GPIOMF_GPIO); i_gpio_mfmix.set_dir(GPIODIR_INOUT); i_gpio_mfmix.set_val(false); i_gpio_mf.set_function(GPIOMF_GPIO); i_gpio_mf.set_dir(GPIODIR_INOUT); i_gpio_mf.set_val(false); f1in.write(true); f1en.write(true); f2in.write(true); f2en.write(true); f3in.write(true); f3en.write(true); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_0); expect(f1out.name(), f1out, SC_LOGIC_0); expect(f2out.name(), f2out, SC_LOGIC_0); expect(pin3.name(), pin3, SC_LOGIC_0); expect(f3out.name(), f3out, SC_LOGIC_0); /* We toggle a bit more the pins */ f2in.write(false); f2en.write(true); f3in.write(false); f3en.write(true); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_0); expect(f1out.name(), f1out, SC_LOGIC_0); expect(f2out.name(), f2out, SC_LOGIC_0); expect(pin3.name(), pin3, SC_LOGIC_0); expect(f3out.name(), f3out, SC_LOGIC_0); printf("\n\n**** Funtion 1 ****\n"); /* We now switch to function 1 and check that the functions are passed * through. */ i_gpio_mfmix.set_function(1); i_gpio_mf.set_function(1); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_1); expect(f1out.name(), f1out, SC_LOGIC_1); expect(f2out.name(), f2out, SC_LOGIC_0); expect(pin3.name(), pin3, SC_LOGIC_0); expect(f3out.name(), f3out, SC_LOGIC_0); f2in.write(true); f2en.write(true); f3in.write(true); f3en.write(true); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_1); expect(f1out.name(), f1out, SC_LOGIC_1); expect(f2out.name(), f2out, SC_LOGIC_0); expect(f3out.name(), f3out, SC_LOGIC_1); f2in.write(false); f2en.write(true); f3in.write(true); f3en.write(false); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_1); expect(pin3.name(), pin3, SC_LOGIC_Z); expect(f1out.name(), f1out, SC_LOGIC_1); expect(f2out.name(), f2out, SC_LOGIC_0); expect(f3out.name(), f3out, SC_LOGIC_0); /* Z can't be put on wire f3out.*/ printf("\n\n**** Funtion 2 ****\n"); i_gpio_mfmix.set_function(2); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_0); expect(f1out.name(), f1out, SC_LOGIC_0); expect(f2out.name(), f2out, SC_LOGIC_0); f2in.write(true); f2en.write(false); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_Z); expect(f1out.name(), f1out, SC_LOGIC_0); expect(f2out.name(), f2out, SC_LOGIC_0); f2in.write(true); f2en.write(true); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_1); expect(f1out.name(), f1out, SC_LOGIC_0); expect(f2out.name(), f2out, SC_LOGIC_1); } void tb_gpio::testbench(void) { /* Now we check the test case and run the correct TB. */ PRINTF_INFO("TEST", "Starting Testbench Test%d", tn); if (tn == 0) t0(); else SC_REPORT_FATAL("TEST", "Test number too large."); sc_stop(); } void tb_gpio::trace(sc_trace_file *tf) { sc_trace(tf, pin1, pin1.name()); sc_trace(tf, pin_a1, pin_a1.name()); sc_trace(tf, pin_a2, pin_a2.name()); sc_trace(tf, pin3, pin3.name()); sc_trace(tf, f1in, f1in.name()); sc_trace(tf, f1en, f1en.name()); sc_trace(tf, f1out, f1out.name()); sc_trace(tf, f2in, f2in.name()); sc_trace(tf, f2en, f2en.name()); sc_trace(tf, f2out, f2out.name()); sc_trace(tf, f3in, f3in.name()); sc_trace(tf, f3en, f3en.name()); sc_trace(tf, f3out, f3out.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: 09/May/2023 * * Authors: Vittoriano Muttillo, Marco Santic, Luigi Pomante * * * * email: vittoriano.muttillo@guest.univaq.it * * marco.santic@guest.univaq.it * * luigi.pomante@univaq.it * * * ******************************************************************************** * This code has been developed from an HEPSYCODE model used as demonstrator by * * University of L'Aquila. * *******************************************************************************/ #include <systemc.h> #include "../mainsystem.h" #include <math.h> #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
/******************************************************************************* * clkgen.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Emulates the clocks on the ESP32. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "Arduino.h" #include "clkgen.h" void clkgen::gen() { bool lvl = false; while(true) { apb_clk.write(lvl); lvl = !lvl; del1cycle(); } }
/** * 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; } };
/* * Created on: 21. jun. 2019 * Author: Jonathan Horsted Schougaard */ #ifdef HW_COSIM //#define __GMP_WITHIN_CONFIGURE #endif #define DEBUG_SYSTEMC #define SC_INCLUDE_FX #include "hwcore/tb/cnn/tb_pe.hpp" #include <systemc.h> unsigned errors = 0; const char simulation_name[] = "tb_pe"; int sc_main(int argc, char *argv[]) { cout << "INFO: Elaborating " << simulation_name << endl; sc_core::sc_report_handler::set_actions("/IEEE_Std_1666/deprecated", sc_core::SC_DO_NOTHING); sc_report_handler::set_actions(SC_ID_LOGIC_X_TO_BOOL_, SC_LOG); sc_report_handler::set_actions(SC_ID_VECTOR_CONTAINS_LOGIC_VALUE_, SC_LOG); // sc_report_handler::set_actions( SC_ID_OBJECT_EXISTS_, SC_LOG); // sc_set_time_resolution(1,SC_PS); // sc_set_default_time_unit(1,SC_NS); // ModuleSingle modulesingle("modulesingle_i"); return 0; tb_pe<sizeof(int) * 8, sizeof(int) * 4, 1> tb_01("tb_pe"); cout << "INFO: Simulating " << simulation_name << endl; sc_time time_out(1000, SC_US); sc_start(time_out); return errors ? 1 : 0; cout << "INFO: end time is: " << sc_time_stamp().to_string() << ", and max time is: " << time_out.to_string() << std::endl << std::flush; sc_assert(sc_time_stamp() != time_out); cout << "INFO: Post-processing " << simulation_name << endl; cout << "INFO: Simulation " << simulation_name << " " << (errors ? "FAILED" : "PASSED") << " with " << errors << " errors" << std::endl << std::flush; #ifdef __RTL_SIMULATION__ cout << "HW cosim done" << endl; #endif return errors ? 1 : 0; } // test2
#include "systemc.h" /* multi line comment */ // declare some module SC_MODULE(gate) { // inputs sc_in<bool> inA, inB; // outputs sc_out<bool> out; // C function void do_something() { out.write(inA.read() || inB.read()); } // constructor SC_CTOR(gate) { // register method SC_METHOD(do_something); } };
/***************************************************************************** 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. *****************************************************************************/ /***************************************************************************** forkjoin.cpp -- Demo fork/join and dynamic thread creation Original Author: Stuart Swan, Cadence Design Systems, Inc., 2002-10-22 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Andy Goodrich, Forte Design Systems, 19 Aug 2003 Description of Modification: Modified to use 2.1 dynamic process support. *****************************************************************************/ #include <systemc.h> int test_function(double d) { cout << endl << "Test_function sees " << d << endl; return int(d); } void void_function(double d) { cout << endl << "void_function sees " << d << endl; } int ref_function(const double& d) { cout << endl << "ref_function sees " << d << endl; return int(d); } class top : public sc_module { public: top(sc_module_name name) : sc_module(name) { SC_THREAD(main); } void main() { int r; sc_event e1, e2, e3, e4; cout << endl; e1.notify(100, SC_NS); // Spawn several threads that co-operatively execute in round robin order SC_FORK sc_spawn(&r, sc_bind(&top::round_robin, this, "1", sc_ref(e1), sc_ref(e2), 3), "1") , sc_spawn(&r, sc_bind(&top::round_robin, this, "2", sc_ref(e2), sc_ref(e3), 3), "2") , sc_spawn(&r, sc_bind(&top::round_robin, this, "3", sc_ref(e3), sc_ref(e4), 3), "3") , sc_spawn(&r, sc_bind(&top::round_robin, this, "4", sc_ref(e4), sc_ref(e1), 3), "4") , SC_JOIN cout << "Returned int is " << r << endl; cout << endl << endl; // Test that threads in thread pool are successfully reused ... for (int i = 0 ; i < 10; i++) sc_spawn(&r, sc_bind(&top::wait_and_end, this, i)); wait(20, SC_NS); // Show how to use sc_spawn_options sc_spawn_options o; o.set_stack_size(0); // Demo of a function rather than method call, & use return value ... wait( sc_spawn(&r, sc_bind(&test_function, 3.14159)).terminated_event()); cout << "Returned int is " << r << endl; sc_process_handle handle1 = sc_spawn(sc_bind(&void_function, 1.2345)); wait(handle1.terminated_event()); double d = 9.8765; wait( sc_spawn(&r, sc_bind(&ref_function, sc_cref(d))).terminated_event() ); cout << "Returned int is " << r << endl; cout << endl << "Done." << endl; } int round_robin(const char *str, sc_event& receive, sc_event& send, int cnt) { while (--cnt >= 0) { wait(receive); cout << "Round robin thread " << str << " at time " << sc_time_stamp() << endl; wait(10, SC_NS); send.notify(); } return 0; } int wait_and_end(int i) { wait( i + 1, SC_NS); cout << "Thread " << i << " ending." << endl; return 0; } }; int sc_main (int, char*[]) { top top1("Top1"); sc_start(); return 0; }
#include <systemc.h> #include "Producer.h" #include "Consumer.h" int sc_main(int argc, char* argv[]) { // generating the sc_signal sc_signal<int> data_sig; // generating the modules Producer prod1("Producer1"); Consumer cons1("Consumer1"); // connecting modules via signals prod1.data(data_sig); cons1.data(data_sig); // Run the simulation till sc_stop is encountered sc_start(); return 0; }
#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
#include <systemc.h> SC_MODULE (hello_world) { SC_CTOR (hello_world) { } void say_hello() { cout << "Hello World SystemC-2.3.1.\n"; } }; int sc_main(int argc, char* argv[]) { hello_world hello("HELLO"); hello.say_hello(); return(0); }
#ifndef SOBEL_EDGE_DETECTOR_TLM_CPP #define SOBEL_EDGE_DETECTOR_TLM_CPP #include <systemc.h> using namespace sc_core; using namespace sc_dt; using namespace std; #include <tlm.h> #include "sobel_edge_detector_tlm.hpp" #include "address_map.hpp" #include "common_func.hpp" void sobel_edge_detector_tlm::do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address){ unsigned char sobel_results; unsigned char* sobel_results_ptr; sc_uint<8> local_result; dbgimgtarmodprint(use_prints, "Called do_when_read_transaction with an address %016llX and length %d", address, data_length); if ((address >= (SOBEL_INPUT_0_SIZE + SOBEL_INPUT_1_SIZE)) && (address < (SOBEL_INPUT_0_SIZE + SOBEL_INPUT_1_SIZE + SOBEL_OUTPUT_SIZE))) { Edge_Detector::address = address + SOBEL_INPUT_0_ADDRESS_LO; read(); for (int i = 0; i < data_length; i++) { local_result = Edge_Detector::data.range((i + 1) * 8 - 1, i * 8); sobel_results = (unsigned char)local_result; sobel_results_ptr = &sobel_results; memcpy((data + i), sobel_results_ptr, sizeof(char)); // dbgimgtarmodprint(use_prints, "Results on sobel read %01X", sobel_results); } dbgimgtarmodprint(true, "Returning gradient results, X gradient %0d Y gradient %0d", Edge_Detector::data.range(15, 0).to_int(), Edge_Detector::data.range(32, 16).to_int()); } else { sobel_results = 0; sobel_results_ptr = &sobel_results; for (int i =0; i < data_length; i++) { memcpy((data + i), sobel_results_ptr, sizeof(char)); // dbgimgtarmodprint(use_prints, "Results on sobel read %01X", sobel_results); } } } void sobel_edge_detector_tlm::do_when_write_transaction(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address) { dbgimgtarmodprint(use_prints, "Called do_when_write_transaction with an address %016llX and length %d", address, data_length); if (address < (SOBEL_INPUT_0_SIZE + SOBEL_INPUT_1_SIZE)) { if (address < SOBEL_INPUT_0_SIZE) { for (int i = 0; i < data_length; i++) { this->sobel_input[address + i] = *(data + i); } } else if (SOBEL_INPUT_0_SIZE <= address && address < SOBEL_INPUT_0_SIZE + SOBEL_INPUT_1_SIZE) { for (int i = 0; i < data_length; i++) { this->sobel_input[address + i - SOBEL_INPUT_0_SIZE] = *(data + i); } dbgimgtarmodprint(true, "Got full window, will compute sobel gradients"); } Edge_Detector::data = (this->sobel_input[7], this->sobel_input[6], this->sobel_input[5], this->sobel_input[4], this->sobel_input[3], this->sobel_input[2], this->sobel_input[1], this->sobel_input[0]); Edge_Detector::address = address + SOBEL_INPUT_0_ADDRESS_LO; write(); } } void sobel_edge_detector_tlm::read() { Edge_Detector::data = (sc_uint<32>(0), resultSobelGradientY, resultSobelGradientX); Edge_Detector::data = Edge_Detector::data >> ((Edge_Detector::address - SOBEL_OUTPUT_ADDRESS_LO) * 8); } void sobel_edge_detector_tlm::write() { wr_t.notify(0, SC_NS); } void sobel_edge_detector_tlm::wr() { while(1) { Edge_Detector::wait(wr_t); if ((Edge_Detector::address >= SOBEL_INPUT_0_ADDRESS_LO) && (Edge_Detector::address < SOBEL_INPUT_0_ADDRESS_HI)) { int j = 0; localWindow[0][0] = Edge_Detector::data.range((j + 1) * 8 - 1, j * 8); j++; localWindow[0][1] = Edge_Detector::data.range((j + 1) * 8 - 1, j * 8); j++; localWindow[0][2] = Edge_Detector::data.range((j + 1) * 8 - 1, j * 8); j++; localWindow[1][0] = Edge_Detector::data.range((j + 1) * 8 - 1, j * 8); j++; localWindow[1][1] = Edge_Detector::data.range((j + 1) * 8 - 1, j * 8); j++; localWindow[1][2] = Edge_Detector::data.range((j + 1) * 8 - 1, j * 8); j++; localWindow[2][0] = Edge_Detector::data.range((j + 1) * 8 - 1, j * 8); j++; localWindow[2][1] = Edge_Detector::data.range((j + 1) * 8 - 1, j * 8); gotLocalWindow.notify(0, SC_NS); } else if ((Edge_Detector::address >= SOBEL_INPUT_1_ADDRESS_LO) && (Edge_Detector::address < SOBEL_INPUT_1_ADDRESS_HI)) { localWindow[2][2] = data.range(7, 0); gotLocalWindow.notify(0, SC_NS); } } } #endif // SOBEL_EDGE_DETECTOR_TLM_CPP
/****************************************************** * This is the main file for the mips1 ArchC model * * This file is automatically generated by ArchC * * WITHOUT WARRANTY OF ANY KIND, either express * * or implied. * * For more information on ArchC, please visit: * * http://www.archc.org * * * * The ArchC Team * * Computer Systems Laboratory (LSC) * * IC-UNICAMP * * http://www.lsc.ic.unicamp.br * ******************************************************/ // Rodolfo editou aqui // const char *project_name="mips"; const char *project_file="mips1.ac"; const char *archc_version="2.0beta1"; const char *archc_options="-abi -dy "; #include <systemc.h> #include <stdlib.h> #include "mips.H" #include "memory.h" #include "peripheral.h" #include "bus.h" int sc_main(int ac, char *av[]) { int ac2 = ac; char** av2 = (char **) malloc((ac+1) * sizeof (*av2)); for(int i = 0; i < ac; ++i) { size_t length = strlen(av[i])+1; av2[i] = (char *) malloc(length); memcpy(av2[i], av[i], length); } av2[ac] = NULL; //! ISA simulator mips mips_proc1("mips1"); mips mips_proc2("mips2"); //! Bus ac_tlm_bus bus("bus"); // Memory ac_tlm_mem mem("mem"); // Peripheral ac_tlm_peripheral peripheral("peripheral"); #ifdef AC_DEBUG ac_trace("mips1_proc1.trace"); #endif mips_proc1.DM(bus.target_export); mips_proc2.DM(bus.target_export); bus.MEM_port(mem.target_export); bus.PERIPHERAL_port(peripheral.target_export); mips_proc1.init(ac, av); mips_proc1.set_prog_args(); cerr << endl; mips_proc2.init(ac2, av2); mips_proc2.set_prog_args(); cerr << endl; sc_start(); mips_proc1.PrintStat(); mips_proc2.PrintStat(); cerr << endl; #ifdef AC_STATS mips1_proc1.ac_sim_stats.time = sc_simulation_time(); mips1_proc1.ac_sim_stats.print(); #endif #ifdef AC_DEBUG ac_close_trace(); #endif return mips_proc1.ac_exit_status; }
/* * main.cpp * * Created on: 18 de abr de 2017 * Author: vieira */ #include <systemc.h> int sc_main(int argc, char* argv[]){ 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> #include "common_func.hpp" #include "img_generic_extension.hpp" //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; //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 receive_delay; //SC_EVENT sc_event send_response_e; //DEBUG unsigned int transaction_in_progress_id = 0; bool use_prints; //Constructor SC_CTOR(img_target) : socket("socket"), response_transaction(0), m_peq(this, &img_target::peq_cb), use_prints(true) // Construct and name socket { // Register callbacks for incoming interface method calls socket.register_nb_transport_fw(this, &img_target::nb_transport_fw); SC_THREAD(send_response); } 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) { sc_time delay; img_generic_extension* img_ext; switch (phase) { //Case 1: Target is receiving the first transaction of communication -> BEGIN_REQ case tlm::BEGIN_REQ: { //Check for errors here // Increment the transaction reference count trans.acquire(); trans.get_extension(img_ext); dbgmodprint(use_prints, "BEGIN_REQ RECEIVED TRANS ID %0d", img_ext->transaction_number); //Queue a response tlm::tlm_phase int_phase = internal_processing_ph; m_peq.notify(trans, int_phase, receive_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){ dbgmodprint(use_prints, "INTERNAL PHASE: PROCESSING TRANSACTION"); process_transaction(trans); } break; } } } //Response function void send_response() { while(true){ wait(send_response_e); tlm::tlm_sync_enum status; tlm::tlm_phase response_phase; img_generic_extension* img_ext; response_phase = tlm::BEGIN_RESP; status = socket->nb_transport_bw(*response_transaction, response_phase, response_delay); //Check Initiator response switch(status) { case tlm::TLM_ACCEPTED: { // Target only care about acknowledge of the succesful response (*response_transaction).release(); (*response_transaction).get_extension(img_ext); dbgmodprint(use_prints, "TLM_ACCEPTED RECEIVED TRANS ID %0d", img_ext->transaction_number); break; } //Not implementing Updated and Completed Status default: { dbgmodprint(use_prints, "[ERROR] Invalid status received at target"); break; } } } } virtual void do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address){ } virtual void do_when_write_transaction(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address){ } //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_phase phase; img_generic_extension* img_ext; //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(); trans.get_extension(img_ext); dbgmodprint(use_prints, "Processing transaction: %0d", img_ext->transaction_number); this->transaction_in_progress_id = img_ext->transaction_number; //Process transaction switch(cmd) { case tlm::TLM_READ_COMMAND: { unsigned char* response_data_ptr; response_data_ptr = new unsigned char[len]; this->do_when_read_transaction(response_data_ptr, len, addr); //Add read according to length //-----------DEBUG----------- dbgmodprint(use_prints, "[DEBUG] Reading: "); for (long unsigned int i = 0; i < len/sizeof(int); ++i){ dbgmodprint(use_prints, "%02x", *(reinterpret_cast<int*>(response_data_ptr)+i)); } //-----------DEBUG----------- trans.set_data_ptr(response_data_ptr); break; } case tlm::TLM_WRITE_COMMAND: { this->do_when_write_transaction(data_ptr, len, addr); //-----------DEBUG----------- dbgmodprint(use_prints, "[DEBUG] Writing: "); for (long unsigned int i = 0; i < len/sizeof(int); ++i){ dbgmodprint(use_prints, "%02x", *(reinterpret_cast<int*>(data_ptr)+i)); } //-----------DEBUG----------- break; } default: { dbgmodprint(use_prints, "ERROR Command %0d is NOT valid", cmd); } } //Send response dbgmodprint(use_prints, "BEGIN_RESP SENT TRANS ID %0d", img_ext->transaction_number); response_transaction = &trans; //send_response(trans); send_response_e.notify(); } void set_delays(sc_time resp_delay, sc_time rec_delay) { this->response_delay = resp_delay; this->receive_delay = rec_delay; } }; #endif
// ************************************************************************************** // User-defined memory manager, which maintains a pool of transactions // From TLM Duolos tutorials // ************************************************************************************** #ifndef TRANSACTION_MEMORY_MANAGER_CPP #define TRANSACTION_MEMORY_MANAGER_CPP #include <systemc.h> using namespace sc_core; using namespace sc_dt; using namespace std; #include <tlm.h> #include <tlm_utils/simple_initiator_socket.h> #include <tlm_utils/simple_target_socket.h> #include <tlm_utils/peq_with_cb_and_phase.h> class mm: public tlm::tlm_mm_interface { typedef tlm::tlm_generic_payload gp_t; public: mm() : free_list(0), empties(0) #ifdef DEBUG , count(0) #endif // DEBUG {} gp_t* allocate() { #ifdef DEBUG cout << "----------------------------- Called allocate(), #trans = " << ++count << endl; #endif // DEBUG gp_t* ptr; if (free_list) { ptr = free_list->trans; empties = free_list; free_list = free_list->next; } else { ptr = new gp_t(this); } return ptr; } void free(gp_t* trans) { #ifdef DEBUG cout << "----------------------------- Called free(), #trans = " << --count << endl; #endif // DEBUG if (!empties) { empties = new access; empties->next = free_list; empties->prev = 0; if (free_list) free_list->prev = empties; } free_list = empties; free_list->trans = trans; empties = free_list->prev; } private: struct access { gp_t* trans; access* next; access* prev; }; access* free_list; access* empties; #ifdef DEBUG int count; #endif // DEBUG }; #endif // TRANSACTION_MEMORY_MANAGER_CPP
// ================================================================ // NVDLA Open Source Project // // Copyright(c) 2016 - 2017 NVIDIA Corporation. Licensed under the // NVDLA Open Hardware License; Check "LICENSE" which comes with // this distribution for more information. // ================================================================ // File Name: cdp_hls_wrapper.cpp #include "log.h" #include "ac_int.h" #include "ac_channel.h" #include "log.h" #include <systemc.h> #include "arnvdla.h" #define __STDC_FORMAT_MACROS #include <inttypes.h> #include "vlibs.h" #include "cdp_hls_wrapper.h" #pragma CTC SKIP int half2single(void *target, void *source, int numel) { unsigned short *hp = (unsigned short *) source; // Type pun input as an unsigned 16-bit int unsigned int *xp = (unsigned int *) target; // Type pun output as an unsigned 32-bit int unsigned short h, hs, he, hm; unsigned int xs, xe, xm; int xes; int e; static int checkieee = 1; // Flag to check for IEEE754, Endian, and word size double one = 1.0; // Used for checking IEEE754 floating point format unsigned int *ip; // Used for checking IEEE754 floating point format if( checkieee ) { // 1st call, so check for IEEE754, Endian, and word size ip = (unsigned int *) &one; if( *ip ) { // If Big Endian, then no adjustment } else { // If Little Endian, then adjustment will be necessary ip++; } if( *ip != 0x3FF00000u ) { // Check for exact IEEE 754 bit pattern of 1.0 return 1; // Floating point bit pattern is not IEEE 754 } if( sizeof(short) != 2 || sizeof(int) != 4 ) { return 1; // short is not 16-bits, or long is not 32-bits. } checkieee = 0; // Everything checks out OK } if( source == NULL || target == NULL ) // Nothing to convert (e.g., imag part of pure real) return 0; while( numel-- ) { h = *hp++; if( (h & 0x7FFFu) == 0 ) { // Signed zero *xp++ = ((unsigned int) h) << 16; // Return the signed zero } else { // Not zero hs = h & 0x8000u; // Pick off sign bit he = h & 0x7C00u; // Pick off exponent bits hm = h & 0x03FFu; // Pick off mantissa bits if( he == 0 ) { // Denormal will convert to normalized e = -1; // The following loop figures out how much extra to adjust the exponent do { e++; hm <<= 1; } while( (hm & 0x0400u) == 0 ); // Shift until leading bit overflows into exponent bit xs = ((unsigned int) hs) << 16; // Sign bit xes = ((int) (he >> 10)) - 15 + 127 - e; // Exponent unbias the halfp, then bias the single xe = (unsigned int) (xes << 23); // Exponent xm = ((unsigned int) (hm & 0x03FFu)) << 13; // Mantissa *xp++ = (xs | xe | xm); // Combine sign bit, exponent bits, and mantissa bits } else if( he == 0x7C00u ) { // Inf or NaN (all the exponent bits are set) if( hm == 0 ) { // If mantissa is zero ... *xp++ = (((unsigned int) hs) << 16) | ((unsigned int) 0x7F800000u); // Signed Inf } else { *xp++ = (unsigned int) 0xFFC00000u; // NaN, only 1st mantissa bit set } } else { // Normalized number xs = ((unsigned int) hs) << 16; // Sign bit xes = ((int) (he >> 10)) - 15 + 127; // Exponent unbias the halfp, then bias the single xe = (unsigned int) (xes << 23); // Exponent xm = ((unsigned int) hm) << 13; // Mantissa *xp++ = (xs | xe | xm); // Combine sign bit, exponent bits, and mantissa bits } } } return 0; } int single2half(void *target, void *source, int numel) { unsigned short *hp = (unsigned short *) target; // Type pun output as an unsigned 16-bit int unsigned int *xp = (unsigned int *) source; // Type pun input as an unsigned 32-bit int unsigned short hs, he, hm; unsigned int x, xs, xe, xm; int hes; static int checkieee = 1; // Flag to check for IEEE754, Endian, and word size double one = 1.0; // Used for checking IEEE754 floating point format unsigned int *ip; // Used for checking IEEE754 floating point format if( checkieee ) { // 1st call, so check for IEEE754, Endian, and word size ip = (unsigned int *) &one; if( *ip ) { // If Big Endian, then no adjustment } else { // If Little Endian, then adjustment will be necessary ip++; } if( *ip != 0x3FF00000u ) { // Check for exact IEEE 754 bit pattern of 1.0 return 1; // Floating point bit pattern is not IEEE 754 } if( sizeof(short) != 2 || sizeof(int) != 4 ) { return 1; // short is not 16-bits, or long is not 32-bits. } checkieee = 0; // Everything checks out OK } if( source == NULL || target == NULL ) { // Nothing to convert (e.g., imag part of pure real) return 0; } while( numel-- ) { x = *xp++; if( (x & 0x7FFFFFFFu) == 0 ) { // Signed zero *hp++ = (unsigned short) (x >> 16); // Return the signed zero } else { // Not zero xs = x & 0x80000000u; // Pick off sign bit xe = x & 0x7F800000u; // Pick off exponent bits xm = x & 0x007FFFFFu; // Pick off mantissa bits if( xe == 0 ) { // Denormal will underflow, return a signed zero *hp++ = (unsigned short) (xs >> 16); } else if( xe == 0x7F800000u ) { // Inf or NaN (all the exponent bits are set) if( xm == 0 ) { // If mantissa is zero ... *hp++ = (unsigned short) ((xs >> 16) | 0x7C00u); // Signed Inf } else { *hp++ = (unsigned short) 0xFE00u; // NaN, only 1st mantissa bit set } } else { // Normalized number hs = (unsigned short) (xs >> 16); // Sign bit hes = ((int)(xe >> 23)) - 127 + 15; // Exponent unbias the single, then bias the halfp if( hes >= 0x1F ) { // Overflow *hp++ = (unsigned short) ((xs >> 16) | 0x7C00u); // Signed Inf } else if( hes <= 0 ) { // Underflow if( (14 - hes) > 24 ) { // Mantissa shifted all the way off & no rounding possibility hm = (unsigned short) 0u; // Set mantissa to zero } else { xm |= 0x00800000u; // Add the hidden leading bit hm = (unsigned short) (xm >> (14 - hes)); // Mantissa if( (xm >> (13 - hes)) & 0x00000001u ) // Check for rounding hm += (unsigned short) 1u; // Round, might overflow into exp bit, but this is OK } *hp++ = (hs | hm); // Combine sign bit and mantissa bits, biased exponent is zero } else { he = (unsigned short) (hes << 10); // Exponent hm = (unsigned short) (xm >> 13); // Mantissa if( xm & 0x00001000u ) // Check for rounding *hp++ = (hs | he | hm) + (unsigned short) 1u; // Round, might overflow to inf, this is OK else *hp++ = (hs | he | hm); // No rounding } } } } return 0; } #pragma CTC ENDSKIP // Inputs: 12 HLS_FP17 after icvt // Outputs: 1 HLS_FP17 after Interplolation void HLS_CDP_lookup_lut ( vFp32Type square_sum, uint16_t lut_upper_index, bool le, // True: linear_exp table bool exp_mode, // Only for linear_exp table int16_t* lut, // LUT table uint64_t lut_start, uint64_t lut_end, int16_t slope_uflow_scale, // It's accutally signed value int16_t slope_oflow_scale, int16_t index_offset, int8_t index_select, // Outputs bool & underflow, bool & overflow, bool & lut_hit, ac_channel<vFp17Type> & chn_result_fp17) { #if !ASSERT_WAR_CONSTRAIN // assert(density_end - pow(2, cdp_lut_lo_index_select_ + 8) == density_start); #endif // Variables for sub input_offset vFp32Type lut_start_fp32, lut_end_fp32; vFp32Type lut_sub_result_fp32; ac_channel<vFp32Type> chn_square_sum_fp32; ac_channel<vFp32Type> chn_lut_start_fp32, chn_lut_end_fp32; ac_channel<vFp32Type> chn_lut_sub_result_fp32; ac_channel<vFp17Type> chn_lut_sub_result_fp17; float lut_sub_result_float; float lut_shifted; uint16_t lut_offset; int32_t lut_index; ac_channel<vFp17Type> chn_lut_offset_fp17; // Varibales for underflow/overflow vFp16Type slope_fp16; ac_channel<vFp16Type> chn_slope_fp16; ac_channel<vFp17Type> chn_slope_fp17; ac_channel<vFp17Type> chn_lo_sub_result_fp17; ac_channel<vFp17Type> chn_mul_result_fp17; ac_channel<vFp17Type> chn_result_lut_underflow; ac_channel<vFp17Type> chn_result_lut_overflow; // Variables for Interpolation uint16_t result_0, result_1; vFp16Type result_0_fp16, result_1_fp16; ac_channel<vFp16Type> chn_result_0_fp16, chn_result_1_fp16; vFp32Type result_0_fp32, result_1_fp32; ac_channel<vFp32Type> chn_result_0_fp32, chn_result_1_fp32; ac_channel<vFp17Type> chn_result_0_fp17; ac_channel<vFp17Type> chn_result_1_fp17; // ac_channel<vFp17Type> chn_result_underflow_fp17; // ac_channel<vFp17Type> chn_result_overflow_fp17; ac_channel<vFp32Type> chn_L1_minus_L0_fp32; ac_channel<vFp17Type> chn_L1_minus_L0_fp17; ac_channel<vFp17Type> chn_result_lut_tmp; //-------------------------------------------- underflow = false; overflow = false; //exp_underflow = false; //exp_overflow = false; lut_hit = false; //-------------------------------------------- // 1. sub offset lut_start_fp32 = lut_start; chn_lut_start_fp32.write(lut_start_fp32); chn_square_sum_fp32.write(square_sum); HLS_fp32_sub(chn_square_sum_fp32, chn_lut_start_fp32, chn_lut_sub_result_fp32); lut_sub_result_fp32 = chn_lut_sub_result_fp32.read(); lut_sub_result_float = *(float *)(&lut_sub_result_fp32); // vFp32Type is actually integer type cslDebug((70, "lut_start=0x%x, lut_sub_result=0x%x\n", (uint32_t)lut_start_fp32, (uint32_t)lut_sub_result_fp32)); if(lut_sub_result_float <= 0 || std::isnan(lut_sub_result_float)) { underflow = true; } if (!underflow) { if (le && exp_mode) { // Log2. If lo_sub_result_float is 0, exp will be 0 uint32_t tmp_uint32 = *(uint32_t*)(&lut_sub_result_float); int32_t exp_raw = (tmp_uint32 >> 23) & 0xff; // 8bits //int32_t exp = (exp_raw == 0)? 0 : exp_raw - 127; int32_t exp = exp_raw - 127; lut_index = exp - index_offset; lut_offset = (tmp_uint32 >> 7) & 0xffff; if(lut_index < 0) { lut_offset >>= -lut_index; lut_index = 0; underflow = true; } else if (lut_index >= lut_upper_index) { overflow = true; } cslDebug((70, "exp=%d, index_offset=%d, lut_index=%d, lut_offset=%d\n", exp, index_offset, lut_index, lut_offset)); } else { // lo or (le && linear_mode) // To int and Shift using float of C++ // In RTL, HLS is not used in below code if(index_select >= 0) lut_shifted = lut_sub_result_float / pow(2, index_select); else lut_shifted = lut_sub_result_float * pow(2, -index_select); overflow = lut_shifted >= lut_upper_index; lut_index = lut_shifted; lut_offset = (lut_shifted - int32_t(lut_shifted)) * 0x10000; // 16 MSB bits of fraction cslDebug((70, "index_select=%d, lut_shifted=%f, lut_index=%d, lut_offset=%d\n", index_select, lut_shifted, lut_index, lut_offset)); } } // Convert Fraction from special INT16 to HLS_FP17 vU16Type lut_offset_u16 = lut_offset; ac_channel<vU16Type> chn_lut_offset_u16; chn_lut_offset_u16.write(lut_offset_u16); HLS_uint16_to_fp17(chn_lut_offset_u16, chn_lut_offset_fp17); //if ((underflow || (le&&exp_underflow))) { if (underflow) { result_0 = lut[0]; result_0_fp16 = result_0; chn_result_0_fp16.write(result_0_fp16); cslDebug((70, "L0=0x%x\n", result_0)); // Convert result_lo_0 of HLS FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_result_0_fp16, chn_result_0_fp17); slope_fp16 = (int16_t)slope_uflow_scale; chn_slope_fp16.write(slope_fp16); // Convert FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_slope_fp16, chn_slope_fp17); // Convert FP32 to HLS_FP17 if(le && exp_mode) { float offset; #pragma CTC SKIP if(index_offset <= -127) { offset = 0; } #pragma CTC ENDSKIP else { offset = pow(2, index_offset); } ac_channel<vFp32Type> chn_offset, chn_offset_adj; chn_offset.write(*(vFp32Type *)(&offset)); chn_lut_start_fp32.write(lut_start_fp32); HLS_fp32_add(chn_lut_start_fp32, chn_offset, chn_offset_adj); chn_square_sum_fp32.write(square_sum); HLS_fp32_sub(chn_square_sum_fp32, chn_offset_adj, chn_lut_sub_result_fp32); } else { chn_lut_sub_result_fp32.write(lut_sub_result_fp32); } HLS_fp32_to_fp17(chn_lut_sub_result_fp32, chn_lut_sub_result_fp17); // chn_gap * slope HLS_fp17_mul(chn_lut_sub_result_fp17, chn_slope_fp17, chn_mul_result_fp17); HLS_fp17_add(chn_mul_result_fp17, chn_result_0_fp17, chn_result_fp17); } //else if ((overflow || (le&&exp_overflow))) { else if (overflow) { result_1 = lut[lut_upper_index]; result_1_fp16 = result_1; chn_result_1_fp16.write(result_1_fp16); cslDebug((70, "L1=0x%x\n", result_1)); // Convert result_lo_0 of HLS FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_result_1_fp16, chn_result_1_fp17); slope_fp16 = (int16_t)slope_oflow_scale; chn_slope_fp16.write(slope_fp16); // Convert FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_slope_fp16, chn_slope_fp17); // Convert FP32 to HLS_FP17 lut_end_fp32 = lut_end; chn_lut_end_fp32.write(lut_end_fp32); chn_square_sum_fp32.write(square_sum); HLS_fp32_sub(chn_square_sum_fp32, chn_lut_end_fp32, chn_lut_sub_result_fp32); HLS_fp32_to_fp17(chn_lut_sub_result_fp32, chn_lut_sub_result_fp17); // chn_gap * slope HLS_fp17_mul(chn_lut_sub_result_fp17, chn_slope_fp17, chn_mul_result_fp17); HLS_fp17_add(chn_mul_result_fp17, chn_result_1_fp17, chn_result_fp17); } else { result_0 = lut[lut_index]; result_1 = lut[lut_index+1]; result_0_fp16 = result_0; result_1_fp16 = result_1; chn_result_0_fp16.write(result_0_fp16); chn_result_1_fp16.write(result_1_fp16); cslDebug((70, "L0=0x%x, L1=0x%x\n", result_0, result_1)); // Convert HLS_FP16 to HLS_FP32 HLS_fp16_to_fp32(chn_result_0_fp16, chn_result_0_fp32); HLS_fp16_to_fp32(chn_result_1_fp16, chn_result_1_fp32); // Convert result_lo_0 of HLS FP16 to HLS_FP17 chn_result_0_fp16.write(result_0_fp16); HLS_fp16_to_fp17(chn_result_0_fp16, chn_result_0_fp17); // Interpolation HLS_fp32_sub(chn_result_1_fp32, chn_result_0_fp32, chn_L1_minus_L0_fp32); //vFp32Type L1_minus_L0_fp32 = chn_L1_minus_L0_fp32.read(); //cslDebug((70,"L1_minus_L0_fp32=0x%x\n", L1_minus_L0_fp32)); //chn_L1_minus_L0_fp32.write(L1_minus_L0_fp32); HLS_fp32_to_fp17(chn_L1_minus_L0_fp32, chn_L1_minus_L0_fp17); HLS_fp17_mul(chn_L1_minus_L0_fp17, chn_lut_offset_fp17, chn_result_lut_tmp); HLS_fp17_add(chn_result_lut_tmp, chn_result_0_fp17, chn_result_fp17); lut_hit = true; /* float L0_float, L1_float, L1_minus_L0_float, result_float; half2single(&L0_float,&result_0_fp16, 1); cslDebug((70,"L0: %f(0x%x)\n", L0_float, *(int *)(&L0_float) )); half2single(&L1_float,&result_1_fp16, 1); cslDebug((70,"L1: %f(0x%x)\n", L1_float, *(int *)(&L1_float) )); L1_minus_L0_float = L1_float - L0_float; cslDebug((70,"L1-L1: %f(0x%x)\n", L1_minus_L0_float, *(int *)(&L1_minus_L0_float) )); result_float = L0_float + L1_minus_L0_float * lut_offset; cslDebug((70,"result: %f(0x%x)\n", result_float, *(int *)(&result_float) ));*/ } } void HLS_CDP_lookup_fp16 ( int16_t *data_in, // 12 * fp17 int16_t *le_lut, int16_t *lo_lut, // Configurations uint16_t normalz_len, uint16_t raw_method, bool lut_uflow_priority, bool lut_oflow_priority, bool lut_hybrid_priority, uint64_t le_start, int16_t le_index_offset, int8_t le_index_select, uint64_t le_end, uint64_t lo_start, int8_t lo_index_select, uint64_t lo_end, uint16_t datin_offset, uint16_t datin_scale, uint8_t datin_shifter, uint32_t datout_offset, uint16_t datout_scale, uint8_t datout_shifter, int16_t le_slope_uflow_scale, int16_t le_slope_oflow_scale, int16_t lo_slope_uflow_scale, int16_t lo_slope_oflow_scale, bool sqsum_bypass, bool mul_bypass, int16_t *normalz_out, uint32_t *lut_u_flow, uint32_t *lut_o_flow, uint32_t *lut_le_hit, uint32_t *lut_lo_hit, uint32_t *lut_hybrid_hit) // 16bits { int i; // Outputs bool le_underflow; bool le_overflow; //bool exp_underflow; //bool exp_overflow; bool lo_underflow; bool lo_overflow; bool le_hit; bool lo_hit; // Variables int32_t icvt_data_out[12]; ac_channel<vFp32Type> fp17tofp32_out[12]; ac_channel<vFp32Type> square_array[12]; //ac_channel<vFp32Type> square_sum; vFp32Type square_result[12]; // Outputs of lut tables ac_channel<vFp17Type> chn_result_le_fp17; ac_channel<vFp17Type> chn_result_lo_fp17; // ac_channel<vFp17Type> chn_result_fp17; ac_channel<vFp17Type> chn_result_to_ocvt_fp17; ac_channel<vFp17Type> chn_ocvt_out_fp17; #if 0 // Initialization le_underflow = false; le_overflow = false; exp_underflow = false; exp_overflow = false; lo_underflow = false; lo_overflow = false; le_hit = false; lo_hit = false; #endif vFp32Type icvt_data_out_fp32[12]; float tmp[12], din_offset, din_scale; half2single(&din_offset, &datin_offset, 1); half2single(&din_scale, &datin_scale, 1); cslDebug((70, "Data before input converter(float)\n")); for(i=0; i<12; i++) { half2single(&tmp[i], &data_in[i], 1); cslDebug((70, "%f(0x%x) ", tmp[i], *(int *)(&tmp[i]) )); } cslDebug((70, "\n")); cslDebug((70, "Data after square(float)\n")); for(i=0; i<12; i++) { tmp[i] = tmp[i] * tmp[i]; cslDebug((70, "%f(0x%x) ", tmp[i], *(int *)(&tmp[i]) )); } cslDebug((70, "\n")); for(i=0; i<12; i++) { //***** Input Convertor (FP16->FP17) ****** cdp_icvt_hls(&data_in[i], datin_offset, datin_scale, datin_shifter, NVDLA_CDP_RDMA_D_DATA_FORMAT_0_INPUT_DATA_FP16, &icvt_data_out[i]);
//***** Convert FP17 to FP32 ****** ac_channel<vFp17Type> chn_a; chn_a.write(icvt_data_out[i]); HLS_fp17_to_fp32(chn_a, fp17tofp32_out[i]); icvt_data_out_fp32[i] = fp17tofp32_out[i].read(); ac_channel<vFp32Type> chn_b, chn_c; chn_b.write(icvt_data_out_fp32[i]); chn_c.write(icvt_data_out_fp32[i]); if(sqsum_bypass) { square_result[i] = icvt_data_out_fp32[i]; } else { HLS_fp32_mul(chn_b, chn_c, square_array[i]); // HLS_FP32 mul square_result[i] = square_array[i].read(); //keep data to re-write the square_array later } } // cslDebug((70, "Data after input convertor(FP17):\n")); // for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&icvt_data_out[i]) )); // cslDebug((70, "\n")); cslDebug((70, "Data after input convertor(FP32):\n")); for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&icvt_data_out_fp32[i]) )); cslDebug((70, "\n")); cslDebug((70, "Data after square:\n")); for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&square_result[i]) )); cslDebug((70, "\n")); //***** Per Element ****** for (i=0; i<4; i++) { le_underflow = false; le_overflow = false; //exp_underflow = false; //exp_overflow = false; lo_underflow = false; lo_overflow = false; le_hit = false; lo_hit = false; //re-write square_array in each iteration since it is empty after read for(int j=0; j<12; j++) square_array[j].write(square_result[j]); //***** Sum ****** vFp32Type square_sum_result; if(sqsum_bypass) { square_sum_result = square_array[i+4].read(); } else { ac_channel<vFp32Type> square_sum_1, square_sum_2; HLS_fp32_add(square_array[i+3], square_array[i+5], square_sum_1); //3 + 5 HLS_fp32_add(square_sum_1, square_array[i+4], square_sum_2); //sum3 = (3 + 5) + 4 ac_channel<vFp32Type> square_sum_3, square_sum_4; if(normalz_len > 0) //5+ elements { HLS_fp32_add(square_array[i+2], square_array[i+6], square_sum_3); //2 + 6 HLS_fp32_add(square_sum_2, square_sum_3, square_sum_4); //sum5 = sum3 + (2 + 6) } ac_channel<vFp32Type> square_sum_5, square_sum_6; if(normalz_len > 1) //7+ elements { HLS_fp32_add(square_array[i+1], square_array[i+7], square_sum_5); //1 + 7 HLS_fp32_add(square_sum_4, square_sum_5, square_sum_6); //sum7 = sum5 + (1 + 7) } ac_channel<vFp32Type> square_sum_7, square_sum_8; if(normalz_len > 2) //9 elements { HLS_fp32_add(square_array[i+0], square_array[i+8], square_sum_7); //1 + 7 HLS_fp32_add(square_sum_6, square_sum_7, square_sum_8); //sum9 = sum7 + (0 + 8) } switch(normalz_len) { case 0: square_sum_result = square_sum_2.read(); break; case 1: square_sum_result = square_sum_4.read(); break; case 2: square_sum_result = square_sum_6.read(); break; case 3: square_sum_result = square_sum_8.read(); break; #pragma CTC SKIP default: break; #pragma CTC ENDSKIP } } cslDebug((70, "Square sum: %x\n", *(int *)(&square_sum_result) )); // Look up Raw table if(NVDLA_CDP_S_LUT_CFG_0_LUT_LE_FUNCTION_EXPONENT == raw_method) { //raw lut is exponential cslDebug((70, "Lookup exp table\n")); HLS_CDP_lookup_lut(square_sum_result, 64, true, true, le_lut, le_start, le_end, le_slope_uflow_scale, le_slope_oflow_scale, le_index_offset, le_index_select, le_underflow, le_overflow, le_hit, chn_result_le_fp17); } else { // raw lut is linear cslDebug((70, "Lookup lin table\n")); HLS_CDP_lookup_lut(square_sum_result, 64, true, false, le_lut, le_start, le_end, le_slope_uflow_scale, le_slope_oflow_scale, le_index_offset, le_index_select, le_underflow, le_overflow, le_hit, chn_result_le_fp17); } cslDebug((70, "Lookup lo table\n")); // Look up LO(Linear Only) table HLS_CDP_lookup_lut(square_sum_result, 256, false, false, lo_lut, lo_start, lo_end, lo_slope_uflow_scale, lo_slope_oflow_scale, 0, lo_index_select, lo_underflow, lo_overflow, lo_hit, chn_result_lo_fp17); vFp17Type result_le = chn_result_le_fp17.read(); vFp17Type result_lo = chn_result_lo_fp17.read(); vFp17Type result_out; // Select result between RAW table and Density Table if(le_underflow && lo_underflow) { result_out = lut_uflow_priority? result_lo : result_le; (*lut_u_flow)++; } else if(le_overflow && lo_overflow) { result_out = lut_oflow_priority? result_lo : result_le; (*lut_o_flow)++; } else { if(le_hit ^ lo_hit) { result_out = le_hit? result_le : result_lo; if(le_hit) { (*lut_le_hit)++; } else { (*lut_lo_hit)++; } } else { if(lut_hybrid_priority) result_out = result_lo; else result_out = result_le; (*lut_hybrid_hit)++; } } cslDebug((70, "le:%x, lo:%x, out:%x\n" , *(int *)(&result_le), *(int *)(&result_lo), *(int *)(&result_out) )); if(mul_bypass) { float icvt_data_out_float = *(float *)&icvt_data_out_fp32[i+4]; if(std::isnan(icvt_data_out_float)) { chn_result_to_ocvt_fp17.write(icvt_data_out[i+4]); } else { chn_result_to_ocvt_fp17.write(result_out); } } else { ac_channel<vFp17Type> chn_result_fp17, chn_icvt_data_out_fp17; chn_result_fp17.write(result_out); vFp17Type icvt_data_out_fp17 = icvt_data_out[i+4]; chn_icvt_data_out_fp17.write(icvt_data_out_fp17); HLS_fp17_mul(chn_icvt_data_out_fp17, chn_result_fp17, chn_result_to_ocvt_fp17); } // Output Converter int64_t ocvt_data_in = chn_result_to_ocvt_fp17.read(); cslDebug((70, "ocvt_data_in:%x\n", (int)ocvt_data_in)); uint8_t flag; cdp_ocvt_hls(&ocvt_data_in, datout_offset, datout_scale, datout_shifter, NVDLA_CDP_RDMA_D_DATA_FORMAT_0_INPUT_DATA_FP16, &normalz_out[i], &flag); } }
// ================================================================ // NVDLA Open Source Project // // Copyright(c) 2016 - 2017 NVIDIA Corporation. Licensed under the // NVDLA Open Hardware License; Check "LICENSE" which comes with // this distribution for more information. // ================================================================ // File Name: cdp_hls_wrapper.cpp #include "log.h" #include "ac_int.h" #include "ac_channel.h" #include "log.h" #include <systemc.h> #include "arnvdla.h" #define __STDC_FORMAT_MACROS #include <inttypes.h> #include "vlibs.h" #include "cdp_hls_wrapper.h" #pragma CTC SKIP int half2single(void *target, void *source, int numel) { unsigned short *hp = (unsigned short *) source; // Type pun input as an unsigned 16-bit int unsigned int *xp = (unsigned int *) target; // Type pun output as an unsigned 32-bit int unsigned short h, hs, he, hm; unsigned int xs, xe, xm; int xes; int e; static int checkieee = 1; // Flag to check for IEEE754, Endian, and word size double one = 1.0; // Used for checking IEEE754 floating point format unsigned int *ip; // Used for checking IEEE754 floating point format if( checkieee ) { // 1st call, so check for IEEE754, Endian, and word size ip = (unsigned int *) &one; if( *ip ) { // If Big Endian, then no adjustment } else { // If Little Endian, then adjustment will be necessary ip++; } if( *ip != 0x3FF00000u ) { // Check for exact IEEE 754 bit pattern of 1.0 return 1; // Floating point bit pattern is not IEEE 754 } if( sizeof(short) != 2 || sizeof(int) != 4 ) { return 1; // short is not 16-bits, or long is not 32-bits. } checkieee = 0; // Everything checks out OK } if( source == NULL || target == NULL ) // Nothing to convert (e.g., imag part of pure real) return 0; while( numel-- ) { h = *hp++; if( (h & 0x7FFFu) == 0 ) { // Signed zero *xp++ = ((unsigned int) h) << 16; // Return the signed zero } else { // Not zero hs = h & 0x8000u; // Pick off sign bit he = h & 0x7C00u; // Pick off exponent bits hm = h & 0x03FFu; // Pick off mantissa bits if( he == 0 ) { // Denormal will convert to normalized e = -1; // The following loop figures out how much extra to adjust the exponent do { e++; hm <<= 1; } while( (hm & 0x0400u) == 0 ); // Shift until leading bit overflows into exponent bit xs = ((unsigned int) hs) << 16; // Sign bit xes = ((int) (he >> 10)) - 15 + 127 - e; // Exponent unbias the halfp, then bias the single xe = (unsigned int) (xes << 23); // Exponent xm = ((unsigned int) (hm & 0x03FFu)) << 13; // Mantissa *xp++ = (xs | xe | xm); // Combine sign bit, exponent bits, and mantissa bits } else if( he == 0x7C00u ) { // Inf or NaN (all the exponent bits are set) if( hm == 0 ) { // If mantissa is zero ... *xp++ = (((unsigned int) hs) << 16) | ((unsigned int) 0x7F800000u); // Signed Inf } else { *xp++ = (unsigned int) 0xFFC00000u; // NaN, only 1st mantissa bit set } } else { // Normalized number xs = ((unsigned int) hs) << 16; // Sign bit xes = ((int) (he >> 10)) - 15 + 127; // Exponent unbias the halfp, then bias the single xe = (unsigned int) (xes << 23); // Exponent xm = ((unsigned int) hm) << 13; // Mantissa *xp++ = (xs | xe | xm); // Combine sign bit, exponent bits, and mantissa bits } } } return 0; } int single2half(void *target, void *source, int numel) { unsigned short *hp = (unsigned short *) target; // Type pun output as an unsigned 16-bit int unsigned int *xp = (unsigned int *) source; // Type pun input as an unsigned 32-bit int unsigned short hs, he, hm; unsigned int x, xs, xe, xm; int hes; static int checkieee = 1; // Flag to check for IEEE754, Endian, and word size double one = 1.0; // Used for checking IEEE754 floating point format unsigned int *ip; // Used for checking IEEE754 floating point format if( checkieee ) { // 1st call, so check for IEEE754, Endian, and word size ip = (unsigned int *) &one; if( *ip ) { // If Big Endian, then no adjustment } else { // If Little Endian, then adjustment will be necessary ip++; } if( *ip != 0x3FF00000u ) { // Check for exact IEEE 754 bit pattern of 1.0 return 1; // Floating point bit pattern is not IEEE 754 } if( sizeof(short) != 2 || sizeof(int) != 4 ) { return 1; // short is not 16-bits, or long is not 32-bits. } checkieee = 0; // Everything checks out OK } if( source == NULL || target == NULL ) { // Nothing to convert (e.g., imag part of pure real) return 0; } while( numel-- ) { x = *xp++; if( (x & 0x7FFFFFFFu) == 0 ) { // Signed zero *hp++ = (unsigned short) (x >> 16); // Return the signed zero } else { // Not zero xs = x & 0x80000000u; // Pick off sign bit xe = x & 0x7F800000u; // Pick off exponent bits xm = x & 0x007FFFFFu; // Pick off mantissa bits if( xe == 0 ) { // Denormal will underflow, return a signed zero *hp++ = (unsigned short) (xs >> 16); } else if( xe == 0x7F800000u ) { // Inf or NaN (all the exponent bits are set) if( xm == 0 ) { // If mantissa is zero ... *hp++ = (unsigned short) ((xs >> 16) | 0x7C00u); // Signed Inf } else { *hp++ = (unsigned short) 0xFE00u; // NaN, only 1st mantissa bit set } } else { // Normalized number hs = (unsigned short) (xs >> 16); // Sign bit hes = ((int)(xe >> 23)) - 127 + 15; // Exponent unbias the single, then bias the halfp if( hes >= 0x1F ) { // Overflow *hp++ = (unsigned short) ((xs >> 16) | 0x7C00u); // Signed Inf } else if( hes <= 0 ) { // Underflow if( (14 - hes) > 24 ) { // Mantissa shifted all the way off & no rounding possibility hm = (unsigned short) 0u; // Set mantissa to zero } else { xm |= 0x00800000u; // Add the hidden leading bit hm = (unsigned short) (xm >> (14 - hes)); // Mantissa if( (xm >> (13 - hes)) & 0x00000001u ) // Check for rounding hm += (unsigned short) 1u; // Round, might overflow into exp bit, but this is OK } *hp++ = (hs | hm); // Combine sign bit and mantissa bits, biased exponent is zero } else { he = (unsigned short) (hes << 10); // Exponent hm = (unsigned short) (xm >> 13); // Mantissa if( xm & 0x00001000u ) // Check for rounding *hp++ = (hs | he | hm) + (unsigned short) 1u; // Round, might overflow to inf, this is OK else *hp++ = (hs | he | hm); // No rounding } } } } return 0; } #pragma CTC ENDSKIP // Inputs: 12 HLS_FP17 after icvt // Outputs: 1 HLS_FP17 after Interplolation void HLS_CDP_lookup_lut ( vFp32Type square_sum, uint16_t lut_upper_index, bool le, // True: linear_exp table bool exp_mode, // Only for linear_exp table int16_t* lut, // LUT table uint64_t lut_start, uint64_t lut_end, int16_t slope_uflow_scale, // It's accutally signed value int16_t slope_oflow_scale, int16_t index_offset, int8_t index_select, // Outputs bool & underflow, bool & overflow, bool & lut_hit, ac_channel<vFp17Type> & chn_result_fp17) { #if !ASSERT_WAR_CONSTRAIN // assert(density_end - pow(2, cdp_lut_lo_index_select_ + 8) == density_start); #endif // Variables for sub input_offset vFp32Type lut_start_fp32, lut_end_fp32; vFp32Type lut_sub_result_fp32; ac_channel<vFp32Type> chn_square_sum_fp32; ac_channel<vFp32Type> chn_lut_start_fp32, chn_lut_end_fp32; ac_channel<vFp32Type> chn_lut_sub_result_fp32; ac_channel<vFp17Type> chn_lut_sub_result_fp17; float lut_sub_result_float; float lut_shifted; uint16_t lut_offset; int32_t lut_index; ac_channel<vFp17Type> chn_lut_offset_fp17; // Varibales for underflow/overflow vFp16Type slope_fp16; ac_channel<vFp16Type> chn_slope_fp16; ac_channel<vFp17Type> chn_slope_fp17; ac_channel<vFp17Type> chn_lo_sub_result_fp17; ac_channel<vFp17Type> chn_mul_result_fp17; ac_channel<vFp17Type> chn_result_lut_underflow; ac_channel<vFp17Type> chn_result_lut_overflow; // Variables for Interpolation uint16_t result_0, result_1; vFp16Type result_0_fp16, result_1_fp16; ac_channel<vFp16Type> chn_result_0_fp16, chn_result_1_fp16; vFp32Type result_0_fp32, result_1_fp32; ac_channel<vFp32Type> chn_result_0_fp32, chn_result_1_fp32; ac_channel<vFp17Type> chn_result_0_fp17; ac_channel<vFp17Type> chn_result_1_fp17; // ac_channel<vFp17Type> chn_result_underflow_fp17; // ac_channel<vFp17Type> chn_result_overflow_fp17; ac_channel<vFp32Type> chn_L1_minus_L0_fp32; ac_channel<vFp17Type> chn_L1_minus_L0_fp17; ac_channel<vFp17Type> chn_result_lut_tmp; //-------------------------------------------- underflow = false; overflow = false; //exp_underflow = false; //exp_overflow = false; lut_hit = false; //-------------------------------------------- // 1. sub offset lut_start_fp32 = lut_start; chn_lut_start_fp32.write(lut_start_fp32); chn_square_sum_fp32.write(square_sum); HLS_fp32_sub(chn_square_sum_fp32, chn_lut_start_fp32, chn_lut_sub_result_fp32); lut_sub_result_fp32 = chn_lut_sub_result_fp32.read(); lut_sub_result_float = *(float *)(&lut_sub_result_fp32); // vFp32Type is actually integer type cslDebug((70, "lut_start=0x%x, lut_sub_result=0x%x\n", (uint32_t)lut_start_fp32, (uint32_t)lut_sub_result_fp32)); if(lut_sub_result_float <= 0 || std::isnan(lut_sub_result_float)) { underflow = true; } if (!underflow) { if (le && exp_mode) { // Log2. If lo_sub_result_float is 0, exp will be 0 uint32_t tmp_uint32 = *(uint32_t*)(&lut_sub_result_float); int32_t exp_raw = (tmp_uint32 >> 23) & 0xff; // 8bits //int32_t exp = (exp_raw == 0)? 0 : exp_raw - 127; int32_t exp = exp_raw - 127; lut_index = exp - index_offset; lut_offset = (tmp_uint32 >> 7) & 0xffff; if(lut_index < 0) { lut_offset >>= -lut_index; lut_index = 0; underflow = true; } else if (lut_index >= lut_upper_index) { overflow = true; } cslDebug((70, "exp=%d, index_offset=%d, lut_index=%d, lut_offset=%d\n", exp, index_offset, lut_index, lut_offset)); } else { // lo or (le && linear_mode) // To int and Shift using float of C++ // In RTL, HLS is not used in below code if(index_select >= 0) lut_shifted = lut_sub_result_float / pow(2, index_select); else lut_shifted = lut_sub_result_float * pow(2, -index_select); overflow = lut_shifted >= lut_upper_index; lut_index = lut_shifted; lut_offset = (lut_shifted - int32_t(lut_shifted)) * 0x10000; // 16 MSB bits of fraction cslDebug((70, "index_select=%d, lut_shifted=%f, lut_index=%d, lut_offset=%d\n", index_select, lut_shifted, lut_index, lut_offset)); } } // Convert Fraction from special INT16 to HLS_FP17 vU16Type lut_offset_u16 = lut_offset; ac_channel<vU16Type> chn_lut_offset_u16; chn_lut_offset_u16.write(lut_offset_u16); HLS_uint16_to_fp17(chn_lut_offset_u16, chn_lut_offset_fp17); //if ((underflow || (le&&exp_underflow))) { if (underflow) { result_0 = lut[0]; result_0_fp16 = result_0; chn_result_0_fp16.write(result_0_fp16); cslDebug((70, "L0=0x%x\n", result_0)); // Convert result_lo_0 of HLS FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_result_0_fp16, chn_result_0_fp17); slope_fp16 = (int16_t)slope_uflow_scale; chn_slope_fp16.write(slope_fp16); // Convert FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_slope_fp16, chn_slope_fp17); // Convert FP32 to HLS_FP17 if(le && exp_mode) { float offset; #pragma CTC SKIP if(index_offset <= -127) { offset = 0; } #pragma CTC ENDSKIP else { offset = pow(2, index_offset); } ac_channel<vFp32Type> chn_offset, chn_offset_adj; chn_offset.write(*(vFp32Type *)(&offset)); chn_lut_start_fp32.write(lut_start_fp32); HLS_fp32_add(chn_lut_start_fp32, chn_offset, chn_offset_adj); chn_square_sum_fp32.write(square_sum); HLS_fp32_sub(chn_square_sum_fp32, chn_offset_adj, chn_lut_sub_result_fp32); } else { chn_lut_sub_result_fp32.write(lut_sub_result_fp32); } HLS_fp32_to_fp17(chn_lut_sub_result_fp32, chn_lut_sub_result_fp17); // chn_gap * slope HLS_fp17_mul(chn_lut_sub_result_fp17, chn_slope_fp17, chn_mul_result_fp17); HLS_fp17_add(chn_mul_result_fp17, chn_result_0_fp17, chn_result_fp17); } //else if ((overflow || (le&&exp_overflow))) { else if (overflow) { result_1 = lut[lut_upper_index]; result_1_fp16 = result_1; chn_result_1_fp16.write(result_1_fp16); cslDebug((70, "L1=0x%x\n", result_1)); // Convert result_lo_0 of HLS FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_result_1_fp16, chn_result_1_fp17); slope_fp16 = (int16_t)slope_oflow_scale; chn_slope_fp16.write(slope_fp16); // Convert FP16 to HLS_FP17 HLS_fp16_to_fp17(chn_slope_fp16, chn_slope_fp17); // Convert FP32 to HLS_FP17 lut_end_fp32 = lut_end; chn_lut_end_fp32.write(lut_end_fp32); chn_square_sum_fp32.write(square_sum); HLS_fp32_sub(chn_square_sum_fp32, chn_lut_end_fp32, chn_lut_sub_result_fp32); HLS_fp32_to_fp17(chn_lut_sub_result_fp32, chn_lut_sub_result_fp17); // chn_gap * slope HLS_fp17_mul(chn_lut_sub_result_fp17, chn_slope_fp17, chn_mul_result_fp17); HLS_fp17_add(chn_mul_result_fp17, chn_result_1_fp17, chn_result_fp17); } else { result_0 = lut[lut_index]; result_1 = lut[lut_index+1]; result_0_fp16 = result_0; result_1_fp16 = result_1; chn_result_0_fp16.write(result_0_fp16); chn_result_1_fp16.write(result_1_fp16); cslDebug((70, "L0=0x%x, L1=0x%x\n", result_0, result_1)); // Convert HLS_FP16 to HLS_FP32 HLS_fp16_to_fp32(chn_result_0_fp16, chn_result_0_fp32); HLS_fp16_to_fp32(chn_result_1_fp16, chn_result_1_fp32); // Convert result_lo_0 of HLS FP16 to HLS_FP17 chn_result_0_fp16.write(result_0_fp16); HLS_fp16_to_fp17(chn_result_0_fp16, chn_result_0_fp17); // Interpolation HLS_fp32_sub(chn_result_1_fp32, chn_result_0_fp32, chn_L1_minus_L0_fp32); //vFp32Type L1_minus_L0_fp32 = chn_L1_minus_L0_fp32.read(); //cslDebug((70,"L1_minus_L0_fp32=0x%x\n", L1_minus_L0_fp32)); //chn_L1_minus_L0_fp32.write(L1_minus_L0_fp32); HLS_fp32_to_fp17(chn_L1_minus_L0_fp32, chn_L1_minus_L0_fp17); HLS_fp17_mul(chn_L1_minus_L0_fp17, chn_lut_offset_fp17, chn_result_lut_tmp); HLS_fp17_add(chn_result_lut_tmp, chn_result_0_fp17, chn_result_fp17); lut_hit = true; /* float L0_float, L1_float, L1_minus_L0_float, result_float; half2single(&L0_float,&result_0_fp16, 1); cslDebug((70,"L0: %f(0x%x)\n", L0_float, *(int *)(&L0_float) )); half2single(&L1_float,&result_1_fp16, 1); cslDebug((70,"L1: %f(0x%x)\n", L1_float, *(int *)(&L1_float) )); L1_minus_L0_float = L1_float - L0_float; cslDebug((70,"L1-L1: %f(0x%x)\n", L1_minus_L0_float, *(int *)(&L1_minus_L0_float) )); result_float = L0_float + L1_minus_L0_float * lut_offset; cslDebug((70,"result: %f(0x%x)\n", result_float, *(int *)(&result_float) ));*/ } } void HLS_CDP_lookup_fp16 ( int16_t *data_in, // 12 * fp17 int16_t *le_lut, int16_t *lo_lut, // Configurations uint16_t normalz_len, uint16_t raw_method, bool lut_uflow_priority, bool lut_oflow_priority, bool lut_hybrid_priority, uint64_t le_start, int16_t le_index_offset, int8_t le_index_select, uint64_t le_end, uint64_t lo_start, int8_t lo_index_select, uint64_t lo_end, uint16_t datin_offset, uint16_t datin_scale, uint8_t datin_shifter, uint32_t datout_offset, uint16_t datout_scale, uint8_t datout_shifter, int16_t le_slope_uflow_scale, int16_t le_slope_oflow_scale, int16_t lo_slope_uflow_scale, int16_t lo_slope_oflow_scale, bool sqsum_bypass, bool mul_bypass, int16_t *normalz_out, uint32_t *lut_u_flow, uint32_t *lut_o_flow, uint32_t *lut_le_hit, uint32_t *lut_lo_hit, uint32_t *lut_hybrid_hit) // 16bits { int i; // Outputs bool le_underflow; bool le_overflow; //bool exp_underflow; //bool exp_overflow; bool lo_underflow; bool lo_overflow; bool le_hit; bool lo_hit; // Variables int32_t icvt_data_out[12]; ac_channel<vFp32Type> fp17tofp32_out[12]; ac_channel<vFp32Type> square_array[12]; //ac_channel<vFp32Type> square_sum; vFp32Type square_result[12]; // Outputs of lut tables ac_channel<vFp17Type> chn_result_le_fp17; ac_channel<vFp17Type> chn_result_lo_fp17; // ac_channel<vFp17Type> chn_result_fp17; ac_channel<vFp17Type> chn_result_to_ocvt_fp17; ac_channel<vFp17Type> chn_ocvt_out_fp17; #if 0 // Initialization le_underflow = false; le_overflow = false; exp_underflow = false; exp_overflow = false; lo_underflow = false; lo_overflow = false; le_hit = false; lo_hit = false; #endif vFp32Type icvt_data_out_fp32[12]; float tmp[12], din_offset, din_scale; half2single(&din_offset, &datin_offset, 1); half2single(&din_scale, &datin_scale, 1); cslDebug((70, "Data before input converter(float)\n")); for(i=0; i<12; i++) { half2single(&tmp[i], &data_in[i], 1); cslDebug((70, "%f(0x%x) ", tmp[i], *(int *)(&tmp[i]) )); } cslDebug((70, "\n")); cslDebug((70, "Data after square(float)\n")); for(i=0; i<12; i++) { tmp[i] = tmp[i] * tmp[i]; cslDebug((70, "%f(0x%x) ", tmp[i], *(int *)(&tmp[i]) )); } cslDebug((70, "\n")); for(i=0; i<12; i++) { //***** Input Convertor (FP16->FP17) ****** cdp_icvt_hls(&data_in[i], datin_offset, datin_scale, datin_shifter, NVDLA_CDP_RDMA_D_DATA_FORMAT_0_INPUT_DATA_FP16, &icvt_data_out[i]);
//***** Convert FP17 to FP32 ****** ac_channel<vFp17Type> chn_a; chn_a.write(icvt_data_out[i]); HLS_fp17_to_fp32(chn_a, fp17tofp32_out[i]); icvt_data_out_fp32[i] = fp17tofp32_out[i].read(); ac_channel<vFp32Type> chn_b, chn_c; chn_b.write(icvt_data_out_fp32[i]); chn_c.write(icvt_data_out_fp32[i]); if(sqsum_bypass) { square_result[i] = icvt_data_out_fp32[i]; } else { HLS_fp32_mul(chn_b, chn_c, square_array[i]); // HLS_FP32 mul square_result[i] = square_array[i].read(); //keep data to re-write the square_array later } } // cslDebug((70, "Data after input convertor(FP17):\n")); // for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&icvt_data_out[i]) )); // cslDebug((70, "\n")); cslDebug((70, "Data after input convertor(FP32):\n")); for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&icvt_data_out_fp32[i]) )); cslDebug((70, "\n")); cslDebug((70, "Data after square:\n")); for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&square_result[i]) )); cslDebug((70, "\n")); //***** Per Element ****** for (i=0; i<4; i++) { le_underflow = false; le_overflow = false; //exp_underflow = false; //exp_overflow = false; lo_underflow = false; lo_overflow = false; le_hit = false; lo_hit = false; //re-write square_array in each iteration since it is empty after read for(int j=0; j<12; j++) square_array[j].write(square_result[j]); //***** Sum ****** vFp32Type square_sum_result; if(sqsum_bypass) { square_sum_result = square_array[i+4].read(); } else { ac_channel<vFp32Type> square_sum_1, square_sum_2; HLS_fp32_add(square_array[i+3], square_array[i+5], square_sum_1); //3 + 5 HLS_fp32_add(square_sum_1, square_array[i+4], square_sum_2); //sum3 = (3 + 5) + 4 ac_channel<vFp32Type> square_sum_3, square_sum_4; if(normalz_len > 0) //5+ elements { HLS_fp32_add(square_array[i+2], square_array[i+6], square_sum_3); //2 + 6 HLS_fp32_add(square_sum_2, square_sum_3, square_sum_4); //sum5 = sum3 + (2 + 6) } ac_channel<vFp32Type> square_sum_5, square_sum_6; if(normalz_len > 1) //7+ elements { HLS_fp32_add(square_array[i+1], square_array[i+7], square_sum_5); //1 + 7 HLS_fp32_add(square_sum_4, square_sum_5, square_sum_6); //sum7 = sum5 + (1 + 7) } ac_channel<vFp32Type> square_sum_7, square_sum_8; if(normalz_len > 2) //9 elements { HLS_fp32_add(square_array[i+0], square_array[i+8], square_sum_7); //1 + 7 HLS_fp32_add(square_sum_6, square_sum_7, square_sum_8); //sum9 = sum7 + (0 + 8) } switch(normalz_len) { case 0: square_sum_result = square_sum_2.read(); break; case 1: square_sum_result = square_sum_4.read(); break; case 2: square_sum_result = square_sum_6.read(); break; case 3: square_sum_result = square_sum_8.read(); break; #pragma CTC SKIP default: break; #pragma CTC ENDSKIP } } cslDebug((70, "Square sum: %x\n", *(int *)(&square_sum_result) )); // Look up Raw table if(NVDLA_CDP_S_LUT_CFG_0_LUT_LE_FUNCTION_EXPONENT == raw_method) { //raw lut is exponential cslDebug((70, "Lookup exp table\n")); HLS_CDP_lookup_lut(square_sum_result, 64, true, true, le_lut, le_start, le_end, le_slope_uflow_scale, le_slope_oflow_scale, le_index_offset, le_index_select, le_underflow, le_overflow, le_hit, chn_result_le_fp17); } else { // raw lut is linear cslDebug((70, "Lookup lin table\n")); HLS_CDP_lookup_lut(square_sum_result, 64, true, false, le_lut, le_start, le_end, le_slope_uflow_scale, le_slope_oflow_scale, le_index_offset, le_index_select, le_underflow, le_overflow, le_hit, chn_result_le_fp17); } cslDebug((70, "Lookup lo table\n")); // Look up LO(Linear Only) table HLS_CDP_lookup_lut(square_sum_result, 256, false, false, lo_lut, lo_start, lo_end, lo_slope_uflow_scale, lo_slope_oflow_scale, 0, lo_index_select, lo_underflow, lo_overflow, lo_hit, chn_result_lo_fp17); vFp17Type result_le = chn_result_le_fp17.read(); vFp17Type result_lo = chn_result_lo_fp17.read(); vFp17Type result_out; // Select result between RAW table and Density Table if(le_underflow && lo_underflow) { result_out = lut_uflow_priority? result_lo : result_le; (*lut_u_flow)++; } else if(le_overflow && lo_overflow) { result_out = lut_oflow_priority? result_lo : result_le; (*lut_o_flow)++; } else { if(le_hit ^ lo_hit) { result_out = le_hit? result_le : result_lo; if(le_hit) { (*lut_le_hit)++; } else { (*lut_lo_hit)++; } } else { if(lut_hybrid_priority) result_out = result_lo; else result_out = result_le; (*lut_hybrid_hit)++; } } cslDebug((70, "le:%x, lo:%x, out:%x\n" , *(int *)(&result_le), *(int *)(&result_lo), *(int *)(&result_out) )); if(mul_bypass) { float icvt_data_out_float = *(float *)&icvt_data_out_fp32[i+4]; if(std::isnan(icvt_data_out_float)) { chn_result_to_ocvt_fp17.write(icvt_data_out[i+4]); } else { chn_result_to_ocvt_fp17.write(result_out); } } else { ac_channel<vFp17Type> chn_result_fp17, chn_icvt_data_out_fp17; chn_result_fp17.write(result_out); vFp17Type icvt_data_out_fp17 = icvt_data_out[i+4]; chn_icvt_data_out_fp17.write(icvt_data_out_fp17); HLS_fp17_mul(chn_icvt_data_out_fp17, chn_result_fp17, chn_result_to_ocvt_fp17); } // Output Converter int64_t ocvt_data_in = chn_result_to_ocvt_fp17.read(); cslDebug((70, "ocvt_data_in:%x\n", (int)ocvt_data_in)); uint8_t flag; cdp_ocvt_hls(&ocvt_data_in, datout_offset, datout_scale, datout_shifter, NVDLA_CDP_RDMA_D_DATA_FORMAT_0_INPUT_DATA_FP16, &normalz_out[i], &flag); } }
/******************************************************************************* * pn532_base.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 "pn532_base.h" #include "info.h" void pn532_base::pushack() { to.write(0x00); to.write(0x00); to.write(0xFF); to.write(0x00); to.write(0xFF); to.write(0x00); } void pn532_base::pushsyntaxerr() { to.write(0x00); to.write(0x00); to.write(0xFF); to.write(0x01); to.write(0xFF); to.write(0x7F); to.write(0x81); to.write(0x00); } void pn532_base::pushpreamble(int len, bool hosttopn, int cmd, unsigned char *c) { to.write(0x00); to.write(0x00); to.write(0xFF); to.write(len); to.write(0x100-len); /* Now we clear the checksum as we begin with the TFI. */ *c = 0; pushandcalc((hosttopn)?0xd4:0xd5, c); pushandcalc(cmd, c); } void pn532_base::setcardnotpresent() { mif.tags = 0; mif.sens_res = 0x0000; mif.sel_res = 0; mif.uidLength = 0; mif.uidValue = 0x0000; } void pn532_base::setcardpresent(uint32_t uid) { mif.tags = 1; mif.sens_res = 0x5522; mif.sel_res = 0; mif.uidLength = 4; mif.uidValue = uid; std::map<int, data_block_t>::iterator i; for(i = mif.mem.begin(); i != mif.mem.end(); i++) i->second.authenticated = false; mif.lastincmd = 0x0; mif.bn = 0x0; } void pn532_base::mifset(int pos, const char *value) { int i; bool fillzero; fillzero = false; for (i = 0; i < 15; i = i + 1) { if (!fillzero) { mif.mem[pos].data[i] = value[i]; if (value[i] == '\0') fillzero = true; } else mif.mem[pos].data[i] = 0; } } void pn532_base::mifsetn(int pos, const uint8_t *value, int len) { int i; bool fillzero; fillzero = false; for (i = 0; i < 15; i = i + 1) { if (!fillzero) { mif.mem[pos].data[i] = value[i]; if (i == len-1) fillzero = true; } else mif.mem[pos].data[i] = 0; } } void pn532_base::start_of_simulation() { /* We begin setting the card as non-present. */ setcardnotpresent(); mif.mxrtypassiveactivation = 0xff; /* And we initialize the device to off and no IRQ. */ opstate.write(OPOFF); } pn532_base::resp_t pn532_base::pushresp() { unsigned char cksum = 0; /* Now we can start processing the commands. */ if (mif.cmd == 0x4a && !mif.cmdbad) { /* If we got a card, we return the data on it. */ if (mif.tags > 0) { /* Calculate size. */ int len = 1 + 1 + mif.tags * (1+2+1+1+mif.uidLength) + 1; int i; /* Preamble */ pushpreamble(len, false, 0x4B, &cksum); /* Packet */ pushandcalc(mif.tags, &cksum);/* NbTg */ for(i = 1; i <= mif.tags; i = i + 1) { pushandcalc(i, &cksum); /* Tag no. */ pushandcalc(mif.sens_res>>8, &cksum);/* sens res upper */ pushandcalc(mif.sens_res&0xff, &cksum);/* sens res lower */ pushandcalc(mif.sel_res, &cksum); /* sel res */ pushandcalc(mif.uidLength, &cksum); /* NFCID Len */ } /* NFCID */ pushandcalc(mif.uidValue>>24, &cksum); pushandcalc((mif.uidValue&0xff0000)>>16, &cksum); pushandcalc((mif.uidValue&0xff00)>>8, &cksum); pushandcalc(mif.uidValue&0xff, &cksum); to.write(0x100-cksum); /* DCS */ to.write(0x00); /* ZERO */ /* If there is no card, and it is configured to infinite retries, we need * to try again. */ } else if (mif.retries == 0xff) { return RESP_RETRY; /* If we had a number of retries set, we then decrement the count and * retry. */ } else if (mif.retries > 0) { mif.retries = mif.retries - 1; return RESP_RETRY; /* If we are out of retries, we can then return an empty frame. */ } else { /* If no target came in, we return an empty list. */ /* Preamble */ pushpreamble(0x3, false, 0x4B, &cksum); /* Packet */ pushandcalc(0, &cksum); /* NbTg */ to.write(0x100-cksum); /* DCS */ to.write(0x00); /* ZERO */ } } /* SAMConfiguration command */ else if (mif.cmd == 0x14 && !mif.cmdbad) { pushpreamble(0x2, false, 0x15, &cksum); to.write(0x100-cksum); /* DCS */ to.write(0x00); /* ZERO */ } /* Get Firmware Version. */ else if (mif.cmd == 0x02 && !mif.cmdbad) { pushpreamble(0x06, false, 0x3, &cksum); /* Firmware Version, we just pick something cool from * one of the examples. */ pushandcalc(0x32, &cksum); /* IC */ pushandcalc(0x01, &cksum); /* Firmware Version */ pushandcalc(0x06, &cksum); /* Revision */ pushandcalc(0x07, &cksum); /* Support */ to.write(0x100-cksum); /* DCS */ to.write(0x00); /* ZERO */ } /* InDataExchange Command */ else if (mif.cmd == 0x40) { /* We don't process the actual MiFare commands, we just return that it * was authenticated ok. */ /* We return the data. If the command is bad, we return a failure and * some random junk. */ if (mif.cmdbad) { PRINTF_INFO("MIFARE", "Command Rejected"); pushpreamble(0x06, false, 0x41, &cksum); pushandcalc(0x55, &cksum); /* BAD */ pushandcalc(mif.lastincmd, &cksum); pushandcalc(0x02, &cksum); pushandcalc(0x03, &cksum); } else if (mif.lastincmd == 0x60) { PRINTF_INFO("MIFARE", "Block 0x%02x Authenticated", mif.bn); pushpreamble(0x06, false, 0x41, &cksum); pushandcalc(0x00, &cksum); /* OK */ pushandcalc(mif.lastincmd, &cksum); pushandcalc(0x02, &cksum); pushandcalc(0x03, &cksum); } else if (mif.lastincmd == 0xA0) { PRINTF_INFO("MIFARE", "Write to block 0x%02x", mif.bn); pushpreamble(0x06, false, 0x41, &cksum); pushandcalc(0x00, &cksum); /* OK */ pushandcalc(mif.lastincmd, &cksum); pushandcalc(0x02, &cksum); pushandcalc(0x03, &cksum); } else if (mif.lastincmd == 0x30) { PRINTF_INFO("MIFARE", "Read from block 0x%02x", mif.bn); int p; pushpreamble(21, false, 0x41, &cksum); pushandcalc(0x00, &cksum); /* OK */ p = 0; while (p < 16) { pushandcalc(mif.mem[mif.bn].data[p], &cksum); p = p + 1; } pushandcalc(0x90, &cksum); pushandcalc(0x00, &cksum); } else { PRINTF_INFO("MIFARE", "Other Command"); pushpreamble(0x06, false, 0x41, &cksum); pushandcalc(0x00, &cksum); /* OK */ pushandcalc(mif.lastincmd, &cksum); pushandcalc(0x02, &cksum); pushandcalc(0x03, &cksum); } to.write(0x100-cksum); /* DCS */ to.write(0x00); /* ZERO */ } else { /* For unknown commands we just return a syntax error. */ pushsyntaxerr(); } /* We also clear the command so we do not keep on sending it back. */ mif.cmd = 0; return RESP_OK; } void pn532_base::resp_th() { while(true) { /* We first wait for a command to come in. */ wait(newcommand_ev | ack_ev); /* Anytime we get a new command, we need to dump what we were doing before * and start it. So, we move the state back to OPACK to issue the new ACK. */ if (newcommand_ev.triggered()) { ack_ev.notify(200, SC_US); opstate.write(OPACK); /* For other times, we just process whatever command came in. */ } else switch (opstate.read()) { /* The manual was not clear what happens if the host does not read * the ACK. There are three possible options: * - it gets merged with the next command * - it gets overwitten * - the command does not start until the ACK was read * I am then assuming the third is the one. */ case OPACK: /* We dump any previous possible data in the to FIFO, like a * previous unread response, and we push the ACK. Then we wait * for it to be read out. */ flush_to(); pushack(); opstate.write(OPACKRDOUT); break; /* After the ACK has been read out, we do a delay. Some commands have * a predelay too. */ case OPACKRDOUT: if (mif.predelay != 0) { ack_ev.notify(sc_time(mif.predelay, SC_MS)); opstate.write(OPPREDELAY); } else { ack_ev.notify(sc_time(mif.delay, SC_MS)); opstate.write(OPBUSY); } break; case OPPREDELAY: ack_ev.notify(sc_time(mif.delay, SC_MS)); opstate.write(OPBUSY); break; /* Then we send the response. */ case OPBUSY: flush_to(); /* We try to push a response. If there is a retry request, we * reissue the delay and do it again. */ if (RESP_RETRY == pushresp()) ack_ev.notify(sc_time(mif.delay, SC_MS)); /* If the response was ok, we go to the READOUT state. */ else opstate.write(OPREADOUT); break; case OPREADOUT: opstate.write(OPIDLE); default: ; } } } void pn532_base::process_th() { unsigned char cksum = 0; unsigned char msg; enum {IDLE, UNLOCK1, UNLOCK2, UNLOCK3, UNLOCK4, UNLOCK5, PD0, PDN, DCS, LOCK} pn532state; while(true) { msg = grab(&cksum); switch(pn532state) { case IDLE: if (msg == 0x0) pn532state = UNLOCK1; else { PRINTF_WARN("PN532", "Warning: got an illegal preamble."); pn532state = IDLE; } break; case UNLOCK1: if (msg == 0x0) pn532state = UNLOCK2; else { PRINTF_WARN("PN532","Warning: got an illegal preamble, byte 2."); pn532state = IDLE; } break; case UNLOCK2: /* The first 0x0 can be as long as the customer wants, so we * discard any extra 0x0 received. */ if (msg == 0x0) pn532state = UNLOCK2; else if (msg == 0xff) pn532state = UNLOCK3; else { PRINTF_WARN("PN532","Warning: got an illegal preamble, byte 3."); pn532state = IDLE; } break; case UNLOCK3: /* And we collect the length of the next command. */ mif.len = msg; pn532state = UNLOCK4; break; case UNLOCK4: /* Anytime we go to the UNLOCK5 (TFI state) we clear the cksum. */ cksum = 0; /* Now we check the LCS, it should be the complement of the LEN. */ if (0x100 - mif.len != msg) { PRINTF_WARN("PN532", "Warning: got illegal LCS."); } pn532state = UNLOCK5; break; case UNLOCK5: { unsigned char tfi = msg; if (tfi != 0xD4) { PRINTF_WARN("PN532", "Warning: got illegal TFI %02x", tfi); pn532state = IDLE; } mif.len = mif.len - 1; pn532state = PD0; break; } case PD0: if (pn532state == PD0) mif.cmd = msg; mif.len = mif.len - 1; if (mif.len == 0) pn532state = DCS; else pn532state = PDN; /* We dump any previous command in the fifo. */ while(to.num_available() != 0) { cksum = cksum + to.read(); } break; case PDN: /* Some packages have a packet. If it has one we take it in to the * right places. Any remaining bytes or packets in unsupported * messages are pitched. */ mif.len = mif.len - 1; mif.cmdbad = false; /* SAM command */ if (mif.cmd == 0x14) { mif.mode = msg; if (mif.len<2) { mif.cmdbad = true; } else { mif.timeout=grab(&cksum); mif.len = mif.len-1; mif.useirq=grab(&cksum); mif.len = mif.len-1; } } /* InDataExchange */ else if (mif.cmd == 0x40) { /* For the InDataExchange command we are talking to the card. * This varies a lot according to the card, and it can get * quite complex. We are trying to do something simple here, * so all we do is check for a few commands. */ /* We first get the header. */ if (mif.len < 2) mif.cmdbad = true; else { /* msg has the Target No. */ mif.lastincmd = grab(&cksum); mif.len = mif.len - 1; /* cmd */ mif.bn = grab(&cksum); mif.len = mif.len - 1; /* Block No. */ /* Authenticate */ if (mif.lastincmd == 0x60 && mif.len >= 10) { mif.mem[mif.bn].authenticated = true; /* Write */ } else if (mif.lastincmd == 0xA0 && mif.len >= 16 && mif.mem[mif.bn].authenticated) { int p; p = 0; while (p < 16) { mif.mem[mif.bn].data[p] = grab(&cksum); mif.len = mif.len - 1; p = p + 1; } /* Read */ } else if (mif.lastincmd == 0x30 && mif.mem[mif.bn].authenticated) { ; /* Other commands we simply return a good as we do not know * what to do. */ } else { mif.cmdbad = false; } } } else if (mif.cmd == 0x32) { int cfgitem = msg; int cfg[3]; switch (cfgitem) { case 0x1: cfg[0] = grab(&cksum); mif.len = mif.len - 1; PRINTF_INFO("PN532", "Accepted RFConfiguration [0x1]=%02x", cfg[0]); break; case 0x2: cfg[0] = grab(&cksum); mif.len = mif.len - 1; cfg[1] = grab(&cksum); mif.len = mif.len - 1; cfg[2] = grab(&cksum); mif.len = mif.len - 1; PRINTF_INFO("PN532", "Accepted RFConfiguration [0x2]=RFU: %02x", cfg[0]); PRINTF_INFO("PN532", "Accepted RFConfiguration [0x2]=fATR_RES_Timeout: %02x", cfg[1]); PRINTF_INFO("PN532", "Accepted RFConfiguration [0x2]=fRetryTimeout: %02x", cfg[2]); break; case 0x4: cfg[0] = grab(&cksum); mif.len = mif.len - 1; PRINTF_INFO("PN532", "Accepted RFConfiguration [0x4]=MxRetryCOM: %02x", cfg[0]); break; case 0x5: cfg[0] = grab(&cksum); mif.len = mif.len - 1; cfg[1] = grab(&cksum); mif.len = mif.len - 1; cfg[2] = grab(&cksum); mif.len = mif.len - 1; PRINTF_INFO("PN532", "Accepted RFConfiguration [0x5]=MxRtyATR: %02x",cfg[0]); PRINTF_INFO("PN532", "Accepted RFConfiguration [0x5]=MxRtyPSL: %02x", cfg[1]); PRINTF_INFO("PN532", "Accepted RFConfiguration [0x5]=MxRtyPassiveActivation: %02x", cfg[2]); mif.mxrtypassiveactivation = cfg[2]; break; } if (mif.len<1) { mif.cmdbad = true; } else { mif.brty = grab(&cksum); mif.len = mif.len - 1; } /* brty=00 only supports 1 or 2 targets. */ if (mif.maxtg > 2 || mif.maxtg <= 0) mif.cmdbad = true; if (mif.brty != 0x00) mif.cmdbad = true; /* we only support 00*/ } else if (mif.cmd == 0x4a) { mif.maxtg = msg; if (mif.len<1) { mif.cmdbad = true; } else { mif.brty = grab(&cksum); mif.len = mif.len - 1; } /* brty=00 only supports 1 or 2 targets. */ if (mif.maxtg > 2 || mif.maxtg <= 0) mif.cmdbad = true; if (mif.brty != 0x00) mif.cmdbad = true; /* we only support 00*/ } /* We flush out the rest of the payload. */ while (mif.len > 0) { pn532state = DCS; int i = grab(&cksum); PRINTF_INFO("I", "%02x", i); mif.len = mif.len - 1; } /* And we go to the DCS. */ pn532state = DCS; break; case DCS: { /* We now check the DCS. Note that the DCS was added, so we should * see zero. If it is wrong, we need to backtrack to get the * expected value. */ if (cksum != 0) { PRINTF_WARN("PN532", "Got the DCS to be %02x when expected %02x", msg, 0x100 - (0xff & (cksum - msg))); } pn532state = LOCK; break; } case LOCK: /* We check the command to make sure it is a LOCK. */ if (msg != 0x00) { PRINTF_WARN("PN532", "Relock did not match!"); } /* And we return to idle. */ pn532state = IDLE; /* Now we can execute the command. */ if (mif.cmd == 0x4a) { PRINTF_INFO("PN532", "Accepted Inlist Passive Target"); /* We put then the response in the buffer */ mif.predelay = 5; mif.delay = 200; /* We set the retries to the maximum set and notify the process * to begin. */ mif.retries = mif.mxrtypassiveactivation; newcommand_ev.notify(); } else if (mif.cmd == 0x14) { PRINTF_INFO("PN532", "Accepted SAM configuration command"); /* We put then the response in the buffer */ mif.predelay = 5; mif.delay = 20; newcommand_ev.notify(); } else if (mif.cmd == 0x02) { PRINTF_INFO("PN532", "Accepted getVersion com
mand"); mif.predelay = 2; mif.delay = 20; newcommand_ev.notify(); } else if (mif.cmd == 0x40) { PRINTF_INFO("PN532", "Accepted InDataExchange command"); mif.predelay = 0; mif.delay = 1; newcommand_ev.notify(); } else if (mif.cmd == 0x32) { mif.predelay = 0; mif.delay = 1; newcommand_ev.notify(); } else { /* Illegal commands also are processed as commands, so an * ACK is returned, just the data packet has a syntax error. */ mif.predelay = 0; mif.delay = 1; PRINTF_INFO("PN532", "Accepted Unknown command"); newcommand_ev.notify(); } } pnstate.write(pn532state); } } /* For the IRQ manage, we initialize the thread taking the pin high. Then, when * the TO fifo changes, we will take it either high or low. */ void pn532_base::irqmanage_th() { bool wasempty = true; irq.write(GN_LOGIC_1); while(1) { wait(to.data_written_event() | to.data_read_event()); if (to.num_available() == 0 && !wasempty) { irq.write(GN_LOGIC_1); /* If the read_th was waiting to read data, we then wake it up to * go to the next state. */ if (opstate.read() == OPACKRDOUT || opstate.read() == OPREADOUT) ack_ev.notify(); } else irq.write(GN_LOGIC_0); wasempty = to.num_available() == 0; } } void pn532_base::trace(sc_trace_file *tf) { sc_trace(tf, opstate, opstate.name()); sc_trace(tf, ack_ev, ack_ev.name()); sc_trace(tf, newcommand_ev, newcommand_ev.name()); sc_trace(tf, pnstate, pnstate.name()); sc_trace(tf, intoken, intoken.name()); sc_trace(tf, outtoken, outtoken.name()); sc_trace(tf, irq, irq.name()); }
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** display.cpp -- Original Author: Rocco Jonack, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation: Teodor Vasilache and Dragos Dospinescu, AMIQ Consulting s.r.l. (contributors@amiq.com) Date: 2018-Feb-20 Description of Modification: Included the FC4SC library in order to collect functional coverage data and generate a coverage database. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include <systemc.h> #include "display.h" #include "fc4sc.hpp" void display::entry(){ // Reading Data when valid if high tmp1 = result.read(); cout << "Display : " << tmp1 << " " /* << " at time " << sc_time_stamp() << endl; */ << " at time " << sc_time_stamp().to_double() << endl; i++; // sample the data this->out_cg.sample(result, output_data_ready); if(i == 24) { cout << "Simulation of " << i << " items finished" /* << " at time " << sc_time_stamp() << endl; */ << " at time " << sc_time_stamp().to_double() << endl; // generate the coverage database from the collected data fc4sc::global::coverage_save("coverage_results.xml"); sc_stop(); }; } // EOF
/* * @ASCK */ #include <systemc.h> SC_MODULE (PC) { sc_in <bool> clk; sc_in <sc_uint<14>> prev_addr; sc_out <sc_uint<14>> next_addr; /* ** module global variables */ SC_CTOR (PC){ SC_METHOD (process); sensitive << clk.pos(); } void process () { next_addr.write(prev_addr.read()); } };
#include <systemc.h> class sc_clockx : sc_module, sc_interface { public: sc_event edge; sc_event change; bool val; bool _val; int delta; private: int period; SC_HAS_PROCESS(sc_clockx); void run(void) { int tmp = period/2; edge.notify(SC_ZERO_TIME); change.notify(SC_ZERO_TIME); while(true) { wait(tmp, SC_NS); edge.notify(SC_ZERO_TIME); change.notify(SC_ZERO_TIME); val = !val; } } public: sc_clockx(sc_module_name name, int periodparam): sc_module(name) { SC_THREAD(run); period = periodparam; val = true; _val = true; } bool read() { return val; } void write(bool newval) { _val = newval; if (!(_val == val)) request_update(); } void update() { if (!(_val == val)) { val = _val; change.notify(SC_ZERO_TIME); delta = sc_delta_count(); } } };
/* * @ASCK */ #include <systemc.h> SC_MODULE (ID) { sc_in_clk clk; sc_in <sc_int<8>> prev_A; sc_in <sc_int<8>> prev_B; sc_in <sc_int<13>> prev_Imm; sc_in <sc_uint<3>> prev_Sa; sc_in <sc_uint<5>> prev_AluOp; sc_in <bool> prev_r; sc_in <bool> prev_w; sc_in <bool> prev_AluMux; sc_in <bool> prev_WbMux; sc_in <bool> prev_call; sc_in <bool> prev_regWrite; sc_in <sc_uint<3>> prev_rd; sc_out <sc_int<8>> next_A; sc_out <sc_int<8>> next_B; sc_out <sc_int<13>> next_Imm; sc_out <sc_uint<3>> next_Sa; sc_out <sc_uint<5>> next_AluOp; sc_out <bool> next_r; sc_out <bool> next_w; sc_out <bool> next_AluMux; sc_out <bool> next_WbMux; sc_out <bool> next_call; sc_out <bool> next_regWrite; sc_out <sc_uint<3>> next_rd; /* ** module global variables */ SC_CTOR (ID){ SC_THREAD (process); sensitive << clk.pos(); } void process () { while(true){ wait(); if(now_is_call){ wait(micro_acc_ev); } next_A.write(prev_A.read()); next_B.write(prev_B.read()); next_Imm.write(prev_Imm.read()); next_Sa.write(prev_Sa.read()); next_AluOp.write(prev_AluOp.read()); next_AluMux.write(prev_AluMux.read()); next_r.write(prev_r.read()); next_w.write(prev_w.read()); next_WbMux.write(prev_WbMux.read()); next_call.write(prev_call.read()); next_regWrite.write(prev_regWrite); next_rd.write(prev_rd.read()); } } };
// //------------------------------------------------------------// // Copyright 2009-2012 Mentor Graphics Corporation // // All Rights Reserved Worldwid // // // // Licensed under the Apache License, Version 2.0 (the // // "License"); you may not use this file except in // // compliance with the License. You may obtain a copy of // // the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in // // writing, software distributed under the License is // // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // // CONDITIONS OF ANY KIND, either express or implied. See // // the License for the specific language governing // // permissions and limitations under the License. // //------------------------------------------------------------// #ifndef PACKET_H #define PACKET_H #include <vector> using std::vector; #include <systemc.h> #include <tlm.h> using namespace sc_core; class packet { public: short cmd; int addr; vector<char> data; }; //------------------------------------------------------------------------------ // Begin UVMC-specific code #include "uvmc.h" using namespace uvmc; UVMC_UTILS_3 (packet,cmd,addr,data) #endif // PACKET_H
/************************************************************************** * * * 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 "axi/axi4.h" #include "axi4_segment.h" #include "sysbus_axi_struct.h" #include "systemc_subsystem.h" 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(connections_clk); scs.reset_bar(reset_bar); scs.w_cpu.aw.dat(aw_msg_port); scs.w_cpu.aw.vld(aw_valid_port); scs.w_cpu.aw.rdy(aw_ready_port); scs.w_cpu.w.dat(w_msg_port); scs.w_cpu.w.vld(w_valid_port); scs.w_cpu.w.rdy(w_ready_port); scs.w_cpu.b.dat(b_msg_port); scs.w_cpu.b.vld(b_valid_port); scs.w_cpu.b.rdy(b_ready_port); scs.r_cpu.ar.dat(ar_msg_port); scs.r_cpu.ar.vld(ar_valid_port); scs.r_cpu.ar.rdy(ar_ready_port); scs.r_cpu.r.dat(r_msg_port); scs.r_cpu.r.vld(r_valid_port); scs.r_cpu.r.rdy(r_ready_port); } }; #ifdef QUESTA SC_MODULE_EXPORT(systemc_subsystem_wrapper); #endif
// //------------------------------------------------------------// // 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 Connection Example - Native SC to SC // // This example serves as a review for how to make 'native' TLM connections // between two SystemC components (does not use UVMC). // // (see UVMC_Connections_SC2SC-native.png) // // In SystemC, a ~port~ is connected to an ~export~ or an ~interface~ using // the port's ~bind~ function. An sc_module's port can also be connected to // a port in a parent module, which effectively promotes the port up one // level of hierarchy. // // In this particular example, ~sc_main~ does the following // // - Instantiates ~producer~ and ~consumer~ sc_modules // // - Binds the producer's ~out~ port to the consumer's ~in~ export // // - Calls ~sc_start~ to start the SystemC portion of our testbench. // // The ~bind~ call looks the same for all port-to-export/interface connections, // regardless of the port types and transaction types. The C++ compiler // will let you know if you've attempted an incompatible connection. //----------------------------------------------------------------------------- // (inline source) #include <systemc.h> using namespace sc_core; #include "consumer.h" #include "producer.h" int sc_main(int argc, char* argv[]) { producer prod("prod"); consumer cons("cons"); prod.out.bind(cons.in); sc_start(-1); return 0; }
//----------------------------------------------------- #include <systemc.h> /** * @brief Enum that represents the main FPU operations * */ typedef enum { SC_FPU_ADD = 1, SC_FPU_SUB = 2, SC_FPU_MULT = 3, SC_FPU_DIV = 4 } sc_fpu_op_t; /** * @brief Class the represent and FPU using PV model * */ SC_MODULE (fpu_unit) { protected: //----------------------------Internal variables---------------------------- // Operation type sc_fpu_op_t op_type; // Events to trigger the operation execution sc_event event_op; //-----------------------------Internal methods----------------------------- /** * @brief Performs the operation between the operands * */ void exec_op() { while (true) { wait(event_op); // Perform the operations switch (this->op_type) { case SC_FPU_ADD: this->op_c.write(this->op_a.read() + this->op_b.read()); break; case SC_FPU_SUB: this->op_c.write(this->op_a.read() - this->op_b.read()); break; case SC_FPU_MULT: this->op_c.write(this->op_a.read() * this->op_b.read()); break; case SC_FPU_DIV: this->op_c.write(this->op_a.read() / this->op_b.read()); break; default: break; } } } public: // First operand sc_in<float> op_a; // Second operand sc_in<float> op_b; // Result sc_out<float> op_c; SC_HAS_PROCESS(fpu_unit); /** * @brief Construct a new fpu unit object * * @param name - name of the module */ fpu_unit(sc_module_name name) : sc_module(name) { SC_THREAD(exec_op); } // End of Constructor //------------------------------Public methods------------------------------ /** * @brief Adds two float numbers * */ void add() { this->op_type = SC_FPU_ADD; this->event_op.notify(1, SC_NS); } /** * @brief Divides two float numbers */ void div() { this->op_type = SC_FPU_DIV; this->event_op.notify(3, SC_NS); } /** * @brief Multiplies two float numbers * */ void mult() { this->op_type = SC_FPU_MULT; this->event_op.notify(3, SC_NS); } /** * @brief Subtracts two float numbers * */ void subs() { this->op_type = SC_FPU_SUB; this->event_op.notify(1, SC_NS); } };
#include <memory> #include <systemc.h> #include "Vtop.h" #include "bfm.h" int sc_main(int argc, char* argv[]) { if (false && argc && argv) {} Verilated::debug(0); Verilated::randReset(2); Verilated::commandArgs(argc, argv); ios::sync_with_stdio(); sc_clock clk{"clk", 10, SC_NS, 0.5, 5, SC_NS, true}; sc_signal<bool> reset; sc_signal<bool> cs; sc_signal<bool> rw; sc_signal<uint32_t> addr; sc_signal<uint32_t> data_in; sc_signal<bool> ready; sc_signal<uint32_t> data_out; const std::unique_ptr<Vtop> top{new Vtop{"top"}}; top->clk(clk); top->reset(reset); top->cs(cs); top->rw(rw); top->addr(addr); top->data_in(data_in); top->ready(ready); top->data_out(data_out); const std::unique_ptr<bfm> u_bfm{new bfm("bfm")}; u_bfm->clk(clk); u_bfm->reset(reset); u_bfm->cs(cs); u_bfm->rw(rw); u_bfm->addr(addr); u_bfm->data_in(data_out); u_bfm->ready(ready); u_bfm->data_out(data_in); sc_start(); top->final(); cout << "done, time = " << sc_time_stamp() << endl; return 0; } #ifdef VL_USER_STOP void vl_stop(const char *filename, int linenum, const char *hier) VL_MT_UNSAFE { sc_stop(); cout << "call vl_stop" << endl; } #endif
// ---------------------------------------------------------------------------- // SystemC SCVerify Flow -- sysc_sim_trans.cpp // // HLS version: 10.4b/841621 Production Release // HLS date: Thu Oct 24 17:20:07 PDT 2019 // Flow Packages: HDL_Tcl 8.0a, SCVerify 10.4 // // Generated by: billyk@cad.eecs.harvard.edu // Generated date: Sun May 03 14:22:05 EDT 2020 // // ---------------------------------------------------------------------------- // // ------------------------------------- // sysc_sim_wrapper // Represents a new SC_MODULE having the same interface as the original model SysArray_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/SysArray/SysArray.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<ac_int<8, true >, Connections::SYN_PORT > weight_in_vec[8]; Connections::In<ac_int<8, true >, Connections::SYN_PORT > act_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_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_act_in_vec_0_val; sc_signal< sc_logic > ccs_rtl_SIG_act_in_vec_1_val; sc_signal< sc_logic > ccs_rtl_SIG_act_in_vec_2_val; sc_signal< sc_logic > ccs_rtl_SIG_act_in_vec_3_val; sc_signal< sc_logic > ccs_rtl_SIG_act_in_vec_4_val; sc_signal< sc_logic > ccs_rtl_SIG_act_in_vec_5_val; sc_signal< sc_logic > ccs_rtl_SIG_act_in_vec_6_val; sc_signal< sc_logic > ccs_rtl_SIG_act_in_vec_7_val; sc_signal< sc_logic > ccs_rtl_SIG_act_in_vec_0_rdy; sc_signal< sc_logic > ccs_rtl_SIG_act_in_vec_1_rdy; sc_signal< sc_logic > ccs_rtl_SIG_act_in_vec_2_rdy; sc_signal< sc_logic > ccs_rtl_SIG_act_in_vec_3_rdy; sc_signal< sc_logic > ccs_rtl_SIG_act_in_vec_4_rdy; sc_signal< sc_logic > ccs_rtl_SIG_act_in_vec_5_rdy; sc_signal< sc_logic > ccs_rtl_SIG_act_in_vec_6_rdy; sc_signal< sc_logic > ccs_rtl_SIG_act_in_vec_7_rdy; sc_signal< sc_lv<8> > ccs_rtl_SIG_act_in_vec_0_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_act_in_vec_1_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_act_in_vec_2_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_act_in_vec_3_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_act_in_vec_4_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_act_in_vec_5_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_act_in_vec_6_msg; sc_signal< sc_lv<8> > ccs_rtl_SIG_act_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") , weight_in_vec() , act_in_vec() , accum_out_vec() , ccs_rtl_SIG_clk("ccs_rtl_SIG_clk") , ccs_rtl_SIG_rst("ccs_rtl_SIG_rst") , 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_act_in_vec_0_val("ccs_rtl_SIG_act_in_vec_0_val") , ccs_rtl_SIG_act_in_vec_1_val("ccs_rtl_SIG_act_in_vec_1_val") , ccs_rtl_SIG_act_in_vec_2_val("ccs_rtl_SIG_act_in_vec_2_val") , ccs_rtl_SIG_act_in_vec_3_val("ccs_rtl_SIG_act_in_vec_3_val") , ccs_rtl_SIG_act_in_vec_4_val("ccs_rtl_SIG_act_in_vec_4_val") , ccs_rtl_SIG_act_in_vec_5_val("ccs_rtl_SIG_act_in_vec_5_val") , ccs_rtl_SIG_act_in_vec_6_val("ccs_rtl_SIG_act_in_vec_6_val") , ccs_rtl_SIG_act_in_vec_7_val("ccs_rtl_SIG_act_in_vec_7_val") , ccs_rtl_SIG_act_in_vec_0_rdy("ccs_rtl_SIG_act_in_vec_0_rdy") , ccs_rtl_SIG_act_in_vec_1_rdy("ccs_rtl_SIG_act_in_vec_1_rdy") , ccs_rtl_SIG_act_in_vec_2_rdy("ccs_rtl_SIG_act_in_vec_2_rdy") , ccs_rtl_SIG_act_in_vec_3_rdy("ccs_rtl_SIG_act_in_vec_3_rdy") , ccs_rtl_SIG_act_in_vec_4_rdy("ccs_rtl_SIG_act_in_vec_4_rdy") , ccs_rtl_SIG_act_in_vec_5_rdy("ccs_rtl_SIG_act_in_vec_5_rdy") , ccs_rtl_SIG_act_in_vec_6_rdy("ccs_rtl_SIG_act_in_vec_6_rdy") , ccs_rtl_SIG_act_in_vec_7_rdy("ccs_rtl_SIG_act_in_vec_7_rdy") , ccs_rtl_SIG_act_in_vec_0_msg("ccs_rtl_SIG_act_in_vec_0_msg") , ccs_rtl_SIG_act_in_vec_1_msg("ccs_rtl_SIG_act_in_vec_1_msg") , ccs_rtl_SIG_act_in_vec_2_msg("ccs_rtl_SIG_act_in_vec_2_msg") , ccs_rtl_SIG_act_in_vec_3_msg("ccs_rtl_SIG_act_in_vec_3_msg") , ccs_rtl_SIG_act_in_vec_4_msg("ccs_rtl_SIG_act_in_vec_4_msg") , ccs_rtl_SIG_act_in_vec_5_msg("ccs_rtl_SIG_act_in_vec_5_msg") , ccs_rtl_SIG_act_in_vec_6_msg("ccs_rtl_SIG_act_in_vec_6_msg") , ccs_rtl_SIG_act_in_vec_7_msg("ccs_rtl_SIG_act_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.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.act_in_vec_0_val(ccs_rtl_SIG_act_in_vec_0_val); ccs_rtl.act_in_vec_1_val(ccs_rtl_SIG_act_in_vec_1_val); ccs_rtl.act_in_vec_2_val(ccs_rtl_SIG_act_in_vec_2_val); ccs_rtl.act_in_vec_3_val(ccs_rtl_SIG_act_in_vec_3_val); ccs_rtl.act_in_vec_4_val(ccs_rtl_SIG_act_in_vec_4_val); ccs_rtl.act_in_vec_5_val(ccs_rtl_SIG_act_in_vec_5_val); ccs_rtl.act_in_vec_6_val(ccs_rtl_SIG_act_in_vec_6_val); ccs_rtl.act_in_vec_7_val(ccs_rtl_SIG_act_in_vec_7_val); ccs_rtl.act_in_vec_0_rdy(ccs_rtl_SIG_act_in_vec_0_rdy); ccs_rtl.act_in_vec_1_rdy(ccs_rtl_SIG_act_in_vec_1_rdy); ccs_rtl.act_in_vec_2_rdy(ccs_rtl_SIG_act_in_vec_2_rdy); ccs_rtl.act_in_vec_3_rdy(ccs_rtl_SIG_act_in_vec_3_rdy); ccs_rtl.act_in_vec_4_rdy(ccs_rtl_SIG_act_in_vec_4_rdy); ccs_rtl.act_in_vec_5_rdy(ccs_rtl_SIG_act_in_vec_5_rdy); ccs_rtl.act_in_vec_6_rdy(ccs_rtl_SIG_act_in_vec_6_rdy); ccs_rtl.act_in_vec_7_rdy(ccs_rtl_SIG_act_in_vec_7_rdy); ccs_rtl.act_in_vec_0_msg(ccs_rtl_SIG_act_in_vec_0_msg); ccs_rtl.act_in_vec_1_msg(ccs_rtl_SIG_act_in_vec_1_msg); ccs_rtl.act_in_vec_2_msg(ccs_rtl_SIG_act_in_vec_2_msg); ccs_rtl.act_in_vec_3_msg(ccs_rtl_SIG_act_in_vec_3_msg); ccs_rtl.act_in_vec_4_msg(ccs_rtl_SIG_act_in_vec_4_msg); ccs_rtl.act_in_vec_5_msg(ccs_rtl_SIG_act_in_vec_5_msg); ccs_rtl.act_in_vec_6_msg(ccs_rtl_SIG_act_in_vec_6_msg); ccs_rtl.act_in_vec_7_msg(ccs_rtl_SIG_act_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 << 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 << act_in_vec[0].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << act_in_vec[1].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << act_in_vec[2].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << act_in_vec[3].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << act_in_vec[4].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << act_in_vec[5].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << act_in_vec[6].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << act_in_vec[7].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << ccs_rtl_SIG_act_in_vec_0_rdy << ccs_rtl_SIG_act_in_vec_1_rdy << ccs_rtl_SIG_act_in_vec_2_rdy << ccs_rtl_SIG_act_in_vec_3_rdy << ccs_rtl_SIG_act_in_vec_4_rdy << ccs_rtl_SIG_act_in_vec_5_rdy << ccs_rtl_SIG_act_in_vec_6_rdy << ccs_rtl_SIG_act_in_vec_7_rdy << act_in_vec[0].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << act_in_vec[1].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << act_in_vec[2].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << act_in_vec[3].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << act_in_vec[4].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << act_in_vec[5].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << act_in_vec[6].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << act_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 SysArray_rtl // ------------------------------------- // // --------------------------------------------------------------- // Process: SC_METHOD update_proc // Static sensitivity: sensitive << clk << rst << 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 << act_in_vec[0].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << act_in_vec[1].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << act_in_vec[2].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << act_in_vec[3].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << act_in_vec[4].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << act_in_vec[5].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << act_in_vec[6].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << act_in_vec[7].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val << ccs_rtl_SIG_act_in_vec_0_rdy << ccs_rtl_SIG_act_in_vec_1_rdy << ccs_rtl_SIG_act_in_vec_2_rdy << ccs_rtl_SIG_act_in_vec_3_rdy << ccs_rtl_SIG_act_in_vec_4_rdy << ccs_rtl_SIG_act_in_vec_5_rdy << ccs_rtl_SIG_act_in_vec_6_rdy << ccs_rtl_SIG_act_in_vec_7_rdy << act_in_vec[0].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << act_in_vec[1].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << act_in_vec[2].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << act_in_vec[3].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << act_in_vec[4].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << act_in_vec[5].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << act_in_vec[6].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg << act_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:b8493181-44ed-443f-beb1-e7f82e6a327d-373:clk:b8493181-44ed-443f-beb1-e7f82e6a327d-373 sc_logic t_b8493181_44ed_443f_beb1_e7f82e6a327d_373; // NPS - LV to hold field ccs_rtl_SIG_clk.write(clk.read()); // none.sc_in field_key=rst:b8493181-44ed-443f-beb1-e7f82e6a327d-374:rst:b8493181-44ed-443f-beb1-e7f82e6a327d-374 sc_logic t_b8493181_44ed_443f_beb1_e7f82e6a327d_374; // NPS - LV to hold field type_to_vector(rst.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_374); // read orig port and type convert ccs_rtl_SIG_rst.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_374); // then write to RTL port // none.sc_in field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:val:b8493181-44ed-443f-beb1-e7f82e6a327d-417 sc_logic t_b8493181_44ed_443f_beb1_e7f82e6a327d_417; // NPS - LV to hold field type_to_vector(weight_in_vec[0].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_417); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_0_val.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_417); // then write to RTL port // none.sc_in field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:val:b8493181-44ed-443f-beb1-e7f82e6a327d-417 type_to_vector(weight_in_vec[1].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_417); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_1_val.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_417); // then write to RTL port // none.sc_in field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:val:b8493181-44ed-443f-beb1-e7f82e6a327d-417 type_to_vector(weight_in_vec[2].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_417); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_2_val.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_417); // then write to RTL port // none.sc_in field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:val:b8493181-44ed-443f-beb1-e7f82e6a327d-417 type_to_vector(weight_in_vec[3].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_417); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_3_val.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_417); // then write to RTL port // none.sc_in field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:val:b8493181-44ed-443f-beb1-e7f82e6a327d-417 type_to_vector(weight_in_vec[4].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_417); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_4_val.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_417); // then write to RTL port // none.sc_in field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:val:b8493181-44ed-443f-beb1-e7f82e6a327d-417 type_to_vector(weight_in_vec[5].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_417); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_5_val.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_417); // then write to RTL port // none.sc_in field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:val:b8493181-44ed-443f-beb1-e7f82e6a327d-417 type_to_vector(weight_in_vec[6].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_417); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_6_val.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_417); // then write to RTL port // none.sc_in field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:val:b8493181-44ed-443f-beb1-e7f82e6a327d-417 type_to_vector(weight_in_vec[7].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_417); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_7_val.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_417); // then write to RTL port // none.sc_out field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-427 bool d_b8493181_44ed_443f_beb1_e7f82e6a327d_427; vector_to_type(ccs_rtl_SIG_weight_in_vec_0_rdy.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_427); weight_in_vec[0].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_427); // none.sc_out field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-427 vector_to_type(ccs_rtl_SIG_weight_in_vec_1_rdy.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_427); weight_in_vec[1].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_427); // none.sc_out field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-427 vector_to_type(ccs_rtl_SIG_weight_in_vec_2_rdy.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_427); weight_in_vec[2].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_427); // none.sc_out field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-427 vector_to_type(ccs_rtl_SIG_weight_in_vec_3_rdy.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_427); weight_in_vec[3].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_427); // none.sc_out field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-427 vector_to_type(ccs_rtl_SIG_weight_in_vec_4_rdy.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_427); weight_in_vec[4].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_427); // none.sc_out field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-427 vector_to_type(ccs_rtl_SIG_weight_in_vec_5_rdy.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_427); weight_in_vec[5].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_427); // none.sc_out field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-427 vector_to_type(ccs_rtl_SIG_weight_in_vec_6_rdy.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_427); weight_in_vec[6].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_427); // none.sc_out field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-427 vector_to_type(ccs_rtl_SIG_weight_in_vec_7_rdy.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_427); weight_in_vec[7].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_427); // none.sc_in field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-437 sc_lv< 8 > t_b8493181_44ed_443f_beb1_e7f82e6a327d_437; // 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_b8493181_44ed_443f_beb1_e7f82e6a327d_437); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_0_msg.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_437); // then write to RTL port // none.sc_in field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-437 type_to_vector(weight_in_vec[1].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_b8493181_44ed_443f_beb1_e7f82e6a327d_437); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_1_msg.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_437); // then write to RTL port // none.sc_in field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-437 type_to_vector(weight_in_vec[2].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_b8493181_44ed_443f_beb1_e7f82e6a327d_437); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_2_msg.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_437); // then write to RTL port // none.sc_in field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-437 type_to_vector(weight_in_vec[3].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_b8493181_44ed_443f_beb1_e7f82e6a327d_437); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_3_msg.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_437); // then write to RTL port // none.sc_in field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-437 type_to_vector(weight_in_vec[4].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_b8493181_44ed_443f_beb1_e7f82e6a327d_437); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_4_msg.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_437); // then write to RTL port // none.sc_in field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-437 type_to_vector(weight_in_vec[5].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_b8493181_44ed_443f_beb1_e7f82e6a327d_437); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_5_msg.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_437); // then write to RTL port // none.sc_in field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-437 type_to_vector(weight_in_vec[6].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_b8493181_44ed_443f_beb1_e7f82e6a327d_437); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_6_msg.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_437); // then write to RTL port // none.sc_in field_key=weight_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-388:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-437 type_to_vector(weight_in_vec[7].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_b8493181_44ed_443f_beb1_e7f82e6a327d_437); // read orig port and type convert ccs_rtl_SIG_weight_in_vec_7_msg.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_437); // then write to RTL port // none.sc_in field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:val:b8493181-44ed-443f-beb1-e7f82e6a327d-470 sc_logic t_b8493181_44ed_443f_beb1_e7f82e6a327d_470; // NPS - LV to hold field type_to_vector(act_in_vec[0].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_470); // read orig port and type convert ccs_rtl_SIG_act_in_vec_0_val.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_470); // then write to RTL port // none.sc_in field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:val:b8493181-44ed-443f-beb1-e7f82e6a327d-470 type_to_vector(act_in_vec[1].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_470); // read orig port and type convert ccs_rtl_SIG_act_in_vec_1_val.write(t_b849
3181_44ed_443f_beb1_e7f82e6a327d_470); // then write to RTL port // none.sc_in field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:val:b8493181-44ed-443f-beb1-e7f82e6a327d-470 type_to_vector(act_in_vec[2].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_470); // read orig port and type convert ccs_rtl_SIG_act_in_vec_2_val.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_470); // then write to RTL port // none.sc_in field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:val:b8493181-44ed-443f-beb1-e7f82e6a327d-470 type_to_vector(act_in_vec[3].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_470); // read orig port and type convert ccs_rtl_SIG_act_in_vec_3_val.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_470); // then write to RTL port // none.sc_in field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:val:b8493181-44ed-443f-beb1-e7f82e6a327d-470 type_to_vector(act_in_vec[4].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_470); // read orig port and type convert ccs_rtl_SIG_act_in_vec_4_val.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_470); // then write to RTL port // none.sc_in field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:val:b8493181-44ed-443f-beb1-e7f82e6a327d-470 type_to_vector(act_in_vec[5].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_470); // read orig port and type convert ccs_rtl_SIG_act_in_vec_5_val.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_470); // then write to RTL port // none.sc_in field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:val:b8493181-44ed-443f-beb1-e7f82e6a327d-470 type_to_vector(act_in_vec[6].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_470); // read orig port and type convert ccs_rtl_SIG_act_in_vec_6_val.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_470); // then write to RTL port // none.sc_in field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:val:b8493181-44ed-443f-beb1-e7f82e6a327d-470 type_to_vector(act_in_vec[7].Connections::InBlocking_Ports_abs<ac_int<8, true > >::val.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_470); // read orig port and type convert ccs_rtl_SIG_act_in_vec_7_val.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_470); // then write to RTL port // none.sc_out field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-480 bool d_b8493181_44ed_443f_beb1_e7f82e6a327d_480; vector_to_type(ccs_rtl_SIG_act_in_vec_0_rdy.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_480); act_in_vec[0].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_480); // none.sc_out field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-480 vector_to_type(ccs_rtl_SIG_act_in_vec_1_rdy.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_480); act_in_vec[1].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_480); // none.sc_out field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-480 vector_to_type(ccs_rtl_SIG_act_in_vec_2_rdy.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_480); act_in_vec[2].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_480); // none.sc_out field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-480 vector_to_type(ccs_rtl_SIG_act_in_vec_3_rdy.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_480); act_in_vec[3].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_480); // none.sc_out field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-480 vector_to_type(ccs_rtl_SIG_act_in_vec_4_rdy.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_480); act_in_vec[4].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_480); // none.sc_out field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-480 vector_to_type(ccs_rtl_SIG_act_in_vec_5_rdy.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_480); act_in_vec[5].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_480); // none.sc_out field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-480 vector_to_type(ccs_rtl_SIG_act_in_vec_6_rdy.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_480); act_in_vec[6].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_480); // none.sc_out field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-480 vector_to_type(ccs_rtl_SIG_act_in_vec_7_rdy.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_480); act_in_vec[7].Connections::InBlocking_Ports_abs<ac_int<8, true > >::rdy.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_480); // none.sc_in field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-490 sc_lv< 8 > t_b8493181_44ed_443f_beb1_e7f82e6a327d_490; // NPS - LV to hold field type_to_vector(act_in_vec[0].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_b8493181_44ed_443f_beb1_e7f82e6a327d_490); // read orig port and type convert ccs_rtl_SIG_act_in_vec_0_msg.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_490); // then write to RTL port // none.sc_in field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-490 type_to_vector(act_in_vec[1].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_b8493181_44ed_443f_beb1_e7f82e6a327d_490); // read orig port and type convert ccs_rtl_SIG_act_in_vec_1_msg.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_490); // then write to RTL port // none.sc_in field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-490 type_to_vector(act_in_vec[2].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_b8493181_44ed_443f_beb1_e7f82e6a327d_490); // read orig port and type convert ccs_rtl_SIG_act_in_vec_2_msg.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_490); // then write to RTL port // none.sc_in field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-490 type_to_vector(act_in_vec[3].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_b8493181_44ed_443f_beb1_e7f82e6a327d_490); // read orig port and type convert ccs_rtl_SIG_act_in_vec_3_msg.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_490); // then write to RTL port // none.sc_in field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-490 type_to_vector(act_in_vec[4].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_b8493181_44ed_443f_beb1_e7f82e6a327d_490); // read orig port and type convert ccs_rtl_SIG_act_in_vec_4_msg.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_490); // then write to RTL port // none.sc_in field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-490 type_to_vector(act_in_vec[5].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_b8493181_44ed_443f_beb1_e7f82e6a327d_490); // read orig port and type convert ccs_rtl_SIG_act_in_vec_5_msg.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_490); // then write to RTL port // none.sc_in field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-490 type_to_vector(act_in_vec[6].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_b8493181_44ed_443f_beb1_e7f82e6a327d_490); // read orig port and type convert ccs_rtl_SIG_act_in_vec_6_msg.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_490); // then write to RTL port // none.sc_in field_key=act_in_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-447:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-490 type_to_vector(act_in_vec[7].Connections::InBlocking<ac_int<8, true >, Connections::SYN_PORT >::msg.read(),8,t_b8493181_44ed_443f_beb1_e7f82e6a327d_490); // read orig port and type convert ccs_rtl_SIG_act_in_vec_7_msg.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_490); // then write to RTL port // none.sc_out field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:val:b8493181-44ed-443f-beb1-e7f82e6a327d-515 bool d_b8493181_44ed_443f_beb1_e7f82e6a327d_515; vector_to_type(ccs_rtl_SIG_accum_out_vec_0_val.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_515); accum_out_vec[0].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_515); // none.sc_out field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:val:b8493181-44ed-443f-beb1-e7f82e6a327d-515 vector_to_type(ccs_rtl_SIG_accum_out_vec_1_val.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_515); accum_out_vec[1].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_515); // none.sc_out field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:val:b8493181-44ed-443f-beb1-e7f82e6a327d-515 vector_to_type(ccs_rtl_SIG_accum_out_vec_2_val.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_515); accum_out_vec[2].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_515); // none.sc_out field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:val:b8493181-44ed-443f-beb1-e7f82e6a327d-515 vector_to_type(ccs_rtl_SIG_accum_out_vec_3_val.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_515); accum_out_vec[3].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_515); // none.sc_out field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:val:b8493181-44ed-443f-beb1-e7f82e6a327d-515 vector_to_type(ccs_rtl_SIG_accum_out_vec_4_val.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_515); accum_out_vec[4].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_515); // none.sc_out field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:val:b8493181-44ed-443f-beb1-e7f82e6a327d-515 vector_to_type(ccs_rtl_SIG_accum_out_vec_5_val.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_515); accum_out_vec[5].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_515); // none.sc_out field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:val:b8493181-44ed-443f-beb1-e7f82e6a327d-515 vector_to_type(ccs_rtl_SIG_accum_out_vec_6_val.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_515); accum_out_vec[6].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_515); // none.sc_out field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:val:b8493181-44ed-443f-beb1-e7f82e6a327d-515 vector_to_type(ccs_rtl_SIG_accum_out_vec_7_val.read(), 1, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_515); accum_out_vec[7].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::val.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_515); // none.sc_in field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-519 sc_logic t_b8493181_44ed_443f_beb1_e7f82e6a327d_519; // NPS - LV to hold field type_to_vector(accum_out_vec[0].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_519); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_0_rdy.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_519); // then write to RTL port // none.sc_in field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-519 type_to_vector(accum_out_vec[1].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_519); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_1_rdy.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_519); // then write to RTL port // none.sc_in field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-519 type_to_vector(accum_out_vec[2].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_519); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_2_rdy.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_519); // then write to RTL port // none.sc_in field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-519 type_to_vector(accum_out_vec[3].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_519); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_3_rdy.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_519); // then write to RTL port // none.sc_in field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-519 type_to_vector(accum_out_vec[4].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_519); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_4_rdy.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_519); // then write to RTL port // none.sc_in field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-519 type_to_vector(accum_out_vec[5].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_519); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_5_rdy.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_519); // then write to RTL port // none.sc_in field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-519 type_to_vector(accum_out_vec[6].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_519); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_6_rdy.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_519); // then write to RTL port // none.sc_in field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:rdy:b8493181-44ed-443f-beb1-e7f82e6a327d-519 type_to_vector(accum_out_vec[7].Connections::OutBlocking_Ports_abs<ac_int<32, true > >::rdy.read(),1,t_b8493181_44ed_443f_beb1_e7f82e6a327d_519); // read orig port and type convert ccs_rtl_SIG_accum_out_vec_7_rdy.write(t_b8493181_44ed_443f_beb1_e7f82e6a327d_519); // then write to RTL port // none.sc_out field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-523 sc_dt::sc_lv<32 > d_b8493181_44ed_443f_beb1_e7f82e6a327d_523; vector_to_type(ccs_rtl_SIG_accum_out_vec_0_msg.read(), 32, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_523); accum_out_vec[0].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_523); // none.sc_out field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-523 vector_to_type(ccs_rtl_SIG_accum_out_vec_1_msg.read(), 32, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_523); accum_out_vec[1].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_523); // none.sc_out field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-523 vector_to_type(ccs_rtl_SIG_accum_out_vec_2_msg.read(), 32, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_523); accum_out_vec[2].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_523); // none.sc_out field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-523 vector_to_type(ccs_rtl_SIG_accum_out_vec_3_msg.read(), 32, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_523); accum_out_vec[3].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_523); // none.sc_out field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-523 vector_to_type(ccs_rtl_SIG_accum_out_vec_4_msg.read(), 32, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_523); accum_out_vec[4].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_523); // none.sc_out field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-523 vector_to_type(ccs_rtl_SIG_accum_out_vec_5_msg.read(), 32, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_523); accum_out_vec[5].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_523); // none.sc_out field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-523 vector_to_type(ccs_rtl_SIG_accum_out_vec_6_msg.read(), 32, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_523); accum_out_vec[6].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_523); // none.sc_out field_key=accum_out_vec:b8493181-44ed-443f-beb1-e7f82e6a327d-500:msg:b8493181-44ed-443f-beb1-e7f82e6a327d-523 vector_to_type(ccs_rtl_SIG_accum_out_vec_7_msg.read(), 32, &d_b8493181_44ed_443f_beb1_e7f82e6a327d_523); accum_out_vec[7].Connections::OutBlocking<ac_int<32, true >, Connections::SYN_PORT >::msg.write(d_b8493181_44ed_443f_beb1_e7f82e6a327d_523); } // Include original testbench file(s) #include "/home/billyk/cs148/hls/lab3/SysArray/../../../cmod/lab3/SysArray/testbench.cpp"
#ifndef PACKET_GENERATOR_TLM_CPP #define PACKET_GENERATOR_TLM_CPP #include <systemc.h> using namespace sc_core; using namespace sc_dt; using namespace std; #include <tlm.h> #include <tlm_utils/simple_initiator_socket.h> #include <tlm_utils/simple_target_socket.h> #include <tlm_utils/peq_with_cb_and_phase.h> #include "packetGenerator_tlm.hpp" #include "common_func.hpp" #include "address_map.hpp" void packetGenerator_tlm::do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address){ dbgimgtarmodprint(use_prints, "Called do_when_read_transaction with an address %016llX and length %d", address, data_length); if ((address >= IMG_OUTPUT_SIZE + IMG_OUTPUT_SIZE_SIZE + IMG_OUTPUT_DONE_SIZE) && (address < IMG_OUTPUT_SIZE + IMG_OUTPUT_SIZE_SIZE + IMG_OUTPUT_DONE_SIZE + IMG_OUTPUT_STATUS_SIZE)) { if (packetGenerator::tmp_data_out_valid == true) { *data = 1; dbgimgtarmodprint(true, "Ethernet module still sending data, remaining bytes to send %0d", actual_data_length); } else { *data = 0; } } else { *data = 0; } } void packetGenerator_tlm::do_when_write_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address) { dbgimgtarmodprint(use_prints, "Called do_when_write_transaction with an address %016llX and length %d", address, data_length); if (address < IMG_OUTPUT_SIZE) { memcpy(tmp_data + address, data, data_length); } else if ((address >= IMG_OUTPUT_SIZE) && (address < IMG_OUTPUT_SIZE + IMG_OUTPUT_SIZE_SIZE)) { unsigned char *data_length_ptr = (unsigned char *)&tmp_data_length; memcpy(data_length_ptr + address - IMG_OUTPUT_SIZE, data, data_length); dbgimgtarmodprint(true, "Current data_length %0d", tmp_data_length); } else if ((address >= IMG_OUTPUT_SIZE + IMG_OUTPUT_SIZE_SIZE) && (address < IMG_OUTPUT_SIZE + IMG_OUTPUT_SIZE_SIZE + IMG_OUTPUT_DONE_SIZE) && (*data == 1)) { if (tmp_data_length == 0) { *(tmp_data) = 0; tmp_data_length = 1; } dbgimgtarmodprint(true, "Preparing to send %0d bytes", tmp_data_length); fill_data(tmp_data, (int)tmp_data_length); tmp_data_length = 0; } } //Backdoor write/read for debug purposes void packetGenerator_tlm::backdoor_write(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address) { sc_dt::uint64 local_address = address - IMG_OUTPUT_ADDRESS_LO; memcpy((tmp_data + local_address), data, data_length); for (int i = 0; (i < 10) && (local_address + i < IMG_OUTPUT_SIZE); i++) { dbgimgtarmodprint(true, "Backdoor Writing: %0d\n", *(tmp_data + local_address + i)); } } void packetGenerator_tlm::backdoor_read(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address) { sc_dt::uint64 local_address = address - IMG_OUTPUT_ADDRESS_LO; data = new unsigned char[data_length]; memcpy(data, (tmp_data + local_address), data_length); for (int i = 0; (i < 10) && (local_address + i < IMG_OUTPUT_SIZE); i++) { dbgimgtarmodprint(true, "Backdoor Reading: %0d\n", *(tmp_data + local_address + i)); } } #endif // PACKET_GENERATOR_TLM_CPP
/******************************************************************************** * University of L'Aquila - HEPSYCODE Source Code License * * * * * * (c) 2018-2019 Centre of Excellence DEWS All rights reserved * ******************************************************************************** * <one line to give the program's name and a brief idea of what it does.> * * Copyright (C) 2022 Vittoriano Muttillo, Luigi Pomante * * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * ******************************************************************************** * * * Created on: 09/May/2023 * * Authors: Vittoriano Muttillo, Marco Santic, Luigi Pomante * * * * email: vittoriano.muttillo@guest.univaq.it * * marco.santic@guest.univaq.it * * luigi.pomante@univaq.it * * * ******************************************************************************** * This code has been developed from an HEPSYCODE model used as demonstrator by * * University of L'Aquila. * *******************************************************************************/ #include <systemc.h> #include "../mainsystem.h" #include <math.h> //----------------------------------------------------------------------------- // Physical constants //----------------------------------------------------------------------------- static double sTC_I_0 = 77.3 ; // [A] Nominal current //static double sTC_T_0 = 298.15 ; // [K] Ambient temperature //static double sTC_R_0 = 0.01 ; // [Ω] Data-sheet R_DS_On (Drain-Source resistance in the On State) static double sTC_V_0 = 47.2 ; // [V] Nominal voltage //static double sTC_Alpha = 0.002 ; // [Ω/K] Temperature coefficient of Drain-Source resistance in the On State //static double sTC_ThermalConstant = 0.75 ; //static double sTC_Tau = 0.02 ; // [s] Sampling period //----------------------------------------------------------------------------- // Simulation related data //----------------------------------------------------------------------------- //#define N_CYCLES 1000 // Change by command line option -n<number> #define sTC_NOISE 0.2 // Measurement noise = 10% static double sTC_time_Ex = 0 ; // Simple time simulation //----------------------------------------------------------------------------- // Mnemonics to access the array that contains the sampled data //----------------------------------------------------------------------------- #define sTC_SAMPLE_LEN 3 // Array of SAMPLE_LEN elements #define sTC_I_INDEX 0 // Current #define sTC_V_INDEX 1 // Voltage #define sTC_TIME_INDEX 2 // Time ///----------------------------------------------------------------------------- // Forward references //----------------------------------------------------------------------------- //static int sTC_initDescriptors(void) ; static void sTC_getSample(int index, double sample[sTC_SAMPLE_LEN]) ; //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void sTC_getSample(int index, double sample[sTC_SAMPLE_LEN]) {HEPSY_S(sampleTimCord_id) // the parameter "index" is needed as device identifier HEPSY_S(sampleTimCord_id) sample[sTC_TIME_INDEX] = sTC_time_Ex ; // Random generation of i (current) HEPSY_S(sampleTimCord_id) double i; double v ; double noise ; // Random i HEPSY_S(sampleTimCord_id) i = (double)rand() / (double)RAND_MAX ; // 0.0 <= i <= 1.0 HEPSY_S(sampleTimCord_id) i *= 2.0 ; // 0.0 <= i <= 2.0 HEPSY_S(sampleTimCord_id) i *= sTC_I_0 ; // 0.0 <= i <= 2.0*I_0 // Postcondition: (0 <= i <= 2.0*I_0) // Add some noise every 3 samples HEPSY_S(sampleTimCord_id) HEPSY_S(sampleTimCord_id) noise = rand() % 3 == 0 ? 1.0 : 0.0 ; HEPSY_S(sampleTimCord_id) HEPSY_S(sampleTimCord_id) HEPSY_S(sampleTimCord_id) noise *= (double)rand() / (double)RAND_MAX ; HEPSY_S(sampleTimCord_id) noise *= 2.0 ; HEPSY_S(sampleTimCord_id) noise -= 1.0 ; HEPSY_S(sampleTimCord_id) HEPSY_S(sampleTimCord_id) noise *= (sTC_NOISE * sTC_I_0 ) ; // NOISE as % of I_0 HEPSY_S(sampleTimCord_id) i += noise ; // Postcondition: (-NOISE*I_0 <= i <= (2.0+NOISE)*I_0 ) // Random v HEPSY_S(sampleTimCord_id) v = (double)rand() / (double)RAND_MAX ; // 0.0 <= i <= 1.0 HEPSY_S(sampleTimCord_id) v *= 2.0 ; // 0.0 <= i <= 2.0 HEPSY_S(sampleTimCord_id) v *= sTC_V_0 ; // 0.0 <= i <= 2.0*I_0 // Postcondition: (0 <= i <= 2.0*I_0) // Add some noise every 3 samples HEPSY_S(sampleTimCord_id) HEPSY_S(sampleTimCord_id) noise = rand() % 3 == 0 ? 1.0 : 0.0 ; HEPSY_S(sampleTimCord_id) HEPSY_S(sampleTimCord_id) HEPSY_S(sampleTimCord_id) noise *= (double)rand() / (double)RAND_MAX ; HEPSY_S(sampleTimCord_id) noise *= 2.0 ; HEPSY_S(sampleTimCord_id) noise -= 1.0 ; HEPSY_S(sampleTimCord_id) HEPSY_S(sampleTimCord_id) noise *= (sTC_NOISE * sTC_V_0 ) ; // NOISE as % of I_0 HEPSY_S(sampleTimCord_id) v += noise ; // Postcondition: (-NOISE*V_0 <= v <= (2.0+NOISE)*V_0 ) HEPSY_S(sampleTimCord_id) sample[sTC_I_INDEX] = i ; HEPSY_S(sampleTimCord_id) sample[sTC_V_INDEX] = v ; } void mainsystem::sampleTimCord_main() { // datatype for channels stimulus_system_payload stimulus_system_payload_var; sampleTimCord_cleanData_xx_payload sampleTimCord_cleanData_xx_payload_var; //step var uint16_t step; //device var int dev; // ex_time (for extractFeatures...) double ex_time; //var for samples, to re-use getSample() double sample[sTC_SAMPLE_LEN] ; srand(1); //implementation HEPSY_S(sampleTimCord_id) while(1) {HEPSY_S(sampleTimCord_id) // content HEPSY_S(sampleTimCord_id) stimulus_system_payload_var = stimulus_system_port_out->read(); HEPSY_S(sampleTimCord_id) dev = 0; HEPSY_S(sampleTimCord_id) step = stimulus_system_payload_var.example; //step HEPSY_S(sampleTimCord_id) ex_time = sc_time_stamp().to_seconds(); //providing sample to ward device 0 (cleanData_01) HEPSY_S(sampleTimCord_id) sTC_getSample(dev, sample); // cout << "sampleTimCord \t dev: " << dev // <<"\t s0:" << sample[0] // <<"\t s1:" << sample[1] // <<"\t s3:" << sample[2] // << endl; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.dev = dev++; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.step = step; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.ex_time = ex_time; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.sample_i = sample[sTC_I_INDEX]; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.sample_v = sample[sTC_V_INDEX]; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_01_channel->write(sampleTimCord_cleanData_xx_payload_var); //providing sample to ward device 1 (cleanData_02) HEPSY_S(sampleTimCord_id) sTC_getSample(dev, sample); // cout << "sampleTimCord \t dev: " << dev // <<"\t s0:" << sample[0] // <<"\t s1:" << sample[1] // <<"\t s3:" << sample[2] // << endl; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.dev = dev++; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.step = step; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.ex_time = ex_time; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.sample_i = sample[sTC_I_INDEX]; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.sample_v = sample[sTC_V_INDEX]; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_02_channel->write(sampleTimCord_cleanData_xx_payload_var); //providing sample to ward device 2 (cleanData_03) HEPSY_S(sampleTimCord_id) sTC_getSample(dev, sample); // cout << "sampleTimCord \t dev: " << dev // <<"\t s0:" << sample[0] // <<"\t s1:" << sample[1] // <<"\t s3:" << sample[2] // << endl; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.dev = dev++; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.step = step; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.ex_time = ex_time; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.sample_i = sample[sTC_I_INDEX]; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.sample_v = sample[sTC_V_INDEX]; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_03_channel->write(sampleTimCord_cleanData_xx_payload_var); //providing sample to ward device 3 (cleanData_04) HEPSY_S(sampleTimCord_id) sTC_getSample(dev, sample); // cout << "sampleTimCord \t dev: " << dev // <<"\t s0:" << sample[0] // <<"\t s1:" << sample[1] // <<"\t s3:" << sample[2] // << endl; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.dev = dev++; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.step = step; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.ex_time = ex_time; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.sample_i = sample[sTC_I_INDEX]; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.sample_v = sample[sTC_V_INDEX]; HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_04_channel->write(sampleTimCord_cleanData_xx_payload_var); HEPSY_P(sampleTimCord_id) } } //END
//**************************************************************************************** // 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/experimental/SystemC.hpp> #include <crave/ConstrainedRandom.hpp> #include <systemc.h> #include <boost/timer.hpp> #include <crave/experimental/Experimental.hpp> using crave::crv_sequence_item; using crave::crv_constraint; using crave::crv_variable; using crave::crv_object_name; using sc_dt::sc_bv; using sc_dt::sc_uint; using crave::dist; using crave::distribution; using crave::reference; struct ALU12 : public crv_sequence_item { crv_variable<sc_bv<2> > op; crv_variable<sc_uint<12> > a, b; crv_constraint c_dist{ "dist" }; crv_constraint c_add{ "add" }; crv_constraint c_sub{ "sub" }; crv_constraint c_mul{ "mul" }; crv_constraint c_div{ "div" }; ALU12(crv_object_name) { c_dist = { dist(op(), distribution<short>::simple_range(0, 3)) }; c_add = {(op() != 0x0) || (4095 >= a() + b()) }; c_sub = {(op() != 0x1) || ((4095 >= a() - b()) && (b() <= a())) }; c_mul = {(op() != 0x2) || (4095 >= a() * b()) }; c_div = {(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) { crave::init("crave.cfg"); boost::timer timer; ALU12 c("ALU"); CHECK(c.randomize()); std::cout << "first: " << timer.elapsed() << "\n"; for (int i = 0; i < 1000; ++i) { CHECK(c.randomize()); std::cout << c << std::endl; } std::cout << "complete: " << timer.elapsed() << "\n"; 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: vittoriano.muttillo@guest.univaq.it * * marco.santic@guest.univaq.it * * luigi.pomante@univaq.it * * * ******************************************************************************** * This code has been developed from an HEPSYCODE model used as demonstrator by * * University of L'Aquila. * *******************************************************************************/ #include <systemc.h> #include "../mainsystem.h" #include <math.h> #define cD_02_ANN_INPUTS 2 // Number of inputs #define cD_02_ANN_OUTPUTS 1 // Number of outputs //----------------------------------------------------------------------------- // Physical constants //----------------------------------------------------------------------------- static double cD_02_I_0 = 77.3 ; // [A] Nominal current static double cD_02_T_0 = 298.15 ; // [K] Ambient temperature static double cD_02_R_0 = 0.01 ; // [Ω] Data-sheet R_DS_On (Drain-Source resistance in the On State) static double cD_02_V_0 = 47.2 ; // [V] Nominal voltage static double cD_02_Alpha = 0.002 ; // [Ω/K] Temperature coefficient of Drain-Source resistance in the On State static double cD_02_ThermalConstant = 0.75 ; static double cD_02_Tau = 0.02 ; // [s] Sampling period //----------------------------------------------------------------------------- // Status descriptors //----------------------------------------------------------------------------- typedef struct cD_02_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_02_DEVICE ; static cD_02_DEVICE cD_02_device; //----------------------------------------------------------------------------- // Mnemonics to access the array that contains the sampled data //----------------------------------------------------------------------------- #define cD_02_SAMPLE_LEN 3 // Array of SAMPLE_LEN elements #define cD_02_I_INDEX 0 // Current #define cD_02_V_INDEX 1 // Voltage #define cD_02_TIME_INDEX 2 // Time ///----------------------------------------------------------------------------- // Forward references //----------------------------------------------------------------------------- static int cD_02_initDescriptors(cD_02_DEVICE device) ; //static void getSample(int index, double sample[SAMPLE_LEN]) ; static void cD_02_cleanData(int index, double sample[cD_02_SAMPLE_LEN]) ; static double cD_02_extractFeatures(double tPrev, double iPrev, double iNow, double rPrev) ; static void cD_02_normalize(int index, double x[cD_02_ANN_INPUTS]) ; static double cD_02_degradationModel(double tNow) ; //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- int cD_02_initDescriptors(cD_02_DEVICE device) { // for (int i = 0; i < NUM_DEV; i++) // { device.t = cD_02_T_0 ; // Operating temperature = Ambient temperature device.r = cD_02_R_0 ; // Operating R_DS_On = Data-sheet R_DS_On // printf("Init %d \n",i); // } return( EXIT_SUCCESS ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void cD_02_cleanData(int index, double sample[cD_02_SAMPLE_LEN]) { // the parameter "index" could be useful to retrieve the characteristics of the device if ( sample[cD_02_I_INDEX] < 0 ) sample[cD_02_I_INDEX] = 0 ; else if ( sample[cD_02_I_INDEX] > (2.0 * cD_02_I_0) ) sample[cD_02_I_INDEX] = (2.0 * cD_02_I_0) ; // Postcondition: (0 <= sample[I_INDEX] <= 2.0*I_0) if ( sample[cD_02_V_INDEX] < 0 ) sample[cD_02_V_INDEX] = 0 ; else if ( sample[cD_02_V_INDEX] > (2.0 * cD_02_V_0 ) ) sample[cD_02_V_INDEX] = (2.0 * cD_02_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_02_extractFeatures(double tPrev, double iPrev, double iNow, double rPrev) { double t ; // Temperature double i = 0.5*(iPrev + iNow); // Average current //printf("cD_02_extractFeatures tPrev=%f\n",tPrev); t = tPrev + // Previous temperature rPrev * (i * i) * cD_02_Tau - // Heat generated: P = I·R^2 cD_02_ThermalConstant * (tPrev - cD_02_T_0) * cD_02_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_02_degradationModel(double tNow) { double r ; //r = R_0 + Alpha * tNow ; r = cD_02_R_0 * ( 2 - exp(-cD_02_Alpha*tNow) ); return( r ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void cD_02_normalize(int index, double sample[cD_02_ANN_INPUTS]) { double i ; double v ; // Precondition: (0 <= sample[I_INDEX] <= 2*I_0) && (0 <= sample[V_INDEX] <= 2*V_0) i = sample[cD_02_I_INDEX] <= cD_02_I_0 ? 0.0 : 1.0; v = sample[cD_02_V_INDEX] <= cD_02_V_0 ? 0.0 : 1.0; // Postcondition: (i in {0.0, 1.0}) and (v in {0.0, 1.0}) sample[cD_02_I_INDEX] = i ; sample[cD_02_V_INDEX] = v ; } void mainsystem::cleanData_02_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_02_sample[cD_02_SAMPLE_LEN] ; double x[cD_02_ANN_INPUTS + cD_02_ANN_OUTPUTS] ; // NOTE: commented, should be changed param by ref... //cD_02_initDescriptors(cD_02_device); cD_02_device.t = cD_02_T_0 ; // Operating temperature = Ambient temperature cD_02_device.r = cD_02_R_0 ; // Operating R_DS_On = Data-sheet R_DS_On // ### added for time related dynamics //static double cD_02_Tau = 0.02 ; // [s] Sampling period double cD_02_last_sample_time = 0; //implementation HEPSY_S(cleanData_02_id) while(1) {HEPSY_S(cleanData_02_id) // content sampleTimCord_cleanData_xx_payload_var = sampleTimCord_cleanData_02_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_02 rcv \t dev: " << dev // <<"\t step: " << step // <<"\t time_ex:" << ex_time // <<"\t i:" << sample_i // <<"\t v:" << sample_v // << endl; // reconstruct sample cD_02_sample[cD_02_I_INDEX] = sample_i; cD_02_sample[cD_02_V_INDEX] = sample_v; cD_02_sample[cD_02_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_02_cleanData(dev, cD_02_sample) ; cD_02_device.time_Ex = cD_02_sample[cD_02_TIME_INDEX] ; cD_02_device.i = cD_02_sample[cD_02_I_INDEX] ; cD_02_device.v = cD_02_sample[cD_02_V_INDEX] ; // ### added for time related dynamics //static double cD_02_Tau = 0.02 ; // [s] Sampling period cD_02_Tau = ex_time - cD_02_last_sample_time; cD_02_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_02_device.t = cD_02_extractFeatures( cD_02_device.t, // Previous temperature cD_02_device.i, // Previous current cD_02_sample[cD_02_I_INDEX], // Current at this step cD_02_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_02_device.r = cD_02_degradationModel(cD_02_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_02_device.i ; x[1] = cD_02_device.v ; cD_02_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_02_device.i; cleanData_xx_ann_xx_payload_var.device_v = cD_02_device.v; cleanData_xx_ann_xx_payload_var.device_t = cD_02_device.t; cleanData_xx_ann_xx_payload_var.device_r = cD_02_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_02_ann_02_channel->write(cleanData_xx_ann_xx_payload_var); HEPSY_P(cleanData_02_id) } } //END
/******************************************************************************* * tpencoder.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This is a testbench module to emulate a rotary quad encoder with a button. * This encoder encodes the button by forcing pin B high. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "tpencoder.h" void tpencoder::press(bool pb) { if (pb) { pinA.write(GN_LOGIC_1); buttonpressed = true; } else { pinA.write(GN_LOGIC_Z); buttonpressed = false; } } void tpencoder::turnleft(int pulses, bool pressbutton) { /* We start by raising the button, if requested. */ if (pressbutton) press(true); /* If the last was a left turn, we need to do the direction change glitch. * Note that if the button is pressed, we only toggle pin B. */ if (!lastwasright) { wait(speed, SC_MS); pinB.write(GN_LOGIC_1); wait(speed, SC_MS); pinB.write(GN_LOGIC_Z); } /* And we apply the pulses, again, watching for the button. */ wait(phase, SC_MS); while(pulses > 0) { wait(speed-phase, SC_MS); if (!buttonpressed) pinA.write(GN_LOGIC_1); wait(phase, SC_MS); pinB.write(GN_LOGIC_1); wait(speed-phase, SC_MS); if (!buttonpressed) pinA.write(GN_LOGIC_Z); if (edges == 2) wait(phase, SC_MS); pinB.write(GN_LOGIC_Z); if (edges != 2) wait(phase, SC_MS); pulses = pulses - 1; } /* If the customer requested us to press the button with a turn, we release * it now. */ if (pressbutton) { wait(speed, SC_MS); press(false); } /* And we tag that the last was a right turn as when we shift to the left * we can have some odd behaviour. */ lastwasright = true; } void tpencoder::turnright(int pulses, bool pressbutton) { /* We start by raising the button, if requested. */ if (pressbutton) press(true); /* If the last was a right turn, we need to do the direction change glitch. * Note that if the button is pressed, we only toggle pin A. */ if (lastwasright) { wait(speed, SC_MS); if (!buttonpressed) pinA.write(GN_LOGIC_1); wait(speed, SC_MS); pinB.write(GN_LOGIC_1); wait(speed, SC_MS); pinB.write(GN_LOGIC_Z); wait(speed, SC_MS); if (!buttonpressed) pinA.write(GN_LOGIC_Z); } /* And we apply the pulses, again, watching for the button. */ wait(phase, SC_MS); while(pulses > 0) { wait(speed-phase, SC_MS); pinB.write(GN_LOGIC_1); wait(phase, SC_MS); if (!buttonpressed) pinA.write(GN_LOGIC_1); wait(speed-phase, SC_MS); pinB.write(GN_LOGIC_Z); if (edges == 2) wait(phase, SC_MS); if (!buttonpressed) pinA.write(GN_LOGIC_Z); if (edges != 2) wait(phase, SC_MS); pulses = pulses - 1; } /* If the customer requested us to press the button with a turn, we release * it now. */ if (pressbutton) { wait(speed, SC_MS); press(false); } /* And we tag that the last was a left turn, so we can do the left turn to * right turn glitch. */ lastwasright = false; } void tpencoder::start_of_simulation() { pinA.write(GN_LOGIC_Z); pinB.write(GN_LOGIC_Z); } void tpencoder::trace(sc_trace_file *tf) { sc_trace(tf, buttonpressed, buttonpressed.name()); sc_trace(tf, pinA, pinA.name()); sc_trace(tf, pinB, pinB.name()); }
//**************************************************************************************** // 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 ALU32 : public rand_obj { randv<sc_bv<2> > op; randv<sc_uint<32> > a, b; ALU32(rand_obj* parent = 0) : rand_obj(parent), 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) { crave::init("crave.cfg"); boost::timer timer; ALU32 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 <systemc.h> #include "counter.h" #include "counter_tb.h" #include "constants.h" int sc_main(int argc, char* argv[]){ CounterModule* counter = new CounterModule("Counter"); CounterTestbench* testbench = new CounterTestbench("Testbench"); sc_clock Clock("Clock", 10, SC_NS, 0.5, 10, SC_NS, false); sc_signal<bool> Reset; sc_signal<bool> Count_Enable; sc_signal<bool> Up_Down_Ctrl; sc_signal<sc_uint<N> > Count_Out; sc_signal<bool> Overflow_Intr; sc_signal<bool> Underflow_Intr; counter->clk(Clock); counter->reset(Reset); counter->count_enable(Count_Enable); counter->up_down_ctrl(Up_Down_Ctrl); counter->count_out(Count_Out); counter->overflow_intr(Overflow_Intr); counter->underflow_intr(Underflow_Intr); testbench->clk(Clock); testbench->reset(Reset); testbench->count_enable(Count_Enable); testbench->up_down_ctrl(Up_Down_Ctrl); testbench->count_out(Count_Out); testbench->overflow_intr(Overflow_Intr); testbench->underflow_intr(Underflow_Intr); cout << "Starting simulation" << endl; sc_start(); return 0; }
/******************************************************************************* * dns.cpp -- Copyright 2019 Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This is a stubfile that sets several defines for a simplified version of * the LwIP to compile on the ESPMOD SystemC model. This is not a port of * the LwIP. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file was based off the work covered by the license below: * * Author: Jim Pettinato * April 2007 * * ported from uIP resolv.c Copyright (c) 2002-2003, Adam Dunkels. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <systemc.h> #include "dns.h" #include <IPAddress.h> #include "info.h" #include "esp_wifi_types.h" #include "esp_wifi.h" /** * @brief Set the DNS server. **/ void dns_setserver(uint8_t numdns, const ip_addr_t *dnsserver) { if (dnsserver == NULL) PRINTF_ERROR("WIFI", "Invalid DNS server pointer"); PRINTF_INFO("WIFI", "Setting DNS server %d to %s", numdns, IPAddress(dnsserver->u_addr.ip4.addr).toString().c_str()); }
/******************************************************************************* * st7735.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This is a testbench module to emulate the ST7735 display controller. ******************************************************************************* * 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 "st7735.h" void st7735::collect() { pos = 0; collected = 0; while(1) { wait(); /* We check the reset. */ if (!resx.read().islogic()) { PRINTF_WARN("ST7735", "RESX is non-logic value %c", resx.read().to_char()); continue; } else if (resx.read().islow()) { pos = 0; collected = 0; initialized = true; continue; } // If the CSX is not low, we ignore what came in. if (!csx.read().islogic()) { PRINTF_WARN("ST7735", "CSX is non-logic value %c", csx.read().to_char()); continue; } else if (csx.read().ishigh()) continue; // To use the controller, it needs to have been reset. if (!initialized) { PRINTF_WARN("ST7735", "Module has not been reset"); continue; } // Now we check the mode to see what came in. This depends on the mode // selection. switch(im.read().to_uint()) { // SPI mode -- we only react to a chane in the SCL pin. default: /* We first discard the illegal values. */ if (!scl_dcx.read().islogic()) { PRINTF_WARN("ST7735", "SCL is non-logic value %c", scl_dcx.read().to_char()); continue; } /* If we are in readmode, we return the value. */ if (readmode) { if (scl_dcx.read().ishigh()) sda.write(GN_LOGIC_Z); else if (pos > 0) sda.write(((collected & (1 << (pos-1)))>0)?GN_LOGIC_1:GN_LOGIC_0); continue; } /* If it is not a read it is a write. We sample on the rising edge. */ if (scl_dcx.read() != SC_LOGIC_1) continue; /* We increment the counter. If we are using the 3wire interface, we * need to get the DCX first */ if (!spi4w.read().islogic()) { PRINTF_WARN("ST7735", "Tried to latch while spi4w is non-logic value %c", spi4w.read().to_char()); continue; } else if (wrx.read().ishigh()) collected = collected | 0x100; if (pos <= 0 && spi4w.read().islow()) { collected = 0; pos = 9; } else if (pos <= 0) { collected = 0; pos = 8; } else pos = pos - 1; if (spi4w.read().ishigh()) { if (!wrx.read().islogic()) { PRINTF_WARN("ST7735", "Tried to latch non-logic WRX value %c", wrx.read().to_char()); } else if (wrx.read().ishigh()) collected = collected | 0x100; else collected = collected & 0x0ff; } /* If the pin is non-logic we complain and skip it. */ if(!sda.read().islogic()) { PRINTF_WARN("ST7735", "Tried to latch non-logic SDA value %c", sda.read().to_char()); } /* If the logic is valid, we take in the ones. */ else if (sda.read().ishigh()) collected = collected | (1 << (pos-1)); if (pos == 1) { printf("%s: received %03x\n", sc_time_stamp().to_string().c_str(), collected); } break; } } } void st7735::start_of_simulation() { sda.write(GN_LOGIC_Z); osc.write(GN_LOGIC_0); te.write(GN_LOGIC_0); d0.write(GN_LOGIC_Z); d1.write(GN_LOGIC_Z); d2.write(GN_LOGIC_Z); d3.write(GN_LOGIC_Z); d4.write(GN_LOGIC_Z); d5.write(GN_LOGIC_Z); d6.write(GN_LOGIC_Z); d7.write(GN_LOGIC_Z); d8.write(GN_LOGIC_Z); d9.write(GN_LOGIC_Z); d10.write(GN_LOGIC_Z); d11.write(GN_LOGIC_Z); d12.write(GN_LOGIC_Z); d13.write(GN_LOGIC_Z); d14.write(GN_LOGIC_Z); d15.write(GN_LOGIC_Z); d16.write(GN_LOGIC_Z); d17.write(GN_LOGIC_Z); } void st7735::trace(sc_trace_file *tf) { sc_trace(tf, sda, sda.name()); sc_trace(tf, d0, d0.name()); sc_trace(tf, d1, d1.name()); sc_trace(tf, d2, d2.name()); sc_trace(tf, d3, d3.name()); sc_trace(tf, d4, d4.name()); sc_trace(tf, d5, d5.name()); sc_trace(tf, d6, d6.name()); sc_trace(tf, d7, d7.name()); sc_trace(tf, d8, d8.name()); sc_trace(tf, d9, d9.name()); sc_trace(tf, d10, d10.name()); sc_trace(tf, d11, d11.name()); sc_trace(tf, d12, d12.name()); sc_trace(tf, d13, d13.name()); sc_trace(tf, d14, d14.name()); sc_trace(tf, d15, d15.name()); sc_trace(tf, d16, d16.name()); sc_trace(tf, d17, d17.name()); sc_trace(tf, wrx, wrx.name()); sc_trace(tf, rdx, rdx.name()); sc_trace(tf, csx, csx.name()); sc_trace(tf, scl_dcx, scl_dcx.name()); sc_trace(tf, spi4w, spi4w.name()); sc_trace(tf, im, im.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: 09/May/2022 * * Authors: Vittoriano Muttillo, Luigi Pomante * * * * email: vittoriano.muttillo@guest.univaq.it * * luigi.pomante@univaq.it * * * ******************************************************************************** * 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 * *******************************************************************************/ /******************************************************************************** * SystemManager : System Manager file. * * System Manager: HEPSIM System Manager * ********************************************************************************/ /*! \file SystemManager.cpp \brief System Manager Documented file. System Manager: HEPSIM System Manager. */ /******************************************************************************** *** Includes *** *******************************************************************************/ #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 //////////////////////////// /******************************************************************************** *** Functions *** *******************************************************************************/ // 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 float 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; } /******************************************************************************** *** EOF *** ********************************************************************************/
/******************************************************************************* * encoder.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This is a testbench module to emulate a rotary quad encoder with a button. * Two pins are provided for the encoder function and a third one handles * the button. ******************************************************************************* * 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 "encoder.h" void encoder::press(bool pb) { if (pb) pinC.write(GN_LOGIC_1); else pinC.write(GN_LOGIC_Z); } void encoder::turnleft(int pulses, bool pressbutton) { /* We start by raising the button, if requested. */ if (pressbutton) press(true); /* If the last was a left turn, we need to do the direction change glitch. * Note that if the button is pressed, we only toggle pin B. */ if (!lastwasright) { wait(speed, SC_MS); pinB.write(GN_LOGIC_1); wait(speed, SC_MS); pinB.write(GN_LOGIC_Z); } /* And we apply the pulses, again, watching for the button. */ wait(phase, SC_MS); while(pulses > 0) { wait(speed-phase, SC_MS); pinA.write(GN_LOGIC_1); wait(phase, SC_MS); pinB.write(GN_LOGIC_1); wait(speed-phase, SC_MS); pinA.write(GN_LOGIC_Z); if (edges == 2) wait(phase, SC_MS); pinB.write(GN_LOGIC_Z); if (edges != 2) wait(phase, SC_MS); pulses = pulses - 1; } /* If the customer requested us to press the button with a turn, we release * it now. */ if (pressbutton) { wait(speed, SC_MS); press(false); } /* And we tag that the last was a right turn as when we shift to the left * we can have some odd behaviour. */ lastwasright = true; } void encoder::turnright(int pulses, bool pressbutton) { /* We start by raising the button, if requested. */ if (pressbutton) press(true); /* If the last was a right turn, we need to do the direction change glitch. * Note that if the button is pressed, we only toggle pin A. */ if (lastwasright) { wait(speed, SC_MS); pinA.write(GN_LOGIC_1); wait(speed, SC_MS); pinB.write(GN_LOGIC_1); wait(speed, SC_MS); pinB.write(GN_LOGIC_Z); wait(speed, SC_MS); pinA.write(GN_LOGIC_Z); } /* And we apply the pulses, again, watching for the button. */ wait(phase, SC_MS); while(pulses > 0) { wait(speed-phase, SC_MS); pinB.write(GN_LOGIC_1); wait(phase, SC_MS); pinA.write(GN_LOGIC_1); wait(speed-phase, SC_MS); pinB.write(GN_LOGIC_Z); if (edges == 2) wait(phase, SC_MS); pinA.write(GN_LOGIC_Z); if (edges != 2) wait(phase, SC_MS); pulses = pulses - 1; } /* If the customer requested us to press the button with a turn, we release * it now. */ if (pressbutton) { wait(speed, SC_MS); press(false); } /* And we tag that the last was a left turn, so we can do the left turn to * right turn glitch. */ lastwasright = false; } void encoder::start_of_simulation() { pinA.write(GN_LOGIC_Z); pinB.write(GN_LOGIC_Z); pinC.write(GN_LOGIC_Z); } void encoder::trace(sc_trace_file *tf) { sc_trace(tf, pinA, pinA.name()); sc_trace(tf, pinB, pinB.name()); sc_trace(tf, pinC, pinC.name()); }
// //------------------------------------------------------------// // Copyright 2009-2012 Mentor Graphics Corporation // // All Rights Reserved Worldwid // // // // Licensed under the Apache License, Version 2.0 (the // // "License"); you may not use this file except in // // compliance with the License. You may obtain a copy of // // the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in // // writing, software distributed under the License is // // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // // CONDITIONS OF ANY KIND, either express or implied. See // // the License for the specific language governing // // permissions and limitations under the License. // //------------------------------------------------------------// #ifndef PACKET_H #define PACKET_H #include <vector> using std::vector; #include <systemc.h> #include <tlm.h> using namespace sc_core; class packet { public: short cmd; int addr; vector<char> data; }; //------------------------------------------------------------------------------ // Begin UVMC-specific code #include "uvmc.h" using namespace uvmc; UVMC_UTILS_3 (packet,cmd,addr,data) #endif // PACKET_H
#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) { dbgimgtarmodprint(use_prints, "Called do_when_read_transaction with an address %016llX and length %d", address, data_length); this->img_result = *(Filter<IPS_IN_TYPE_TB, IPS_OUT_TYPE_TB, IPS_FILTER_KERNEL_SIZE>::result_ptr); *data = (unsigned char) this->img_result; dbgimgtarmodprint(true, "Returning filter result %f", 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; dbgimgtarmodprint(use_prints, "Called do_when_write_transaction with an address %016llX and length %d", address, data_length); //dbgimgtarmodprint(use_prints, "[DEBUG]: data: %0d, address %0d, data_length %0d, size of char %0d", *data, address, data_length, sizeof(char)); for (int i = 0; i < data_length; i++) { this->img_window[address + i] = (IPS_IN_TYPE_TB) *(data + i); } //dbgimgtarmodprint(use_prints, "[DEBUG]: img_window data: %0f", this->img_window[address]); if (address == 8) { dbgimgtarmodprint(true, "Got full window, starting filtering now"); filter(this->img_window, result); } } #endif // IPS_FILTER_TLM_CPP
/* * 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 <systemc.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/wait.h> #include <fcntl.h> #include <sl_block_device.h> /* #define DEBUG_DEVICE_BLOCK */ #ifdef DEBUG_DEVICE_BLOCK #define DPRINTF(fmt, args...) \ do { printf("sl_block_device: " fmt , ##args); } while (0) #define DCOUT if (1) cout #else #define DPRINTF(fmt, args...) do {} while(0) #define DCOUT if (0) cout #endif #define EPRINTF(fmt, args...) \ do { fprintf(stderr, "sl_block_device: " fmt , ##args); } while (0) sl_block_device::sl_block_device (sc_module_name _name, uint32_t master_id, const char *fname, uint32_t block_size) :sc_module(_name) { char *buf = new char[strlen(_name) + 3]; m_cs_regs = new sl_block_device_CSregs_t; m_cs_regs->m_status = 0; m_cs_regs->m_buffer = 0; m_cs_regs->m_op = 0; m_cs_regs->m_lba = 0; m_cs_regs->m_count = 0; m_cs_regs->m_size = 0; m_cs_regs->m_block_size = block_size; m_cs_regs->m_irqen = 0; m_cs_regs->m_irq = 0; strcpy(buf, _name); buf[strlen(_name)] = '_'; buf[strlen(_name)+1] = 'm'; buf[strlen(_name)+2] = '\0'; master = new sl_block_device_master(buf, master_id); buf[strlen(_name)+1] = 's'; slave = new sl_block_device_slave(buf, m_cs_regs, &ev_op_start, &ev_irq_update); m_fd = -1; open_host_file (fname); SC_THREAD (irq_update_thread); SC_THREAD (control_thread); } sl_block_device::~sl_block_device () { DPRINTF("destructor called\n"); } static off_t get_file_size (int fd) { off_t old_pos = lseek (fd, 0, SEEK_CUR); off_t ret = lseek (fd, 0, SEEK_END); lseek (fd, old_pos, SEEK_SET); return ret; } void sl_block_device::open_host_file (const char *fname) { if (m_fd != -1) { ::close (m_fd); m_fd = -1; } if (fname) { m_fd = ::open(fname, O_RDWR | O_CREAT, 0644); if(m_fd < 0) { EPRINTF("Impossible to open file : %s\n", fname); return; } m_cs_regs->m_size = get_file_size (m_fd) / m_cs_regs->m_block_size; } } master_device * sl_block_device::get_master () { return (master_device *)master; } slave_device * sl_block_device::get_slave () { return (slave_device *)slave; } void sl_block_device::control_thread () { uint32_t offset, addr, transfer_size; uint8_t *data_buff; int func_ret; while(1) { switch(m_cs_regs->m_op) { case BLOCK_DEVICE_NOOP: DPRINTF("Got a BLOCK_DEVICE_NOOP\n"); wait(ev_op_start); break; case BLOCK_DEVICE_READ: m_cs_regs->m_status = BLOCK_DEVICE_BUSY; transfer_size = m_cs_regs->m_count * m_cs_regs->m_block_size; data_buff = new uint8_t[transfer_size + 4]; DPRINTF("Got a BLOCK_DEVICE_READ of size %x\n", transfer_size); /* Read in device */ lseek(m_fd, m_cs_regs->m_lba*m_cs_regs->m_block_size, SEEK_SET); func_ret = ::read(m_fd, data_buff, transfer_size); addr = m_cs_regs->m_buffer; if (func_ret < 0) { EPRINTF("Error in ::read()\n"); m_cs_regs->m_op = BLOCK_DEVICE_NOOP; m_cs_regs->m_status = BLOCK_DEVICE_READ_ERROR; m_cs_regs->m_count = 0; break; } m_cs_regs->m_count = func_ret / m_cs_regs->m_block_size; transfer_size = func_ret; if (transfer_size) { /* Send data in memory */ uint32_t up_4align_limit = transfer_size & ~3; for(offset = 0; offset < up_4align_limit; offset += 4) { func_ret = master->cmd_write(addr + offset, data_buff + offset, 4); if(!func_ret) break; } for (; offset < transfer_size; offset++) { func_ret = master->cmd_write(addr + offset, data_buff + offset, 1); if(!func_ret) break; } if(!func_ret) { EPRINTF("Error in Read\n"); m_cs_regs->m_op = BLOCK_DEVICE_NOOP; m_cs_regs->m_status = BLOCK_DEVICE_READ_ERROR; m_cs_regs->m_count = offset / m_cs_regs->m_block_size; break; } } /* Update everything */ if(m_cs_regs->m_irqen) { m_cs_regs->m_irq = 1; ev_irq_update.notify(); } m_cs_regs->m_op = BLOCK_DEVICE_NOOP; m_cs_regs->m_status = BLOCK_DEVICE_READ_SUCCESS; delete data_buff; break; case BLOCK_DEVICE_WRITE: DPRINTF("Got a BLOCK_DEVICE_WRITE\n"); m_cs_regs->m_status = BLOCK_DEVICE_BUSY; transfer_size = m_cs_regs->m_count * m_cs_regs->m_block_size; data_buff = new uint8_t[transfer_size + 4]; addr = m_cs_regs->m_buffer; /* Read data from memory */ for(offset = 0; offset < transfer_size; offset += 4) { func_ret = master->cmd_read(addr + offset, data_buff + offset, 4); if(!func_ret) break; } if(!func_ret) { m_cs_regs->m_op = BLOCK_DEVICE_NOOP; m_cs_regs->m_status = BLOCK_DEVICE_WRITE_ERROR; break; } /* Write in the device */ lseek(m_fd, m_cs_regs->m_lba*m_cs_regs->m_block_size, SEEK_SET); ::write(m_fd, data_buff, transfer_size); m_cs_regs->m_size = get_file_size (m_fd) / m_cs_regs->m_block_size; /* Update everything */ if(m_cs_regs->m_irqen) { m_cs_regs->m_irq = 1; ev_irq_update.notify(); } m_cs_regs->m_op = BLOCK_DEVICE_NOOP; m_cs_regs->m_status = BLOCK_DEVICE_WRITE_SUCCESS; delete data_buff; break; case BLOCK_DEVICE_FILE_NAME: DPRINTF("Got a BLOCK_DEVICE_FILE_NAME\n"); m_cs_regs->m_status = BLOCK_DEVICE_BUSY; transfer_size = m_cs_regs->m_count * m_cs_regs->m_block_size; data_buff = new uint8_t[transfer_size + 4]; addr = m_cs_regs->m_buffer; /* Read data from memory */ for(offset = 0; offset < transfer_size; offset += 4) { func_ret = master->cmd_read(addr + offset, data_buff + offset, 4); if(!func_ret) break; } if (func_ret) open_host_file ((const char*) data_buff); if(!func_ret || m_fd == -1) { m_cs_regs->m_op = BLOCK_DEVICE_NOOP; m_cs_regs->m_status = BLOCK_DEVICE_WRITE_ERROR; break; } m_cs_regs->m_op = BLOCK_DEVICE_NOOP; m_cs_regs->m_status = BLOCK_DEVICE_WRITE_SUCCESS; delete data_buff; break; default: EPRINTF("Error in command\n"); } } } void sl_block_device::irq_update_thread () { while(1) { wait(ev_irq_update); if(m_cs_regs->m_irq == 1) { DPRINTF("Raising IRQ\n"); irq = 1; } else { DPRINTF("Clearing IRQ\n"); irq = 0; } } return; } /* * sl_block_device_master */ sl_block_device_master::sl_block_device_master (const char *_name, uint32_t node_id) : master_device(_name) { m_crt_tid = 0; m_status = MASTER_READY; m_node_id = node_id; } sl_block_device_master::~sl_block_device_master() { } int sl_block_device_master::cmd_write (uint32_t addr, uint8_t *data, uint8_t nbytes) { DPRINTF("Write to %x [0x%08x]\n", addr, *(uint32_t *)data); send_req (m_crt_tid, addr, data, nbytes, 1); wait (ev_cmd_done); if(m_status != MASTER_CMD_SUCCESS) return 0; return 1; } int sl_block_device_master::cmd_read (uint32_t addr, uint8_t *data, uint8_t nbytes) { m_tr_nbytes = nbytes; m_tr_rdata = 0; DPRINTF ("Read from %x\n", addr); send_req (m_crt_tid, addr, NULL, nbytes, 0); wait (ev_cmd_done); for (int i = 0; i < nbytes; i++) data[i] = ((unsigned char *) &m_tr_rdata)[i]; if (m_status != MASTER_CMD_SUCCESS) return 0; return 1; } void sl_block_device_master::rcv_rsp (uint8_t tid, uint8_t *data, bool bErr, bool bWrite) { if (tid != m_crt_tid) { EPRINTF ("Bad tid (%d / %d)\n", tid, m_crt_tid); } if (bErr) { DPRINTF("Cmd KO\n"); m_status = MASTER_CMD_ERROR; } else { //DPRINTF("Cmd OK\n"); m_status = MASTER_CMD_SUCCESS; } if (!bWrite) { for (int i = 0; i < m_tr_nbytes; i++) ((unsigned char *) &m_tr_rdata)[i] = data[i]; } m_crt_tid++; ev_cmd_done.notify (); } /* * sl_block_device_slave */ sl_block_device_slave::sl_block_device_slave (const char *_name, sl_block_device_CSregs_t *cs_regs, sc_event *op_start, sc_event *irq_update) : slave_device (_name) { m_cs_regs = cs_regs; ev_op_start = op_start; ev_irq_update = irq_update; } sl_block_device_slave::~sl_block_device_slave() { } void sl_block_device_slave::write (unsigned long ofs, unsigned char be, unsigned char *data, bool &bErr) { uint32_t *val = (uint32_t *) data; uint32_t lofs = ofs; uint8_t lbe = be; bErr = false; lofs >>= 2; if (lbe & 0xF0) { lofs += 1; lbe >>= 4; val++; } switch(lofs) { case BLOCK_DEVICE_BUFFER : DPRINTF("BLOCK_DEVICE_BUFFER write: %x\n", *val); m_cs_regs->m_buffer = *val; break; case BLOCK_DEVICE_LBA : DPRINTF("BLOCK_DEVICE_LBA write: %x\n", *val); m_cs_regs->m_lba = *val; break; case BLOCK_DEVICE_COUNT : DPRINTF("BLOCK_DEVICE_COUNT write: %x\n", *val); m_cs_regs->m_count = *val; break; case BLOCK_DEVICE_OP : DPRINTF("BLOCK_DEVICE_OP write: %x\n", *val); if(m_cs_regs->m_status != BLOCK_DEVICE_IDLE) { EPRINTF("Got a command while executing another one\n"); break; } m_cs_regs->m_op = *val; ev_op_start->notify(); break; case BLOCK_DEVICE_IRQ_ENABLE : DPRINTF("BLOCK_DEVICE_IRQ_ENABLE write: %x\n", *val); m_cs_regs->m_irqen = *val; ev_irq_update->notify(); break; case BLOCK_DEVICE_STATUS : case BLOCK_DEVICE_SIZE : case BLOCK_DEVICE_BLOCK_SIZE : default: EPRINTF("Bad %s::%s ofs=0x%X, be=0x%X\n", name (), __FUNCTION__, (unsigned int) ofs, (unsigned int) be); } } void sl_block_device_slave::read (unsigned long ofs, unsigned char be, unsigned char *data, bool &bErr) { uint32_t *val = (uint32_t *)data; uint32_t lofs = ofs; uint8_t lbe = be; bErr = false; lofs >>= 2; if (lbe & 0xF0) { lofs += 1; lbe >>= 4; val++; } switch(lofs) { case BLOCK_DEVICE_BUFFER : *val = m_cs_regs->m_buffer; DPRINTF("BLOCK_DEVICE_BUFFER read: %x\n", *val); break; case BLOCK_DEVICE_LBA : *val = m_cs_regs->m_lba; DPRINTF("BLOCK_DEVICE_LBA read: %x\n", *val); break; case BLOCK_DEVICE_COUNT : *val = m_cs_regs->m_count; DPRINTF("BLOCK_DEVICE_COUNT read: %x\n", *val); break; case BLOCK_DEVICE_OP : *val = m_cs_regs->m_op; DPRINTF("BLOCK_DEVICE_OP read: %x\n", *val); break; case BLOCK_DEVICE_STATUS : *val = m_cs_regs->m_status; DPRINTF("BLOCK_DEVICE_STATUS read: %x\n", *val); if(m_cs_regs->m_status != BLOCK_DEVICE_BUSY) { m_cs_regs->m_status = BLOCK_DEVICE_IDLE; m_cs_regs->m_irq = 0; ev_irq_update->notify(); } break; case BLOCK_DEVICE_IRQ_ENABLE : *val = m_cs_regs->m_irqen; DPRINTF("BLOCK_DEVICE_IRQ_ENABLE read: %x\n", *val); break; case BLOCK_DEVICE_SIZE : *val = m_cs_regs->m_size; DPRINTF("BLOCK_DEVICE_SIZE read: %x\n", *val); break; case BLOCK_DEVICE_BLOCK_SIZE : *val = m_cs_regs->m_block_size; DPRINTF("BLOCK_DEVICE_BLOCK_SIZE read: %x\n", *val); break; default: EPRINTF("Bad %s::%s ofs=0x%X, be=0x%X\n", name (), __FUNCTION__, (unsigned int) ofs, (unsigned int) be); } } void sl_block_device_slave::rcv_rqst (unsigned long ofs, unsigned char be, unsigned char *data, bool bWrite) { bool bErr = false; if(bWrite) this->write(ofs, be, data, bErr); else this->read(ofs, be, data, bErr); send_rsp(bErr); return; } /* * 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: */
// Copyright 2018 Evandro Luis Copercini // // 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 "sdkconfig.h" #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> #include "esp_gap_bt_api.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include <systemc.h> #include "info.h" #include "btmod.h" #if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED) #ifdef ARDUINO_ARCH_ESP32 #include "esp32-hal-log.h" #endif #include "BluetoothSerial.h" #include "esp_bt.h" #include "esp_bt_main.h" #include "esp_gap_bt_api.h" #include "esp_bt_device.h" #include "esp_spp_api.h" #include <esp_log.h> #include "esp32-hal-log.h" const char * _spp_server_name = "ESP32SPP"; #define RX_QUEUE_SIZE 512 #define TX_QUEUE_SIZE 32 static uint32_t _spp_client = 0; static boolean secondConnectionAttempt; static esp_spp_cb_t * custom_spp_callback = NULL; static BluetoothSerialDataCb custom_data_callback = NULL; #define INQ_LEN 0x10 #define INQ_NUM_RSPS 20 #define READY_TIMEOUT (10 * 1000) #define SCAN_TIMEOUT (INQ_LEN * 2 * 1000) static esp_bd_addr_t _peer_bd_addr; static char _remote_name[ESP_BT_GAP_MAX_BDNAME_LEN + 1]; static bool _isRemoteAddressSet; static bool _isMaster; static esp_bt_pin_code_t _pin_code; static int _pin_len; static bool _isPinSet; static bool _enableSSP; #define SPP_RUNNING 0x01 #define SPP_CONNECTED 0x02 #define SPP_CONGESTED 0x04 #define SPP_DISCONNECTED 0x08 typedef struct { size_t len; uint8_t data[]; } spp_packet_t; #if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO) static char *bda2str(esp_bd_addr_t bda, char *str, size_t size) { if (bda == NULL || str == NULL || size < 18) { return NULL; } uint8_t *p = bda; sprintf(str, "%02x:%02x:%02x:%02x:%02x:%02x", p[0], p[1], p[2], p[3], p[4], p[5]); return str; } #endif static bool get_name_from_eir(uint8_t *eir, char *bdname, uint8_t *bdname_len) { if (!eir || !bdname || !bdname_len) { return false; } uint8_t *rmt_bdname, rmt_bdname_len; *bdname = *bdname_len = rmt_bdname_len = 0; rmt_bdname = esp_bt_gap_resolve_eir_data(eir, ESP_BT_EIR_TYPE_CMPL_LOCAL_NAME, &rmt_bdname_len); if (!rmt_bdname) { rmt_bdname = esp_bt_gap_resolve_eir_data(eir, ESP_BT_EIR_TYPE_SHORT_LOCAL_NAME, &rmt_bdname_len); } if (rmt_bdname) { rmt_bdname_len = rmt_bdname_len > ESP_BT_GAP_MAX_BDNAME_LEN ? ESP_BT_GAP_MAX_BDNAME_LEN : rmt_bdname_len; memcpy(bdname, rmt_bdname, rmt_bdname_len); bdname[rmt_bdname_len] = 0; *bdname_len = rmt_bdname_len; return true; } return false; } static bool btSetPin() { esp_bt_pin_type_t pin_type; if (_isPinSet) { if (_pin_len) { log_i("pin set"); pin_type = ESP_BT_PIN_TYPE_FIXED; } else { _isPinSet = false; log_i("pin reset"); pin_type = ESP_BT_PIN_TYPE_VARIABLE; // pin_code would be ignored (default) } return (esp_bt_gap_set_pin(pin_type, _pin_len, _pin_code) == ESP_OK); } return false; } static void esp_spp_cb(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) { /* switch (event) { case ESP_SPP_INIT_EVT: log_i("ESP_SPP_INIT_EVT"); esp_bt_gap_set_scan_mode(ESP_BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); if (!_isMaster) { log_i("ESP_SPP_INIT_EVT: slave: start"); esp_spp_start_srv(ESP_SPP_SEC_NONE, ESP_SPP_ROLE_SLAVE, 0, _spp_server_name); } break; case ESP_SPP_SRV_OPEN_EVT://Server connection open log_i("ESP_SPP_SRV_OPEN_EVT"); if (!_spp_client){ _spp_client = param->open.handle; } else { secondConnectionAttempt = true; esp_spp_disconnect(param->open.handle); } break; case ESP_SPP_CLOSE_EVT://Client connection closed log_i("ESP_SPP_CLOSE_EVT"); if(secondConnectionAttempt) { secondConnectionAttempt = false; } else { _spp_client = 0; } break; case ESP_SPP_CONG_EVT://connection congestion status changed log_v("ESP_SPP_CONG_EVT: %s", param->cong.cong?"CONGESTED":"FREE"); break; case ESP_SPP_WRITE_EVT://write operation completed log_v("ESP_SPP_WRITE_EVT: %u %s", param->write.len, param->write.cong?"CONGESTED":"FREE"); break; case ESP_SPP_DATA_IND_EVT://connection received data log_v("ESP_SPP_DATA_IND_EVT len=%d handle=%d", param->data_ind.len, param->data_ind.handle); //esp_log_buffer_hex("",param->data_ind.data,param->data_ind.len); //for low level debug //ets_printf("r:%u\n", param->data_ind.len); if(custom_data_callback){ custom_data_callback(param->data_ind.data, param->data_ind.len); } break; case ESP_SPP_DISCOVERY_COMP_EVT://discovery complete log_i("ESP_SPP_DISCOVERY_COMP_EVT"); if (param->disc_comp.status == ESP_SPP_SUCCESS) { log_i("ESP_SPP_DISCOVERY_COMP_EVT: spp connect to remote"); esp_spp_connect(ESP_SPP_SEC_AUTHENTICATE, ESP_SPP_ROLE_MASTER, param->disc_comp.scn[0], _peer_bd_addr); } break; case ESP_SPP_OPEN_EVT://Client connection open log_i("ESP_SPP_OPEN_EVT"); if (!_spp_client){ _spp_client = param->open.handle; } else { secondConnectionAttempt = true; esp_spp_disconnect(param->open.handle); } break; case ESP_SPP_START_EVT://server started log_i("ESP_SPP_START_EVT"); break; case ESP_SPP_CL_INIT_EVT://client initiated a connection log_i("ESP_SPP_CL_INIT_EVT"); break; default: break; } if(custom_spp_callback)(*custom_spp_callback)(event, param); */ } void BluetoothSerial::onData(BluetoothSerialDataCb cb){ custom_data_callback = cb; } static void esp_bt_gap_cb(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param) { /* switch(event){ case ESP_BT_GAP_DISC_RES_EVT: log_i("ESP_BT_GAP_DISC_RES_EVT"); #if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO) char bda_str[18]; log_i("Scanned device: %s", bda2str(param->disc_res.bda, bda_str, 18)); #endif for (int i = 0; i < param->disc_res.num_prop; i++) { uint8_t peer_bdname_len; char peer_bdname[ESP_BT_GAP_MAX_BDNAME_LEN + 1]; switch(param->disc_res.prop[i].type) { case ESP_BT_GAP_DEV_PROP_EIR: if (get_name_from_eir((uint8_t*)param->disc_res.prop[i].val, peer_bdname, &peer_bdname_len)) { log_i("ESP_BT_GAP_DISC_RES_EVT : EIR : %s : %d", peer_bdname, peer_bdname_len); if (strlen(_remote_name) == peer_bdname_len && strncmp(peer_bdname, _remote_name, peer_bdname_len) == 0) { log_v("ESP_BT_GAP_DISC_RES_EVT : SPP_START_DISCOVERY_EIR : %s", peer_bdname, peer_bdname_len); _isRemoteAddressSet = true; memcpy(_peer_bd_addr, param->disc_res.bda, ESP_BD_ADDR_LEN); esp_bt_gap_cancel_discovery(); esp_spp_start_discovery(_peer_bd_addr); } } break; case ESP_BT_GAP_DEV_PROP_BDNAME: peer_bdname_len = param->disc_res.prop[i].len; memcpy(peer_bdname, param->disc_res.prop[i].val, peer_bdname_len); peer_bdname_len--; // len includes 0 terminator log_v("ESP_BT_GAP_DISC_RES_EVT : BDNAME : %s : %d", peer_bdname, peer_bdname_len); if (strlen(_remote_name) == peer_bdname_len && strncmp(peer_bdname, _remote_name, peer_bdname_len) == 0) { log_i("ESP_BT_GAP_DISC_RES_EVT : SPP_START_DISCOVERY_BDNAME : %s", peer_bdname); _isRemoteAddressSet = true; memcpy(_peer_bd_addr, param->disc_res.bda, ESP_BD_ADDR_LEN); esp_bt_gap_cancel_discovery(); esp_spp_start_discovery(_peer_bd_addr); } break; case ESP_BT_GAP_DEV_PROP_COD: log_d("ESP_BT_GAP_DEV_PROP_COD"); break; case ESP_BT_GAP_DEV_PROP_RSSI: log_d("ESP_BT_GAP_DEV_PROP_RSSI"); break; default: break; } if (_isRemoteAddressSet) break; } break; case ESP_BT_GAP_DISC_STATE_CHANGED_EVT: log_i("ESP_BT_GAP_DISC_STATE_CHANGED_EVT"); break; case ESP_BT_GAP_RMT_SRVCS_EVT: log_i( "ESP_BT_GAP_RMT_SRVCS_EVT"); break; case ESP_BT_GAP_RMT_SRVC_REC_EVT: log_i("ESP_BT_GAP_RMT_SRVC_REC_EVT"); break; case ESP_BT_GAP_AUTH_CMPL_EVT: if (param->auth_cmpl.stat == ESP_BT_STATUS_SUCCESS) { log_v("authentication success: %s", param->auth_cmpl.device_name); } else { log_e("authentication failed, status:%d", param->auth_cmpl.stat); } break; case ESP_BT_GAP_PIN_REQ_EVT: // default pairing pins log_i("ESP_BT_GAP_PIN_REQ_EVT min_16_digit:%d", param->pin_req.min_16_digit); if (param->pin_req.min_16_digit) { log_i("Input pin code: 0000 0000 0000 0000"); esp_bt_pin_code_t pin_code; memset(pin_code, '0', ESP_BT_PIN_CODE_LEN); esp_bt_gap_pin_reply(param->pin_req.bda, true, 16, pin_code); } else { log_i("Input pin code: 1234"); esp_bt_pin_code_t pin_code; memcpy(pin_code, "1234", 4); esp_bt_gap_pin_reply(param->pin_req.bda, true, 4, pin_code); } break; case ESP_BT_GAP_CFM_REQ_EVT: log_i("ESP_BT_GAP_CFM_REQ_EVT Please compare the numeric value: %d", param->cfm_req.num_val); esp_bt_gap_ssp_confirm_reply(param->cfm_req.bda, true); break; case ESP_BT_GAP_KEY_NOTIF_EVT: log_i("ESP_BT_GAP_KEY_NOTIF_EVT passkey:%d", param->key_notif.passkey); break; case ESP_BT_GAP_KEY_REQ_EVT: log_i("ESP_BT_GAP_KEY_REQ_EVT Please enter passkey!"); break; default: break; } */ } static bool _init_bt(const char *deviceName) { if (!btStarted() && !btStart()){ log_e("initialize controller failed"); return false; } esp_bluedroid_status_t bt_state = esp_bluedroid_get_status(); if (bt_state == ESP_BLUEDROID_STATUS_UNINITIALIZED){ if (esp_bluedroid_init()) { log_e("initialize bluedroid failed"); return false; } } if (bt_state != ESP_BLUEDROID_STATUS_ENABLED){ if (esp_bluedroid_enable()) { log_e("enable bluedroid failed"); return false; } } if (_isMaster && esp_bt_gap_register_callback(esp_bt_gap_cb) != ESP_OK) { log_e("gap register failed"); return false; } /* if (esp_spp_register_callback(esp_spp_cb) != ESP_OK){ log_e("spp register failed"); return false; } */ /* if (esp_spp_init(ESP_SPP_MODE_CB) != ESP_OK){ log_e("spp init failed"); return false; } */ if (esp_bt_sleep_disable() != ESP_OK){ log_e("esp_bt_sleep_disable failed"); } log_i("device name set"); //esp_bt_dev_set_device_name(deviceName); if (_isPinSet) { btSetPin(); } if (_enableSSP) { log_i("Simple Secure Pairing"); //esp_bt_sp_param_t param_type = ESP_BT_SP_IOCAP_MODE; //esp_bt_io_cap_t iocap = ESP_BT_IO_CAP_IO; //esp_bt_gap_set_security_param(param_type, &iocap, sizeof(uint8_t)); } // the default BTA_DM_COD_LOUDSPEAKER does not work with the macOS BT stack esp_bt_cod_t cod; cod.major = 0b00001; cod.minor = 0b000100; cod.service = 0b00000010110; if (esp_bt_gap_set_cod(cod, ESP_BT_INIT_COD) != ESP_OK) { log_e("set cod failed"); return false; } return true; } static bool _stop_bt() { if (btStarted()){ /* if(_spp_client) esp_spp_disconnect(_spp_client); esp_spp_deinit(); */ esp_bluedroid_disable(); esp_bluedroid_deinit(); btStop(); } _spp_client = 0; return true; } static bool waitForConnect(int timeout) { if(btptr == NULL) { PRINTF_ERROR("BSER", "BTPTR not setup"); return false; } wait(sc_time(timeout, SC_MS), btptr->connected_ev); if (btptr->connected_ev.triggered()) return true; else return false; } /* * Serial Bluetooth Arduino * * */ BluetoothSerial::BluetoothSerial() { local_name = "ESP32"; //default bluetooth name } BluetoothSerial::~BluetoothSerial(void) { _stop_bt(); } bool BluetoothSerial::begin(String localName, bool isMaster) { _isMaster = isMaster; if (localName.length()){ local_name = localName; } return _init_bt(local_name.c_str()); } int BluetoothSerial::available(void) { if(btptr == NULL) { PRINTF_ERROR("BSER", "BTPTR not setup"); return -1; } return BTserial.available(); } int BluetoothSerial::peek(void) { if(btptr == NULL) { PRINTF_ERROR("BSER", "BTPTR not setup"); return -1; } return BTserial.peek(); } bool BluetoothSerial::hasClient(void) { return _spp_client > 0; } int BluetoothSerial::read(void) { if(btptr == NULL) { PRINTF_ERROR("BSER", "BTPTR not setup"); return 0; } return BTserial.read(); } size_t BluetoothSerial::write(uint8_t c) { if(btptr == NULL) { PRINTF_ERROR("BSER", "BTPTR not setup"); return 0; } return BTserial.write(c); } size_t BluetoothSerial::write(const uint8_t *buffer, size_t size) { if (!_spp_client){ return 0; } if(btptr == NULL) { PRINTF_ERROR("BSER", "BTPTR not setup"); return 0; } return BTserial.write((char *)buffer, size); } void BluetoothSerial::flush() { if(btptr == NULL) { PRINTF_ERROR("BSER", "BTPTR not setup"); } else BTserial.flush(); } void BluetoothSerial::end() { _stop_bt(); } esp_err_t BluetoothSerial::register_callback(esp_spp_cb_t * callback) { custom_spp_callback = callback; return ESP_OK; } //Simple Secure Pairing void BluetoothSerial::enableSSP() { _enableSSP = true; } /* * Set default parameters for Legacy Pairing * Use fixed pin code */ bool BluetoothSerial::setPin(const char *pin) { bool isEmpty = !(pin && *pin); if (isEmpty && !_isPinSet) { return true; // nothing to do } else if (!isEmpty){ _pin_len = strlen(pin); memcpy(_pin_code, pin, _pin_len); } else { _pin_len = 0; // resetting pin to none (default) } _pin_code[_pin_len] = 0; _isPinSet = true; if (isReady(false, READY_TIMEOUT)) { btSetPin(); } return true; } bool BluetoothSerial::connect(String remoteName) { if (!isReady(true, READY_TIMEOUT)) return false; if (remoteName && remoteName.length() < 1) { log_e("No remote name is provided"); return false; } disconnect(); _isRemoteAddressSet = false; strncpy(_remote_name, remoteName.c_str(), ESP_BT_GAP_MAX_BDNAME_LEN); _remote_name[ESP_BT_GAP_MAX_BDNAME_LEN] = 0; log_i("master : remoteName"); // will first resolve name to address //esp_bt_gap_set_scan_mode(ESP_BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); //if (esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, INQ_LEN, INQ_NUM_RSPS) == ESP_OK) { // return waitForConnect(SCAN_TIMEOUT); //} //return false; return true; } bool BluetoothSerial::connect(uint8_t remoteAddress[]) { if (!isReady(true, READY_TIMEOUT)) return false; if (!remoteAddress) { log_e("No remote address is provided"); return false; } disconnect(); _remote_name[0] = 0; _isRemoteAddressSet = true; memcpy(_peer_bd_addr, remoteAddress, ESP_BD_ADDR_LEN); log_i("master : remoteAddress"); /* if (esp_spp_start_discovery(_peer_bd_addr) == ESP_OK) { return waitForConnect(READY_TIMEOUT); } return false; */ return true; } bool BluetoothSerial::connect() { if (!isReady(true, READY_TIMEOUT)) return false; if (_isRemoteAddressSet){ disconnect(); // use resolved or set address first log_i("master : remoteAddress"); //if (esp_spp_start_discovery(_peer_bd_addr) == ESP_OK) { // return waitForConnect(READY_TIMEOUT); //} //return false; return true; } else if (_remote_name[0]) { disconnect(); log_i("master : remoteName"); // will resolve name to address first - it may take a while //esp_bt_gap_set_scan_mode(ESP_BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); //if (esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, INQ_LEN, INQ_NUM_RSPS) == ESP_OK) { // return waitForConnect(SCAN_TIMEOUT); //} //return false; return true; } log_e("Neither Remote name nor address was provided"); return false; } bool BluetoothSerial::disconnect() { /* if (_spp_client) { flush(); log_i("disconnecting"); if (esp_spp_disconnect(_spp_client) == ESP_OK) { wait(sc_time(READY_TIMEOUT, SC_MS), btptr->disconnected_ev); if (btptr->disconnected_ev.triggered()) return true; else return false; } } return false; */ return true; } bool BluetoothSerial::unpairDevice(uint8_t remoteAddress[]) { if (isReady(false, READY_TIMEOUT)) { log_i("removing bonded device"); return (esp_bt_gap_remove_bond_device(remoteAddress) == ESP_OK); } return false; } bool BluetoothSerial::connected(int timeout) { return waitForConnect(timeout); } bool BluetoothSerial::isReady(bool checkMaster, int timeout) { if (checkMaster && !_isMaster) { log_e("Master mode is not active. Call begin(localName, true) to enable Master mode"); return false; } if (!btStarted()) { log_e("BT is not initialized. Call begin() first"); return false; } wait(sc_time(timeout, SC_MS), btptr->running_ev); if (btptr->running_ev.triggered()) return true; else return false; } #endif
/* * Created on: 21. jun. 2019 * Author: Jonathan Horsted Schougaard */ #ifdef HW_COSIM //#define __GMP_WITHIN_CONFIGURE #endif #define DEBUG_SYSTEMC #define SC_INCLUDE_FX #include "hwcore/tb/pipes/tb_streamcircularlinebuffer.h" #include <cstdlib> #include <iostream> #include <systemc.h> unsigned errors = 0; const char simulation_name[] = "streamcircularlinebuffer_tb"; void flush_io() { std::cout << "flush_io()" << std::flush; } void flush_quick_io() { std::cout << "flush_quick_io()" << std::flush; } int sc_main(int argc, char *argv[]) { if (std::atexit(flush_io) != 0 || std::at_quick_exit(flush_quick_io) != 0) { std::cout << "error setup flush at exit" << std::endl; std::exit(1); } return errors ? 1 : 0; 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_streamcircularlinebuffer<sizeof(int) * 8, 3> top("tb_top_streamcircularlinebuffer"); 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); // assert(sc_time_stamp()!=sc_max_time()); cout << "INFO: Post-processing " << simulation_name << endl; cout << "INFO: Simulation " << simulation_name << " " << (errors ? "FAILED" : "PASSED") << " with " << errors << " errors" << std::endl << std::flush; #ifdef __RTL_SIMULATION__ cout << "HW cosim done" << endl; #endif return errors ? 1 : 0; } // test2
/* Problem 2 Design */ #include<systemc.h> SC_MODULE(counters) { sc_in<sc_uint<8> > in1 , in2 , in3; sc_in<bool> dec1 , dec2 , clock , load1 , load2; sc_out<sc_uint<8> > count1 , count2; sc_out<bool> ended; sc_signal<bool> isOverflow1 , isOverflow2; void handleCount1(); void handleCount2(); void updateEnded(); SC_CTOR(counters) { isOverflow1.write(false); isOverflow2.write(false); SC_METHOD(handleCount1); sensitive<<clock.pos(); SC_METHOD(handleCount2); sensitive<<clock.pos(); SC_METHOD(updateEnded); sensitive<<clock.pos(); } }; void counters::handleCount1() { if(load1.read() == true) { cout<<"@ "<<sc_time_stamp()<<"----------Start registerCount1---------"<<endl; count1.write(in1.read()); cout<<"@ "<<sc_time_stamp()<<"----------End registerCount1---------"<<endl; } else if(dec1.read() == true) { cout<<"@ "<<sc_time_stamp()<<"----------Start decCount1---------"<<endl; if(count1.read() == 0) { isOverflow1.write(true); return; } isOverflow1.write(false); count1.write(count1.read() - 1); cout<<"@ "<<sc_time_stamp()<<"----------End decCount1---------"<<endl; } } void counters::handleCount2() { if(load2.read() == true) { cout<<"@ "<<sc_time_stamp()<<"----------Start registerCount2---------"<<endl; count2.write(in2.read()); cout<<"@ "<<sc_time_stamp()<<"----------End registerCount2---------"<<endl; } else if(dec2.read() == true) { cout<<"@ "<<sc_time_stamp()<<"----------Start decCount2---------"<<endl; if(count2.read() <= in3.read()) { isOverflow2.write(true); return; } isOverflow2.write(false); count2.write(count2.read() - in3.read()); cout<<"@ "<<sc_time_stamp()<<"----------End decCount2---------"<<endl; } } void counters::updateEnded() { cout<<"@ "<<sc_time_stamp()<<"----------Start updateEnded---------"<<endl; if(count1.read() == count2.read() || isOverflow1.read() || isOverflow2.read()) { ended.write(true); } else { ended.write(false); } cout<<"@ "<<sc_time_stamp()<<"----------End updateEnded---------"<<endl; }
//**************************************************************************************** // 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/experimental/SystemC.hpp> #include <crave/ConstrainedRandom.hpp> #include <systemc.h> #include <boost/timer.hpp> #include <crave/experimental/Experimental.hpp> using crave::crv_sequence_item; using crave::crv_constraint; using crave::crv_variable; using crave::crv_object_name; using sc_dt::sc_bv; using sc_dt::sc_uint; struct ALU16 : public crv_sequence_item { crv_variable<sc_bv<2> > op; crv_variable<sc_uint<16> > a, b; crv_constraint c_add{ "add" }; crv_constraint c_sub{ "sub" }; crv_constraint c_mul{ "mul" }; crv_constraint c_div{ "div" }; ALU16(crv_object_name) { c_add = {(op() != 0x0) || (65535 >= a() + b()) }; c_sub = {(op() != 0x1) || ((65535 >= a() - b()) && (b() <= a())) }; c_mul = {(op() != 0x2) || (65535 >= a() * b()) }; c_div = {(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("ALU"); CHECK(c.randomize()); std::cout << "first: " << timer.elapsed() << "\n"; for (int i = 0; i < 1000; ++i) { CHECK(c.randomize()); } std::cout << "complete: " << timer.elapsed() << "\n"; return 0; }