From ac950afda9a88fae4428d2e9863d816520962ede Mon Sep 17 00:00:00 2001 From: Johannes Feldmann Date: Mon, 26 Mar 2018 16:04:17 +0200 Subject: [PATCH 01/38] Created base class for XMLAddressDecoder and created an alternative JSONAddressDecoder class. This class has still no functionality. --- DRAMSys/library/library.pro | 8 +- DRAMSys/library/src/common/AddressDecoder.cpp | 28 ++++++ DRAMSys/library/src/common/AddressDecoder.h | 93 +++++++++++++++++++ .../library/src/common/jsonAddressDecoder.cpp | 44 +++++++++ .../library/src/common/jsonAddressDecoder.h | 58 ++++++++++++ .../library/src/common/xmlAddressdecoder.cpp | 17 +--- .../library/src/common/xmlAddressdecoder.h | 37 ++------ .../core/configuration/Configuration.cpp | 4 +- DRAMSys/library/src/error/errormodel.cpp | 6 +- DRAMSys/library/src/error/errormodel.h | 4 +- DRAMSys/library/src/simulation/Arbiter.h | 14 +-- DRAMSys/library/src/simulation/DRAMSys.cpp | 23 ++++- 12 files changed, 269 insertions(+), 67 deletions(-) create mode 100644 DRAMSys/library/src/common/AddressDecoder.cpp create mode 100644 DRAMSys/library/src/common/AddressDecoder.h create mode 100644 DRAMSys/library/src/common/jsonAddressDecoder.cpp create mode 100644 DRAMSys/library/src/common/jsonAddressDecoder.h diff --git a/DRAMSys/library/library.pro b/DRAMSys/library/library.pro index ad74744a..20a1eb2d 100644 --- a/DRAMSys/library/library.pro +++ b/DRAMSys/library/library.pro @@ -119,7 +119,9 @@ SOURCES += \ src/error/eccbaseclass.cpp \ src/error/ecchamming.cpp \ src/controller/scheduler/Fr_Fcfs_read_priority.cpp \ - src/controller/scheduler/Fr_Fcfs_grouper.cpp + src/controller/scheduler/Fr_Fcfs_grouper.cpp \ + src/common/AddressDecoder.cpp \ + src/common/jsonAddressDecoder.cpp HEADERS += \ src/common/third_party/tinyxml2/tinyxml2.h \ @@ -190,7 +192,9 @@ HEADERS += \ src/error/eccbaseclass.h \ src/error/ecchamming.h \ src/controller/scheduler/Fr_Fcfs_read_priority.h \ - src/controller/scheduler/Fr_Fcfs_grouper.h + src/controller/scheduler/Fr_Fcfs_grouper.h \ + src/common/AddressDecoder.h \ + src/common/jsonAddressDecoder.h thermalsim = $$(THERMALSIM) isEmpty(thermalsim) { diff --git a/DRAMSys/library/src/common/AddressDecoder.cpp b/DRAMSys/library/src/common/AddressDecoder.cpp new file mode 100644 index 00000000..a473b442 --- /dev/null +++ b/DRAMSys/library/src/common/AddressDecoder.cpp @@ -0,0 +1,28 @@ +#include "AddressDecoder.h" +#include "xmlAddressdecoder.h" +#include "jsonAddressDecoder.h" + +CAddressDecoder* CAddressDecoder::m_pInstance = nullptr; + +CAddressDecoder& CAddressDecoder::getInstance() +{ + assert(m_pInstance != nullptr); + return *m_pInstance; +} + +void CAddressDecoder::createInstance(Type t) +{ + assert(m_pInstance == nullptr); + switch(t) + { + case Type::XML: + m_pInstance = new xmlAddressDecoder; + case Type::JSON: + m_pInstance = new JSONAddressDecoder; + } +} + +CAddressDecoder::CAddressDecoder() +{ + +} diff --git a/DRAMSys/library/src/common/AddressDecoder.h b/DRAMSys/library/src/common/AddressDecoder.h new file mode 100644 index 00000000..c5c23a70 --- /dev/null +++ b/DRAMSys/library/src/common/AddressDecoder.h @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2018, University of Kaiserslautern + * All rights reserved. + * + * 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. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER + * OR CONTRIBUTORS 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. + * + * Authors: + * Johannes Feldmann + */ + +#ifndef ADDRESSDECODER_H +#define ADDRESSDECODER_H + +#include +#include +#include +#include +#include + +struct DecodedAddress +{ + DecodedAddress() : channel(0), + rank(0), + bankgroup(0), + row(0), + bank(0), + column(0), + bytes(0) + { + } + + unsigned int channel; + unsigned int rank; + unsigned int bankgroup; + unsigned int row; + unsigned int bank; + unsigned int column; + unsigned int bytes; +}; + +class CAddressDecoder +{ +public: + enum class Type + { + XML, + JSON + }; + +protected: + CAddressDecoder(); + + static CAddressDecoder* m_pInstance; +public: + static CAddressDecoder& getInstance(); + static void createInstance(Type t); + + virtual void setConfiguration(std::string url) = 0; + + virtual DecodedAddress decodeAddress(sc_dt::uint64 addr) = 0; + virtual sc_dt::uint64 encodeAddress(DecodedAddress n) = 0; + + virtual void print() = 0; + + std::map amount; +}; + +#endif // ADDRESSDECODER_H diff --git a/DRAMSys/library/src/common/jsonAddressDecoder.cpp b/DRAMSys/library/src/common/jsonAddressDecoder.cpp new file mode 100644 index 00000000..d82f41bf --- /dev/null +++ b/DRAMSys/library/src/common/jsonAddressDecoder.cpp @@ -0,0 +1,44 @@ +#include "jsonAddressDecoder.h" + +#include + +using std::ifstream; +using std::cout; +using std::endl; + +JSONAddressDecoder::JSONAddressDecoder() +{ + +} + +void JSONAddressDecoder::setConfiguration(std::string url) +{ + ifstream file; + + file.open(url); + + if(!file.is_open()) + { + cout << "Unable to open file " << url << endl; + return; + } + + file.close(); +} + +DecodedAddress JSONAddressDecoder::decodeAddress(sc_dt::uint64 addr) +{ + DecodedAddress result; + + return result; +} + +sc_dt::uint64 JSONAddressDecoder::encodeAddress(DecodedAddress n) +{ + return 0; +} + +void JSONAddressDecoder::print() +{ + +} diff --git a/DRAMSys/library/src/common/jsonAddressDecoder.h b/DRAMSys/library/src/common/jsonAddressDecoder.h new file mode 100644 index 00000000..bc5eb8df --- /dev/null +++ b/DRAMSys/library/src/common/jsonAddressDecoder.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2018, University of Kaiserslautern + * All rights reserved. + * + * 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. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER + * OR CONTRIBUTORS 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. + * + * Authors: + * Johannes Feldmann + */ + +#ifndef JSONADDRESSDECODER_H +#define JSONADDRESSDECODER_H + +#include "AddressDecoder.h" + +class JSONAddressDecoder + : public CAddressDecoder +{ + friend class CAddressDecoder; + +private: + JSONAddressDecoder(); + +public: + virtual void setConfiguration(std::string url); + + virtual DecodedAddress decodeAddress(sc_dt::uint64 addr); + virtual sc_dt::uint64 encodeAddress(DecodedAddress n); + + virtual void print(); +}; + +#endif // JSONADDRESSDECODER_H diff --git a/DRAMSys/library/src/common/xmlAddressdecoder.cpp b/DRAMSys/library/src/common/xmlAddressdecoder.cpp index 31304f1d..639631fa 100644 --- a/DRAMSys/library/src/common/xmlAddressdecoder.cpp +++ b/DRAMSys/library/src/common/xmlAddressdecoder.cpp @@ -49,26 +49,11 @@ xmlAddressDecoder::xmlAddressDecoder() addressmapping = NULL; } -xmlAddressDecoder::xmlAddressDecoder(string addressConfigURI) -{ - setConfiguration(addressConfigURI); -} - -xmlAddressDecoder::xmlAddressDecoder(XMLElement* addressmap) -{ - setConfiguration(addressmap); -} - void xmlAddressDecoder::setConfiguration(std::string addressConfigURI) { tinyxml2::XMLDocument doc; loadXML(addressConfigURI, doc); - setConfiguration(doc.RootElement()); -} - -void xmlAddressDecoder::setConfiguration(tinyxml2::XMLElement* addressMap) -{ - tinyxml2::XMLDocument doc; + tinyxml2::XMLElement* addressMap = doc.RootElement(); string xmlNodeName(addressMap->Name()); if( xmlNodeName != "addressmapping") diff --git a/DRAMSys/library/src/common/xmlAddressdecoder.h b/DRAMSys/library/src/common/xmlAddressdecoder.h index 0e9094fb..ed300670 100644 --- a/DRAMSys/library/src/common/xmlAddressdecoder.h +++ b/DRAMSys/library/src/common/xmlAddressdecoder.h @@ -38,45 +38,20 @@ #ifndef _XMLADDRESSDECODER_H #define _XMLADDRESSDECODER_H -#include -#include -#include -#include #include -#include #include "Utils.h" #include "third_party/tinyxml2/tinyxml2.h" - -struct DecodedAddress -{ - DecodedAddress() : channel(0), - rank(0), - bankgroup(0), - row(0), - bank(0), - column(0), - bytes(0) - { - } - - unsigned int channel; - unsigned int rank; - unsigned int bankgroup; - unsigned int row; - unsigned int bank; - unsigned int column; - unsigned int bytes; -}; +#include "AddressDecoder.h" class xmlAddressDecoder + : public CAddressDecoder { + friend class CAddressDecoder; - private: +private: xmlAddressDecoder(); - xmlAddressDecoder(std::string URI); - xmlAddressDecoder(tinyxml2::XMLElement* addressMap); std::map masks; std::map shifts; @@ -84,13 +59,13 @@ class xmlAddressDecoder tinyxml2::XMLElement* addressmapping; public: - DEF_SINGLETON(xmlAddressDecoder); - DecodedAddress decodeAddress(sc_dt::uint64 addr); sc_dt::uint64 encodeAddress(DecodedAddress n); void setConfiguration(std::string url); +private: void setConfiguration(tinyxml2::XMLElement* addressMap); +public: void print(); std::map amount; diff --git a/DRAMSys/library/src/controller/core/configuration/Configuration.cpp b/DRAMSys/library/src/controller/core/configuration/Configuration.cpp index 93a1d523..29cc6f94 100644 --- a/DRAMSys/library/src/controller/core/configuration/Configuration.cpp +++ b/DRAMSys/library/src/controller/core/configuration/Configuration.cpp @@ -191,7 +191,7 @@ void Configuration::setParameter(std::string name, std::string value) Debug = string2bool(value); else if (name == "NumberOfMemChannels") { NumberOfMemChannels = string2int(value); - unsigned int maxNumberofMemChannels = xmlAddressDecoder::getInstance().amount["channel"]; + unsigned int maxNumberofMemChannels = CAddressDecoder::getInstance().amount["channel"]; if (NumberOfMemChannels > maxNumberofMemChannels) { SC_REPORT_FATAL("Configuration", ("Invalid value for parameter " + name @@ -349,7 +349,7 @@ unsigned int Configuration::getBytesPerBurst() // The least significant bits of the physical address are the byte // offset of the N-byte-wide memory module (DIMM) (a single data word // or burst element has N bytes. N = 2^(# bits for byte offset)). - unsigned int burstElementSizeInBytes = xmlAddressDecoder::getInstance().amount["bytes"]; + unsigned int burstElementSizeInBytes = CAddressDecoder::getInstance().amount["bytes"]; assert(bytesPerBurst == (burstElementSizeInBytes * memSpec.BurstLength)); } diff --git a/DRAMSys/library/src/error/errormodel.cpp b/DRAMSys/library/src/error/errormodel.cpp index e1010f6a..18966452 100644 --- a/DRAMSys/library/src/error/errormodel.cpp +++ b/DRAMSys/library/src/error/errormodel.cpp @@ -48,7 +48,7 @@ void errorModel::init() // Get Configuration parameters: burstLenght = Configuration::getInstance().memSpec.BurstLength; numberOfColumns = Configuration::getInstance().memSpec.NumberOfColumns; - bytesPerColumn = xmlAddressDecoder::getInstance().amount["bytes"]; + bytesPerColumn = CAddressDecoder::getInstance().amount["bytes"]; // Adjust number of bytes per column dynamically to the selected ecc controller bytesPerColumn = Configuration::getInstance().adjustNumBytesAfterECC(bytesPerColumn); @@ -157,7 +157,7 @@ void errorModel::store(tlm::tlm_generic_payload &trans) markBitFlips(); // Get the key for the dataMap from the transaction's address: - DecodedAddress key = xmlAddressDecoder::getInstance().decodeAddress(trans.get_address()); + DecodedAddress key = CAddressDecoder::getInstance().decodeAddress(trans.get_address()); // Set context: setContext(key); @@ -225,7 +225,7 @@ void errorModel::load(tlm::tlm_generic_payload &trans) markBitFlips(); // Get the key for the dataMap from the transaction's address: - DecodedAddress key = xmlAddressDecoder::getInstance().decodeAddress(trans.get_address()); + DecodedAddress key = CAddressDecoder::getInstance().decodeAddress(trans.get_address()); // Set context: setContext(key); diff --git a/DRAMSys/library/src/error/errormodel.h b/DRAMSys/library/src/error/errormodel.h index d85027c5..d3914c6c 100644 --- a/DRAMSys/library/src/error/errormodel.h +++ b/DRAMSys/library/src/error/errormodel.h @@ -120,8 +120,8 @@ class errorModel : public sc_module { bool operator()( const DecodedAddress& first , const DecodedAddress& second) const { - sc_dt::uint64 addrFirst = xmlAddressDecoder::getInstance().encodeAddress(first); - sc_dt::uint64 addrSecond = xmlAddressDecoder::getInstance().encodeAddress(second); + sc_dt::uint64 addrFirst = CAddressDecoder::getInstance().encodeAddress(first); + sc_dt::uint64 addrSecond = CAddressDecoder::getInstance().encodeAddress(second); return addrFirst < addrSecond; } }; diff --git a/DRAMSys/library/src/simulation/Arbiter.h b/DRAMSys/library/src/simulation/Arbiter.h index 114e3d03..5b60b410 100644 --- a/DRAMSys/library/src/simulation/Arbiter.h +++ b/DRAMSys/library/src/simulation/Arbiter.h @@ -151,7 +151,7 @@ private: // adjust address offset: trans.set_address(trans.get_address() - Configuration::getInstance().AddressOffset); - DecodedAddress decodedAddress = xmlAddressDecoder::getInstance().decodeAddress(trans.get_address()); + DecodedAddress decodedAddress = CAddressDecoder::getInstance().decodeAddress(trans.get_address()); return iSocket[decodedAddress.channel]->transport_dbg(trans); } @@ -248,7 +248,7 @@ private: payload.set_auto_extension(genExtension); unsigned int burstlength = payload.get_streaming_width(); - DecodedAddress decodedAddress = xmlAddressDecoder::getInstance().decodeAddress(payload.get_address()); + DecodedAddress decodedAddress = CAddressDecoder::getInstance().decodeAddress(payload.get_address()); // Check the valid range of decodedAddress if (addressIsValid(decodedAddress)) { DramExtension* extension = new DramExtension(Thread(socketId+1), Channel(decodedAddress.channel), Bank(decodedAddress.bank), BankGroup(decodedAddress.bankgroup), Row(decodedAddress.row), Column(decodedAddress.column),burstlength); @@ -260,19 +260,19 @@ private: bool addressIsValid(DecodedAddress& decodedAddress) { - if (decodedAddress.channel >= xmlAddressDecoder::getInstance().amount["channel"]) { + if (decodedAddress.channel >= CAddressDecoder::getInstance().amount["channel"]) { return false; } - if (decodedAddress.bank >= xmlAddressDecoder::getInstance().amount["bank"]) { + if (decodedAddress.bank >= CAddressDecoder::getInstance().amount["bank"]) { return false; } - if (decodedAddress.bankgroup > xmlAddressDecoder::getInstance().amount["bankgroup"]) { + if (decodedAddress.bankgroup > CAddressDecoder::getInstance().amount["bankgroup"]) { return false; } - if (decodedAddress.column >= xmlAddressDecoder::getInstance().amount["column"]) { + if (decodedAddress.column >= CAddressDecoder::getInstance().amount["column"]) { return false; } - if (decodedAddress.row >= xmlAddressDecoder::getInstance().amount["row"]) { + if (decodedAddress.row >= CAddressDecoder::getInstance().amount["row"]) { return false; } return true; diff --git a/DRAMSys/library/src/simulation/DRAMSys.cpp b/DRAMSys/library/src/simulation/DRAMSys.cpp index ea544ee4..403435d4 100644 --- a/DRAMSys/library/src/simulation/DRAMSys.cpp +++ b/DRAMSys/library/src/simulation/DRAMSys.cpp @@ -83,10 +83,25 @@ DRAMSys::DRAMSys(sc_module_name __attribute__((unused)) name, // The xmlAddressDecoder MUST be initialized before calling the // ConfigurationLoader because some information from the xmlAddressDecoder // is needed to assure the coherence of the configuration. - xmlAddressDecoder::getInstance().setConfiguration(pathToResources - + "configs/amconfigs/" - + amconfig); - xmlAddressDecoder::getInstance().print(); + + if(amconfig.find(".xml") != string::npos) + { + CAddressDecoder::createInstance(CAddressDecoder::Type::XML); + CAddressDecoder::getInstance().setConfiguration(pathToResources + + "configs/amconfigs/" + + amconfig); + } + else if(amconfig.find(".json") != string::npos) + { + CAddressDecoder::createInstance(CAddressDecoder::Type::JSON); + CAddressDecoder::getInstance().setConfiguration(pathToResources + amconfig); + } + else + { + cout << "No address mapping loaded. Unknown file extension" << endl; + } + + CAddressDecoder::getInstance().print(); ConfigurationLoader::loadMemSpec(Configuration::getInstance(), pathToResources From 13baae168ba58e7c84441bf2aecdb45736783353 Mon Sep 17 00:00:00 2001 From: Johannes Feldmann Date: Tue, 27 Mar 2018 10:10:50 +0200 Subject: [PATCH 02/38] Third party module for json added. --- .gitmodules | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitmodules b/.gitmodules index 82647b71..60369680 100644 --- a/.gitmodules +++ b/.gitmodules @@ -5,3 +5,6 @@ path = DRAMSys/library/src/common/third_party/DRAMPower url = https://github.com/tukl-msd/DRAMPower.git branch = master +[submodule "DRAMSys/library/src/common/third_party/json"] + path = DRAMSys/library/src/common/third_party/json + url = https://github.com/nlohmann/json.git From 3be950e70467228435a54033f7b5ef6b3794f0b1 Mon Sep 17 00:00:00 2001 From: Johannes Feldmann Date: Tue, 27 Mar 2018 10:17:29 +0200 Subject: [PATCH 03/38] Added missing breaks in switch cases. --- DRAMSys/library/src/common/AddressDecoder.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DRAMSys/library/src/common/AddressDecoder.cpp b/DRAMSys/library/src/common/AddressDecoder.cpp index a473b442..938129c8 100644 --- a/DRAMSys/library/src/common/AddressDecoder.cpp +++ b/DRAMSys/library/src/common/AddressDecoder.cpp @@ -17,8 +17,10 @@ void CAddressDecoder::createInstance(Type t) { case Type::XML: m_pInstance = new xmlAddressDecoder; + break; case Type::JSON: m_pInstance = new JSONAddressDecoder; + break; } } From fd80bcabb3ba7e6380d80ec96a72cccbbd13960c Mon Sep 17 00:00:00 2001 From: Johannes Feldmann Date: Tue, 27 Mar 2018 10:36:09 +0200 Subject: [PATCH 04/38] Output file of ConGen added for test purposes. --- .../amconfigs/am_test_congen_output.json | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 DRAMSys/library/resources/configs/amconfigs/am_test_congen_output.json diff --git a/DRAMSys/library/resources/configs/amconfigs/am_test_congen_output.json b/DRAMSys/library/resources/configs/amconfigs/am_test_congen_output.json new file mode 100644 index 00000000..74d8c492 --- /dev/null +++ b/DRAMSys/library/resources/configs/amconfigs/am_test_congen_output.json @@ -0,0 +1,44 @@ +{ + "Config": { + "numberOfBankBits": 3, + "numberOfRowBits": 14, + "numberOfColumnBits": 10, + "numberOfByteBits": 3, + "numberOfBLBits": 3 + }, + "Name": "merged_sorted", + "Solutions": [ + { + "XOR": [], + "Banks Rows": [ + { + "bank_bits": [ + 18, + 12, + 11 + ], + "rows": { + "row_bits": [ + 24, + 13, + 17, + 14, + 15, + 16, + 25, + 19, + 21, + 20, + 26, + 23, + 29, + 28 + ], + "costs": 477468 + }, + "costs": 477468 + } + ] + } + ] +} \ No newline at end of file From ef9d09662e91fc3eaf9b05ae60d02ea771fbfd52 Mon Sep 17 00:00:00 2001 From: Johannes Feldmann Date: Tue, 27 Mar 2018 14:56:26 +0200 Subject: [PATCH 05/38] Functionality for JSONAddressDecoder added. Fixed several smaller bugs. --- DRAMSys/library/library.pro | 4 +- .../amconfigs/am_test_congen_output.json | 25 +-- DRAMSys/library/resources/resources.pri | 3 +- .../library/src/common/jsonAddressDecoder.cpp | 162 +++++++++++++++++- .../library/src/common/jsonAddressDecoder.h | 12 ++ .../library/src/common/xmlAddressdecoder.h | 12 +- DRAMSys/library/src/simulation/DRAMSys.cpp | 4 +- 7 files changed, 198 insertions(+), 24 deletions(-) diff --git a/DRAMSys/library/library.pro b/DRAMSys/library/library.pro index 20a1eb2d..df48ed98 100644 --- a/DRAMSys/library/library.pro +++ b/DRAMSys/library/library.pro @@ -51,6 +51,7 @@ INCLUDEPATH += $${systemc_home}/include INCLUDEPATH += src/common/third_party/DRAMPower/src INCLUDEPATH += src/common/third_party/DRAMPower/src/libdrampower +INCLUDEPATH += src/common/third_party/json/include DEFINES += TIXML_USE_STL DEFINES += SC_INCLUDE_DYNAMIC_PROCESSES @@ -194,7 +195,8 @@ HEADERS += \ src/controller/scheduler/Fr_Fcfs_read_priority.h \ src/controller/scheduler/Fr_Fcfs_grouper.h \ src/common/AddressDecoder.h \ - src/common/jsonAddressDecoder.h + src/common/jsonAddressDecoder.h \ + src/common/third_party/json/include/nlohmann/json.hpp thermalsim = $$(THERMALSIM) isEmpty(thermalsim) { diff --git a/DRAMSys/library/resources/configs/amconfigs/am_test_congen_output.json b/DRAMSys/library/resources/configs/amconfigs/am_test_congen_output.json index 74d8c492..3aca28c7 100644 --- a/DRAMSys/library/resources/configs/amconfigs/am_test_congen_output.json +++ b/DRAMSys/library/resources/configs/amconfigs/am_test_congen_output.json @@ -9,30 +9,31 @@ "Name": "merged_sorted", "Solutions": [ { - "XOR": [], + "XOR": [ + ], "Banks Rows": [ { "bank_bits": [ - 18, - 12, - 11 + 27, + 28, + 29 ], "rows": { "row_bits": [ - 24, 13, - 17, 14, 15, 16, - 25, + 17, + 18, 19, - 21, 20, - 26, + 21, + 22, 23, - 29, - 28 + 24, + 25, + 26 ], "costs": 477468 }, @@ -41,4 +42,4 @@ ] } ] -} \ No newline at end of file +} diff --git a/DRAMSys/library/resources/resources.pri b/DRAMSys/library/resources/resources.pri index cd77f0c8..cb6615b2 100644 --- a/DRAMSys/library/resources/resources.pri +++ b/DRAMSys/library/resources/resources.pri @@ -172,4 +172,5 @@ DISTFILES += \ $$PWD/configs/simulator/lpddr4.xml \ $$PWD/simulations/lpddr4-single-device.xml \ $$PWD/configs/amconfigs/am_lpddr4.xml \ - $$PWD/configs/memspecs/MICRON_6Gb_LPDDR4-3200_NDA_NDA_NDA.xml + $$PWD/configs/memspecs/MICRON_6Gb_LPDDR4-3200_NDA_NDA_NDA.xml \ + $$PWD/configs/amconfigs/am_test_congen_output.json diff --git a/DRAMSys/library/src/common/jsonAddressDecoder.cpp b/DRAMSys/library/src/common/jsonAddressDecoder.cpp index d82f41bf..dd9c8b62 100644 --- a/DRAMSys/library/src/common/jsonAddressDecoder.cpp +++ b/DRAMSys/library/src/common/jsonAddressDecoder.cpp @@ -1,4 +1,5 @@ #include "jsonAddressDecoder.h" +#include "Utils.h" #include @@ -6,6 +7,14 @@ using std::ifstream; using std::cout; using std::endl; +#include + +using json = nlohmann::json; + +#include + +using std::set; + JSONAddressDecoder::JSONAddressDecoder() { @@ -23,22 +32,173 @@ void JSONAddressDecoder::setConfiguration(std::string url) return; } + // parse json file + json data; + file >> data; + file.close(); + + // extract data + // For simplicity takethe first solution of one or more available ones. + auto sol = data["Solutions"].begin(); + assert(sol != data["Solutions"].end()); + + // Set for connected bits + set sUsed; + + // get XOR connections + unsigned num = (*sol)["XOR"].size()>>1; + + for(unsigned i = 0; i < num; i++) + { + m_vXor.push_back(pair ((*sol)["XOR"].at(i), (*sol)["XOR"].at(i+num))); + } + + // get all bank bits + unsigned counter = 0; + for(auto it = (*sol)["Banks Rows"][0]["bank_bits"].begin(); it != (*sol)["Banks Rows"][0]["bank_bits"].end(); it++) + { + m_vBankBits.push_back(pair(counter++, (*it))); + sUsed.insert((unsigned)(*it)); + } + + // get all row bits bits + counter = 0; + for(auto it = (*sol)["Banks Rows"][0]["rows"]["row_bits"].begin(); it != (*sol)["Banks Rows"][0]["rows"]["row_bits"].end(); it++) + { + m_vRowBits.push_back(pair(counter++, (*it))); + sUsed.insert((unsigned)(*it)); + } + + // Add byte bits (fixed) + sUsed.insert(0); + sUsed.insert(1); + sUsed.insert(2); + + // Theset bits are ignored + sUsed.insert(30); + sUsed.insert(31); + + // Create Column mapping + counter = 0; + for(unsigned i = 0; i < 32; i++) + { + if(sUsed.find(i) != sUsed.end()) + continue; // Already mapped + + m_vColumnBits.push_back(pair(counter++, i)); + } + + amount["channel"] = 1; + amount["bank"] = pow(2.0, m_vBankBits.size()); + amount["row"] = pow(2.0, m_vRowBits.size()); + amount["column"] = pow(2.0, m_vColumnBits.size()); + amount["bytes"] = pow(2.0, 3); } DecodedAddress JSONAddressDecoder::decodeAddress(sc_dt::uint64 addr) { DecodedAddress result; + // Apply XOR + for(auto it = m_vXor.begin(); it != m_vXor.end(); it++) + { + addr &= ~(1 << it->first); + addr |= (((addr >> it->first) & 1) ^ ((addr >> it->second) & 1)) << it->first; + } + + // Unsed + result.bankgroup = 0; + result.channel = 0; + result.rank = 0; + + // Pass through of the three byte bits + result.bytes = addr & 0x7; + + // Bank + result.bank = 0; + for(auto it = m_vBankBits.begin(); it != m_vBankBits.end(); it++) + { + result.bank |= ((addr >> it->second) & 1) << it->first; + } + + // Row + result.row = 0; + for(auto it = m_vRowBits.begin(); it != m_vRowBits.end(); it++) + { + result.row |= ((addr >> it->second) & 1) << it->first; + } + + // Column + result.column = 0; + for(auto it = m_vColumnBits.begin(); it != m_vColumnBits.end(); it++) + { + result.column |= ((addr >> it->second) & 1) << it->first; + } + return result; } sc_dt::uint64 JSONAddressDecoder::encodeAddress(DecodedAddress n) { - return 0; + sc_dt::uint64 address = 0; + for(auto it = m_vBankBits.begin(); it != m_vBankBits.end(); it++) + { + address |= ((n.bank >> it->first) & 1) << it->second; + } + for(auto it = m_vRowBits.begin(); it != m_vRowBits.end(); it++) + { + address |= ((n.row >> it->first) & 1) << it->second; + } + for(auto it = m_vColumnBits.begin(); it != m_vColumnBits.end(); it++) + { + address |= ((n.column >> it->first) & 1) << it->second; + } + + address |= n.bytes; + + // Apply XOR + for(auto it = m_vXor.begin(); it != m_vXor.end(); it++) + { + address &= ~(1 << it->first); + address |= (((address >> it->first) & 1) ^ ((address >> it->second) & 1)) << it->first; + } + + return address; } void JSONAddressDecoder::print() { + map> output; + for(auto it = m_vBankBits.begin(); it != m_vBankBits.end(); it++) + { + output[it->second] = pair(it->first , 'B'); + } + for(auto it = m_vRowBits.begin(); it != m_vRowBits.end(); it++) + { + output[it->second] = pair(it->first , 'R'); + } + for(auto it = m_vColumnBits.begin(); it != m_vColumnBits.end(); it++) + { + output[it->second] = pair(it->first , 'C'); + } + + // add byte bits + output[0] = pair(0 , 'b'); + output[1] = pair(1 , 'b'); + output[2] = pair(2 , 'b'); + + cout << "Used addressmapping:" << endl; + cout << headline << endl; + for(unsigned i = 0; i < 32; i++) + { + cout << " " << i << " "; + } + cout << endl; + for(unsigned i = 0; i < 32; i++) + { + cout << " " << output[i].second << "(" << output[i].first << ") "; + } + cout << endl; } diff --git a/DRAMSys/library/src/common/jsonAddressDecoder.h b/DRAMSys/library/src/common/jsonAddressDecoder.h index bc5eb8df..354b7513 100644 --- a/DRAMSys/library/src/common/jsonAddressDecoder.h +++ b/DRAMSys/library/src/common/jsonAddressDecoder.h @@ -38,6 +38,13 @@ #include "AddressDecoder.h" +#include +#include + +using std::vector; +using std::pair; +using std::map; + class JSONAddressDecoder : public CAddressDecoder { @@ -46,6 +53,11 @@ class JSONAddressDecoder private: JSONAddressDecoder(); + vector> m_vXor; + vector> m_vBankBits; + vector> m_vRowBits; + vector> m_vColumnBits; + public: virtual void setConfiguration(std::string url); diff --git a/DRAMSys/library/src/common/xmlAddressdecoder.h b/DRAMSys/library/src/common/xmlAddressdecoder.h index ed300670..03ade6c5 100644 --- a/DRAMSys/library/src/common/xmlAddressdecoder.h +++ b/DRAMSys/library/src/common/xmlAddressdecoder.h @@ -50,7 +50,6 @@ class xmlAddressDecoder friend class CAddressDecoder; private: - xmlAddressDecoder(); std::map masks; @@ -59,16 +58,13 @@ private: tinyxml2::XMLElement* addressmapping; public: - DecodedAddress decodeAddress(sc_dt::uint64 addr); - sc_dt::uint64 encodeAddress(DecodedAddress n); + virtual DecodedAddress decodeAddress(sc_dt::uint64 addr); + virtual sc_dt::uint64 encodeAddress(DecodedAddress n); void setConfiguration(std::string url); -private: - void setConfiguration(tinyxml2::XMLElement* addressMap); -public: - void print(); - std::map amount; +public: + virtual void print(); }; #endif diff --git a/DRAMSys/library/src/simulation/DRAMSys.cpp b/DRAMSys/library/src/simulation/DRAMSys.cpp index 403435d4..245b4aca 100644 --- a/DRAMSys/library/src/simulation/DRAMSys.cpp +++ b/DRAMSys/library/src/simulation/DRAMSys.cpp @@ -94,7 +94,9 @@ DRAMSys::DRAMSys(sc_module_name __attribute__((unused)) name, else if(amconfig.find(".json") != string::npos) { CAddressDecoder::createInstance(CAddressDecoder::Type::JSON); - CAddressDecoder::getInstance().setConfiguration(pathToResources + amconfig); + CAddressDecoder::getInstance().setConfiguration(pathToResources + + "configs/amconfigs/" + + amconfig); } else { From 22b766a04da932a1d025827af6993a8f9a5ef32b Mon Sep 17 00:00:00 2001 From: Johannes Feldmann Date: Tue, 27 Mar 2018 16:15:33 +0200 Subject: [PATCH 06/38] Added more comments. Simulator will throw an exception if no proper address mapping could be loaded. --- .../library/src/common/jsonAddressDecoder.cpp | 49 +++++++++++++++++-- .../library/src/common/jsonAddressDecoder.h | 9 ++-- DRAMSys/library/src/simulation/DRAMSys.cpp | 3 +- 3 files changed, 51 insertions(+), 10 deletions(-) diff --git a/DRAMSys/library/src/common/jsonAddressDecoder.cpp b/DRAMSys/library/src/common/jsonAddressDecoder.cpp index dd9c8b62..ad828f02 100644 --- a/DRAMSys/library/src/common/jsonAddressDecoder.cpp +++ b/DRAMSys/library/src/common/jsonAddressDecoder.cpp @@ -39,22 +39,24 @@ void JSONAddressDecoder::setConfiguration(std::string url) file.close(); // extract data - // For simplicity takethe first solution of one or more available ones. + // For simplicity take the first solution of one or more available ones. auto sol = data["Solutions"].begin(); assert(sol != data["Solutions"].end()); - // Set for connected bits + // Set for connected bits. Used to find the remaining bits, which are not part of the json file = column bits. set sUsed; // get XOR connections + // An XOR connection needs two parameters: A bank bit and a Row bit. + // These parameters are all stored in one array with the following pattern: bank0, bank1, ..., row0, row1, ... unsigned num = (*sol)["XOR"].size()>>1; - for(unsigned i = 0; i < num; i++) { m_vXor.push_back(pair ((*sol)["XOR"].at(i), (*sol)["XOR"].at(i+num))); } // get all bank bits + // Each bank bit of the address will be stored with a counter value which assigns the bit position DecodedAddress struct. unsigned counter = 0; for(auto it = (*sol)["Banks Rows"][0]["bank_bits"].begin(); it != (*sol)["Banks Rows"][0]["bank_bits"].end(); it++) { @@ -63,6 +65,7 @@ void JSONAddressDecoder::setConfiguration(std::string url) } // get all row bits bits + // Each Row bit of the address will be stored with a counter value which assigns the bit position DecodedAddress struct. counter = 0; for(auto it = (*sol)["Banks Rows"][0]["rows"]["row_bits"].begin(); it != (*sol)["Banks Rows"][0]["rows"]["row_bits"].end(); it++) { @@ -80,6 +83,8 @@ void JSONAddressDecoder::setConfiguration(std::string url) sUsed.insert(31); // Create Column mapping + // These bits are not stored in the JSON file, but can be generated. All bits, which are until now not used for any other purpose are column bits. + // Each column bit of the address will be stored with a counter value which assigns the bit position DecodedAddress struct. counter = 0; for(unsigned i = 0; i < 32; i++) { @@ -89,6 +94,7 @@ void JSONAddressDecoder::setConfiguration(std::string url) m_vColumnBits.push_back(pair(counter++, i)); } + // Fill the amount map. This is copied from xmlAddressDecoder without further investigation amount["channel"] = 1; amount["bank"] = pow(2.0, m_vBankBits.size()); amount["row"] = pow(2.0, m_vRowBits.size()); @@ -101,6 +107,8 @@ DecodedAddress JSONAddressDecoder::decodeAddress(sc_dt::uint64 addr) DecodedAddress result; // Apply XOR + // For each used xor: + // Get the bank bit and row bit. Apply a bitwise xor operator and save it back to the bank bit. for(auto it = m_vXor.begin(); it != m_vXor.end(); it++) { addr &= ~(1 << it->first); @@ -116,6 +124,10 @@ DecodedAddress JSONAddressDecoder::decodeAddress(sc_dt::uint64 addr) result.bytes = addr & 0x7; // Bank + // it->second: position of the target bit in the address + // it->first: target position of the bit in the variable + // For each bank bit: + // shift address bit to position 0. Clear all other bits. shift it the right bank bit. Add it to the set of bank bits. result.bank = 0; for(auto it = m_vBankBits.begin(); it != m_vBankBits.end(); it++) { @@ -123,6 +135,10 @@ DecodedAddress JSONAddressDecoder::decodeAddress(sc_dt::uint64 addr) } // Row + // it->second: position of the target bit in the address + // it->first: target position of the bit in the variable + // For each row bit: + // shift address bit to position 0. Clear all other bits. shift it the right row bit. Add it to the set of row bits. result.row = 0; for(auto it = m_vRowBits.begin(); it != m_vRowBits.end(); it++) { @@ -130,6 +146,10 @@ DecodedAddress JSONAddressDecoder::decodeAddress(sc_dt::uint64 addr) } // Column + // it->second: position of the target bit in the address + // it->first: target position of the bit in the variable + // For each column bit: + // shift address bit to position 0. Clear all other bits. shift it the right column bit. Add it to the set of column bits. result.column = 0; for(auto it = m_vColumnBits.begin(); it != m_vColumnBits.end(); it++) { @@ -142,23 +162,42 @@ DecodedAddress JSONAddressDecoder::decodeAddress(sc_dt::uint64 addr) sc_dt::uint64 JSONAddressDecoder::encodeAddress(DecodedAddress n) { sc_dt::uint64 address = 0; - for(auto it = m_vBankBits.begin(); it != m_vBankBits.end(); it++) + + // Bank + // it->first: position of the target bit in the DecodedAddress struct field + // it->second: target position of the bit in the address + // For each bank bit: + // shift bank bit to position 0. Clear all other bits. shift it the right address bit. Add it to the set of address bits. + for(auto it = m_vBankBits.begin(); it != m_vBankBits.end(); it++) { address |= ((n.bank >> it->first) & 1) << it->second; } + // Row + // it->first: position of the target bit in the DecodedAddress struct field + // it->second: target position of the bit in the address + // For each row bit: + // shift row bit to position 0. Clear all other bits. shift it the right address bit. Add it to the set of address bits. for(auto it = m_vRowBits.begin(); it != m_vRowBits.end(); it++) { address |= ((n.row >> it->first) & 1) << it->second; } + // Column + // it->first: position of the target bit in the DecodedAddress struct field + // it->second: target position of the bit in the address + // For each column bit: + // shift column bit to position 0. Clear all other bits. shift it the right address bit. Add it to the set of address bits. for(auto it = m_vColumnBits.begin(); it != m_vColumnBits.end(); it++) { address |= ((n.column >> it->first) & 1) << it->second; } + // Add the unchanged byte bits address |= n.bytes; // Apply XOR - for(auto it = m_vXor.begin(); it != m_vXor.end(); it++) + // For each used xor: + // Get the bank bit and row bit. Apply a bitwise xor operator and save it back to the bank bit. + for(auto it = m_vXor.begin(); it != m_vXor.end(); it++) { address &= ~(1 << it->first); address |= (((address >> it->first) & 1) ^ ((address >> it->second) & 1)) << it->first; diff --git a/DRAMSys/library/src/common/jsonAddressDecoder.h b/DRAMSys/library/src/common/jsonAddressDecoder.h index 354b7513..843db6fc 100644 --- a/DRAMSys/library/src/common/jsonAddressDecoder.h +++ b/DRAMSys/library/src/common/jsonAddressDecoder.h @@ -53,10 +53,11 @@ class JSONAddressDecoder private: JSONAddressDecoder(); - vector> m_vXor; - vector> m_vBankBits; - vector> m_vRowBits; - vector> m_vColumnBits; + vector> m_vXor; // This container stores for each used xor gate a pair which consists of "First/Number of an address bit which corresponds to a bank" + // and "Second/Number of an address bit which corresponds to a row" + vector> m_vBankBits; // This container stores for each bank bit a pair which consists of "First/Number of the bank bit" and "Second/Number of the address bit" + vector> m_vRowBits; // This container stores for each row bit a pair which consists of "First/Number of the row bit" and "Second/Number of the address bit" + vector> m_vColumnBits; // This container stores for each column bit a pair which consists of "First/Number of the column bit" and "Second/Number of the address bit" public: virtual void setConfiguration(std::string url); diff --git a/DRAMSys/library/src/simulation/DRAMSys.cpp b/DRAMSys/library/src/simulation/DRAMSys.cpp index 245b4aca..0b2db6fc 100644 --- a/DRAMSys/library/src/simulation/DRAMSys.cpp +++ b/DRAMSys/library/src/simulation/DRAMSys.cpp @@ -40,6 +40,7 @@ #include #include #include +#include #include "DRAMSys.h" #include "Setup.h" @@ -100,7 +101,7 @@ DRAMSys::DRAMSys(sc_module_name __attribute__((unused)) name, } else { - cout << "No address mapping loaded. Unknown file extension" << endl; + throw std::runtime_error("No address mapping loaded. Unknown file extension"); } CAddressDecoder::getInstance().print(); From 9ed217c01d12edc75f141b96c69a93a497a8d110 Mon Sep 17 00:00:00 2001 From: Johannes Feldmann Date: Fri, 30 Mar 2018 16:47:43 +0200 Subject: [PATCH 07/38] Created a section for address decoding with json files. --- README.md | 123 ++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 96 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index e16a7dde..7cbda275 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Configure git on your machine. Some basic configurations follow. Replace $ git config --global user.name "FirstName OtherNames LastName" $ git config --global user.email rhrkuser@rhrk.uni-kl.de $ git config --global credential.helper ’cache --timeout=3600’ -$ git config --global color.ui auto +$ git config --global color.ui auto ``` Login using your **git.rhrk** account. Fork the repository by clicking in @@ -239,17 +239,17 @@ ln -s lib/ lib-macosx64 $ brew install python3 ``` -Python3 (via homebrew) will be installed in +Python3 (via homebrew) will be installed in ``` /usr/local/Cellar/python3/3.5.2_2/Frameworks/Python.framework ``` or you can install manually using official package provided in [link](https://www.python.org/downloads/) -**Note:** Official Python Package will be installed in +**Note:** Official Python Package will be installed in ``` /Library/Frameworks/Python.framework -``` +``` - Install the QtCreator using offical setup file from [link](https://www.qt.io/download-open-source/#section-2) @@ -292,7 +292,7 @@ export LIBQWT_HEADERS=/opt/qwt-6.1.4/lib/qwt.framework/Headers - For the trace analyzer the file: ``` -/opt/local/Library/Frameworks/Python.framework/Versions/3.5/include/python3.4m/pyport.h +/opt/local/Library/Frameworks/Python.framework/Versions/3.5/include/python3.4m/pyport.h ``` has to be changed like [this](https://trac.macports.org/attachment/ticket/44288/issue10910-workaround.txt) @@ -431,13 +431,13 @@ Below, the sub-configurations are listed and explained. - "1": enables thermal simulation - "0": static temperature during simulation - *SimulationProgressBar* (boolean) - - "1": enables the simulation progress bar + - "1": enables the simulation progress bar - "0": disables the simulation progress bar - *NumberOfDevicesOnDIMM* (unsigned int) - Number of devices on dual inline memory module - *CheckTLM2Protocol* (boolean) - - "1": enables the TLM 2.0 Protocol Checking - - "0": disables the TLM 2.0 Protocol Checking + - "1": enables the TLM 2.0 Protocol Checking + - "0": disables the TLM 2.0 Protocol Checking - *ECCControllerMode* (string) - "Disabled": No ECC Controller is used - "Hamming": Enables an ECC Controller with classic SECDED implementation using Hamming Code @@ -503,6 +503,10 @@ Below, the sub-configurations are listed and explained. - **Address Mapping** + There are currently two different file formats to describe the address mapping. This software automatically chooses the correct interpreter using the file extension as selection criterion. So please make sure that all files have the correct extension. + +- **XML file format** + XML files describe the address mapping to be used in the simulation. Example for 1GB x64 DIMM with: 8 x 1 Gbit x8 Devices (Micron MT41J128M8) with Page Size: 1KB @@ -510,23 +514,23 @@ Below, the sub-configurations are listed and explained. [am_ddr3_8x1Gbx8_dimm_p1KB_brc.xml](DRAMSys/library/resources/configs/amconfigs/am_ddr3_8x1Gbx8_dimm_p1KB_brc.xml) ``` xml - - + @@ -537,18 +541,18 @@ Below, the sub-configurations are listed and explained. ``` Some more examples with graphical representation follow: - + [am_wideio.xml](DRAMSys/library/resources/configs/amconfigs/am_wideio.xml) ``` xml - + - + ``` @@ -568,6 +572,71 @@ Below, the sub-configurations are listed and explained. ![Address Mapping Sample 2](DRAMSys/docs/images/am_wideio_brc.png) +- **JSON file format** + + This file format is generated by ConGen. It does not have an unambiguous assignment of the address lines. + + The format delivers more information than needed for an address mapping. + Unused data: + - Block "Config": Gives you information about the ConGen configuration + - Key "Name": Name of the trace file which was used by ConGen + - All items of the array "Solutions" but the first one: Alternative solution with same result. + - Key "costs": Number of row misses which this configuration produces while playing the trace. + + Used data: + - First item of array "Solution": + - "XOR": Array of row and bank bits which are connected with an xor. Order of the bit: bank1, bank2, ..., row1, row2, ... + - "bank_bits": Number of the addres bits which are connected to a bank bit + - "row_bits": Number of the addres bits which are connected to a row bit + + ```json + { + "Config": { + "numberOfBankBits": 3, + "numberOfRowBits": 14, + "numberOfColumnBits": 10, + "numberOfByteBits": 3, + "numberOfBLBits": 3 + }, + "Name": "trace_name", + "Solutions": [ + { + "XOR": [ + ], + "Banks Rows": [ + { + "bank_bits": [ + 27, + 28, + 29 + ], + "rows": { + "row_bits": [ + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26 + ], + "costs": 477468 + }, + "costs": 477468 + } + ] + } + ] + } +``` + - **Memory Configuration** The content of [fifo.xml](DRAMSys/library/resources/configs/memconfigs/fifo.xml) is @@ -676,7 +745,7 @@ A description of the content each directory follows. - **scripts**: useful tools. - **simulations**: main configuration files. - **traces**: pre-recorded trace files that may be used as stimuli in simulations. - + #### Log Collector Script Users can profit of running multiple simulations automatically with @@ -741,28 +810,28 @@ For more information check the documentation in [DRAMSylva folder](DRAMSys/libra the socket id (thread) of a payload. It is added in the Arbiter and is sent to the Controller. ![Payload Extension information](DRAMSys/docs/images/PayloadExtension.png) - + - **Transaction object with Memory Manager** - + The TracePlayer allocates the memory for the transaction object by calling allocatePayload method. - + The acquire method is called before passing the transaction object in TracePlayer, Arbiter and Controller. The release method is called after each component is done with the transaction object. After the final call of release method, the free method of the memory manager is called to free the transaction object. - + ![Payload Memory Manager](DRAMSys/docs/images/PayloadMemoryManager.png) - **Architecture of the backend TLM model** The below figure shows our custom TLM protocol between the Controller and the Dram. A new transaction enters the Controller with the BEGIN_REQ phase is stored in frontendPEQ. The callback function of the frontendPEQ is called and send the payload to the Scheduler. - + The Scheduler checks the address of payload and the current state to determine proper command (Active, Precharge, Read or Write). Then the ControllerCore sends the payload with the corresponding phase (BEGIN_ACT, BEGIN_PRE, BEGIN_RD or BEGIN_WR) to the Dram by calling nb_transport_fw method. - - The Dram receives the transaction then send back to the Controller by calling nb_transport_bw with appropriate END phase (END_ACT, END_PRE, END_RD or END_WR). + + The Dram receives the transaction then send back to the Controller by calling nb_transport_bw with appropriate END phase (END_ACT, END_PRE, END_RD or END_WR). ![Architecture backend TLM](DRAMSys/docs/images/TransactionPhase.png) -### DRAMSys Thermal Simulation +### DRAMSys Thermal Simulation The thermal simulation is performed by a **3D-ICE** [8] server accessed through the network. Therefore users interested in thermal simulation during From ff91c37df335f3806b40efff556e5087cefe328f Mon Sep 17 00:00:00 2001 From: Johannes Feldmann Date: Fri, 30 Mar 2018 17:51:12 +0200 Subject: [PATCH 08/38] Changes suggest by review colleagues. --- DRAMSys/library/src/common/AddressDecoder.cpp | 43 +++++++++++++++++-- DRAMSys/library/src/common/AddressDecoder.h | 8 ++-- .../library/src/common/jsonAddressDecoder.cpp | 35 +++++++++++++++ .../library/src/common/jsonAddressDecoder.h | 6 ++- .../library/src/common/xmlAddressdecoder.h | 6 ++- .../core/configuration/Configuration.cpp | 4 +- DRAMSys/library/src/error/errormodel.cpp | 6 +-- DRAMSys/library/src/error/errormodel.h | 4 +- DRAMSys/library/src/simulation/Arbiter.h | 14 +++--- DRAMSys/library/src/simulation/DRAMSys.cpp | 10 ++--- 10 files changed, 105 insertions(+), 31 deletions(-) diff --git a/DRAMSys/library/src/common/AddressDecoder.cpp b/DRAMSys/library/src/common/AddressDecoder.cpp index 938129c8..63e2e921 100644 --- a/DRAMSys/library/src/common/AddressDecoder.cpp +++ b/DRAMSys/library/src/common/AddressDecoder.cpp @@ -1,16 +1,51 @@ +/* + * Copyright (c) 2018, University of Kaiserslautern + * All rights reserved. + * + * 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. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER + * OR CONTRIBUTORS 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. + * + * Authors: + * Johannes Feldmann + */ + #include "AddressDecoder.h" #include "xmlAddressdecoder.h" #include "jsonAddressDecoder.h" -CAddressDecoder* CAddressDecoder::m_pInstance = nullptr; +AddressDecoder* AddressDecoder::m_pInstance = nullptr; -CAddressDecoder& CAddressDecoder::getInstance() +AddressDecoder& AddressDecoder::getInstance() { assert(m_pInstance != nullptr); return *m_pInstance; } -void CAddressDecoder::createInstance(Type t) +void AddressDecoder::createInstance(Type t) { assert(m_pInstance == nullptr); switch(t) @@ -24,7 +59,7 @@ void CAddressDecoder::createInstance(Type t) } } -CAddressDecoder::CAddressDecoder() +AddressDecoder::AddressDecoder() { } diff --git a/DRAMSys/library/src/common/AddressDecoder.h b/DRAMSys/library/src/common/AddressDecoder.h index c5c23a70..be74980f 100644 --- a/DRAMSys/library/src/common/AddressDecoder.h +++ b/DRAMSys/library/src/common/AddressDecoder.h @@ -63,7 +63,7 @@ struct DecodedAddress unsigned int bytes; }; -class CAddressDecoder +class AddressDecoder { public: enum class Type @@ -73,11 +73,11 @@ public: }; protected: - CAddressDecoder(); + AddressDecoder(); - static CAddressDecoder* m_pInstance; + static AddressDecoder* m_pInstance; public: - static CAddressDecoder& getInstance(); + static AddressDecoder& getInstance(); static void createInstance(Type t); virtual void setConfiguration(std::string url) = 0; diff --git a/DRAMSys/library/src/common/jsonAddressDecoder.cpp b/DRAMSys/library/src/common/jsonAddressDecoder.cpp index dd9c8b62..9fdf09bd 100644 --- a/DRAMSys/library/src/common/jsonAddressDecoder.cpp +++ b/DRAMSys/library/src/common/jsonAddressDecoder.cpp @@ -1,3 +1,38 @@ +/* + * Copyright (c) 2018, University of Kaiserslautern + * All rights reserved. + * + * 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. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "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 COPYRIGHT HOLDER + * OR CONTRIBUTORS 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. + * + * Authors: + * Johannes Feldmann + */ + #include "jsonAddressDecoder.h" #include "Utils.h" diff --git a/DRAMSys/library/src/common/jsonAddressDecoder.h b/DRAMSys/library/src/common/jsonAddressDecoder.h index 354b7513..475d084d 100644 --- a/DRAMSys/library/src/common/jsonAddressDecoder.h +++ b/DRAMSys/library/src/common/jsonAddressDecoder.h @@ -46,9 +46,11 @@ using std::pair; using std::map; class JSONAddressDecoder - : public CAddressDecoder + : public AddressDecoder { - friend class CAddressDecoder; + // Friendship needed so that the AddressDecoder can access the + // constructor of this class to create the object in CreateInstance. + friend class AddressDecoder; private: JSONAddressDecoder(); diff --git a/DRAMSys/library/src/common/xmlAddressdecoder.h b/DRAMSys/library/src/common/xmlAddressdecoder.h index 03ade6c5..7266b8df 100644 --- a/DRAMSys/library/src/common/xmlAddressdecoder.h +++ b/DRAMSys/library/src/common/xmlAddressdecoder.h @@ -45,9 +45,11 @@ #include "AddressDecoder.h" class xmlAddressDecoder - : public CAddressDecoder + : public AddressDecoder { - friend class CAddressDecoder; + // Friendship needed so that the AddressDecoder can access the + // constructor of this class to create the object in CreateInstance. + friend class AddressDecoder; private: xmlAddressDecoder(); diff --git a/DRAMSys/library/src/controller/core/configuration/Configuration.cpp b/DRAMSys/library/src/controller/core/configuration/Configuration.cpp index 29cc6f94..d7070107 100644 --- a/DRAMSys/library/src/controller/core/configuration/Configuration.cpp +++ b/DRAMSys/library/src/controller/core/configuration/Configuration.cpp @@ -191,7 +191,7 @@ void Configuration::setParameter(std::string name, std::string value) Debug = string2bool(value); else if (name == "NumberOfMemChannels") { NumberOfMemChannels = string2int(value); - unsigned int maxNumberofMemChannels = CAddressDecoder::getInstance().amount["channel"]; + unsigned int maxNumberofMemChannels = AddressDecoder::getInstance().amount["channel"]; if (NumberOfMemChannels > maxNumberofMemChannels) { SC_REPORT_FATAL("Configuration", ("Invalid value for parameter " + name @@ -349,7 +349,7 @@ unsigned int Configuration::getBytesPerBurst() // The least significant bits of the physical address are the byte // offset of the N-byte-wide memory module (DIMM) (a single data word // or burst element has N bytes. N = 2^(# bits for byte offset)). - unsigned int burstElementSizeInBytes = CAddressDecoder::getInstance().amount["bytes"]; + unsigned int burstElementSizeInBytes = AddressDecoder::getInstance().amount["bytes"]; assert(bytesPerBurst == (burstElementSizeInBytes * memSpec.BurstLength)); } diff --git a/DRAMSys/library/src/error/errormodel.cpp b/DRAMSys/library/src/error/errormodel.cpp index 18966452..9a40a869 100644 --- a/DRAMSys/library/src/error/errormodel.cpp +++ b/DRAMSys/library/src/error/errormodel.cpp @@ -48,7 +48,7 @@ void errorModel::init() // Get Configuration parameters: burstLenght = Configuration::getInstance().memSpec.BurstLength; numberOfColumns = Configuration::getInstance().memSpec.NumberOfColumns; - bytesPerColumn = CAddressDecoder::getInstance().amount["bytes"]; + bytesPerColumn = AddressDecoder::getInstance().amount["bytes"]; // Adjust number of bytes per column dynamically to the selected ecc controller bytesPerColumn = Configuration::getInstance().adjustNumBytesAfterECC(bytesPerColumn); @@ -157,7 +157,7 @@ void errorModel::store(tlm::tlm_generic_payload &trans) markBitFlips(); // Get the key for the dataMap from the transaction's address: - DecodedAddress key = CAddressDecoder::getInstance().decodeAddress(trans.get_address()); + DecodedAddress key = AddressDecoder::getInstance().decodeAddress(trans.get_address()); // Set context: setContext(key); @@ -225,7 +225,7 @@ void errorModel::load(tlm::tlm_generic_payload &trans) markBitFlips(); // Get the key for the dataMap from the transaction's address: - DecodedAddress key = CAddressDecoder::getInstance().decodeAddress(trans.get_address()); + DecodedAddress key = AddressDecoder::getInstance().decodeAddress(trans.get_address()); // Set context: setContext(key); diff --git a/DRAMSys/library/src/error/errormodel.h b/DRAMSys/library/src/error/errormodel.h index d3914c6c..f7efed69 100644 --- a/DRAMSys/library/src/error/errormodel.h +++ b/DRAMSys/library/src/error/errormodel.h @@ -120,8 +120,8 @@ class errorModel : public sc_module { bool operator()( const DecodedAddress& first , const DecodedAddress& second) const { - sc_dt::uint64 addrFirst = CAddressDecoder::getInstance().encodeAddress(first); - sc_dt::uint64 addrSecond = CAddressDecoder::getInstance().encodeAddress(second); + sc_dt::uint64 addrFirst = AddressDecoder::getInstance().encodeAddress(first); + sc_dt::uint64 addrSecond = AddressDecoder::getInstance().encodeAddress(second); return addrFirst < addrSecond; } }; diff --git a/DRAMSys/library/src/simulation/Arbiter.h b/DRAMSys/library/src/simulation/Arbiter.h index 5b60b410..72e8e1c8 100644 --- a/DRAMSys/library/src/simulation/Arbiter.h +++ b/DRAMSys/library/src/simulation/Arbiter.h @@ -151,7 +151,7 @@ private: // adjust address offset: trans.set_address(trans.get_address() - Configuration::getInstance().AddressOffset); - DecodedAddress decodedAddress = CAddressDecoder::getInstance().decodeAddress(trans.get_address()); + DecodedAddress decodedAddress = AddressDecoder::getInstance().decodeAddress(trans.get_address()); return iSocket[decodedAddress.channel]->transport_dbg(trans); } @@ -248,7 +248,7 @@ private: payload.set_auto_extension(genExtension); unsigned int burstlength = payload.get_streaming_width(); - DecodedAddress decodedAddress = CAddressDecoder::getInstance().decodeAddress(payload.get_address()); + DecodedAddress decodedAddress = AddressDecoder::getInstance().decodeAddress(payload.get_address()); // Check the valid range of decodedAddress if (addressIsValid(decodedAddress)) { DramExtension* extension = new DramExtension(Thread(socketId+1), Channel(decodedAddress.channel), Bank(decodedAddress.bank), BankGroup(decodedAddress.bankgroup), Row(decodedAddress.row), Column(decodedAddress.column),burstlength); @@ -260,19 +260,19 @@ private: bool addressIsValid(DecodedAddress& decodedAddress) { - if (decodedAddress.channel >= CAddressDecoder::getInstance().amount["channel"]) { + if (decodedAddress.channel >= AddressDecoder::getInstance().amount["channel"]) { return false; } - if (decodedAddress.bank >= CAddressDecoder::getInstance().amount["bank"]) { + if (decodedAddress.bank >= AddressDecoder::getInstance().amount["bank"]) { return false; } - if (decodedAddress.bankgroup > CAddressDecoder::getInstance().amount["bankgroup"]) { + if (decodedAddress.bankgroup > AddressDecoder::getInstance().amount["bankgroup"]) { return false; } - if (decodedAddress.column >= CAddressDecoder::getInstance().amount["column"]) { + if (decodedAddress.column >= AddressDecoder::getInstance().amount["column"]) { return false; } - if (decodedAddress.row >= CAddressDecoder::getInstance().amount["row"]) { + if (decodedAddress.row >= AddressDecoder::getInstance().amount["row"]) { return false; } return true; diff --git a/DRAMSys/library/src/simulation/DRAMSys.cpp b/DRAMSys/library/src/simulation/DRAMSys.cpp index 245b4aca..e37ae09f 100644 --- a/DRAMSys/library/src/simulation/DRAMSys.cpp +++ b/DRAMSys/library/src/simulation/DRAMSys.cpp @@ -86,15 +86,15 @@ DRAMSys::DRAMSys(sc_module_name __attribute__((unused)) name, if(amconfig.find(".xml") != string::npos) { - CAddressDecoder::createInstance(CAddressDecoder::Type::XML); - CAddressDecoder::getInstance().setConfiguration(pathToResources + AddressDecoder::createInstance(AddressDecoder::Type::XML); + AddressDecoder::getInstance().setConfiguration(pathToResources + "configs/amconfigs/" + amconfig); } else if(amconfig.find(".json") != string::npos) { - CAddressDecoder::createInstance(CAddressDecoder::Type::JSON); - CAddressDecoder::getInstance().setConfiguration(pathToResources + AddressDecoder::createInstance(AddressDecoder::Type::JSON); + AddressDecoder::getInstance().setConfiguration(pathToResources + "configs/amconfigs/" + amconfig); } @@ -103,7 +103,7 @@ DRAMSys::DRAMSys(sc_module_name __attribute__((unused)) name, cout << "No address mapping loaded. Unknown file extension" << endl; } - CAddressDecoder::getInstance().print(); + AddressDecoder::getInstance().print(); ConfigurationLoader::loadMemSpec(Configuration::getInstance(), pathToResources From 42b5ad004e686328f181ed9b3b33a5a260b3f240 Mon Sep 17 00:00:00 2001 From: Johannes Feldmann Date: Tue, 3 Apr 2018 10:41:35 +0200 Subject: [PATCH 09/38] Add missing '\' in library.pro --- DRAMSys/library/library.pro | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/DRAMSys/library/library.pro b/DRAMSys/library/library.pro index 4dbfd863..56353e00 100644 --- a/DRAMSys/library/library.pro +++ b/DRAMSys/library/library.pro @@ -126,6 +126,7 @@ SOURCES += \ HEADERS += \ src/common/third_party/tinyxml2/tinyxml2.h \ + src/common/third_party/json/include/nlohmann/json.hpp \ src/common/xmlAddressdecoder.h \ src/common/Utils.h \ src/common/TlmRecorder.h \ @@ -193,12 +194,11 @@ HEADERS += \ src/error/eccbaseclass.h \ src/error/ecchamming.h \ src/controller/scheduler/Fr_Fcfs_read_priority.h \ - src/controller/scheduler/Fr_Fcfs_grouper.h + src/controller/scheduler/Fr_Fcfs_grouper.h \ src/simulation/IArbiter.h \ src/simulation/SimpleArbiter.h \ src/common/AddressDecoder.h \ - src/common/jsonAddressDecoder.h \ - src/common/third_party/json/include/nlohmann/json.hpp + src/common/jsonAddressDecoder.h thermalsim = $$(THERMALSIM) isEmpty(thermalsim) { From 23648c6f6060379d4a3cd7df0664df9e7bf73690 Mon Sep 17 00:00:00 2001 From: Johannes Feldmann Date: Tue, 3 Apr 2018 11:43:40 +0200 Subject: [PATCH 10/38] Added default case to AddressDecoder::CreateInstance. --- DRAMSys/library/src/common/AddressDecoder.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/DRAMSys/library/src/common/AddressDecoder.cpp b/DRAMSys/library/src/common/AddressDecoder.cpp index 63e2e921..266e9bca 100644 --- a/DRAMSys/library/src/common/AddressDecoder.cpp +++ b/DRAMSys/library/src/common/AddressDecoder.cpp @@ -56,6 +56,9 @@ void AddressDecoder::createInstance(Type t) case Type::JSON: m_pInstance = new JSONAddressDecoder; break; + default: + throw std::logic_error("Instance type not supported."); + break; } } From 7a715d171fb722bbb538c9de8bd3d9c2f41c2aa7 Mon Sep 17 00:00:00 2001 From: Johannes Feldmann Date: Tue, 10 Apr 2018 16:36:57 +0200 Subject: [PATCH 11/38] Fixed a bug in the XOR mapping --- DRAMSys/library/src/common/jsonAddressDecoder.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/DRAMSys/library/src/common/jsonAddressDecoder.cpp b/DRAMSys/library/src/common/jsonAddressDecoder.cpp index 3f32cb79..333c200d 100644 --- a/DRAMSys/library/src/common/jsonAddressDecoder.cpp +++ b/DRAMSys/library/src/common/jsonAddressDecoder.cpp @@ -146,8 +146,11 @@ DecodedAddress JSONAddressDecoder::decodeAddress(sc_dt::uint64 addr) // Get the bank bit and row bit. Apply a bitwise xor operator and save it back to the bank bit. for(auto it = m_vXor.begin(); it != m_vXor.end(); it++) { + unsigned new_bank_bit; + // Bank Row + new_bank_bit = (((addr >> it->first) & 1) ^ ((addr >> it->second) & 1)); addr &= ~(1 << it->first); - addr |= (((addr >> it->first) & 1) ^ ((addr >> it->second) & 1)) << it->first; + addr |= new_bank_bit << it->first; } // Unsed @@ -234,8 +237,10 @@ sc_dt::uint64 JSONAddressDecoder::encodeAddress(DecodedAddress n) // Get the bank bit and row bit. Apply a bitwise xor operator and save it back to the bank bit. for(auto it = m_vXor.begin(); it != m_vXor.end(); it++) { - address &= ~(1 << it->first); - address |= (((address >> it->first) & 1) ^ ((address >> it->second) & 1)) << it->first; + unsigned new_bank_bit; + new_bank_bit = (((address >> it->first) & 1) ^ ((address >> it->second) & 1)); + address &= ~(1 << it->first); + address |= new_bank_bit << it->first; } return address; From ad51dcfdb19dfe8eb69b68a833c244a2e287c712 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Thu, 12 Apr 2018 23:16:59 +0200 Subject: [PATCH 12/38] Script to apply coding-style rules. --- utils/make_pretty.sh | 46 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100755 utils/make_pretty.sh diff --git a/utils/make_pretty.sh b/utils/make_pretty.sh new file mode 100755 index 00000000..95adcbf2 --- /dev/null +++ b/utils/make_pretty.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash + +# Copyright (c) 2018, University of Kaiserslautern +# All rights reserved. +# +# 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. Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "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 COPYRIGHT HOLDER +# OR CONTRIBUTORS 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. +# +# Author: Éder F. Zulian + +BASEDIR="$(pwd)/.." +export ARTISTIC_STYLE_OPTIONS="$BASEDIR/DRAMSys/DRAMSys.astylerc" +EXCLUDEDIR="$BASEDIR/DRAMSys/library/src/common/third_party" +OPT="--suffix=none --lineend=linux" +astyle --recursive "$BASEDIR/*.cpp" "$BASEDIR/*.h" --exclude=$EXCLUDEDIR $OPT + +# if [ $? -ne 0 ] ; then read -sn1 -p "Error executing astyle!"; fi + +#astyle --recursive "$BASEDIR/*.cpp" --exclude="$BASEDIR/DRAMSys/library/src/common/third_party/DRAMPower $BASEDIR/DRAMSys/library/src/common/third_party/json $BASEDIR/DRAMSys/library/src/common/third_party/tinyxml2" --suffix=none + + + From da565df24d89df57bb1c8b5fc50a29b174cd807a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Thu, 12 Apr 2018 23:20:10 +0200 Subject: [PATCH 13/38] Coding-style script improved --- utils/make_pretty.sh | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/utils/make_pretty.sh b/utils/make_pretty.sh index 95adcbf2..f3a804b0 100755 --- a/utils/make_pretty.sh +++ b/utils/make_pretty.sh @@ -33,14 +33,12 @@ # Author: Éder F. Zulian BASEDIR="$(pwd)/.." -export ARTISTIC_STYLE_OPTIONS="$BASEDIR/DRAMSys/DRAMSys.astylerc" EXCLUDEDIR="$BASEDIR/DRAMSys/library/src/common/third_party" OPT="--suffix=none --lineend=linux" + +export ARTISTIC_STYLE_OPTIONS="$BASEDIR/DRAMSys/DRAMSys.astylerc" astyle --recursive "$BASEDIR/*.cpp" "$BASEDIR/*.h" --exclude=$EXCLUDEDIR $OPT -# if [ $? -ne 0 ] ; then read -sn1 -p "Error executing astyle!"; fi - -#astyle --recursive "$BASEDIR/*.cpp" --exclude="$BASEDIR/DRAMSys/library/src/common/third_party/DRAMPower $BASEDIR/DRAMSys/library/src/common/third_party/json $BASEDIR/DRAMSys/library/src/common/third_party/tinyxml2" --suffix=none - - - +if [ $? -ne 0 ]; then + read -sn1 -p "Error executing astyle!"; +fi From db2b31ae4b2a8c19a620141982b70aa75d3f3fa1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Thu, 12 Apr 2018 23:25:26 +0200 Subject: [PATCH 14/38] Coding style script improved and doc updated --- coding-style.md | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/coding-style.md b/coding-style.md index 7b686d65..d0509550 100644 --- a/coding-style.md +++ b/coding-style.md @@ -26,9 +26,9 @@ sudo apt-get -y install clang-format ``` **Hint:** -You can use [utils/install.sh](./utils/install.sh) in order to install -dependencies. First read and understand the script then execute it. Type your -password if required. +You can use [install.sh](./utils/install.sh) in order to install dependencies. +First read and understand the script then execute it. Type your password if +required. ## DRAMSys Coding Style for C++ Code @@ -145,14 +145,21 @@ There is a plugin for VIM. More information can be found in + Select the **Enable auto format on file save** check box to automatically beautify files when you save them. +## Applying the Coding Style + +The script [make_pretty.sh](./utils/make_pretty.sh) applies the coding style +to the project excluding thrid party code. ## References -[Linux kernel coding style](https://github.com/torvalds/linux/blob/master/Documentation/process/coding-style.rst) +[Linux kernel coding +style](https://github.com/torvalds/linux/blob/master/Documentation/process/coding-style.rst) -[C++ Core Guidelines](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#S-cpl) +[C++ Core +Guidelines](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#S-cpl) -[PEP 8 -- Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/) +[PEP 8 -- Style Guide for Python +Code](https://www.python.org/dev/peps/pep-0008/) [Qt Documentation - Beautifying Source Code](http://doc.qt.io/qtcreator/creator-beautifier.html) From 747dcbb777d26f35f8b48f17e3b5db9c337656a0 Mon Sep 17 00:00:00 2001 From: sprado Date: Tue, 15 May 2018 15:36:31 +0200 Subject: [PATCH 15/38] TlmRecorder destructor fixed --- DRAMSys/library/src/common/TlmRecorder.cpp | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/DRAMSys/library/src/common/TlmRecorder.cpp b/DRAMSys/library/src/common/TlmRecorder.cpp index 59e546aa..1499d9a2 100644 --- a/DRAMSys/library/src/common/TlmRecorder.cpp +++ b/DRAMSys/library/src/common/TlmRecorder.cpp @@ -72,16 +72,6 @@ TlmRecorder::~TlmRecorder() { if (db) closeConnection(); - sqlite3_finalize(insertTransactionStatement); - sqlite3_finalize(insertRangeStatement); - sqlite3_finalize(updateRangeStatement); - sqlite3_finalize(insertPhaseStatement); - sqlite3_finalize(updatePhaseStatement); - sqlite3_finalize(insertGeneralInfoStatement); - sqlite3_finalize(insertDebugMessageStatement); - sqlite3_finalize(updateDataStrobeStatement); - sqlite3_finalize(insertPowerStatement); - } void TlmRecorder::recordPower(double timeInSeconds, double averagePower) @@ -414,6 +404,15 @@ void TlmRecorder::closeConnection() printDebugMessage( "Number of transactions written to DB: " + std::to_string(totalNumTransactions - 1)); printDebugMessage("tlmPhaseRecorder:\tEnd Recording"); + sqlite3_finalize(insertTransactionStatement); + sqlite3_finalize(insertRangeStatement); + sqlite3_finalize(updateRangeStatement); + sqlite3_finalize(insertPhaseStatement); + sqlite3_finalize(updatePhaseStatement); + sqlite3_finalize(insertGeneralInfoStatement); + sqlite3_finalize(insertDebugMessageStatement); + sqlite3_finalize(updateDataStrobeStatement); + sqlite3_finalize(insertPowerStatement); sqlite3_close(db); db = NULL; } From 2d91748340144ef10ee2b643703cbb498a6a89bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Fri, 18 May 2018 13:33:29 +0200 Subject: [PATCH 16/38] Fix: single quote --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7cbda275..f2894a5e 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Configure git on your machine. Some basic configurations follow. Replace ``` bash $ git config --global user.name "FirstName OtherNames LastName" $ git config --global user.email rhrkuser@rhrk.uni-kl.de -$ git config --global credential.helper ’cache --timeout=3600’ +$ git config --global credential.helper 'cache --timeout=3600' $ git config --global color.ui auto ``` From 7038b9211bfcd1aafd821b294c95be7decc55f57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Fri, 18 May 2018 13:36:42 +0200 Subject: [PATCH 17/38] PEP8 --- DRAMSys/traceAnalyzer/scripts/metrics.py | 31 +++++++++++++----------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/DRAMSys/traceAnalyzer/scripts/metrics.py b/DRAMSys/traceAnalyzer/scripts/metrics.py index 1b6e73ce..64db6dd6 100644 --- a/DRAMSys/traceAnalyzer/scripts/metrics.py +++ b/DRAMSys/traceAnalyzer/scripts/metrics.py @@ -212,7 +212,7 @@ def paralellism(connection, thread): @threadMetric -def thread_conclusion_in_ns(connection,thread): +def thread_conclusion_in_ns(connection, thread): cursor = connection.cursor() query = """ SELECT max(PhaseEnd)/1000 FROM Phases INNER JOIN Transactions on Phases.transact=Transactions.id WHERE TThread = :Thread """ cursor.execute(query, {"Thread": thread}) @@ -267,10 +267,10 @@ def bank_overlap_ratio(connection): prevTime = 0 for c in cursor: - trace.append([(int(c[0]/clk[0])),c[1]]) + trace.append([(int(c[0]/clk[0])), c[1]]) - #Insert a pseudo precharge all to mark the end of the trace - trace.append([traceEnd,"PRE_ALL"]) + # Insert a pseudo precharge all to mark the end of the trace + trace.append([traceEnd, "PRE_ALL"]) bankCounter = 0 bankTime = [] @@ -297,12 +297,11 @@ def bank_overlap_ratio(connection): elif(t[1] == "RDA"): bankCounter -= 1 else: - print ("ERROR") + print("ERROR") return 0 - for i in range(0, getNumberOfBanks(connection)+1): - bankTime[i] = round(bankTime[i]/traceEnd * 100,2) + bankTime[i] = round(bankTime[i]/traceEnd * 100, 2) return ",".join(format(x, "6.2f") for x in bankTime) @@ -483,8 +482,8 @@ def getMetrics(pathToTrace): if (len(getThreads(connection)) > 1): for thread in getThreads(connection): for threadMetric in threadMetrics: - res = "Thread {0}: {1}".format(thread,threadMetric.__name__.replace("_"," ")) - selectedMetrics.append(res) + res = "Thread {0}: {1}".format(thread, threadMetric.__name__.replace("_", " ")) + selectedMetrics.append(res) res = "pass ratio" selectedMetrics.append(res) @@ -492,7 +491,7 @@ def getMetrics(pathToTrace): return selectedMetrics -def calculateMetrics(pathToTrace, selectedMetrics = []): +def calculateMetrics(pathToTrace, selectedMetrics=[]): calculatedMetrics = [] connection = sqlite3.connect(pathToTrace) @@ -501,9 +500,13 @@ def calculateMetrics(pathToTrace, selectedMetrics = []): bankwiseLogic = mcconfig.getValue("BankwiseLogic") if bankwiseLogic == "0": - pdnMetrics = [time_in_PDNA_in_ns, time_in_PDNA_percent, time_in_PDNP_in_ns, time_in_PDNP_percent, time_in_SREF_in_ns, time_in_SREF_percent] + pdnMetrics = [time_in_PDNA_in_ns, time_in_PDNA_percent, + time_in_PDNP_in_ns, time_in_PDNP_percent, + time_in_SREF_in_ns, time_in_SREF_percent] else: - pdnMetrics = [time_in_PDNAB_in_ns, time_in_PDNAB_percent, time_in_PDNPB_in_ns, time_in_PDNPB_percent, time_in_SREFB_in_ns, time_in_SREFB_percent] + pdnMetrics = [time_in_PDNAB_in_ns, time_in_PDNAB_percent, + time_in_PDNPB_in_ns, time_in_PDNPB_percent, + time_in_SREFB_in_ns, time_in_SREFB_percent] for m in pdnMetrics: if m not in metrics: @@ -544,12 +547,12 @@ def calculateMetrics(pathToTrace, selectedMetrics = []): for metric in threadMetrics: if(selectedMetrics[len(metrics) + len(threadMetrics)*(thread-1) + threadMetrics.index(metric)]): mres = metric(connection, thread) - mname = "Thread {0} - {1}".format(thread,metric.__name__.replace("_"," ")) + mname = "Thread {0} - {1}".format(thread, metric.__name__.replace("_", " ")) res = (mname, mres) calculatedMetrics.append(res) print("{0}: {1}".format(res[0], res[1])) - if(selectedMetrics[len(selectedMetrics) -1]): + if (selectedMetrics[len(selectedMetrics) - 1]): calculatedMetrics.extend(passRatio(connection)) # refreshMissDecision(connection, calculatedMetrics) From 2c0e6ece30b78d2f830ba1997f564d958139f168 Mon Sep 17 00:00:00 2001 From: "Eder F. Zulian" Date: Fri, 18 May 2018 14:44:50 +0200 Subject: [PATCH 18/38] Changes to get build working again after merging pr190 See also: Pull request #190 Issue #198 --- DRAMSys/library/library.pro | 2 +- DRAMSys/library/src/common/jsonAddressDecoder.cpp | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/DRAMSys/library/library.pro b/DRAMSys/library/library.pro index 23f56ddc..7a455f7f 100644 --- a/DRAMSys/library/library.pro +++ b/DRAMSys/library/library.pro @@ -126,7 +126,6 @@ SOURCES += \ HEADERS += \ src/common/third_party/tinyxml2/tinyxml2.h \ - src/common/third_party/json/include/nlohmann/json.hpp \ src/common/xmlAddressdecoder.h \ src/common/Utils.h \ src/common/TlmRecorder.h \ @@ -199,6 +198,7 @@ HEADERS += \ src/simulation/SimpleArbiter.h \ src/common/AddressDecoder.h \ src/common/jsonAddressDecoder.h + #src/common/third_party/json/include/nlohmann/json.hpp \ thermalsim = $$(THERMALSIM) isEmpty(thermalsim) { diff --git a/DRAMSys/library/src/common/jsonAddressDecoder.cpp b/DRAMSys/library/src/common/jsonAddressDecoder.cpp index 333c200d..9a867bc9 100644 --- a/DRAMSys/library/src/common/jsonAddressDecoder.cpp +++ b/DRAMSys/library/src/common/jsonAddressDecoder.cpp @@ -42,9 +42,11 @@ using std::ifstream; using std::cout; using std::endl; +#if 0 // Problems with gcc version on KOA for more details refer to pull-request #190 and issue #198 #include using json = nlohmann::json; +#endif #include @@ -67,6 +69,7 @@ void JSONAddressDecoder::setConfiguration(std::string url) return; } +#if 0 //XXX: Problems with gcc version on KOA for more details refer to pull-request #190 and issue #198 // parse json file json data; file >> data; @@ -135,6 +138,7 @@ void JSONAddressDecoder::setConfiguration(std::string url) amount["row"] = pow(2.0, m_vRowBits.size()); amount["column"] = pow(2.0, m_vColumnBits.size()); amount["bytes"] = pow(2.0, 3); +#endif } DecodedAddress JSONAddressDecoder::decodeAddress(sc_dt::uint64 addr) From 9891f0f77f7bf1c8f8de5472d1ee2b8251d2b78a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Thu, 24 May 2018 09:53:58 +0200 Subject: [PATCH 19/38] Trace generator script. Trace generator script for a given address mapping. This script can be easily modified for your needs. --- .../library/resources/scripts/trace_gen.py | 130 ++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100755 DRAMSys/library/resources/scripts/trace_gen.py diff --git a/DRAMSys/library/resources/scripts/trace_gen.py b/DRAMSys/library/resources/scripts/trace_gen.py new file mode 100755 index 00000000..6b51235b --- /dev/null +++ b/DRAMSys/library/resources/scripts/trace_gen.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python +# vim: set fileencoding=utf-8 + +# Copyright (c) 2018, University of Kaiserslautern +# All rights reserved. +# +# 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. Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "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 COPYRIGHT HOLDER +# OR CONTRIBUTORS 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. +# +# Author: Éder F. Zulian + +import ctypes + +# A trace file is a pre-recorded file containing memory transactions. Each +# memory transaction has a timestamp that tells the simulator when it shall +# happen, a transaction type (read or write) and a memory address given in +# hexadecimal. +# +# Here is an example syntax: +# +# ``` +# # Comment lines begin with # +# # [clock-cyle]: [write|read] [hex-address] +# 31: read 0x400140 +# 33: read 0x400160 +# 56: write 0x7fff8000 +# 81: read 0x400180 +# ``` +# +# The timestamp corresponds to the time the request is to be issued and it is +# given in cycles of the bus master device. Example: the device is a FPGA with +# frequency 200 MHz (clock period of 5 ns). If the timestamp is 10 it means +# that the request is to be issued when time is 50 ns. +# + +# The default values given as example assume the following address mapping: +# +# DIMM Characteristics: +# Byte Offset (Y): 8 [0:2] (8-byte-wide memory module, i.e., 64-bit-wide data bus) -> 3 bit +# Cols (C): 1K [3:12] (A0 - A9) -> 10 bit +# Rows (R): 128K [13:29] (A0 - A16) -> 17 bit +# Bank (B): 8 [30:32] (BA0 - BA2) -> 3 bit +# +# 3 3 3 | 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 | 1 1 1 +# 2 1 0 | 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 | 2 1 0 9 8 7 6 5 4 3 | 2 1 0 +# B B B | R R R R R R R R R R R R R R R R R | C C C C C C C C C C | Y Y Y +# + +# Transaction type (read or write) +transaction = 'read' + +# Channel information. This is DRAMSys specific. The channel bits come after +# the last regular address bit. +num_ch = 1 # Number of channels +ch_shift = 33 # Shift to reach the frist bit reserved for channels in the address +ch_mask = 0x3 # Mask for all channel bits in the address + +# Bank information +num_banks = 8 # Number of banks +bank_shift = 30 # Shift to reach the frist bit reserved for banks in the address +bank_mask = 0x7 # Mask for all bank bits in the address + +# Row information +num_rows = 128 * 1024 # Number of rows +row_shift = 13 # Shift to reach the frist bit reserved for rows in the address +row_mask = 0x1ffff # Mask for all row bits in the address + +# Column information +num_col = 1 * 1024 # Number of columns +col_shift = 3 # Shift to reach the frist bit reserved for columns in the address +col_mask = 0x3ff # Mask for all column bits in the address + +# Burst length of 8 columns. 8 columns written/read per access (in 4 full +# clock cycles of the memory bus). +burst_len = 8 + +# Initial clock cycle +clock_cycle = 0 + +# Clock cycle increment between two accesses +clock_increment = 10 + + +def clear_bits(mask, shift, val): + m = ctypes.c_uint64(~(mask << shift)).value + return ctypes.c_uint64(val & m).value + + +def set_bits(mask, shift, val, v): + val = clear_bits(mask, shift, val) + return ctypes.c_uint64(val | (v << shift)).value + + +address = 0 +for ch in range(0, num_ch): + address = set_bits(ch_mask, ch_shift, address, ch) + for b in range(0, num_banks): + address = set_bits(bank_mask, bank_shift, address, b) + for row in range(0, num_rows): + address = set_bits(row_mask, row_shift, address, row) + clock_cycle = clock_cycle + clock_increment + for col in range(0, num_col, burst_len): + address = set_bits(col_mask, col_shift, address, col) + print "# clock cycle: {0:d} | {1} | address: 0x{2:010X} | channel: {3} | bank: {4} | row: {5} | column: {6}".format(clock_cycle, transaction, address, ch, b, row, col) + print "{0:d}:\t{1}\t0x{2:010X}".format(clock_cycle, transaction, address) + clock_cycle = clock_cycle + clock_increment From e53945f873a35e8fa1e7dd873e61374390befa5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Thu, 24 May 2018 14:49:22 +0200 Subject: [PATCH 20/38] Added support to bank groups --- .../library/resources/scripts/trace_gen.py | 36 +++++++++++-------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/DRAMSys/library/resources/scripts/trace_gen.py b/DRAMSys/library/resources/scripts/trace_gen.py index 6b51235b..2f93f2f2 100755 --- a/DRAMSys/library/resources/scripts/trace_gen.py +++ b/DRAMSys/library/resources/scripts/trace_gen.py @@ -73,11 +73,17 @@ import ctypes # Transaction type (read or write) transaction = 'read' -# Channel information. This is DRAMSys specific. The channel bits come after -# the last regular address bit. +# Channel information. If your address mapping does not have bank groups keep +# it equal to 1 and set the shift to the extreme left of the address. num_ch = 1 # Number of channels -ch_shift = 33 # Shift to reach the frist bit reserved for channels in the address -ch_mask = 0x3 # Mask for all channel bits in the address +ch_shift = 34 # Shift to reach the frist bit reserved for channels in the address +ch_mask = 0x1 # Mask for all channel bits in the address + +# Bank group information. If your address mapping does not have bank groups +# keep it equal to 1 and set the shift to the extreme left of the address. +num_bank_groups = 1 # Number of bank groups +bank_group_shift = 33 # Shift to reach the frist bit reserved for bank groups in the address +bank_group_mask = 0x1 # Mask for all bits in the address related to bank groups # Bank information num_banks = 8 # Number of banks @@ -118,13 +124,15 @@ def set_bits(mask, shift, val, v): address = 0 for ch in range(0, num_ch): address = set_bits(ch_mask, ch_shift, address, ch) - for b in range(0, num_banks): - address = set_bits(bank_mask, bank_shift, address, b) - for row in range(0, num_rows): - address = set_bits(row_mask, row_shift, address, row) - clock_cycle = clock_cycle + clock_increment - for col in range(0, num_col, burst_len): - address = set_bits(col_mask, col_shift, address, col) - print "# clock cycle: {0:d} | {1} | address: 0x{2:010X} | channel: {3} | bank: {4} | row: {5} | column: {6}".format(clock_cycle, transaction, address, ch, b, row, col) - print "{0:d}:\t{1}\t0x{2:010X}".format(clock_cycle, transaction, address) - clock_cycle = clock_cycle + clock_increment + for bg in range(0, num_bank_groups): + address = set_bits(bank_group_mask, bank_group_shift, address, bg) + for b in range(0, num_banks): + address = set_bits(bank_mask, bank_shift, address, b) + for row in range(0, num_rows): + address = set_bits(row_mask, row_shift, address, row) + clock_cycle = clock_cycle + clock_increment + for col in range(0, num_col, burst_len): + address = set_bits(col_mask, col_shift, address, col) + print "# clock cycle: {0:d} | {1} | address: 0x{2:010X} | channel: {3} | bank group: {4} | bank: {5} | row: {6} | column: {7}".format(clock_cycle, transaction, address, ch, bg, b, row, col) + print "{0:d}:\t{1}\t0x{2:010X}".format(clock_cycle, transaction, address) + clock_cycle = clock_cycle + clock_increment From 953902166ebede727208d5b699f6b7f1c919eea6 Mon Sep 17 00:00:00 2001 From: "Eder F. Zulian" Date: Thu, 24 May 2018 15:21:36 +0200 Subject: [PATCH 21/38] Using python3 print style Other changes: - double increment in the clock cycle removed. - bank_group --> bgroup --- DRAMSys/library/resources/scripts/trace_gen.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/DRAMSys/library/resources/scripts/trace_gen.py b/DRAMSys/library/resources/scripts/trace_gen.py index 2f93f2f2..cbbff5a2 100755 --- a/DRAMSys/library/resources/scripts/trace_gen.py +++ b/DRAMSys/library/resources/scripts/trace_gen.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#! /usr/bin/env python3 # vim: set fileencoding=utf-8 # Copyright (c) 2018, University of Kaiserslautern @@ -73,7 +73,7 @@ import ctypes # Transaction type (read or write) transaction = 'read' -# Channel information. If your address mapping does not have bank groups keep +# Channel information. If your address mapping does not have channel bits keep # it equal to 1 and set the shift to the extreme left of the address. num_ch = 1 # Number of channels ch_shift = 34 # Shift to reach the frist bit reserved for channels in the address @@ -82,8 +82,8 @@ ch_mask = 0x1 # Mask for all channel bits in the address # Bank group information. If your address mapping does not have bank groups # keep it equal to 1 and set the shift to the extreme left of the address. num_bank_groups = 1 # Number of bank groups -bank_group_shift = 33 # Shift to reach the frist bit reserved for bank groups in the address -bank_group_mask = 0x1 # Mask for all bits in the address related to bank groups +bgroup_shift = 33 # Shift to reach the frist bit reserved for bank groups in the address +bgroup_mask = 0x1 # Mask for all bits in the address related to bank groups # Bank information num_banks = 8 # Number of banks @@ -125,14 +125,13 @@ address = 0 for ch in range(0, num_ch): address = set_bits(ch_mask, ch_shift, address, ch) for bg in range(0, num_bank_groups): - address = set_bits(bank_group_mask, bank_group_shift, address, bg) + address = set_bits(bgroup_mask, bgroup_shift, address, bg) for b in range(0, num_banks): address = set_bits(bank_mask, bank_shift, address, b) for row in range(0, num_rows): address = set_bits(row_mask, row_shift, address, row) - clock_cycle = clock_cycle + clock_increment for col in range(0, num_col, burst_len): address = set_bits(col_mask, col_shift, address, col) - print "# clock cycle: {0:d} | {1} | address: 0x{2:010X} | channel: {3} | bank group: {4} | bank: {5} | row: {6} | column: {7}".format(clock_cycle, transaction, address, ch, bg, b, row, col) - print "{0:d}:\t{1}\t0x{2:010X}".format(clock_cycle, transaction, address) + print('# clock cycle: {0:d} | {1} | address: 0x{2:010X} | channel: {3} | bank group: {4} | bank: {5} | row: {6} | column: {7}'.format(clock_cycle, transaction, address, ch, bg, b, row, col)) + print('{0:d}:\t{1}\t0x{2:010X}'.format(clock_cycle, transaction, address)) clock_cycle = clock_cycle + clock_increment From c665ea166b777071e80b15b09b4ea3b030845ebc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Fri, 25 May 2018 17:08:21 +0200 Subject: [PATCH 22/38] README updated Trace generator script that for simple tests. The script can be easily changed and provides a way to quickly generate accesses to all channels, all bank groups, all banks, all rows and all columns of the memory. Be aware that a trace which covers all rows and all columns may be huge (several giga bytes) depending on your memory. --- README.md | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/README.md b/README.md index f2894a5e..b2ef9fd2 100644 --- a/README.md +++ b/README.md @@ -791,6 +791,61 @@ The script runs one instance of DRAMSys for each of the files in the list. **The For more information check the documentation in [DRAMSylva folder](DRAMSys/library/resources/scripts/DRAMSylva). +#### Trace Generator Script + +A python script for generating simple traces for tests is provided. +[trace_gen.py](DRAMSys/library/resources/scripts/trace_gen.py). + +Example on how to run the script: +``` bash +$ cd DRAMSys/library/resources/scripts +$ ./trace_gen.py > trace.stl +``` + +Now change your configuration file to use the new generated trace file and run +your simulation. + + +You can open the script with a text editor and change some parameters to fit your needs. +``` +# Transaction type (read or write) +transaction = 'read' + +# Channel information. +num_ch = 1 # Number of channels +ch_shift = 34 # Shift to reach the frist bit reserved for channels in the address +ch_mask = 0x1 # Mask for all channel bits in the address + +# Bank group information. +num_bank_groups = 1 # Number of bank groups +bgroup_shift = 33 # Shift to reach the frist bit reserved for bank groups in the address +bgroup_mask = 0x1 # Mask for all bits in the address related to bank groups + +# Bank information +num_banks = 8 # Number of banks +bank_shift = 30 # Shift to reach the frist bit reserved for banks in the address +bank_mask = 0x7 # Mask for all bank bits in the address + +# Row information +num_rows = 128 * 1024 # Number of rows +row_shift = 13 # Shift to reach the frist bit reserved for rows in the address +row_mask = 0x1ffff # Mask for all row bits in the address + +# Column information +num_col = 1 * 1024 # Number of columns +col_shift = 3 # Shift to reach the frist bit reserved for columns in the address +col_mask = 0x3ff # Mask for all column bits in the address + +# Burst length +burst_len = 8 + +# Initial clock cycle +clock_cycle = 0 + +# Clock cycle increment between two accesses +clock_increment = 10 +``` + #### DRAMsys Diagrams - **TLM Approximately Timed (AT)** From f522eb417d4d20962b1b58de909509a407917656 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Fri, 25 May 2018 17:22:20 +0200 Subject: [PATCH 23/38] README updated --- README.md | 38 ++++++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index b2ef9fd2..8c9a5d26 100644 --- a/README.md +++ b/README.md @@ -793,10 +793,11 @@ For more information check the documentation in [DRAMSylva folder](DRAMSys/libra #### Trace Generator Script -A python script for generating simple traces for tests is provided. +A python script for generating input traces for simple tests is provided. [trace_gen.py](DRAMSys/library/resources/scripts/trace_gen.py). Example on how to run the script: + ``` bash $ cd DRAMSys/library/resources/scripts $ ./trace_gen.py > trace.stl @@ -805,12 +806,32 @@ $ ./trace_gen.py > trace.stl Now change your configuration file to use the new generated trace file and run your simulation. +The script can be easily changed and provides a way to quickly generate +accesses to all channels, all bank groups, all banks, all rows and all columns +of a memory. + +**Be aware that a trace which covers all rows and all columns may be huge +(several gigabytes) depending on your memory.** + +The defaul values in the script serve as an example. They consider the address +mapping that follows. -You can open the script with a text editor and change some parameters to fit your needs. ``` -# Transaction type (read or write) -transaction = 'read' +DDR3-SDRAM DIMM Characteristics: +Byte Offset (Y): 8 [0:2] (8-byte-wide memory module, i.e., 64-bit-wide data bus) -> 3 bit +Cols (C): 1K [3:12] (A0 - A9) -> 10 bit +Rows (R): 128K [13:29] (A0 - A16) -> 17 bit +Bank (B): 8 [30:32] (BA0 - BA2) -> 3 bit +3 3 3 | 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 | 1 1 1 +2 1 0 | 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 | 2 1 0 9 8 7 6 5 4 3 | 2 1 0 +B B B | R R R R R R R R R R R R R R R R R | C C C C C C C C C C | Y Y Y +``` + +The parameters for the DDR3-SDRAM DIMM with address mapping presented above +the configuration are presented below. + +``` # Channel information. num_ch = 1 # Number of channels ch_shift = 34 # Shift to reach the frist bit reserved for channels in the address @@ -838,14 +859,11 @@ col_mask = 0x3ff # Mask for all column bits in the address # Burst length burst_len = 8 - -# Initial clock cycle -clock_cycle = 0 - -# Clock cycle increment between two accesses -clock_increment = 10 ``` +Open the script with a text editor and change some parameters to fit your +needs. + #### DRAMsys Diagrams - **TLM Approximately Timed (AT)** From 20428ec2f2d66b206264fb2fedbb40d971e9e16e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Fri, 25 May 2018 17:27:38 +0200 Subject: [PATCH 24/38] readme updated --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8c9a5d26..0007548c 100644 --- a/README.md +++ b/README.md @@ -829,7 +829,7 @@ B B B | R R R R R R R R R R R R R R R R R | C C C C C C C C C C | Y Y Y ``` The parameters for the DDR3-SDRAM DIMM with address mapping presented above -the configuration are presented below. +are presented below. ``` # Channel information. From ac95b6233bdda9b53b578cc6ca962b50765e362e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Fri, 25 May 2018 17:29:59 +0200 Subject: [PATCH 25/38] README updated --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0007548c..5e0193c2 100644 --- a/README.md +++ b/README.md @@ -793,8 +793,8 @@ For more information check the documentation in [DRAMSylva folder](DRAMSys/libra #### Trace Generator Script -A python script for generating input traces for simple tests is provided. -[trace_gen.py](DRAMSys/library/resources/scripts/trace_gen.py). +The [trace_gen](DRAMSys/library/resources/scripts/trace_gen.py) script for +generating input traces for simple tests is provided. Example on how to run the script: From 2b3c268093557221a098256d5ffae0a63a0bcc1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Mon, 28 May 2018 17:40:27 +0200 Subject: [PATCH 26/38] trace_gen.py added to qt creator --- DRAMSys/library/resources/resources.pri | 1 + 1 file changed, 1 insertion(+) diff --git a/DRAMSys/library/resources/resources.pri b/DRAMSys/library/resources/resources.pri index 115c4ba7..731a8eec 100644 --- a/DRAMSys/library/resources/resources.pri +++ b/DRAMSys/library/resources/resources.pri @@ -32,6 +32,7 @@ OTHER_FILES += resources/scripts/DRAMSylva/README OTHER_FILES += resources/scripts/DRAMSylva/DRAMSylva.patch OTHER_FILES += resources/scripts/DRAMSylva/DRAMSylva.sh OTHER_FILES += resources/scripts/DRAMSylva/DRAMSylvaCSVPlot.py +OTHER_FILES += resources/scripts/trace_gen.py # Trace Files OTHER_FILES += resources/traces/chstone-aes_32.stl From 5a6aa137fa16582fdcddc990b63b68fe521528f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Mon, 28 May 2018 17:48:25 +0200 Subject: [PATCH 27/38] Reference to coding-style document on README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 5e0193c2..d2ab4e5e 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,10 @@ export LD_LIBRARY_PATH=${LD_LIBRARY_PATH:+${LD_LIBRARY_PATH}:}$LIBQWT_HOME export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${SYSTEMC_HOME}/lib-$SYSTEMC_TARGET_ARCH ``` +### Coding Style + +Please read the [coding-style document](coding-style.md) before start coding. + ### Buiding with QTCreator Execute the *QTCreator*. From 5b67f2b268ba2de4dd2f8b3a2750fb9a38833ebb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Tue, 29 May 2018 11:38:54 +0200 Subject: [PATCH 28/38] Coding-style applied the project. $ cd util $ ./make_pretty.sh --- DRAMSys/gem5/main.cpp | 56 +- DRAMSys/library/src/common/AddressDecoder.cpp | 7 +- DRAMSys/library/src/common/AddressDecoder.h | 22 +- DRAMSys/library/src/common/DebugManager.cpp | 19 +- DRAMSys/library/src/common/DebugManager.h | 2 +- DRAMSys/library/src/common/TlmRecorder.cpp | 249 +- DRAMSys/library/src/common/TlmRecorder.h | 70 +- DRAMSys/library/src/common/Utils.cpp | 150 +- DRAMSys/library/src/common/Utils.h | 59 +- DRAMSys/library/src/common/dramExtension.cpp | 72 +- DRAMSys/library/src/common/dramExtension.h | 47 +- .../library/src/common/jsonAddressDecoder.cpp | 149 +- .../library/src/common/jsonAddressDecoder.h | 14 +- .../src/common/tlm2_base_protocol_checker.h | 2104 ++++++++--------- .../library/src/common/xmlAddressdecoder.cpp | 34 +- .../library/src/common/xmlAddressdecoder.h | 4 +- DRAMSys/library/src/controller/Command.cpp | 11 +- DRAMSys/library/src/controller/Command.h | 2 +- DRAMSys/library/src/controller/Controller.cpp | 432 ++-- DRAMSys/library/src/controller/Controller.h | 51 +- .../src/controller/ControllerState.cpp | 53 +- .../library/src/controller/ControllerState.h | 15 +- DRAMSys/library/src/controller/IController.h | 6 +- .../src/controller/RowBufferStates.cpp | 26 +- .../library/src/controller/RowBufferStates.h | 5 +- .../src/controller/core/ControllerCore.cpp | 117 +- .../src/controller/core/ControllerCore.h | 29 +- DRAMSys/library/src/controller/core/Slots.cpp | 35 +- DRAMSys/library/src/controller/core/Slots.h | 2 +- .../src/controller/core/TimingCalculation.cpp | 86 +- .../src/controller/core/TimingCalculation.h | 5 +- .../core/configuration/Configuration.cpp | 193 +- .../core/configuration/Configuration.h | 22 +- .../configuration/ConfigurationLoader.cpp | 140 +- .../core/configuration/ConfigurationLoader.h | 34 +- .../controller/core/configuration/MemSpec.h | 89 +- .../core/configuration/thermalSimConfig.h | 16 +- .../core/powerdown/IPowerDownManager.h | 116 +- .../controller/core/powerdown/NoPowerDown.h | 4 +- .../core/powerdown/PowerDownManager.cpp | 97 +- .../core/powerdown/PowerDownManager.h | 6 +- .../powerdown/PowerDownManagerBankwise.cpp | 84 +- .../core/powerdown/PowerDownManagerBankwise.h | 5 +- .../powerdown/PowerDownManagerTimeout.cpp | 85 +- .../core/powerdown/PowerDownManagerTimeout.h | 3 +- .../PowerDownManagerTimeoutBankwise.cpp | 77 +- .../PowerDownManagerTimeoutBankwise.h | 3 +- .../controller/core/refresh/IRefreshManager.h | 11 +- .../core/refresh/RefreshManager.cpp | 244 +- .../controller/core/refresh/RefreshManager.h | 19 +- .../core/refresh/RefreshManagerBankwise.cpp | 70 +- .../core/refresh/RefreshManagerBankwise.h | 23 +- .../core/scheduling/ScheduledCommand.cpp | 34 +- .../core/scheduling/ScheduledCommand.h | 21 +- .../scheduling/checker/ActivateChecker.cpp | 92 +- .../core/scheduling/checker/ActivateChecker.h | 19 +- .../core/scheduling/checker/ICommandChecker.h | 4 +- .../scheduling/checker/PowerDownChecker.cpp | 97 +- .../scheduling/checker/PowerDownChecker.h | 15 +- .../checker/PrechargeAllChecker.cpp | 87 +- .../scheduling/checker/PrechargeAllChecker.h | 21 +- .../scheduling/checker/PrechargeChecker.cpp | 54 +- .../scheduling/checker/PrechargeChecker.h | 12 +- .../core/scheduling/checker/ReadChecker.cpp | 114 +- .../core/scheduling/checker/ReadChecker.h | 24 +- .../scheduling/checker/RefreshChecker.cpp | 128 +- .../core/scheduling/checker/RefreshChecker.h | 21 +- .../core/scheduling/checker/WriteChecker.cpp | 133 +- .../core/scheduling/checker/WriteChecker.h | 22 +- .../library/src/controller/scheduler/Fifo.cpp | 21 +- .../library/src/controller/scheduler/Fifo.h | 9 +- .../src/controller/scheduler/FifoStrict.cpp | 20 +- .../src/controller/scheduler/FifoStrict.h | 11 +- .../src/controller/scheduler/Fr_Fcfs.cpp | 42 +- .../src/controller/scheduler/Fr_Fcfs.h | 15 +- .../controller/scheduler/Fr_Fcfs_grouper.cpp | 140 +- .../controller/scheduler/Fr_Fcfs_grouper.h | 10 +- .../scheduler/Fr_Fcfs_read_priority.cpp | 84 +- .../scheduler/Fr_Fcfs_read_priority.h | 6 +- .../src/controller/scheduler/IScheduler.cpp | 29 +- .../src/controller/scheduler/IScheduler.h | 10 +- .../library/src/controller/scheduler/SMS.cpp | 167 +- .../library/src/controller/scheduler/SMS.h | 22 +- .../src/controller/scheduler/ThreadLoad.cpp | 56 +- .../src/controller/scheduler/ThreadLoad.h | 12 +- DRAMSys/library/src/error/ECC/Bit.cpp | 15 +- DRAMSys/library/src/error/ECC/Bit.h | 110 +- DRAMSys/library/src/error/ECC/ECC.cpp | 106 +- DRAMSys/library/src/error/ECC/ECC.h | 23 +- DRAMSys/library/src/error/ECC/ECC_Test.cpp | 176 +- DRAMSys/library/src/error/ECC/Word.cpp | 162 +- DRAMSys/library/src/error/ECC/Word.h | 70 +- DRAMSys/library/src/error/eccbaseclass.cpp | 30 +- DRAMSys/library/src/error/eccbaseclass.h | 19 +- DRAMSys/library/src/error/ecchamming.cpp | 60 +- DRAMSys/library/src/error/ecchamming.h | 11 +- DRAMSys/library/src/error/errormodel.cpp | 298 +-- DRAMSys/library/src/error/errormodel.h | 23 +- DRAMSys/library/src/simulation/Arbiter.h | 80 +- DRAMSys/library/src/simulation/DRAMSys.cpp | 139 +- DRAMSys/library/src/simulation/DRAMSys.h | 8 +- DRAMSys/library/src/simulation/Dram.h | 490 ++-- .../library/src/simulation/ExampleInitiator.h | 59 +- DRAMSys/library/src/simulation/IArbiter.h | 49 +- .../library/src/simulation/MemoryManager.cpp | 36 +- .../library/src/simulation/MemoryManager.h | 14 +- .../library/src/simulation/ReorderBuffer.h | 70 +- DRAMSys/library/src/simulation/Setup.cpp | 18 +- DRAMSys/library/src/simulation/Setup.h | 10 +- .../library/src/simulation/SimpleArbiter.h | 53 +- DRAMSys/library/src/simulation/StlPlayer.cpp | 41 +- DRAMSys/library/src/simulation/StlPlayer.h | 3 +- .../src/simulation/TemperatureController.cpp | 24 +- .../src/simulation/TemperatureController.h | 30 +- .../library/src/simulation/TraceGenerator.h | 15 +- .../library/src/simulation/TracePlayer.cpp | 50 +- DRAMSys/library/src/simulation/TracePlayer.h | 15 +- .../src/simulation/TracePlayerListener.h | 2 +- DRAMSys/library/src/simulation/TraceSetup.cpp | 43 +- DRAMSys/library/src/simulation/TraceSetup.h | 4 +- DRAMSys/simulator/main.cpp | 17 +- .../businessObjects/calculatedMetric.h | 12 +- .../traceAnalyzer/businessObjects/comment.h | 12 +- .../businessObjects/generalinfo.h | 15 +- .../businessObjects/phases/phase.cpp | 89 +- .../businessObjects/phases/phase.h | 304 ++- .../businessObjects/phases/phasefactory.cpp | 95 +- .../businessObjects/phases/phasefactory.h | 4 +- .../businessObjects/pythoncaller.cpp | 107 +- .../businessObjects/pythoncaller.h | 12 +- .../businessObjects/testresult.h | 19 +- .../businessObjects/timespan.cpp | 2 +- .../traceAnalyzer/businessObjects/timespan.h | 32 +- .../businessObjects/tracecalculatedmetrics.h | 25 +- .../businessObjects/tracetestresults.cpp | 5 +- .../businessObjects/tracetestresults.h | 17 +- .../traceAnalyzer/businessObjects/tracetime.h | 9 +- .../businessObjects/transaction.cpp | 27 +- .../businessObjects/transaction.h | 75 +- DRAMSys/traceAnalyzer/data/QueryTexts.h | 13 +- DRAMSys/traceAnalyzer/data/tracedb.cpp | 145 +- DRAMSys/traceAnalyzer/data/tracedb.h | 27 +- DRAMSys/traceAnalyzer/evaluationtool.cpp | 84 +- DRAMSys/traceAnalyzer/evaluationtool.h | 7 +- DRAMSys/traceAnalyzer/gototimedialog.cpp | 12 +- DRAMSys/traceAnalyzer/gototimedialog.h | 6 +- DRAMSys/traceAnalyzer/main.cpp | 25 +- DRAMSys/traceAnalyzer/mainwindow.cpp | 22 +- DRAMSys/traceAnalyzer/mainwindow.h | 6 +- DRAMSys/traceAnalyzer/markerplotitem.cpp | 7 +- DRAMSys/traceAnalyzer/markerplotitem.h | 6 +- .../presentation/commenttreewidget.cpp | 35 +- .../presentation/commenttreewidget.h | 16 +- .../presentation/debugmessagetreewidget.cpp | 49 +- .../presentation/debugmessagetreewidget.h | 14 +- .../presentation/pornotracescroller.cpp | 120 +- .../presentation/pornotracescroller.h | 8 +- .../selectedtransactiontreewidget.cpp | 6 +- .../selectedtransactiontreewidget.h | 5 +- .../presentation/tracePlotMouseLabel.cpp | 20 +- .../presentation/tracePlotMouseLabel.h | 14 +- .../presentation/tracedrawing.cpp | 73 +- .../traceAnalyzer/presentation/tracedrawing.h | 12 +- .../presentation/tracedrawingproperties.h | 26 +- .../presentation/tracemetrictreewidget.cpp | 29 +- .../presentation/tracemetrictreewidget.h | 6 +- .../presentation/tracenavigator.cpp | 91 +- .../presentation/tracenavigator.h | 35 +- .../traceAnalyzer/presentation/traceplot.cpp | 276 +-- .../traceAnalyzer/presentation/traceplot.h | 54 +- .../presentation/traceplotitem.cpp | 17 +- .../presentation/traceplotitem.h | 15 +- .../presentation/tracetesttreewidget.cpp | 38 +- .../presentation/tracetesttreewidget.h | 9 +- .../presentation/transactiontreewidget.cpp | 51 +- .../presentation/transactiontreewidget.h | 10 +- .../presentation/util/clkgrid.cpp | 31 +- .../traceAnalyzer/presentation/util/clkgrid.h | 3 +- .../presentation/util/colorgenerator.cpp | 62 +- .../presentation/util/customlabelscaledraw.h | 12 +- .../presentation/util/engineeringScaleDraw.h | 10 +- .../presentation/util/testlight.cpp | 8 +- DRAMSys/traceAnalyzer/queryeditor.cpp | 16 +- DRAMSys/traceAnalyzer/queryeditor.h | 2 +- DRAMSys/traceAnalyzer/schedulerwrapper.h | 18 +- DRAMSys/traceAnalyzer/selectmetrics.cpp | 39 +- DRAMSys/traceAnalyzer/selectmetrics.h | 4 +- DRAMSys/traceAnalyzer/traceanalyzer.cpp | 42 +- DRAMSys/traceAnalyzer/traceanalyzer.h | 7 +- DRAMSys/traceAnalyzer/tracefiletab.cpp | 21 +- DRAMSys/traceAnalyzer/tracefiletab.h | 9 +- 191 files changed, 6058 insertions(+), 5675 deletions(-) diff --git a/DRAMSys/gem5/main.cpp b/DRAMSys/gem5/main.cpp index 8a3b1222..c152b377 100644 --- a/DRAMSys/gem5/main.cpp +++ b/DRAMSys/gem5/main.cpp @@ -55,7 +55,7 @@ class Gem5SimControlDRAMsys: public Gem5SystemC::Gem5SimControl { public: Gem5SimControlDRAMsys(string configFile) : - Gem5SystemC::Gem5SimControl("gem5",configFile,0,"MemoryAccess") + Gem5SystemC::Gem5SimControl("gem5", configFile, 0, "MemoryAccess") { } @@ -66,37 +66,38 @@ public: }; -struct AddressOffset: sc_module -{ - private: +struct AddressOffset: sc_module { +private: unsigned long long int offset; - public: +public: tlm_utils::simple_target_socket t_socket; tlm_utils::simple_initiator_socket i_socket; - AddressOffset(sc_module_name, unsigned long long int o) : offset(o),t_socket("t_socket"),i_socket("i_socket") + AddressOffset(sc_module_name, unsigned long long int o) : offset(o), + t_socket("t_socket"), i_socket("i_socket") { - t_socket.register_nb_transport_fw(this,&AddressOffset::nb_transport_fw); - t_socket.register_transport_dbg(this,&AddressOffset::transport_dbg); - t_socket.register_b_transport(this,&AddressOffset::b_transport); - i_socket.register_nb_transport_bw(this,&AddressOffset::nb_transport_bw); + t_socket.register_nb_transport_fw(this, &AddressOffset::nb_transport_fw); + t_socket.register_transport_dbg(this, &AddressOffset::transport_dbg); + t_socket.register_b_transport(this, &AddressOffset::b_transport); + i_socket.register_nb_transport_bw(this, &AddressOffset::nb_transport_bw); } //Forward Interface - tlm::tlm_sync_enum nb_transport_fw(tlm_generic_payload &trans, tlm_phase &phase, sc_time &delay) + tlm::tlm_sync_enum nb_transport_fw(tlm_generic_payload &trans, tlm_phase &phase, + sc_time &delay) { //std::cout << "NB "<< this->name() <<": " << trans.get_address() << " -" << offset; - trans.set_address(trans.get_address()-offset); + trans.set_address(trans.get_address() - offset); //std::cout << " = " << trans.get_address() << std::endl; - return i_socket->nb_transport_fw(trans,phase,delay); + return i_socket->nb_transport_fw(trans, phase, delay); } unsigned int transport_dbg(tlm::tlm_generic_payload &trans) { // adjust address offset: //std::cout << "Debug "<< this->name() <<": " << trans.get_address() << " -" << offset; - trans.set_address(trans.get_address()-offset); + trans.set_address(trans.get_address() - offset); //std::cout << " = " << trans.get_address() << std::endl; return i_socket->transport_dbg(trans); } @@ -105,16 +106,17 @@ struct AddressOffset: sc_module { // adjust address offset: //std::cout << "B "<< this->name() <<": " << trans.get_address() << " -" << offset; - trans.set_address(trans.get_address()-offset); + trans.set_address(trans.get_address() - offset); //std::cout << " = " << trans.get_address() << std::endl; i_socket->b_transport(trans, delay); } //Backward Interface - tlm::tlm_sync_enum nb_transport_bw(tlm_generic_payload &trans, tlm_phase &phase, sc_time &delay) + tlm::tlm_sync_enum nb_transport_bw(tlm_generic_payload &trans, tlm_phase &phase, + sc_time &delay) { //trans.set_address(trans.get_address()+offset); - return t_socket->nb_transport_bw(trans,phase,delay); + return t_socket->nb_transport_bw(trans, phase, delay); } }; @@ -132,18 +134,15 @@ int sc_main(int argc, char **argv) string gem5ConfigFile; string resources; - if(argc > 1) - { + if (argc > 1) { // Get path of resources: resources = pathOfFile(argv[0]) - + string("/../../DRAMSys/library/resources/"); + + string("/../../DRAMSys/library/resources/"); SimulationXML = argv[1]; gem5ConfigFile = argv[2]; - } - else - { - SC_REPORT_FATAL("sc_main","Please provide configuration files"); + } else { + SC_REPORT_FATAL("sc_main", "Please provide configuration files"); } // Instantiate DRAMSys: @@ -177,8 +176,8 @@ int sc_main(int argc, char **argv) Gem5SystemC::Gem5SlaveTransactor dramInterface("transactor1", "transactor1"); Gem5SystemC::Gem5SlaveTransactor nvmInterface("transactor2", "transactor2"); - AddressOffset nvmOffset("nvmOffset",0); - AddressOffset dramOffset("dramOffset", (2147483648-67108863));//+67108863); + AddressOffset nvmOffset("nvmOffset", 0); + AddressOffset dramOffset("dramOffset", (2147483648 - 67108863)); //+67108863); dramInterface.socket.bind(dramOffset.t_socket); dramOffset.i_socket.bind(dramSys.tSocket); // ID0 @@ -194,9 +193,8 @@ int sc_main(int argc, char **argv) sc_core::sc_set_stop_mode(SC_STOP_FINISH_DELTA); sc_core::sc_start(); - if (!sc_core::sc_end_of_simulation_invoked()) - { - SC_REPORT_INFO("sc_main","Simulation stopped without explicit sc_stop()"); + if (!sc_core::sc_end_of_simulation_invoked()) { + SC_REPORT_INFO("sc_main", "Simulation stopped without explicit sc_stop()"); sc_core::sc_stop(); } diff --git a/DRAMSys/library/src/common/AddressDecoder.cpp b/DRAMSys/library/src/common/AddressDecoder.cpp index 266e9bca..0f91f62d 100644 --- a/DRAMSys/library/src/common/AddressDecoder.cpp +++ b/DRAMSys/library/src/common/AddressDecoder.cpp @@ -37,9 +37,9 @@ #include "xmlAddressdecoder.h" #include "jsonAddressDecoder.h" -AddressDecoder* AddressDecoder::m_pInstance = nullptr; +AddressDecoder *AddressDecoder::m_pInstance = nullptr; -AddressDecoder& AddressDecoder::getInstance() +AddressDecoder &AddressDecoder::getInstance() { assert(m_pInstance != nullptr); return *m_pInstance; @@ -48,8 +48,7 @@ AddressDecoder& AddressDecoder::getInstance() void AddressDecoder::createInstance(Type t) { assert(m_pInstance == nullptr); - switch(t) - { + switch (t) { case Type::XML: m_pInstance = new xmlAddressDecoder; break; diff --git a/DRAMSys/library/src/common/AddressDecoder.h b/DRAMSys/library/src/common/AddressDecoder.h index be74980f..40513fc2 100644 --- a/DRAMSys/library/src/common/AddressDecoder.h +++ b/DRAMSys/library/src/common/AddressDecoder.h @@ -42,15 +42,14 @@ #include #include -struct DecodedAddress -{ +struct DecodedAddress { DecodedAddress() : channel(0), - rank(0), - bankgroup(0), - row(0), - bank(0), - column(0), - bytes(0) + rank(0), + bankgroup(0), + row(0), + bank(0), + column(0), + bytes(0) { } @@ -66,8 +65,7 @@ struct DecodedAddress class AddressDecoder { public: - enum class Type - { + enum class Type { XML, JSON }; @@ -75,9 +73,9 @@ public: protected: AddressDecoder(); - static AddressDecoder* m_pInstance; + static AddressDecoder *m_pInstance; public: - static AddressDecoder& getInstance(); + static AddressDecoder &getInstance(); static void createInstance(Type t); virtual void setConfiguration(std::string url) = 0; diff --git a/DRAMSys/library/src/common/DebugManager.cpp b/DRAMSys/library/src/common/DebugManager.cpp index f84146c6..51e2380e 100644 --- a/DRAMSys/library/src/common/DebugManager.cpp +++ b/DRAMSys/library/src/common/DebugManager.cpp @@ -40,37 +40,38 @@ using namespace std; void DebugManager::printDebugMessage(string sender, string message) { - if(Configuration::getInstance().Debug) - { + if (Configuration::getInstance().Debug) { if (writeToConsole) - cout << " at " << sc_time_stamp() << "\t in " << sender << "\t: " << message << endl; + cout << " at " << sc_time_stamp() << "\t in " << sender << "\t: " << message << + endl; if (writeToFile && debugFile) - debugFile << " at " << sc_time_stamp() << " in " << sender << "\t: " << message << "\n"; + debugFile << " at " << sc_time_stamp() << " in " << sender << "\t: " << message + << "\n"; } } void DebugManager::printMessage(string sender, string message) { - cout << " at " << sc_time_stamp() << "\t in " << sender << "\t: " << message << endl; + cout << " at " << sc_time_stamp() << "\t in " << sender << "\t: " << message << + endl; } void DebugManager::openDebugFile(string filename) { - if(debugFile) + if (debugFile) debugFile.close(); debugFile.open(filename); } DebugManager::DebugManager() : - writeToConsole(true), writeToFile(true) + writeToConsole(true), writeToFile(true) { } DebugManager::~DebugManager() { - if (writeToFile) - { + if (writeToFile) { debugFile.flush(); debugFile.close(); } diff --git a/DRAMSys/library/src/common/DebugManager.h b/DRAMSys/library/src/common/DebugManager.h index 69740367..be40527b 100644 --- a/DRAMSys/library/src/common/DebugManager.h +++ b/DRAMSys/library/src/common/DebugManager.h @@ -58,7 +58,7 @@ public: private: DebugManager(); - DebugManager(const DebugManager&){} + DebugManager(const DebugManager &) {} ofstream debugFile; }; diff --git a/DRAMSys/library/src/common/TlmRecorder.cpp b/DRAMSys/library/src/common/TlmRecorder.cpp index 1499d9a2..b75141a6 100644 --- a/DRAMSys/library/src/common/TlmRecorder.cpp +++ b/DRAMSys/library/src/common/TlmRecorder.cpp @@ -48,13 +48,16 @@ using namespace std; -TlmRecorder::TlmRecorder(sc_module_name /*name*/, string uri, string dbname, bool recenable) : sqlScriptURI(uri), dbName(dbname), recordingEnabled(recenable), totalNumTransactions(1), simulationTimeCoveredByRecording(SC_ZERO_TIME) +TlmRecorder::TlmRecorder(sc_module_name /*name*/, string uri, string dbname, + bool recenable) : sqlScriptURI(uri), dbName(dbname), + recordingEnabled(recenable), totalNumTransactions(1), + simulationTimeCoveredByRecording(SC_ZERO_TIME) { if (TlmRecorder::recordingEnabled == true) { recordedData.reserve(transactionCommitRate); setUpTransactionTerminatingPhases(); openDB(TlmRecorder::dbName.c_str()); - char * sErrMsg; + char *sErrMsg; sqlite3_exec(db, "PRAGMA main.page_size = 4096", NULL, NULL, &sErrMsg); sqlite3_exec(db, "PRAGMA main.cache_size=10000", NULL, NULL, &sErrMsg); sqlite3_exec(db, "PRAGMA main.locking_mode=EXCLUSIVE", NULL, NULL, &sErrMsg); @@ -83,10 +86,10 @@ void TlmRecorder::recordPower(double timeInSeconds, double averagePower) } } -void TlmRecorder::recordPhase(tlm::tlm_generic_payload& trans, tlm::tlm_phase phase, sc_time time) +void TlmRecorder::recordPhase(tlm::tlm_generic_payload &trans, + tlm::tlm_phase phase, sc_time time) { - if(TlmRecorder::recordingEnabled) - { + if (TlmRecorder::recordingEnabled) { if (currentTransactionsInSystem.count(&trans) == 0) introduceTransactionSystem(trans); @@ -94,17 +97,14 @@ void TlmRecorder::recordPhase(tlm::tlm_generic_payload& trans, tlm::tlm_phase ph string phaseBeginPrefix = "BEGIN_"; string phaseEndPrefix = "END_"; - if (phaseName.find(phaseBeginPrefix) != string::npos) - { + if (phaseName.find(phaseBeginPrefix) != string::npos) { phaseName.erase(0, phaseBeginPrefix.length()); assert(currentTransactionsInSystem.count(&trans) != 0); - currentTransactionsInSystem[&trans].insertPhase(phaseName,time); - } - else - { + currentTransactionsInSystem[&trans].insertPhase(phaseName, time); + } else { phaseName.erase(0, phaseEndPrefix.length()); assert(currentTransactionsInSystem.count(&trans) != 0); - currentTransactionsInSystem[&trans].setPhaseEnd(phaseName,time); + currentTransactionsInSystem[&trans].setPhaseEnd(phaseName, time); } bool phaseTerminatesTransaction = count(transactionTerminatingPhases.begin(), @@ -117,10 +117,10 @@ void TlmRecorder::recordPhase(tlm::tlm_generic_payload& trans, tlm::tlm_phase ph } -void TlmRecorder::updateDataStrobe(const sc_time& begin,const sc_time& end, tlm::tlm_generic_payload& trans) +void TlmRecorder::updateDataStrobe(const sc_time &begin, const sc_time &end, + tlm::tlm_generic_payload &trans) { - if(TlmRecorder::recordingEnabled) - { + if (TlmRecorder::recordingEnabled) { assert(currentTransactionsInSystem.count(&trans) != 0); currentTransactionsInSystem[&trans].timeOnDataStrobe.start = begin; currentTransactionsInSystem[&trans].timeOnDataStrobe.end = end; @@ -130,44 +130,48 @@ void TlmRecorder::updateDataStrobe(const sc_time& begin,const sc_time& end, tlm: void TlmRecorder::recordDebugMessage(std::string message, sc_time time) { - if(TlmRecorder::recordingEnabled) + if (TlmRecorder::recordingEnabled) insertDebugMessageInDB(message, time); } // ------------- internal ----------------------- -void TlmRecorder::introduceTransactionSystem(tlm::tlm_generic_payload& trans) +void TlmRecorder::introduceTransactionSystem(tlm::tlm_generic_payload &trans) { unsigned int id = totalNumTransactions++; currentTransactionsInSystem[&trans].id = id; currentTransactionsInSystem[&trans].address = trans.get_address(); currentTransactionsInSystem[&trans].burstlength = trans.get_streaming_width(); - currentTransactionsInSystem[&trans].dramExtension = DramExtension::getExtension(trans); + currentTransactionsInSystem[&trans].dramExtension = DramExtension::getExtension( + trans); - if(DramExtension::getExtension(trans).getThread().ID() == Controller::ControllerThreadId()) + if (DramExtension::getExtension(trans).getThread().ID() == + Controller::ControllerThreadId()) currentTransactionsInSystem[&trans].timeOfGeneration = SC_ZERO_TIME; else - currentTransactionsInSystem[&trans].timeOfGeneration = GenerationExtension::getExtension(&trans).TimeOfGeneration(); + currentTransactionsInSystem[&trans].timeOfGeneration = + GenerationExtension::getExtension(&trans).TimeOfGeneration(); - printDebugMessage("New transaction #" + to_string(id) + " generation time " + currentTransactionsInSystem[&trans].timeOfGeneration.to_string()); + printDebugMessage("New transaction #" + to_string(id) + " generation time " + + currentTransactionsInSystem[&trans].timeOfGeneration.to_string()); - if (id % transactionCommitRate == 0) - { + if (id % transactionCommitRate == 0) { printDebugMessage( - "Committing transactions " + to_string(id - transactionCommitRate + 1) + " - " - + to_string(id)); + "Committing transactions " + to_string(id - transactionCommitRate + 1) + " - " + + to_string(id)); commitRecordedDataToDB(); } } -void TlmRecorder::removeTransactionFromSystem(tlm::tlm_generic_payload& trans) +void TlmRecorder::removeTransactionFromSystem(tlm::tlm_generic_payload &trans) { assert(currentTransactionsInSystem.count(&trans) != 0); - printDebugMessage("Removing transaction #" + to_string(currentTransactionsInSystem[&trans].id)); + printDebugMessage("Removing transaction #" + to_string( + currentTransactionsInSystem[&trans].id)); - Transaction& recordingData = currentTransactionsInSystem[&trans]; + Transaction &recordingData = currentTransactionsInSystem[&trans]; recordedData.push_back(recordingData); currentTransactionsInSystem.erase(&trans); } @@ -175,18 +179,17 @@ void TlmRecorder::removeTransactionFromSystem(tlm::tlm_generic_payload& trans) void TlmRecorder::commitRecordedDataToDB() { sqlite3_exec(db, "BEGIN;", 0, 0, 0); - for(Transaction& recordingData: recordedData) - { + for (Transaction &recordingData : recordedData) { assert(recordingData.recordedPhases.size() > 0); insertTransactionInDB(recordingData); - for(Transaction::Phase& phaseData: recordingData.recordedPhases) - { - insertPhaseInDB(phaseData.name,phaseData.interval.start,phaseData.interval.end,recordingData.id); + for (Transaction::Phase &phaseData : recordingData.recordedPhases) { + insertPhaseInDB(phaseData.name, phaseData.interval.start, + phaseData.interval.end, recordingData.id); } sc_time rangeBegin = recordingData.recordedPhases.front().interval.start; sc_time rangeEnd = recordingData.recordedPhases.back().interval.end; - insertRangeInDB(recordingData.id,rangeBegin,rangeEnd); + insertRangeInDB(recordingData.id, rangeBegin, rangeEnd); } sqlite3_exec(db, "COMMIT;", 0, 0, 0); @@ -196,7 +199,7 @@ void TlmRecorder::commitRecordedDataToDB() void TlmRecorder::Transaction::insertPhase(string name, sc_time begin) { - recordedPhases.push_back(Phase(name,begin)); + recordedPhases.push_back(Phase(name, begin)); } void TlmRecorder::Transaction::setPhaseEnd(string name, sc_time end) @@ -204,32 +207,28 @@ void TlmRecorder::Transaction::setPhaseEnd(string name, sc_time end) // Find the latest recorder phase for that transaction with a matching name and update it // Note: Transaction have the same phase multiple times (e.g. PRE->ACT->REF->ACT->RD) only update the latest // one that has been recorder - for(int i = recordedPhases.size() - 1; i >= 0;i--) - { - Phase& data = recordedPhases[i]; - if(data.name == name) - { + for (int i = recordedPhases.size() - 1; i >= 0; i--) { + Phase &data = recordedPhases[i]; + if (data.name == name) { data.interval.end = end; return; } } - SC_REPORT_FATAL("Recording Error", "While trying to set phase end: phaseBegin has not been recorded"); + SC_REPORT_FATAL("Recording Error", + "While trying to set phase end: phaseBegin has not been recorded"); } void TlmRecorder::openDB(std::string name) { ifstream f(name.c_str()); - if(f.good()) - { - if(remove(name.c_str()) != 0) - { - SC_REPORT_FATAL("TlmRecorder", "Error deleting file" ); + if (f.good()) { + if (remove(name.c_str()) != 0) { + SC_REPORT_FATAL("TlmRecorder", "Error deleting file" ); } } - if (sqlite3_open(name.c_str(), &db) != SQLITE_OK) - { + if (sqlite3_open(name.c_str(), &db) != SQLITE_OK) { SC_REPORT_FATAL("Error in TraceRecorder", "Error cannot open database"); sqlite3_close(db); } @@ -247,117 +246,152 @@ void TlmRecorder::setUpTransactionTerminatingPhases() transactionTerminatingPhases.push_back(tlm::END_RESP); // Refresh All - transactionTerminatingPhases.push_back(static_cast(END_REFA)); + transactionTerminatingPhases.push_back(static_cast + (END_REFA)); // Refresh Bank - transactionTerminatingPhases.push_back(static_cast(END_REFB)); + transactionTerminatingPhases.push_back(static_cast + (END_REFB)); // Phases for Power Down - transactionTerminatingPhases.push_back(static_cast(END_PDNA)); - transactionTerminatingPhases.push_back(static_cast(END_PDNP)); - transactionTerminatingPhases.push_back(static_cast(END_SREF)); + transactionTerminatingPhases.push_back(static_cast + (END_PDNA)); + transactionTerminatingPhases.push_back(static_cast + (END_PDNP)); + transactionTerminatingPhases.push_back(static_cast + (END_SREF)); // Phases for Power Down Bankwise - transactionTerminatingPhases.push_back(static_cast(END_PDNAB)); - transactionTerminatingPhases.push_back(static_cast(END_PDNPB)); - transactionTerminatingPhases.push_back(static_cast(END_SREFB)); + transactionTerminatingPhases.push_back(static_cast + (END_PDNAB)); + transactionTerminatingPhases.push_back(static_cast + (END_PDNPB)); + transactionTerminatingPhases.push_back(static_cast + (END_SREFB)); } void TlmRecorder::prepareSqlStatements() { insertTransactionString = - "INSERT INTO Transactions VALUES (:id,:rangeID,:address,:burstlength,:thread,:channel,:bank,:bankgroup,:row,:column,:dataStrobeBegin,:dataStrobeEnd, :timeOfGeneration,:command)"; + "INSERT INTO Transactions VALUES (:id,:rangeID,:address,:burstlength,:thread,:channel,:bank,:bankgroup,:row,:column,:dataStrobeBegin,:dataStrobeEnd, :timeOfGeneration,:command)"; insertRangeString = "INSERT INTO Ranges VALUES (:id,:begin,:end)"; updateRangeString = "UPDATE Ranges SET End = :end WHERE ID = :id"; - updateDataStrobeString = "UPDATE Transactions SET DataStrobeBegin = :begin, DataStrobeEnd = :end WHERE ID = :id"; + updateDataStrobeString = + "UPDATE Transactions SET DataStrobeBegin = :begin, DataStrobeEnd = :end WHERE ID = :id"; insertPhaseString = - "INSERT INTO Phases (PhaseName,PhaseBegin,PhaseEnd,Transact) VALUES (:name,:begin,:end,:transaction)"; + "INSERT INTO Phases (PhaseName,PhaseBegin,PhaseEnd,Transact) VALUES (:name,:begin,:end,:transaction)"; updatePhaseString = - "UPDATE Phases SET PhaseEnd = :end WHERE Transact = :trans AND PhaseName = :name"; + "UPDATE Phases SET PhaseEnd = :end WHERE Transact = :trans AND PhaseName = :name"; insertGeneralInfoString = - "INSERT INTO GeneralInfo (NumberOfTransactions,TraceEnd,NumberOfBanks,clk,UnitOfTime,MCconfig,Memspec,Traces, WindowSize, FlexibleRefresh, MaxRefBurst, ControllerThread) VALUES" - "(:numberOfTransactions,:end,:numberOfBanks,:clk,:unitOfTime,:mcconfig,:memspec,:traces,:windowSize, :flexibleRefresh, :maxRefBurst, :controllerThread)"; - insertDebugMessageString = "INSERT INTO DebugMessages (Time,Message) Values (:time,:message)"; + "INSERT INTO GeneralInfo (NumberOfTransactions,TraceEnd,NumberOfBanks,clk,UnitOfTime,MCconfig,Memspec,Traces, WindowSize, FlexibleRefresh, MaxRefBurst, ControllerThread) VALUES" + "(:numberOfTransactions,:end,:numberOfBanks,:clk,:unitOfTime,:mcconfig,:memspec,:traces,:windowSize, :flexibleRefresh, :maxRefBurst, :controllerThread)"; + insertDebugMessageString = + "INSERT INTO DebugMessages (Time,Message) Values (:time,:message)"; insertPowerString = "INSERT INTO Power VALUES (:time,:averagePower)"; - sqlite3_prepare_v2(db, insertTransactionString.c_str(), -1, &insertTransactionStatement, 0); + sqlite3_prepare_v2(db, insertTransactionString.c_str(), -1, + &insertTransactionStatement, 0); sqlite3_prepare_v2(db, insertRangeString.c_str(), -1, &insertRangeStatement, 0); sqlite3_prepare_v2(db, updateRangeString.c_str(), -1, &updateRangeStatement, 0); sqlite3_prepare_v2(db, insertPhaseString.c_str(), -1, &insertPhaseStatement, 0); sqlite3_prepare_v2(db, updatePhaseString.c_str(), -1, &updatePhaseStatement, 0); - sqlite3_prepare_v2(db, updateDataStrobeString.c_str(), -1, &updateDataStrobeStatement, 0); - sqlite3_prepare_v2(db, insertGeneralInfoString.c_str(), -1, &insertGeneralInfoStatement, 0); - sqlite3_prepare_v2(db, insertDebugMessageString.c_str(), -1, &insertDebugMessageStatement, 0); + sqlite3_prepare_v2(db, updateDataStrobeString.c_str(), -1, + &updateDataStrobeStatement, 0); + sqlite3_prepare_v2(db, insertGeneralInfoString.c_str(), -1, + &insertGeneralInfoStatement, 0); + sqlite3_prepare_v2(db, insertDebugMessageString.c_str(), -1, + &insertDebugMessageStatement, 0); sqlite3_prepare_v2(db, insertPowerString.c_str(), -1, &insertPowerStatement, 0); } -void TlmRecorder::insertDebugMessageInDB(string message, const sc_time& time) +void TlmRecorder::insertDebugMessageInDB(string message, const sc_time &time) { sqlite3_bind_int64(insertDebugMessageStatement, 1, time.value()); - sqlite3_bind_text(insertDebugMessageStatement, 2, message.c_str(), message.length(), 0); + sqlite3_bind_text(insertDebugMessageStatement, 2, message.c_str(), + message.length(), 0); executeSqlStatement(insertDebugMessageStatement); } void TlmRecorder::insertGeneralInfo() { sqlite3_bind_int64(insertGeneralInfoStatement, 1, totalNumTransactions - 1); - sqlite3_bind_int64(insertGeneralInfoStatement, 2, simulationTimeCoveredByRecording.value()); + sqlite3_bind_int64(insertGeneralInfoStatement, 2, + simulationTimeCoveredByRecording.value()); sqlite3_bind_int(insertGeneralInfoStatement, 3, Configuration::getInstance().memSpec.NumberOfBanks); - sqlite3_bind_int(insertGeneralInfoStatement, 4, Configuration::getInstance().memSpec.clk.value()); + sqlite3_bind_int(insertGeneralInfoStatement, 4, + Configuration::getInstance().memSpec.clk.value()); sqlite3_bind_text(insertGeneralInfoStatement, 5, "PS", 2, NULL); - sqlite3_bind_text(insertGeneralInfoStatement, 6, mcconfig.c_str(), mcconfig.length(), NULL); - sqlite3_bind_text(insertGeneralInfoStatement, 7, memspec.c_str(), memspec.length(), NULL); - sqlite3_bind_text(insertGeneralInfoStatement, 8, traces.c_str(), traces.length(), NULL); + sqlite3_bind_text(insertGeneralInfoStatement, 6, mcconfig.c_str(), + mcconfig.length(), NULL); + sqlite3_bind_text(insertGeneralInfoStatement, 7, memspec.c_str(), + memspec.length(), NULL); + sqlite3_bind_text(insertGeneralInfoStatement, 8, traces.c_str(), + traces.length(), NULL); if (!Configuration::getInstance().EnableWindowing) sqlite3_bind_int64(insertGeneralInfoStatement, 9, 0); else - sqlite3_bind_int64(insertGeneralInfoStatement, 9, (Configuration::getInstance().memSpec.clk*Configuration::getInstance().WindowSize).value()); - if (Configuration::getInstance().ControllerCoreEnableRefPostpone || Configuration::getInstance().ControllerCoreEnableRefPullIn) - { - sqlite3_bind_int(insertGeneralInfoStatement, 10, 1); - sqlite3_bind_int(insertGeneralInfoStatement, 11, std::max(Configuration::getInstance().ControllerCoreMaxPulledInARCmd, Configuration::getInstance().ControllerCoreMaxPostponedARCmd)); + sqlite3_bind_int64(insertGeneralInfoStatement, 9, + (Configuration::getInstance().memSpec.clk * + Configuration::getInstance().WindowSize).value()); + if (Configuration::getInstance().ControllerCoreEnableRefPostpone + || Configuration::getInstance().ControllerCoreEnableRefPullIn) { + sqlite3_bind_int(insertGeneralInfoStatement, 10, 1); + sqlite3_bind_int(insertGeneralInfoStatement, 11, + std::max(Configuration::getInstance().ControllerCoreMaxPulledInARCmd, + Configuration::getInstance().ControllerCoreMaxPostponedARCmd)); + } else { + sqlite3_bind_int(insertGeneralInfoStatement, 10, 0); + sqlite3_bind_int(insertGeneralInfoStatement, 11, 0); } - else - { - sqlite3_bind_int(insertGeneralInfoStatement, 10, 0); - sqlite3_bind_int(insertGeneralInfoStatement, 11, 0); - } - sqlite3_bind_int(insertGeneralInfoStatement, 12, Controller::ControllerThreadId()); ; + sqlite3_bind_int(insertGeneralInfoStatement, 12, + Controller::ControllerThreadId()); ; executeSqlStatement(insertGeneralInfoStatement); } -void TlmRecorder::insertTransactionInDB(Transaction& recordingData) +void TlmRecorder::insertTransactionInDB(Transaction &recordingData) { sqlite3_bind_int(insertTransactionStatement, 1, recordingData.id); sqlite3_bind_int(insertTransactionStatement, 2, recordingData.id); sqlite3_bind_int(insertTransactionStatement, 3, recordingData.address); sqlite3_bind_int(insertTransactionStatement, 4, recordingData.burstlength); - sqlite3_bind_int(insertTransactionStatement, 5, recordingData.dramExtension.getThread().ID()); - sqlite3_bind_int(insertTransactionStatement, 6, recordingData.dramExtension.getChannel().ID()); - sqlite3_bind_int(insertTransactionStatement, 7, recordingData.dramExtension.getBank().ID()); - sqlite3_bind_int(insertTransactionStatement, 8, recordingData.dramExtension.getBankGroup().ID()); - sqlite3_bind_int(insertTransactionStatement, 9, recordingData.dramExtension.getRow().ID()); - sqlite3_bind_int(insertTransactionStatement, 10, recordingData.dramExtension.getColumn().ID()); - sqlite3_bind_int64(insertTransactionStatement, 11, recordingData.timeOnDataStrobe.start.value()); - sqlite3_bind_int64(insertTransactionStatement, 12, recordingData.timeOnDataStrobe.end.value()); - sqlite3_bind_int64(insertTransactionStatement, 13, recordingData.timeOfGeneration.value()); + sqlite3_bind_int(insertTransactionStatement, 5, + recordingData.dramExtension.getThread().ID()); + sqlite3_bind_int(insertTransactionStatement, 6, + recordingData.dramExtension.getChannel().ID()); + sqlite3_bind_int(insertTransactionStatement, 7, + recordingData.dramExtension.getBank().ID()); + sqlite3_bind_int(insertTransactionStatement, 8, + recordingData.dramExtension.getBankGroup().ID()); + sqlite3_bind_int(insertTransactionStatement, 9, + recordingData.dramExtension.getRow().ID()); + sqlite3_bind_int(insertTransactionStatement, 10, + recordingData.dramExtension.getColumn().ID()); + sqlite3_bind_int64(insertTransactionStatement, 11, + recordingData.timeOnDataStrobe.start.value()); + sqlite3_bind_int64(insertTransactionStatement, 12, + recordingData.timeOnDataStrobe.end.value()); + sqlite3_bind_int64(insertTransactionStatement, 13, + recordingData.timeOfGeneration.value()); executeSqlStatement(insertTransactionStatement); } -void TlmRecorder::insertRangeInDB(unsigned int id, const sc_time& begin, const sc_time& end) +void TlmRecorder::insertRangeInDB(unsigned int id, const sc_time &begin, + const sc_time &end) { sqlite3_bind_int(insertRangeStatement, 1, id); sqlite3_bind_int64(insertRangeStatement, 2, begin.value()); sqlite3_bind_int64(insertRangeStatement, 3, end.value()); executeSqlStatement(insertRangeStatement); } -void TlmRecorder::insertPhaseInDB(string phaseName, const sc_time& begin, const sc_time& end, +void TlmRecorder::insertPhaseInDB(string phaseName, const sc_time &begin, + const sc_time &end, unsigned int transactionID) { - sqlite3_bind_text(insertPhaseStatement, 1, phaseName.c_str(), phaseName.length(), 0); + sqlite3_bind_text(insertPhaseStatement, 1, phaseName.c_str(), + phaseName.length(), 0); sqlite3_bind_int64(insertPhaseStatement, 2, begin.value()); sqlite3_bind_int64(insertPhaseStatement, 3, end.value()); sqlite3_bind_int(insertPhaseStatement, 4, transactionID); @@ -365,12 +399,12 @@ void TlmRecorder::insertPhaseInDB(string phaseName, const sc_time& begin, const } -void TlmRecorder::executeSqlStatement(sqlite3_stmt* statement) +void TlmRecorder::executeSqlStatement(sqlite3_stmt *statement) { int errorCode = sqlite3_step(statement); - if (errorCode != SQLITE_DONE) - { - reportFatal("Error in TraceRecorder", string("Could not execute statement. Error code: ") + to_string(errorCode)); + if (errorCode != SQLITE_DONE) { + reportFatal("Error in TraceRecorder", + string("Could not execute statement. Error code: ") + to_string(errorCode)); } sqlite3_reset(statement); } @@ -379,10 +413,9 @@ void TlmRecorder::executeSqlCommand(string command) { printDebugMessage("Creating database by running provided sql script"); - char * errMsg = 0; + char *errMsg = 0; int rc = sqlite3_exec(db, command.c_str(), NULL, 0, &errMsg); - if (rc != SQLITE_OK) - { + if (rc != SQLITE_OK) { SC_REPORT_FATAL("SQLITE Error", errMsg); sqlite3_free(errMsg); } @@ -397,12 +430,12 @@ void TlmRecorder::printDebugMessage(std::string message) void TlmRecorder::closeConnection() { - if(TlmRecorder::recordingEnabled) - { + if (TlmRecorder::recordingEnabled) { commitRecordedDataToDB(); insertGeneralInfo(); printDebugMessage( - "Number of transactions written to DB: " + std::to_string(totalNumTransactions - 1)); + "Number of transactions written to DB: " + std::to_string( + totalNumTransactions - 1)); printDebugMessage("tlmPhaseRecorder:\tEnd Recording"); sqlite3_finalize(insertTransactionStatement); sqlite3_finalize(insertRangeStatement); diff --git a/DRAMSys/library/src/common/TlmRecorder.h b/DRAMSys/library/src/common/TlmRecorder.h index bec9e68a..f984dc4a 100644 --- a/DRAMSys/library/src/common/TlmRecorder.h +++ b/DRAMSys/library/src/common/TlmRecorder.h @@ -55,7 +55,8 @@ using namespace std; -class TlmRecorder : public sc_module { +class TlmRecorder : public sc_module +{ public: std::string sqlScriptURI; std::string dbName; @@ -64,22 +65,32 @@ public: TlmRecorder(sc_module_name /*name*/, string uri, string dbname, bool recenable); ~TlmRecorder(); - void recordMCconfig(string mcconfig){this->mcconfig = mcconfig;} - void recordMemspec(string memspec){this->memspec = memspec;} - void recordTracenames(string traces){this->traces = traces;} + void recordMCconfig(string mcconfig) + { + this->mcconfig = mcconfig; + } + void recordMemspec(string memspec) + { + this->memspec = memspec; + } + void recordTracenames(string traces) + { + this->traces = traces; + } - void recordPhase(tlm::tlm_generic_payload &trans, tlm::tlm_phase phase, sc_time time); + void recordPhase(tlm::tlm_generic_payload &trans, tlm::tlm_phase phase, + sc_time time); void recordPower(double timeInSeconds, double averagePower); void recordDebugMessage(std::string message, sc_time time); - void updateDataStrobe(const sc_time& begin, const sc_time& end, tlm::tlm_generic_payload& trans); + void updateDataStrobe(const sc_time &begin, const sc_time &end, + tlm::tlm_generic_payload &trans); void closeConnection(); private: - struct Transaction - { - Transaction(){} - Transaction(unsigned int id):id(id){} + struct Transaction { + Transaction() {} + Transaction(unsigned int id): id(id) {} unsigned int id; unsigned int address; @@ -88,53 +99,56 @@ private: sc_time timeOfGeneration; TimeInterval timeOnDataStrobe; - struct Phase - { - Phase(string name,sc_time begin): name(name), interval(begin,SC_ZERO_TIME){} + struct Phase { + Phase(string name, sc_time begin): name(name), interval(begin, SC_ZERO_TIME) {} string name; TimeInterval interval; }; std::vector recordedPhases; - void insertPhase(string name,sc_time begin); - void setPhaseEnd(string name,sc_time end); + void insertPhase(string name, sc_time begin); + void setPhaseEnd(string name, sc_time end); }; - std::string mcconfig,memspec,traces; + std::string mcconfig, memspec, traces; void prepareSqlStatements(); void executeSqlCommand(std::string command); - void executeSqlStatement(sqlite3_stmt* statement); + void executeSqlStatement(sqlite3_stmt *statement); void openDB(std::string name); void createTables(std::string pathToURI); void setUpTransactionTerminatingPhases(); - void introduceTransactionSystem(tlm::tlm_generic_payload& trans); - void removeTransactionFromSystem(tlm::tlm_generic_payload& trans); + void introduceTransactionSystem(tlm::tlm_generic_payload &trans); + void removeTransactionFromSystem(tlm::tlm_generic_payload &trans); void commitRecordedDataToDB(); void insertGeneralInfo(); - void insertTransactionInDB(Transaction& recordingData); - void insertRangeInDB(unsigned int id, const sc_time& begin, const sc_time& end); - void insertPhaseInDB(string phaseName, const sc_time& begin, const sc_time& end, unsigned int transactionID); - void insertDebugMessageInDB(string message, const sc_time& time); + void insertTransactionInDB(Transaction &recordingData); + void insertRangeInDB(unsigned int id, const sc_time &begin, const sc_time &end); + void insertPhaseInDB(string phaseName, const sc_time &begin, const sc_time &end, + unsigned int transactionID); + void insertDebugMessageInDB(string message, const sc_time &time); void printDebugMessage(std::string message); static const int transactionCommitRate = 1000; vector recordedData; - map currentTransactionsInSystem; + map currentTransactionsInSystem; unsigned int totalNumTransactions; sc_time simulationTimeCoveredByRecording; std::vector transactionTerminatingPhases; sqlite3 *db = NULL; - sqlite3_stmt *insertTransactionStatement, *insertRangeStatement, *updateRangeStatement, - *insertPhaseStatement, *updatePhaseStatement, *insertGeneralInfoStatement, *insertDebugMessageStatement, *updateDataStrobeStatement, *insertPowerStatement; - std::string insertTransactionString, insertRangeString, updateRangeString, insertPhaseString, updatePhaseString, insertGeneralInfoString, - insertDebugMessageString, updateDataStrobeString, insertPowerString; + sqlite3_stmt *insertTransactionStatement, *insertRangeStatement, + *updateRangeStatement, + *insertPhaseStatement, *updatePhaseStatement, *insertGeneralInfoStatement, + *insertDebugMessageStatement, *updateDataStrobeStatement, *insertPowerStatement; + std::string insertTransactionString, insertRangeString, updateRangeString, + insertPhaseString, updatePhaseString, insertGeneralInfoString, + insertDebugMessageString, updateDataStrobeString, insertPowerString; }; #endif diff --git a/DRAMSys/library/src/common/Utils.cpp b/DRAMSys/library/src/common/Utils.cpp index 18bd282a..6634201b 100644 --- a/DRAMSys/library/src/common/Utils.cpp +++ b/DRAMSys/library/src/common/Utils.cpp @@ -52,7 +52,8 @@ bool TimeInterval::timeIsInInterval(sc_time time) bool TimeInterval::intersects(TimeInterval other) { - return other.timeIsInInterval(this->start) || this->timeIsInInterval(other.start); + return other.timeIsInInterval(this->start) + || this->timeIsInInterval(other.start); } sc_time getDistance(sc_time a, sc_time b) @@ -76,17 +77,16 @@ std::string phaseNameToString(tlm::tlm_phase phase) return str; } -unsigned int queryUIntParameter(XMLElement* node, string name) +unsigned int queryUIntParameter(XMLElement *node, string name) { int result = 0; - XMLElement* element; + XMLElement *element; for (element = node->FirstChildElement("parameter"); element != NULL; - element = element->NextSiblingElement("parameter")) - { - if (element->Attribute("id") == name) - { + element = element->NextSiblingElement("parameter")) { + if (element->Attribute("id") == name) { sc_assert(!strcmp(element->Attribute("type"), "uint")); - XMLError __attribute__((unused)) error = element->QueryIntAttribute("value", &result); + XMLError __attribute__((unused)) error = element->QueryIntAttribute("value", + &result); sc_assert(!error); return result; } @@ -96,31 +96,28 @@ unsigned int queryUIntParameter(XMLElement* node, string name) return 0; } -bool parameterExists(tinyxml2::XMLElement* node, std::string name) +bool parameterExists(tinyxml2::XMLElement *node, std::string name) { - XMLElement* element; + XMLElement *element; for (element = node->FirstChildElement("parameter"); element != NULL; - element = element->NextSiblingElement("parameter")) - { - if (element->Attribute("id") == name) - { + element = element->NextSiblingElement("parameter")) { + if (element->Attribute("id") == name) { return true; } } return false; } -double queryDoubleParameter(XMLElement* node, string name) +double queryDoubleParameter(XMLElement *node, string name) { double result = 0; - XMLElement* element; + XMLElement *element; for (element = node->FirstChildElement("parameter"); element != NULL; - element = element->NextSiblingElement("parameter")) - { - if (element->Attribute("id") == name) - { + element = element->NextSiblingElement("parameter")) { + if (element->Attribute("id") == name) { sc_assert(!strcmp(element->Attribute("type"), "double")); - XMLError __attribute__((unused)) error = element->QueryDoubleAttribute("value", &result); + XMLError __attribute__((unused)) error = element->QueryDoubleAttribute("value", + &result); sc_assert(!error); return result; } @@ -130,17 +127,16 @@ double queryDoubleParameter(XMLElement* node, string name) return 0; } -bool queryBoolParameter(XMLElement* node, string name) +bool queryBoolParameter(XMLElement *node, string name) { bool result = false; - XMLElement* element;// = node->FirstChildElement("parameter"); + XMLElement *element;// = node->FirstChildElement("parameter"); for (element = node->FirstChildElement("parameter"); element != NULL; - element = element->NextSiblingElement("parameter")) - { - if (element->Attribute("id") == name) - { + element = element->NextSiblingElement("parameter")) { + if (element->Attribute("id") == name) { sc_assert(!strcmp(element->Attribute("type"), "bool")); - XMLError __attribute__((unused)) error = element->QueryBoolAttribute("value", &result); + XMLError __attribute__((unused)) error = element->QueryBoolAttribute("value", + &result); sc_assert(!error); return result; } @@ -150,14 +146,12 @@ bool queryBoolParameter(XMLElement* node, string name) return 0; } -string queryStringParameter(XMLElement* node, string name) +string queryStringParameter(XMLElement *node, string name) { - XMLElement* element; + XMLElement *element; for (element = node->FirstChildElement("parameter"); element != NULL; - element = element->NextSiblingElement("parameter")) - { - if (element->Attribute("id") == name) - { + element = element->NextSiblingElement("parameter")) { + if (element->Attribute("id") == name) { return element->Attribute("value"); } } @@ -168,36 +162,57 @@ string queryStringParameter(XMLElement* node, string name) string errorToString(XMLError error) { - switch(error){ - case XML_NO_ERROR: return "no error"; case XML_NO_ATTRIBUTE: return "NO_ATTRIBUTE"; - case XML_WRONG_ATTRIBUTE_TYPE: return "WRONG_ATTRIBUTE_TYPE"; - case XML_ERROR_FILE_NOT_FOUND: return "FILE_NOT_FOUND"; - case XML_ERROR_FILE_COULD_NOT_BE_OPENED: return "FILE_COULD_NOT_BE_OPENED"; - case XML_ERROR_FILE_READ_ERROR: return "FILE_READ_ERROR"; - case XML_ERROR_ELEMENT_MISMATCH: return "ERROR_ELEMENT_MISMATCH"; - case XML_ERROR_PARSING_ELEMENT: return "ERROR_PARSING_ELEMENT"; - case XML_ERROR_PARSING_ATTRIBUTE: return "ERROR_PARSING_ATTRIBUTE"; - case XML_ERROR_IDENTIFYING_TAG: return "ERROR_IDENTIFYING_TAG"; - case XML_ERROR_PARSING_TEXT: return "ERROR_PARSING_TEXT"; - case XML_ERROR_PARSING_CDATA: return "ERROR_PARSING_CDATA"; - case XML_ERROR_PARSING_COMMENT: return "ERROR_PARSING_COMMENT"; - case XML_ERROR_PARSING_DECLARATION: return "ERROR_PARSING_DECLARATION"; - case XML_ERROR_PARSING_UNKNOWN: return "ERROR_PARSING_UNKNOWN"; - case XML_ERROR_EMPTY_DOCUMENT: return "ERROR_EMPTY_DOCUMENT"; - case XML_ERROR_MISMATCHED_ELEMENT: return "ERROR_MISMATCHED_ELEMENT"; - case XML_ERROR_PARSING: return "ERROR_PARSING"; - case XML_CAN_NOT_CONVERT_TEXT: return "CAN_NOT_CONVERT_TEXT"; - case XML_NO_TEXT_NODE: return "NO_TEXT_NODE"; - default: return ""; + switch (error) { + case XML_NO_ERROR: + return "no error"; + case XML_NO_ATTRIBUTE: + return "NO_ATTRIBUTE"; + case XML_WRONG_ATTRIBUTE_TYPE: + return "WRONG_ATTRIBUTE_TYPE"; + case XML_ERROR_FILE_NOT_FOUND: + return "FILE_NOT_FOUND"; + case XML_ERROR_FILE_COULD_NOT_BE_OPENED: + return "FILE_COULD_NOT_BE_OPENED"; + case XML_ERROR_FILE_READ_ERROR: + return "FILE_READ_ERROR"; + case XML_ERROR_ELEMENT_MISMATCH: + return "ERROR_ELEMENT_MISMATCH"; + case XML_ERROR_PARSING_ELEMENT: + return "ERROR_PARSING_ELEMENT"; + case XML_ERROR_PARSING_ATTRIBUTE: + return "ERROR_PARSING_ATTRIBUTE"; + case XML_ERROR_IDENTIFYING_TAG: + return "ERROR_IDENTIFYING_TAG"; + case XML_ERROR_PARSING_TEXT: + return "ERROR_PARSING_TEXT"; + case XML_ERROR_PARSING_CDATA: + return "ERROR_PARSING_CDATA"; + case XML_ERROR_PARSING_COMMENT: + return "ERROR_PARSING_COMMENT"; + case XML_ERROR_PARSING_DECLARATION: + return "ERROR_PARSING_DECLARATION"; + case XML_ERROR_PARSING_UNKNOWN: + return "ERROR_PARSING_UNKNOWN"; + case XML_ERROR_EMPTY_DOCUMENT: + return "ERROR_EMPTY_DOCUMENT"; + case XML_ERROR_MISMATCHED_ELEMENT: + return "ERROR_MISMATCHED_ELEMENT"; + case XML_ERROR_PARSING: + return "ERROR_PARSING"; + case XML_CAN_NOT_CONVERT_TEXT: + return "CAN_NOT_CONVERT_TEXT"; + case XML_NO_TEXT_NODE: + return "NO_TEXT_NODE"; + default: + return ""; } } -void loadXML(string uri, XMLDocument& doc) +void loadXML(string uri, XMLDocument &doc) { XMLError error = doc.LoadFile(uri.c_str()); - if (error) - { + if (error) { reportFatal("Configuration", "Error loading xml from: " + uri + " " + errorToString(error)); } @@ -207,8 +222,7 @@ string loadTextFileContents(string filename) { ifstream in(filename.c_str(), ios::in | ios::binary); - if (in) - { + if (in) { string contents; in.seekg(0, ios::end); contents.resize(in.tellg()); @@ -216,15 +230,13 @@ string loadTextFileContents(string filename) in.read(&contents[0], contents.size()); in.close(); return (contents); - } - else - { + } else { reportFatal("Error loading file", "Could not load textfile from " + filename); return ""; } } -void setUpDummy(tlm::tlm_generic_payload& payload, Bank& bank) +void setUpDummy(tlm::tlm_generic_payload &payload, Bank &bank) { payload.set_address(bank.getStartAddress()); payload.set_command(tlm::TLM_READ_COMMAND); @@ -233,7 +245,9 @@ void setUpDummy(tlm::tlm_generic_payload& payload, Bank& bank) payload.set_dmi_allowed(false); payload.set_byte_enable_length(0); payload.set_streaming_width(0); - payload.set_extension(new DramExtension(Thread(Controller::ControllerThreadId()), bank, BankGroup(0), Row(0), Column(0))); //payload takes ownership + payload.set_extension(new DramExtension(Thread( + Controller::ControllerThreadId()), bank, BankGroup(0), Row(0), + Column(0))); //payload takes ownership //TODO .. Dummies muessen noch banggruppe und rank sauber bekommen .. noch was ueberlegen!!! } @@ -242,15 +256,13 @@ std::string getFileName(std::string uri) // Remove directory if present. // Do this before extension removal incase directory has a period character. const size_t last_slash_idx = uri.find_last_of("\\/"); - if (std::string::npos != last_slash_idx) - { + if (std::string::npos != last_slash_idx) { uri.erase(0, last_slash_idx + 1); } // Remove extension if present. const size_t period_idx = uri.rfind('.'); - if (std::string::npos != period_idx) - { + if (std::string::npos != period_idx) { uri.erase(period_idx); } return uri; diff --git a/DRAMSys/library/src/common/Utils.h b/DRAMSys/library/src/common/Utils.h index 1e08cace..ac7a71a1 100644 --- a/DRAMSys/library/src/common/Utils.h +++ b/DRAMSys/library/src/common/Utils.h @@ -58,22 +58,23 @@ public: \ //TODO : move to timing specific header sc_time getDistance(sc_time a, sc_time b); -struct TimeInterval -{ - sc_time start,end; - TimeInterval() : start(SC_ZERO_TIME), end(SC_ZERO_TIME){} - TimeInterval(sc_time start,sc_time end) : start(start), end(end){} +struct TimeInterval { + sc_time start, end; + TimeInterval() : start(SC_ZERO_TIME), end(SC_ZERO_TIME) {} + TimeInterval(sc_time start, sc_time end) : start(start), end(end) {} - sc_time getLength() {return getDistance(start,end);} + sc_time getLength() + { + return getDistance(start, end); + } bool timeIsInInterval(sc_time time); bool intersects(TimeInterval other); }; template -inline Val getElementFromMap(const std::map& m, Key key) +inline Val getElementFromMap(const std::map &m, Key key) { - if (m.count(key) == 0) - { + if (m.count(key) == 0) { SC_REPORT_FATAL("Map", "Element not in map"); } @@ -81,17 +82,17 @@ inline Val getElementFromMap(const std::map& m, Key key) } template -bool isIn(const T& value, const std::vector& collection) +bool isIn(const T &value, const std::vector &collection) { - for (T t : collection) - { + for (T t : collection) { if (t == value) return true; } return false; } -constexpr const char headline[] = "========================================================="; +constexpr const char headline[] = + "========================================================="; static inline void loadbar(unsigned int x, unsigned int n, @@ -108,24 +109,24 @@ static inline void loadbar(unsigned int x, for (unsigned int x = 0; x < c; x++) std::cout << "█"; - if(rest >= 0 && rest < 0.125 && c != w) + if (rest >= 0 && rest < 0.125 && c != w) std::cout << " "; - if(rest >= 0.125 && rest < 2*0.125) + if (rest >= 0.125 && rest < 2 * 0.125) std::cout << "▏"; - if(rest >= 2*0.125 && rest < 3*0.125) + if (rest >= 2 * 0.125 && rest < 3 * 0.125) std::cout << "▎"; - if(rest >= 3*0.125 && rest < 4*0.125) + if (rest >= 3 * 0.125 && rest < 4 * 0.125) std::cout << "▍"; - if(rest >= 4*0.125 && rest < 5*0.125) + if (rest >= 4 * 0.125 && rest < 5 * 0.125) std::cout << "▌"; - if(rest >= 5*0.125 && rest < 6*0.125) + if (rest >= 5 * 0.125 && rest < 6 * 0.125) std::cout << "▋"; - if(rest >= 6*0.125 && rest < 7*0.125) + if (rest >= 6 * 0.125 && rest < 7 * 0.125) std::cout << "▊"; - if(rest >= 7*0.125 && rest < 8*0.125) + if (rest >= 7 * 0.125 && rest < 8 * 0.125) std::cout << "▉"; - for (unsigned int x = c; x < (w-1); x++) + for (unsigned int x = c; x < (w - 1); x++) std::cout << " "; std::cout << "|\r" << std::flush; } @@ -137,15 +138,15 @@ std::string phaseNameToString(tlm::tlm_phase phase); //TODO : Move to other source specific to xml std::string getFileName(std::string uri); -bool parameterExists(tinyxml2::XMLElement* node, std::string name); +bool parameterExists(tinyxml2::XMLElement *node, std::string name); std::string loadTextFileContents(std::string filename); -void loadXML(std::string uri, tinyxml2::XMLDocument& doc); -unsigned int queryUIntParameter(tinyxml2::XMLElement* node, std::string name); -std::string queryStringParameter(tinyxml2::XMLElement* node, std::string name); -bool queryBoolParameter(tinyxml2::XMLElement* node, std::string name); -double queryDoubleParameter(tinyxml2::XMLElement* node, std::string name); +void loadXML(std::string uri, tinyxml2::XMLDocument &doc); +unsigned int queryUIntParameter(tinyxml2::XMLElement *node, std::string name); +std::string queryStringParameter(tinyxml2::XMLElement *node, std::string name); +bool queryBoolParameter(tinyxml2::XMLElement *node, std::string name); +double queryDoubleParameter(tinyxml2::XMLElement *node, std::string name); -void setUpDummy(tlm::tlm_generic_payload& payload, Bank& bank); +void setUpDummy(tlm::tlm_generic_payload &payload, Bank &bank); #endif /* UTILS_COMMON_H_ */ diff --git a/DRAMSys/library/src/common/dramExtension.cpp b/DRAMSys/library/src/common/dramExtension.cpp index 6a19eb08..bfb7b7c4 100644 --- a/DRAMSys/library/src/common/dramExtension.cpp +++ b/DRAMSys/library/src/common/dramExtension.cpp @@ -48,26 +48,32 @@ DramExtension::DramExtension() : { } -DramExtension::DramExtension(const Thread &thread, const Bank &bank, const BankGroup &bankgroup, const Row &row, const Column &column, unsigned int burstlength) : - thread(thread), channel(0), bank(bank), bankgroup(bankgroup), row(row), column(column), burstlength(burstlength) +DramExtension::DramExtension(const Thread &thread, const Bank &bank, + const BankGroup &bankgroup, const Row &row, const Column &column, + unsigned int burstlength) : + thread(thread), channel(0), bank(bank), bankgroup(bankgroup), row(row), + column(column), burstlength(burstlength) { } -DramExtension::DramExtension(const Thread &thread, const Channel &channel, const Bank &bank, const BankGroup &bankgroup, const Row &row, const Column &column, unsigned int burstlength) : - thread(thread), channel(channel), bank(bank), bankgroup(bankgroup), row(row), column(column), burstlength(burstlength) +DramExtension::DramExtension(const Thread &thread, const Channel &channel, + const Bank &bank, const BankGroup &bankgroup, const Row &row, + const Column &column, unsigned int burstlength) : + thread(thread), channel(channel), bank(bank), bankgroup(bankgroup), row(row), + column(column), burstlength(burstlength) { } -DramExtension& DramExtension::getExtension(const tlm_generic_payload *payload) +DramExtension &DramExtension::getExtension(const tlm_generic_payload *payload) { DramExtension *result = NULL; payload->get_extension(result); - sc_assert(result!=NULL); + sc_assert(result != NULL); return *result; } -DramExtension& DramExtension::getExtension(const tlm_generic_payload &payload) +DramExtension &DramExtension::getExtension(const tlm_generic_payload &payload) { return DramExtension::getExtension(&payload); } @@ -113,14 +119,14 @@ Row DramExtension::getRow(const tlm_generic_payload &payload) } -tlm_extension_base* DramExtension::clone() const +tlm_extension_base *DramExtension::clone() const { return new DramExtension(thread, bank, bankgroup, row, column, burstlength); } -void DramExtension::copy_from(const tlm_extension_base& ext) +void DramExtension::copy_from(const tlm_extension_base &ext) { - const DramExtension& cpyFrom = static_cast(ext); + const DramExtension &cpyFrom = static_cast(ext); thread = cpyFrom.thread; bank = cpyFrom.bank; bankgroup = cpyFrom.bankgroup; @@ -169,87 +175,91 @@ void DramExtension::incrementRow() ++row; } -tlm_extension_base* GenerationExtension::clone() const +tlm_extension_base *GenerationExtension::clone() const { return new GenerationExtension(timeOfGeneration); } -void GenerationExtension::copy_from(const tlm_extension_base& ext) +void GenerationExtension::copy_from(const tlm_extension_base &ext) { - const GenerationExtension& cpyFrom = static_cast(ext); + const GenerationExtension &cpyFrom = static_cast + (ext); timeOfGeneration = cpyFrom.timeOfGeneration; } -GenerationExtension& GenerationExtension::getExtension(const tlm::tlm_generic_payload* payload) +GenerationExtension &GenerationExtension::getExtension(const + tlm::tlm_generic_payload *payload) { GenerationExtension *result = NULL; payload->get_extension(result); - sc_assert(result!=NULL); + sc_assert(result != NULL); return *result; } -sc_time GenerationExtension::getTimeOfGeneration(const tlm::tlm_generic_payload *payload) +sc_time GenerationExtension::getTimeOfGeneration(const tlm::tlm_generic_payload + *payload) { return GenerationExtension::getExtension(payload).TimeOfGeneration(); } -sc_time GenerationExtension::getTimeOfGeneration(const tlm::tlm_generic_payload &payload) +sc_time GenerationExtension::getTimeOfGeneration(const tlm::tlm_generic_payload + &payload) { return GenerationExtension::getTimeOfGeneration(&payload); } //THREAD -bool operator ==(const Thread& lhs, const Thread& rhs) +bool operator ==(const Thread &lhs, const Thread &rhs) { return lhs.ID() == rhs.ID(); } -bool operator !=(const Thread& lhs, const Thread& rhs) +bool operator !=(const Thread &lhs, const Thread &rhs) { return !(lhs == rhs); } -bool operator <(const Thread& lhs, const Thread& rhs) +bool operator <(const Thread &lhs, const Thread &rhs) { return lhs.ID() < rhs.ID(); } //CHANNEL -bool operator ==(const Channel& lhs, const Channel& rhs) +bool operator ==(const Channel &lhs, const Channel &rhs) { return lhs.ID() == rhs.ID(); } -bool operator !=(const Channel& lhs, const Channel& rhs) +bool operator !=(const Channel &lhs, const Channel &rhs) { return !(lhs == rhs); } //BANKGROUP -bool operator ==(const BankGroup& lhs, const BankGroup& rhs) +bool operator ==(const BankGroup &lhs, const BankGroup &rhs) { return lhs.ID() == rhs.ID(); } -bool operator !=(const BankGroup& lhs, const BankGroup& rhs) +bool operator !=(const BankGroup &lhs, const BankGroup &rhs) { return !(lhs == rhs); } //BANK -bool operator ==(const Bank& lhs, const Bank& rhs) +bool operator ==(const Bank &lhs, const Bank &rhs) { return lhs.ID() == rhs.ID(); } -bool operator !=(const Bank& lhs, const Bank& rhs) +bool operator !=(const Bank &lhs, const Bank &rhs) { return !(lhs == rhs); } -bool operator <(const Bank& lhs, const Bank& rhs) +bool operator <(const Bank &lhs, const Bank &rhs) { return lhs.ID() < rhs.ID(); } @@ -257,14 +267,14 @@ bool operator <(const Bank& lhs, const Bank& rhs) //ROW const Row Row::NO_ROW; -bool operator ==(const Row& lhs, const Row& rhs) +bool operator ==(const Row &lhs, const Row &rhs) { if (lhs.isNoRow != rhs.isNoRow) return false; return lhs.ID() == rhs.ID(); } -bool operator !=(const Row& lhs, const Row& rhs) +bool operator !=(const Row &lhs, const Row &rhs) { return !(lhs == rhs); } @@ -277,12 +287,12 @@ const Row Row::operator ++() //COLUMN -bool operator ==(const Column& lhs, const Column& rhs) +bool operator ==(const Column &lhs, const Column &rhs) { return lhs.ID() == rhs.ID(); } -bool operator !=(const Column& lhs, const Column& rhs) +bool operator !=(const Column &lhs, const Column &rhs) { return !(lhs == rhs); } diff --git a/DRAMSys/library/src/common/dramExtension.h b/DRAMSys/library/src/common/dramExtension.h index b61ac90d..19176cc5 100644 --- a/DRAMSys/library/src/common/dramExtension.h +++ b/DRAMSys/library/src/common/dramExtension.h @@ -46,7 +46,7 @@ class Thread { public: explicit Thread(unsigned int id) : - id(id) + id(id) { } @@ -62,7 +62,7 @@ class Channel { public: explicit Channel(unsigned int id) : - id(id) + id(id) { } unsigned int ID() const @@ -77,7 +77,7 @@ class BankGroup { public: explicit BankGroup(unsigned int id) : - id(id) + id(id) { } unsigned int ID() const @@ -92,7 +92,7 @@ class Bank { public: Bank(unsigned int id) : - id(id) + id(id) { } unsigned int ID() const @@ -121,11 +121,11 @@ public: static const Row NO_ROW; Row() : - id(0), isNoRow(true) + id(0), isNoRow(true) { } explicit Row(unsigned int id) : - id(id), isNoRow(false) + id(id), isNoRow(false) { } @@ -146,7 +146,7 @@ class Column { public: explicit Column(unsigned int id) : - id(id) + id(id) { } @@ -163,16 +163,18 @@ class DramExtension: public tlm::tlm_extension { public: DramExtension(); - DramExtension(const Thread& thread, const Bank& bank, const BankGroup& bankgroup, const Row& row, const Column& column, - unsigned int burstlength = 0); - DramExtension(const Thread& thread, const Channel& channel, const Bank& bank, const BankGroup& bankgroup, const Row& row, - const Column& column, unsigned int burstlength = 0); + DramExtension(const Thread &thread, const Bank &bank, + const BankGroup &bankgroup, const Row &row, const Column &column, + unsigned int burstlength = 0); + DramExtension(const Thread &thread, const Channel &channel, const Bank &bank, + const BankGroup &bankgroup, const Row &row, + const Column &column, unsigned int burstlength = 0); - virtual tlm_extension_base* clone() const; - virtual void copy_from(const tlm_extension_base& ext); + virtual tlm_extension_base *clone() const; + virtual void copy_from(const tlm_extension_base &ext); - static DramExtension& getExtension(const tlm::tlm_generic_payload *payload); - static DramExtension& getExtension(const tlm::tlm_generic_payload &payload); + static DramExtension &getExtension(const tlm::tlm_generic_payload *payload); + static DramExtension &getExtension(const tlm::tlm_generic_payload &payload); // Used for convience, caller could also use getExtension(..) to access these field static Bank getBank(const tlm::tlm_generic_payload *payload); @@ -211,11 +213,16 @@ private: class GenerationExtension : public tlm::tlm_extension { public: - GenerationExtension(sc_time timeOfGeneration) : timeOfGeneration(timeOfGeneration) {} - virtual tlm_extension_base* clone() const; - virtual void copy_from(const tlm_extension_base& ext); - static GenerationExtension& getExtension(const tlm::tlm_generic_payload *payload); - sc_time TimeOfGeneration() const {return timeOfGeneration;} + GenerationExtension(sc_time timeOfGeneration) : timeOfGeneration( + timeOfGeneration) {} + virtual tlm_extension_base *clone() const; + virtual void copy_from(const tlm_extension_base &ext); + static GenerationExtension &getExtension(const tlm::tlm_generic_payload + *payload); + sc_time TimeOfGeneration() const + { + return timeOfGeneration; + } static sc_time getTimeOfGeneration(const tlm::tlm_generic_payload *payload); static sc_time getTimeOfGeneration(const tlm::tlm_generic_payload &payload); diff --git a/DRAMSys/library/src/common/jsonAddressDecoder.cpp b/DRAMSys/library/src/common/jsonAddressDecoder.cpp index 9a867bc9..7253d656 100644 --- a/DRAMSys/library/src/common/jsonAddressDecoder.cpp +++ b/DRAMSys/library/src/common/jsonAddressDecoder.cpp @@ -63,8 +63,7 @@ void JSONAddressDecoder::setConfiguration(std::string url) file.open(url); - if(!file.is_open()) - { + if (!file.is_open()) { cout << "Unable to open file " << url << endl; return; } @@ -85,29 +84,29 @@ void JSONAddressDecoder::setConfiguration(std::string url) set sUsed; // get XOR connections - // An XOR connection needs two parameters: A bank bit and a Row bit. - // These parameters are all stored in one array with the following pattern: bank0, bank1, ..., row0, row1, ... - unsigned num = (*sol)["XOR"].size()>>1; - for(unsigned i = 0; i < num; i++) - { - m_vXor.push_back(pair ((*sol)["XOR"].at(i), (*sol)["XOR"].at(i+num))); + // An XOR connection needs two parameters: A bank bit and a Row bit. + // These parameters are all stored in one array with the following pattern: bank0, bank1, ..., row0, row1, ... + unsigned num = (*sol)["XOR"].size() >> 1; + for (unsigned i = 0; i < num; i++) { + m_vXor.push_back(pair ((*sol)["XOR"].at(i), + (*sol)["XOR"].at(i + num))); } // get all bank bits - // Each bank bit of the address will be stored with a counter value which assigns the bit position DecodedAddress struct. + // Each bank bit of the address will be stored with a counter value which assigns the bit position DecodedAddress struct. unsigned counter = 0; - for(auto it = (*sol)["Banks Rows"][0]["bank_bits"].begin(); it != (*sol)["Banks Rows"][0]["bank_bits"].end(); it++) - { - m_vBankBits.push_back(pair(counter++, (*it))); + for (auto it = (*sol)["Banks Rows"][0]["bank_bits"].begin(); + it != (*sol)["Banks Rows"][0]["bank_bits"].end(); it++) { + m_vBankBits.push_back(pair(counter++, (*it))); sUsed.insert((unsigned)(*it)); } // get all row bits bits - // Each Row bit of the address will be stored with a counter value which assigns the bit position DecodedAddress struct. + // Each Row bit of the address will be stored with a counter value which assigns the bit position DecodedAddress struct. counter = 0; - for(auto it = (*sol)["Banks Rows"][0]["rows"]["row_bits"].begin(); it != (*sol)["Banks Rows"][0]["rows"]["row_bits"].end(); it++) - { - m_vRowBits.push_back(pair(counter++, (*it))); + for (auto it = (*sol)["Banks Rows"][0]["rows"]["row_bits"].begin(); + it != (*sol)["Banks Rows"][0]["rows"]["row_bits"].end(); it++) { + m_vRowBits.push_back(pair(counter++, (*it))); sUsed.insert((unsigned)(*it)); } @@ -121,18 +120,17 @@ void JSONAddressDecoder::setConfiguration(std::string url) sUsed.insert(31); // Create Column mapping - // These bits are not stored in the JSON file, but can be generated. All bits, which are until now not used for any other purpose are column bits. - // Each column bit of the address will be stored with a counter value which assigns the bit position DecodedAddress struct. + // These bits are not stored in the JSON file, but can be generated. All bits, which are until now not used for any other purpose are column bits. + // Each column bit of the address will be stored with a counter value which assigns the bit position DecodedAddress struct. counter = 0; - for(unsigned i = 0; i < 32; i++) - { - if(sUsed.find(i) != sUsed.end()) + for (unsigned i = 0; i < 32; i++) { + if (sUsed.find(i) != sUsed.end()) continue; // Already mapped m_vColumnBits.push_back(pair(counter++, i)); } - // Fill the amount map. This is copied from xmlAddressDecoder without further investigation + // Fill the amount map. This is copied from xmlAddressDecoder without further investigation amount["channel"] = 1; amount["bank"] = pow(2.0, m_vBankBits.size()); amount["row"] = pow(2.0, m_vRowBits.size()); @@ -146,10 +144,9 @@ DecodedAddress JSONAddressDecoder::decodeAddress(sc_dt::uint64 addr) DecodedAddress result; // Apply XOR - // For each used xor: - // Get the bank bit and row bit. Apply a bitwise xor operator and save it back to the bank bit. - for(auto it = m_vXor.begin(); it != m_vXor.end(); it++) - { + // For each used xor: + // Get the bank bit and row bit. Apply a bitwise xor operator and save it back to the bank bit. + for (auto it = m_vXor.begin(); it != m_vXor.end(); it++) { unsigned new_bank_bit; // Bank Row new_bank_bit = (((addr >> it->first) & 1) ^ ((addr >> it->second) & 1)); @@ -166,35 +163,32 @@ DecodedAddress JSONAddressDecoder::decodeAddress(sc_dt::uint64 addr) result.bytes = addr & 0x7; // Bank - // it->second: position of the target bit in the address - // it->first: target position of the bit in the variable - // For each bank bit: - // shift address bit to position 0. Clear all other bits. shift it the right bank bit. Add it to the set of bank bits. + // it->second: position of the target bit in the address + // it->first: target position of the bit in the variable + // For each bank bit: + // shift address bit to position 0. Clear all other bits. shift it the right bank bit. Add it to the set of bank bits. result.bank = 0; - for(auto it = m_vBankBits.begin(); it != m_vBankBits.end(); it++) - { + for (auto it = m_vBankBits.begin(); it != m_vBankBits.end(); it++) { result.bank |= ((addr >> it->second) & 1) << it->first; } // Row - // it->second: position of the target bit in the address - // it->first: target position of the bit in the variable - // For each row bit: - // shift address bit to position 0. Clear all other bits. shift it the right row bit. Add it to the set of row bits. + // it->second: position of the target bit in the address + // it->first: target position of the bit in the variable + // For each row bit: + // shift address bit to position 0. Clear all other bits. shift it the right row bit. Add it to the set of row bits. result.row = 0; - for(auto it = m_vRowBits.begin(); it != m_vRowBits.end(); it++) - { + for (auto it = m_vRowBits.begin(); it != m_vRowBits.end(); it++) { result.row |= ((addr >> it->second) & 1) << it->first; } // Column - // it->second: position of the target bit in the address - // it->first: target position of the bit in the variable - // For each column bit: - // shift address bit to position 0. Clear all other bits. shift it the right column bit. Add it to the set of column bits. + // it->second: position of the target bit in the address + // it->first: target position of the bit in the variable + // For each column bit: + // shift address bit to position 0. Clear all other bits. shift it the right column bit. Add it to the set of column bits. result.column = 0; - for(auto it = m_vColumnBits.begin(); it != m_vColumnBits.end(); it++) - { + for (auto it = m_vColumnBits.begin(); it != m_vColumnBits.end(); it++) { result.column |= ((addr >> it->second) & 1) << it->first; } @@ -204,47 +198,43 @@ DecodedAddress JSONAddressDecoder::decodeAddress(sc_dt::uint64 addr) sc_dt::uint64 JSONAddressDecoder::encodeAddress(DecodedAddress n) { sc_dt::uint64 address = 0; - + // Bank - // it->first: position of the target bit in the DecodedAddress struct field - // it->second: target position of the bit in the address - // For each bank bit: - // shift bank bit to position 0. Clear all other bits. shift it the right address bit. Add it to the set of address bits. - for(auto it = m_vBankBits.begin(); it != m_vBankBits.end(); it++) - { + // it->first: position of the target bit in the DecodedAddress struct field + // it->second: target position of the bit in the address + // For each bank bit: + // shift bank bit to position 0. Clear all other bits. shift it the right address bit. Add it to the set of address bits. + for (auto it = m_vBankBits.begin(); it != m_vBankBits.end(); it++) { address |= ((n.bank >> it->first) & 1) << it->second; } // Row - // it->first: position of the target bit in the DecodedAddress struct field - // it->second: target position of the bit in the address - // For each row bit: - // shift row bit to position 0. Clear all other bits. shift it the right address bit. Add it to the set of address bits. - for(auto it = m_vRowBits.begin(); it != m_vRowBits.end(); it++) - { + // it->first: position of the target bit in the DecodedAddress struct field + // it->second: target position of the bit in the address + // For each row bit: + // shift row bit to position 0. Clear all other bits. shift it the right address bit. Add it to the set of address bits. + for (auto it = m_vRowBits.begin(); it != m_vRowBits.end(); it++) { address |= ((n.row >> it->first) & 1) << it->second; } // Column - // it->first: position of the target bit in the DecodedAddress struct field - // it->second: target position of the bit in the address - // For each column bit: - // shift column bit to position 0. Clear all other bits. shift it the right address bit. Add it to the set of address bits. - for(auto it = m_vColumnBits.begin(); it != m_vColumnBits.end(); it++) - { + // it->first: position of the target bit in the DecodedAddress struct field + // it->second: target position of the bit in the address + // For each column bit: + // shift column bit to position 0. Clear all other bits. shift it the right address bit. Add it to the set of address bits. + for (auto it = m_vColumnBits.begin(); it != m_vColumnBits.end(); it++) { address |= ((n.column >> it->first) & 1) << it->second; } - // Add the unchanged byte bits + // Add the unchanged byte bits address |= n.bytes; // Apply XOR - // For each used xor: - // Get the bank bit and row bit. Apply a bitwise xor operator and save it back to the bank bit. - for(auto it = m_vXor.begin(); it != m_vXor.end(); it++) - { - unsigned new_bank_bit; - new_bank_bit = (((address >> it->first) & 1) ^ ((address >> it->second) & 1)); - address &= ~(1 << it->first); - address |= new_bank_bit << it->first; + // For each used xor: + // Get the bank bit and row bit. Apply a bitwise xor operator and save it back to the bank bit. + for (auto it = m_vXor.begin(); it != m_vXor.end(); it++) { + unsigned new_bank_bit; + new_bank_bit = (((address >> it->first) & 1) ^ ((address >> it->second) & 1)); + address &= ~(1 << it->first); + address |= new_bank_bit << it->first; } return address; @@ -254,16 +244,13 @@ void JSONAddressDecoder::print() { map> output; - for(auto it = m_vBankBits.begin(); it != m_vBankBits.end(); it++) - { + for (auto it = m_vBankBits.begin(); it != m_vBankBits.end(); it++) { output[it->second] = pair(it->first , 'B'); } - for(auto it = m_vRowBits.begin(); it != m_vRowBits.end(); it++) - { + for (auto it = m_vRowBits.begin(); it != m_vRowBits.end(); it++) { output[it->second] = pair(it->first , 'R'); } - for(auto it = m_vColumnBits.begin(); it != m_vColumnBits.end(); it++) - { + for (auto it = m_vColumnBits.begin(); it != m_vColumnBits.end(); it++) { output[it->second] = pair(it->first , 'C'); } @@ -274,13 +261,11 @@ void JSONAddressDecoder::print() cout << "Used addressmapping:" << endl; cout << headline << endl; - for(unsigned i = 0; i < 32; i++) - { + for (unsigned i = 0; i < 32; i++) { cout << " " << i << " "; } cout << endl; - for(unsigned i = 0; i < 32; i++) - { + for (unsigned i = 0; i < 32; i++) { cout << " " << output[i].second << "(" << output[i].first << ") "; } cout << endl; diff --git a/DRAMSys/library/src/common/jsonAddressDecoder.h b/DRAMSys/library/src/common/jsonAddressDecoder.h index ee25d77e..10180f21 100644 --- a/DRAMSys/library/src/common/jsonAddressDecoder.h +++ b/DRAMSys/library/src/common/jsonAddressDecoder.h @@ -55,11 +55,15 @@ class JSONAddressDecoder private: JSONAddressDecoder(); - vector> m_vXor; // This container stores for each used xor gate a pair which consists of "First/Number of an address bit which corresponds to a bank" - // and "Second/Number of an address bit which corresponds to a row" - vector> m_vBankBits; // This container stores for each bank bit a pair which consists of "First/Number of the bank bit" and "Second/Number of the address bit" - vector> m_vRowBits; // This container stores for each row bit a pair which consists of "First/Number of the row bit" and "Second/Number of the address bit" - vector> m_vColumnBits; // This container stores for each column bit a pair which consists of "First/Number of the column bit" and "Second/Number of the address bit" + vector> + m_vXor; // This container stores for each used xor gate a pair which consists of "First/Number of an address bit which corresponds to a bank" + // and "Second/Number of an address bit which corresponds to a row" + vector> + m_vBankBits; // This container stores for each bank bit a pair which consists of "First/Number of the bank bit" and "Second/Number of the address bit" + vector> + m_vRowBits; // This container stores for each row bit a pair which consists of "First/Number of the row bit" and "Second/Number of the address bit" + vector> + m_vColumnBits; // This container stores for each column bit a pair which consists of "First/Number of the column bit" and "Second/Number of the address bit" public: virtual void setConfiguration(std::string url); diff --git a/DRAMSys/library/src/common/tlm2_base_protocol_checker.h b/DRAMSys/library/src/common/tlm2_base_protocol_checker.h index 99b5ce10..dc2bf9a6 100755 --- a/DRAMSys/library/src/common/tlm2_base_protocol_checker.h +++ b/DRAMSys/library/src/common/tlm2_base_protocol_checker.h @@ -1,1055 +1,1049 @@ - -// Filename: tlm2_base_protocol_checker.h - -//---------------------------------------------------------------------- -// Copyright (c) 2008-2013 by Doulos Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -//---------------------------------------------------------------------- - -// Author: John Aynsley, Doulos - -// Version 1, 11 July 2008 -// Version 2, 16 July 2008 Only generate ref_count > 1 warning from 1st checker of path -// Version 3, 17 July 2008 Support compilation under SystemC 2.1.v1 -// Version 4, 12 Aug 2008 Add header #include -// Version 5, 08 Sep 2008 Fix bugs in message text -// Version 6, 01 Aug 2010 Update messages to refer to OSCI TLM-2.0 LRM of July 2009 -// Version 7, 25 Oct 2011 Minor bug fix for certain compilers: replace u_char with uchar_t -// Version 8, 02 Nov 2011 Support the endianness conversion functions by excluding the -// tlm_endian_context extension from the protocol checks -// Version 9, 17 Aug 2012 Fix LRM reference on line 805 (should be 8.2.11 a) [NOT YET RELEASED] -// Version 10, 3 Jan 2013 Updated messages to refer to IEEE Std 1666-2011, the combined SystemC + TLM-2.0 LRM -// Added checks related to the generic payload option attribute -// Version 11, 14 Mar 2016 Fix minor bug - start_phase should be a copy, not a reference - -// TLM-2.0 Base Protocol Compliance Checker - -/* -Instantiate this checker module in-line between initiator and target, initiator and interconnect, -or interconnect and target by binding the target_socket and initiator_socket -Binding two checkers either side of an interconnect component, or interleaving a series of -checkers with interconnect components, will enable some deeper checks as against having just -a single checker - -For example - - Initiator *initiator; - Bus *bus; - Memory *memory; - ... - initiator->socket.bind(bus->target_socket); - bus->initiator_socket.bind(memory->socket); - -might become - - tlm_utils::tlm2_base_protocol_checker<32> *checker1; - tlm_utils::tlm2_base_protocol_checker<32> *checker2; - ... - initiator->socket.bind(checker1->target_socket); - checker1->initiator_socket.bind(bus->target_socket); - bus->initiator_socket.bind(checker2->target_socket); - checker2->initiator_socket.bind(memory->socket); - - -GENERAL FEATURES OF THE BASE PROTOCOL CHECKER - -The checks are relatively expensive, hence by default the number of checks is limited. -A maximum number can be set explicitly by calling set_num_checks(max) -Checking can be deactivated at any time by calling set_num_checks(0) -All checkers decrement a single global count, because having some checkers running and -others not can cause bogus violation reports -It is not permitted to turn checks on by calling set_num_checks() once checking has been -deactivated, because this could cause bogus violation reports - -The DMI and debug checks are unaffected by the num_checks count (because they are cheap) - -The error messages contain User Manual references - -The checker is designed to be used with a transaction pool: otherwise it could consume -a lot of memory. The checker keeps a local copy of each transaction object -Failures are reported with a severity of SC_ERROR. The actions may be overridden by calling: - sc_report_handler::set_actions("tlm2_protocol_checker", ...); - -SPECIFIC CHECKS - -nb_transport: phase sequence BEGIN_REQ -> END_REQ -> BEGIN_RESP -> END_RESP -Must not have two outstanding requests or responses (exclusion rules) -Must not have decreasing timing annotations on calls to or returns from nb_transport_fw/bw -Phase extensions permitted and ignored -Must not call b_transport during nb_transport phase sequence and vice-versa - -nb_transport: memory manager must be set -nb_transport: reference count must be non-zero -First checker in BEGIN_REQ path should see ref_count == 1 (warning only) -An interconnect component that sets a memory manager should also clear it -An interconnect component that sets extensions with no memory manager should also clear them -(Does not bother with these memory manager checks for DMI and debug) - -Transaction object must be properly initialized -Many generic payload attributes must not be modified during the transaction lifetime -Transaction object must not be re-allocated for a new transaction while still in use -DMI descriptor must be properly initialized -Debug transaction must be properly initialized -Debug byte count must be less than data_length - -Checks that require multiple checkers to be instantiated along a transaction path: -The BEGIN_RESP path must be the reverse of the BEGIN_REQ path -Transaction object must not be sent with BEGIN_REQ while participating in a previous response -Interconnect component must not set response status attribute to TLM_OK_RESPONSE -Interconnect component must not modify data array on the response path - -Generic payload option attribute (IEEE Std 1666-2011, SystemC 2.3.x) -gp_option must be properly initialized and only used for DMI and debug transport -When gp_option is used, other gp attributes must be initalized and used as per the transport interfaces -*/ - - -// ******************** PREAMBLE ******************** - - -#ifndef __tlm2_base_protocol_checker__ -#define __tlm2_base_protocol_checker__ - -#include "systemc" -using std::cout; -using std::endl; -using std::dec; -using std::hex; - -#include "tlm.h" -#include -#include - - -namespace tlm_utils { - - -// Number of checks remaining -const sc_dt::uint64 default_num_checks = 100000; -static sc_dt::uint64 num_checks = default_num_checks; - - -// Types used when building a trace of the transaction path -typedef unsigned char uchar_t; -typedef std::deque deque_t; - -struct path_t { - path_t () { response_in_progress = false; ok_response = false; resp_data_ptr = 0; } - - bool response_in_progress; - bool ok_response; - deque_t path; - uchar_t* resp_data_ptr; // Copy of data on response path -}; - -// Global variable used for checks involving multiple checkers along a transaction path -static std::map shared_map; - - -// ******************** CLASS DEFINITION ******************** - - -template -class tlm2_base_protocol_checker - -: public sc_core::sc_module -, public tlm::tlm_fw_transport_if -, public tlm::tlm_bw_transport_if -{ -public: - - // Instantiate and bind checker inline between an existing pair of initiator and target sockets - - tlm::tlm_target_socket target_socket; - tlm::tlm_initiator_socket initiator_socket; - - SC_CTOR(tlm2_base_protocol_checker) - : m_request_in_progress(0), m_response_in_progress(0) - { - target_socket .bind( *this ); - initiator_socket.bind( *this ); - } - - - // Access methods for num_checks count - - static void set_num_checks(sc_dt::uint64 n) { - if (num_checks == 0) - SC_REPORT_FATAL("tlm2_protocol_checker", "Method set_num_checks called after checking has stopped due to maximum number of checks being reached"); - num_checks = n; - } - - static sc_dt::uint64 get_num_checks() { return num_checks; } - - - // TLM-2.0 interface methods for initiator and target sockets, instrumented with checks - - virtual tlm::tlm_sync_enum nb_transport_fw( - tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_core::sc_time& delay) - { - tlm::tlm_phase start_phase = phase; - - if (num_checks) - nb_transport_fw_pre_checks( trans, phase, delay ); - - tlm::tlm_sync_enum status; - status = initiator_socket->nb_transport_fw( trans, phase, delay ); - - if (num_checks) - nb_transport_fw_post_checks( trans, start_phase, phase, delay, status ); - - return status; - } - - virtual tlm::tlm_sync_enum nb_transport_bw( - tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_core::sc_time& delay) - { - if (num_checks) - nb_transport_bw_pre_checks( trans, phase, delay ); - - tlm::tlm_sync_enum status; - status = target_socket->nb_transport_bw( trans, phase, delay ); - - if (num_checks) - nb_transport_bw_post_checks( trans, phase, delay, status ); - - return status; - } - - virtual void b_transport( tlm::tlm_generic_payload& trans, sc_core::sc_time& delay ) - { - if (num_checks) - b_transport_pre_checks( trans, delay ); - - initiator_socket->b_transport( trans, delay ); - - if (num_checks) - b_transport_post_checks( trans, delay ); - } - - virtual bool get_direct_mem_ptr(tlm::tlm_generic_payload& trans, - tlm::tlm_dmi& dmi_data) - { - get_direct_mem_ptr_pre_checks( trans, dmi_data ); - - bool status; - status = initiator_socket->get_direct_mem_ptr( trans, dmi_data ); - - get_direct_mem_ptr_post_checks( trans, dmi_data ); - return status; - } - - virtual void invalidate_direct_mem_ptr(sc_dt::uint64 start_range, - sc_dt::uint64 end_range) - { - target_socket->invalidate_direct_mem_ptr(start_range, end_range); - } - - virtual unsigned int transport_dbg(tlm::tlm_generic_payload& trans) - { - transport_dbg_pre_checks( trans ); - - unsigned int count; - count = initiator_socket->transport_dbg( trans ); - - transport_dbg_post_checks( trans, count ); - return count; - } - - -private: - void b_transport_pre_checks( tlm::tlm_generic_payload& trans, sc_core::sc_time& delay); - - void b_transport_post_checks( tlm::tlm_generic_payload& trans, sc_core::sc_time& delay); - - void nb_transport_fw_pre_checks( - tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_core::sc_time& delay); - - void nb_transport_fw_post_checks( - tlm::tlm_generic_payload& trans, tlm::tlm_phase& start_phase, tlm::tlm_phase& phase, - sc_core::sc_time& delay, tlm::tlm_sync_enum status); - - void nb_transport_bw_pre_checks( - tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_core::sc_time& delay); - - void nb_transport_bw_post_checks( - tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_core::sc_time& delay, - tlm::tlm_sync_enum status); - - void nb_transport_response_checks( - tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_core::sc_time& delay, - const char* txt2, const char* txt3, const char* txt4); - - void check_initial_state( tlm::tlm_generic_payload& trans, const char* txt2 ); - void check_trans_not_modified( tlm::tlm_generic_payload& trans, const char* txt2 ); - void check_response_path( tlm::tlm_generic_payload& trans, const char* txt2 ); - void remember_gp_option( tlm::tlm_generic_payload& trans ); - - void get_direct_mem_ptr_pre_checks( tlm::tlm_generic_payload& trans, tlm::tlm_dmi& dmi_data ); - - void get_direct_mem_ptr_post_checks( tlm::tlm_generic_payload& trans, tlm::tlm_dmi& dmi_data ); - - void transport_dbg_pre_checks( tlm::tlm_generic_payload& trans ); - - void transport_dbg_post_checks( tlm::tlm_generic_payload& trans, unsigned int count ); - - void tlm2error( tlm::tlm_generic_payload& trans, const char* ref, bool warning = false ); - -private: - - struct state_t { - state_t() { b_call = 0; ph = tlm::UNINITIALIZED_PHASE; gp = 0; } - - bool has_mm; - unsigned int b_call; // Number of b_transport calls in progress - tlm::tlm_phase ph; - sc_core::sc_time time; // Current time + annotated delay - tlm::tlm_generic_payload* gp; // Points to new data and byte enable buffers - uchar_t* data_ptr; // Stores original pointers - uchar_t* byte_enable_ptr; - }; - - // Transaction state for the specific hop where this checker is inlined - std::map m_map; - - // Flags for exclusion rules - tlm::tlm_generic_payload* m_request_in_progress; - tlm::tlm_generic_payload* m_response_in_progress; - - std::ostringstream txt; - -}; - - - -// ******************** MEMBER FUNCTION DEFINITIONS ******************** - - -#define BOILERPLATE \ -template \ -void tlm2_base_protocol_checker:: - - -BOILERPLATE -b_transport_pre_checks( - tlm::tlm_generic_payload& trans, sc_core::sc_time& /*delay*/) -{ - ++ m_map[&trans].b_call; - - if ( trans.has_mm() && trans.get_ref_count() == 0) - { - txt << "Transaction passed to b_transport with memory manager and reference count of 0"; - tlm2error(trans, "14.5 t)"); - } - check_initial_state(trans, "b_transport"); - -#if !(defined SYSTEMC_VERSION & SYSTEMC_VERSION <= 20050714) - if (sc_core::sc_get_current_process_handle().proc_kind() == sc_core::SC_METHOD_PROC_) - { - txt << "b_transport called from method process"; - tlm2error(trans, "11.1.1.4 b)"); - } -#endif - - if (m_map[&trans].ph > 0 && m_map[&trans].ph < 4) - { - txt << "b_transport called during a sequence of nb_transport calls"; - tlm2error(trans, "15.2.10 c)"); - } -} - - -BOILERPLATE -b_transport_post_checks( - tlm::tlm_generic_payload& trans, sc_core::sc_time& /*delay*/) -{ - check_response_path(trans, "b_transport"); - check_trans_not_modified(trans, "b_transport"); - -- m_map[&trans].b_call; -} - - -BOILERPLATE -nb_transport_fw_pre_checks( - tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_core::sc_time& delay) -{ - if ( !trans.has_mm() ) - { - txt << "Transaction passed to nb_transport_fw with no memory manager set"; - tlm2error(trans, "14.5 i)"); - } - if ( trans.get_ref_count() == 0) - { - txt << "Transaction passed to nb_transport_fw with reference count of 0"; - tlm2error(trans, "14.5 t)"); - } - - switch (phase) - { - case tlm::BEGIN_REQ: - check_initial_state(trans, "nb_transport_fw"); - - if (m_map[&trans].ph > 0 && m_map[&trans].ph < 4) // END_RESP -> BEGIN_REQ is legal - { - txt << "Phase " << phase << " sent out-of-sequence on forward path, detected in nb_transport_fw"; - tlm2error(trans, "15.2.4"); - } - - if (m_request_in_progress) - { - txt << "Transaction violates BEGIN_REQ exclusion rule, detected in nb_transport_fw"; - tlm2error(trans, "15.2.6 e)"); - } - m_request_in_progress = &trans; - - if (m_map[&trans].b_call) - { - txt << "nb_transport_fw called during a b_transport call"; - tlm2error(trans, "15.2.10 c)"); - } - break; - - case tlm::END_REQ: - case tlm::BEGIN_RESP: - case tlm::UNINITIALIZED_PHASE: - txt << "Phase " << phase << " sent on forward path, detected in nb_transport_fw"; - tlm2error(trans, " 15.2.3 c)"); - break; - - case tlm::END_RESP: - if (m_map[&trans].ph != tlm::BEGIN_RESP) - { - txt << "Phase " << phase << " sent out-of-sequence on forward path, detected in nb_transport_fw"; - tlm2error(trans, "15.2.4"); - } - m_response_in_progress = 0; - break; - } - - if (phase < 5) // Ignore extended phases - m_map[&trans].ph = phase; - - if (sc_core::sc_time_stamp() + delay < m_map[&trans].time) - { - txt << "nb_transport_fw called with decreasing timing annotation:" - << " delay = " << delay - << ", sc_time_stamp() + delay from previous call = " << m_map[&trans].time; - tlm2error(trans, "15.2.7 c)"); - } - m_map[&trans].time = sc_core::sc_time_stamp() + delay; -} - - -BOILERPLATE -nb_transport_fw_post_checks( - tlm::tlm_generic_payload& trans, tlm::tlm_phase& start_phase, tlm::tlm_phase& phase, - sc_core::sc_time& delay, tlm::tlm_sync_enum status) -{ - if (status == tlm::TLM_UPDATED) - { - nb_transport_response_checks( - trans, phase, delay, "(forward) return", "Return from nb_transport_fw", "nb_transport_fw"); - } - else if (status == tlm::TLM_COMPLETED) - { - if (start_phase == tlm::BEGIN_REQ) - check_response_path(trans, "nb_transport_fw"); - m_request_in_progress = 0; - m_map[&trans].ph = tlm::UNINITIALIZED_PHASE; - } - - // Transaction object should not be re-allocated, even during the END_RESP phase - //if (phase != tlm::END_RESP) - { - std::ostringstream txt; - txt << "nb_transport_fw, phase = " << phase; - check_trans_not_modified(trans, txt.str().c_str()); - } -} - - -BOILERPLATE -nb_transport_bw_pre_checks( - tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_core::sc_time& delay) -{ - if ( !trans.has_mm() ) - { - txt << "Transaction passed to nb_transport_bw with no memory manager set"; - tlm2error(trans, "14.5 i)"); - } - if ( trans.get_ref_count() == 0) - { - txt << "Transaction passed to nb_transport_bw with reference count of 0"; - tlm2error(trans, "14.5 t)"); - } - nb_transport_response_checks( - trans, phase, delay, "backward", "nb_transport_bw called", "nb_transport_bw"); -} - - -BOILERPLATE -nb_transport_bw_post_checks( - tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_core::sc_time& delay, - tlm::tlm_sync_enum status) -{ - if (status == tlm::TLM_UPDATED) - { - switch (phase) - { - case tlm::BEGIN_REQ: - txt << "Phase " << phase << " sent out-of-sequence on (backward) return path, detected in nb_transport_bw"; - tlm2error(trans, "15.2.4"); - break; - - case tlm::END_REQ: - case tlm::BEGIN_RESP: - case tlm::UNINITIALIZED_PHASE: - txt << "Phase " << phase << " sent on (backward) return path, detected in nb_transport_bw"; - tlm2error(trans, "15.2.3 c)"); - break; - - case tlm::END_RESP: - if (m_map[&trans].ph != tlm::BEGIN_RESP) - { - txt << "Phase " << phase << " sent out-of-sequence on (backward) return path, detected in nb_transport_bw"; - tlm2error(trans, "15.2.4"); - } - - m_response_in_progress = 0; - break; - } - - if (phase < 5) // Ignore extended phases - m_map[&trans].ph = phase; - - if (sc_core::sc_time_stamp() + delay < m_map[&trans].time) - { - txt << "Return from nb_transport_bw with decreasing timing annotation:" - << " delay = " << delay - << ", sc_time_stamp() + delay from previous call = " << m_map[&trans].time; - tlm2error(trans, "15.2.7 c)"); - } - m_map[&trans].time = sc_core::sc_time_stamp() + delay; - } - else if (status == tlm::TLM_COMPLETED) - { - m_response_in_progress = 0; - m_map[&trans].ph = tlm::UNINITIALIZED_PHASE; - } - - // Transaction object should not be re-allocated, even during the END_RESP phase - //if (phase != tlm::END_RESP) - { - std::ostringstream txt; - txt << "nb_transport_bw, phase = " << phase; - check_trans_not_modified(trans, txt.str().c_str()); - } -} - - -BOILERPLATE -nb_transport_response_checks( - tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_core::sc_time& delay, - const char* txt2, const char* txt3, const char* txt4) -{ - if (trans.is_response_ok()) - if (shared_map[&trans].response_in_progress && !shared_map[&trans].ok_response) - { - txt << "Interconnect component sets response status attribute to TLM_OK_RESPONSE" - << ", detected in " << txt4; - tlm2error(trans, "14.7"); - - } - - switch (phase) - { - case tlm::BEGIN_REQ: - case tlm::END_RESP: - case tlm::UNINITIALIZED_PHASE: - txt << "Phase " << phase << " sent on " << txt2 << " path" - << ", detected in " << txt4; - tlm2error(trans, "15.2.3 c)"); - break; - - case tlm::END_REQ: - if (m_map[&trans].ph != tlm::BEGIN_REQ) - { - txt << "Phase " << phase << " sent out-of-sequence on " << txt2 << " path" - << ", detected in " << txt4; - tlm2error(trans, "15.2.4"); - } - - m_request_in_progress = 0; - break; - - case tlm::BEGIN_RESP: - if (m_map[&trans].ph != tlm::BEGIN_REQ && m_map[&trans].ph != tlm::END_REQ) - { - txt << "Phase " << phase << " sent out-of-sequence on " << txt2 << " path" - << ", detected in " << txt4; - tlm2error(trans, "15.2.4"); - } - - if (&trans == m_request_in_progress) - m_request_in_progress = 0; - - if (m_response_in_progress) - { - txt << "Transaction violates BEGIN_RESP exclusion rule" - << ", detected in " << txt4; - tlm2error(trans, "15.2.6 f)"); - } - m_response_in_progress = &trans; - - check_response_path(trans, txt4); - break; - } - - if (phase < 5) // Ignore extended phases - m_map[&trans].ph = phase; - - if (sc_core::sc_time_stamp() + delay < m_map[&trans].time) - { - txt << txt3 << " with decreasing timing annotation:" - << " delay = " << delay - << ", sc_time_stamp() + delay from previous call = " << m_map[&trans].time; - tlm2error(trans, "15.2.7 c)"); - } - m_map[&trans].time = sc_core::sc_time_stamp() + delay; -} - - -BOILERPLATE -check_initial_state( - tlm::tlm_generic_payload& trans, const char* txt2 ) -{ - if (num_checks > 0) - { - --num_checks; - if (num_checks == 0) - SC_REPORT_INFO("tlm2_protocol_checker", "Checkers deactivated after executing the set number of checks"); - } - - if ( trans.has_mm() && trans.get_ref_count() > 1 && shared_map[&trans].path.empty() ) - { - txt << "New transaction passed to " << txt2 << " with reference count = " - << trans.get_ref_count(); - tlm2error(trans, "14.5 t)", true); - } - if (trans.get_data_ptr() == 0 && trans.get_command() != tlm::TLM_IGNORE_COMMAND) - { - txt << "Transaction not properly initialized: data_ptr == 0, detected in " << txt2; - tlm2error(trans, "14.11 e)"); - } - if (trans.get_data_length() == 0 && trans.get_command() != tlm::TLM_IGNORE_COMMAND) - { - txt << "Transaction not properly initialized: data_langth == 0, detected in " << txt2; - tlm2error(trans, "14.12 d)"); - } - if (trans.get_byte_enable_ptr() != 0 && trans.get_byte_enable_length() == 0) - { - txt << "Transaction not properly initialized: " - << "byte_enable_ptr != 0 and byte_enable_length == 0, detected in " << txt2; - tlm2error(trans, "14.14 f)"); - } - if (trans.get_streaming_width() == 0) - { - txt << "Transaction not properly initialized: streaming_width == 0, detected in " << txt2; - tlm2error(trans, "14.15 f)"); - } - if (trans.is_dmi_allowed()) - { - txt << "Transaction not properly initialized: dmi_allowed == true, detected in " << txt2; - tlm2error(trans, "14.16"); - } - if (trans.get_response_status() != tlm::TLM_INCOMPLETE_RESPONSE) - { - txt << "Transaction not properly initialized: response_status != TLM_INCOMPLETE_RESPONSE, detected in " << txt2; - tlm2error(trans, "14.17 e)"); - } - if (trans.get_gp_option() != tlm::TLM_MIN_PAYLOAD) - { - txt << "Transaction not properly initialized: gp_option != TLM_MIN_PAYLOAD, detected in " << txt2; - tlm2error(trans, "14.8 g)"); - } - - // Setup clones of transaction and buffers in map - tlm::tlm_generic_payload* gp = m_map[&trans].gp; - if (gp == 0) - gp = new tlm::tlm_generic_payload; // Memory leak: transactions are never cleared from map - else - { - delete [] gp->get_data_ptr(); - gp->free_all_extensions(); - } - gp->set_data_ptr( new uchar_t[trans.get_data_length()] ); - m_map[&trans].data_ptr = trans.get_data_ptr(); - - if (gp->get_byte_enable_ptr()) - delete [] gp->get_byte_enable_ptr(); - if (trans.get_byte_enable_ptr()) - gp->set_byte_enable_ptr( new uchar_t[trans.get_byte_enable_length()] ); - else - gp->set_byte_enable_ptr(0); - m_map[&trans].byte_enable_ptr = trans.get_byte_enable_ptr(); - - gp->deep_copy_from(trans); - m_map[&trans].gp = gp; - m_map[&trans].time = sc_core::SC_ZERO_TIME; - m_map[&trans].has_mm = trans.has_mm(); - - // Store request path checker sequence - if (shared_map[&trans].resp_data_ptr) - { - delete [] shared_map[&trans].resp_data_ptr; - shared_map[&trans].resp_data_ptr = 0; - } - if (shared_map[&trans].response_in_progress) - { - txt << "Transaction object sent with BEGIN_REQ while still being used on a previous response path, detected in " << txt2; - tlm2error(trans, "14.5 x)"); - } - shared_map[&trans].ok_response = false; - shared_map[&trans].path.push_back(this); -} - - -BOILERPLATE -remember_gp_option( - tlm::tlm_generic_payload& trans) -{ - // Setup clone of transaction in map in order to check gp_option only - tlm::tlm_generic_payload* gp = m_map[&trans].gp; - if (gp == 0) - gp = new tlm::tlm_generic_payload; // Memory leak: transactions are never cleared from map - gp->set_gp_option( trans.get_gp_option() ); - m_map[&trans].gp = gp; -} - - -BOILERPLATE -check_trans_not_modified( - tlm::tlm_generic_payload& trans, const char* txt2 ) -{ - tlm::tlm_generic_payload* init = m_map[&trans].gp; - - if (trans.get_command() != init->get_command()) - { - txt << "Command attribute modified during transaction lifetime, detected in " << txt2; - tlm2error(trans, "14.7"); - } - if (trans.get_data_ptr() != m_map[&trans].data_ptr) - { - txt << "Data pointer attribute modified during transaction lifetime, detected in " << txt2; - tlm2error(trans, "14.7"); - } - if (trans.get_data_length() != init->get_data_length()) - { - txt << "Data length attribute modified during transaction lifetime, detected in " << txt2; - tlm2error(trans, "14.7"); - } - if (trans.get_command() == tlm::TLM_WRITE_COMMAND) - for (unsigned int i = 0; i < init->get_data_length(); i++) - if (trans.get_data_ptr()[i] != init->get_data_ptr()[i]) - { - txt << "Data array modified during transaction lifetime, detected in " << txt2; - tlm2error(trans, "14.7"); - } - if (trans.get_byte_enable_ptr() != m_map[&trans].byte_enable_ptr) - { - txt << "Byte enable pointer attribute modified during transaction lifetime, detected in " << txt2; - tlm2error(trans, "14.7"); - } - if (trans.get_byte_enable_length() != init->get_byte_enable_length()) - { - txt << "Byte enable length attribute modified during transaction lifetime, detected in " << txt2; - tlm2error(trans, "14.7"); - } - if (trans.get_byte_enable_ptr()) - for (unsigned int i = 0; i < init->get_byte_enable_length(); i++) - if (trans.get_byte_enable_ptr()[i] != init->get_byte_enable_ptr()[i]) - { - txt << "Byte enable array modified during transaction lifetime, detected in " << txt2; - tlm2error(trans, "14.7"); - } - if (trans.get_streaming_width() != init->get_streaming_width()) - { - txt << "Streaming width attribute modified during transaction lifetime, detected in " << txt2; - tlm2error(trans, "14.7"); - } - if (init->get_gp_option() == tlm::TLM_MIN_PAYLOAD && trans.get_gp_option() != tlm::TLM_MIN_PAYLOAD) - { - txt << "Generic payload option attribute modified during transaction lifetime, detected in " << txt2; - tlm2error(trans, "14.8 g)"); - } - if ( !m_map[&trans].has_mm ) - { - if (trans.has_mm()) - { - txt << "Interconnect component sets a memory manager, but does not clear it on return, detected in " << txt2; - tlm2error(trans, "14.5 aa)"); - } - - for (unsigned int i = 0; i < tlm::max_num_extensions(); i++) - // Exclude tlm_endian_context extension from the check because it is not cloned in m_map - if (i != tlm::tlm_endian_context::ID) - if (trans.get_extension(i)) - if ( !m_map[&trans].gp->get_extension(i) ) - { - txt << "Extension set (index = " << i << ") without also being deleted in the absence of a memory manager, detected in " << txt2; - tlm2error(trans, "14.5 aa)"); - } - } - - uchar_t* resp_data_ptr = shared_map[&trans].resp_data_ptr; - if (resp_data_ptr) - for (unsigned int i = 0; i < trans.get_data_length(); i++) - if (trans.get_data_ptr()[i] != resp_data_ptr[i]) - { - txt << "Transaction data array modified in interconnect component on response path, detected in " << txt2; - tlm2error(trans, "14.7"); - } -} - - -BOILERPLATE -check_response_path( - tlm::tlm_generic_payload& trans, const char* txt2 ) -{ - if ( !shared_map[&trans].path.empty() ) - { - if ( this != shared_map[&trans].path.back() ) - { - txt << "BEGIN_RESP path is not the reverse of the BEGIN_REQ path."; - txt << "\nBEGIN_REQ path includes these checkers: -> "; - deque_t path = shared_map[&trans].path; - for (deque_t::iterator i = path.begin(); i < path.end(); i++) - txt << (*i)->name() << " -> "; - txt << "\nDetected in " << txt2; - tlm2error(trans, "15.2.11 a)"); - } - shared_map[&trans].path.pop_back(); - shared_map[&trans].response_in_progress = !shared_map[&trans].path.empty(); - shared_map[&trans].ok_response = trans.is_response_ok(); - - // Create a copy of the data array for comparison on the response path - if ( !shared_map[&trans].resp_data_ptr ) - { - shared_map[&trans].resp_data_ptr = new uchar_t[trans.get_data_length()]; - memcpy(shared_map[&trans].resp_data_ptr, trans.get_data_ptr(), trans.get_data_length()); - } - } -} - - -BOILERPLATE -get_direct_mem_ptr_pre_checks( - tlm::tlm_generic_payload& trans, tlm::tlm_dmi& dmi_data ) -{ - remember_gp_option(trans); - - if (dmi_data.get_dmi_ptr() != 0) - { - txt << "DMI descriptor not properly initialized: dmi_ptr != 0"; - tlm2error(trans, "11.2.5 f)"); - } - if (!dmi_data.is_none_allowed()) - { - txt << "DMI descriptor not properly initialized: granted_access != DMI_ACCESS_NONE"; - tlm2error(trans, "11.2.5 a)"); - } - if (dmi_data.get_start_address() != 0) - { - txt << "DMI descriptor not properly initialized: start_address != 0"; - tlm2error(trans, "11.2.5 u)"); - } - if (dmi_data.get_end_address() != (sc_dt::uint64)(-1)) - { - txt << "DMI descriptor not properly initialized: end_address != 0"; - tlm2error(trans, "11.2.5 u)"); - } - if (dmi_data.get_read_latency() != sc_core::SC_ZERO_TIME) - { - txt << "DMI descriptor not properly initialized: read_latency != SC_ZERO_TIME"; - tlm2error(trans, "11.2.5 ac)"); - } - if (dmi_data.get_write_latency() != sc_core::SC_ZERO_TIME) - { - txt << "DMI descriptor not properly initialized: write_latency != SC_ZERO_TIME"; - tlm2error(trans, "11.2.5 ac)"); - } - - if (trans.get_gp_option() == tlm::TLM_FULL_PAYLOAD) - { - /* - if (trans.is_dmi_allowed()) // Would be rather brutal to flag dmi_allowed as an arror for a DMI transaction! - { - txt << "DMI transaction not properly initialized: dmi_allowed == true"; - tlm2error(trans, "14.8 e) & 14.16"); - } - */ - if (trans.get_response_status() != tlm::TLM_INCOMPLETE_RESPONSE) - { - txt << "DMI transaction not properly initialized: response_status != TLM_INCOMPLETE_RESPONSE"; - tlm2error(trans, "14.8 e) & 14.17 e)"); - } - } - else if (trans.get_gp_option() == tlm::TLM_FULL_PAYLOAD_ACCEPTED) - { - txt << "DMI transaction not properly initialized: gp_option == TLM_FULL_PAYLOAD_ACCEPTED"; - tlm2error(trans, "14.8 c) & e) & j)"); - } -} - - -BOILERPLATE -get_direct_mem_ptr_post_checks( tlm::tlm_generic_payload& trans, tlm::tlm_dmi& /*dmi_data*/ ) -{ - tlm::tlm_generic_payload* init = m_map[&trans].gp; - - if (init->get_gp_option() == tlm::TLM_MIN_PAYLOAD && trans.get_gp_option() != tlm::TLM_MIN_PAYLOAD) - { - txt << "DMI transaction gp_option attribute value TLM_MIN_PAYLOAD modified during transaction lifetime"; - tlm2error(trans, "14.8 h)"); - } - else if (init->get_gp_option() == tlm::TLM_FULL_PAYLOAD && trans.get_gp_option() == tlm::TLM_MIN_PAYLOAD) - { - txt << "DMI transaction gp_option attribute value changed from TLM_FULL_PAYLOAD to TLM_MIN_PAYLOAD"; - tlm2error(trans, "14.8 j)"); - } -} - - -BOILERPLATE -transport_dbg_pre_checks( tlm::tlm_generic_payload& trans ) -{ - remember_gp_option(trans); - - if (trans.get_data_length() > 0 && trans.get_data_ptr() == 0) - { - txt << "Debug transaction has data_ptr == 0"; - tlm2error(trans, "11.3.4 l)"); - } - - if (trans.get_gp_option() == tlm::TLM_FULL_PAYLOAD) - { - if (trans.get_byte_enable_ptr() != 0 && trans.get_byte_enable_length() == 0) - { - txt << "Debug transaction not properly initialized: " - << "byte_enable_ptr != 0 and byte_enable_length == 0"; - tlm2error(trans, "14.8 f) & 14.14 f)"); - } - if (trans.get_streaming_width() == 0) - { - txt << "Debug transaction not properly initialized: streaming_width == 0"; - tlm2error(trans, "14.8 f) & 14.15 f)"); - } - if (trans.is_dmi_allowed()) - { - txt << "Debug transaction not properly initialized: dmi_allowed == true"; - tlm2error(trans, "14.8 f) & 14.16"); - } - if (trans.get_response_status() != tlm::TLM_INCOMPLETE_RESPONSE) - { - txt << "Debug transaction not properly initialized: response_status != TLM_INCOMPLETE_RESPONSE"; - tlm2error(trans, "14.8 f) & 14.17 e)"); - } - } - else if (trans.get_gp_option() == tlm::TLM_FULL_PAYLOAD_ACCEPTED) - { - txt << "Debug transaction not properly initialized: gp_option == TLM_FULL_PAYLOAD_ACCEPTED"; - tlm2error(trans, "14.8 c) & f) & l)"); - }} - - -BOILERPLATE -transport_dbg_post_checks( tlm::tlm_generic_payload& trans, unsigned int count ) -{ - tlm::tlm_generic_payload* init = m_map[&trans].gp; - - if (trans.get_data_length() > 0 && trans.get_data_ptr() == 0) - { - txt << "Debug transaction has data_ptr == 0"; - tlm2error(trans, "11.3.4 l)"); - } - if (count > trans.get_data_length()) - { - txt << "Count returned from transport_dbg is greater than data_length"; - tlm2error(trans, "11.3.4 s)"); - } - - if (init->get_gp_option() == tlm::TLM_MIN_PAYLOAD && trans.get_gp_option() != tlm::TLM_MIN_PAYLOAD) - { - txt << "Debug transaction gp_option attribute value TLM_MIN_PAYLOAD modified during transaction lifetime"; - tlm2error(trans, "14.8 h)"); - } - else if (init->get_gp_option() == tlm::TLM_FULL_PAYLOAD && trans.get_gp_option() == tlm::TLM_MIN_PAYLOAD) - { - txt << "Debug transaction gp_option attribute value changed from TLM_FULL_PAYLOAD to TLM_MIN_PAYLOAD"; - tlm2error(trans, "14.8 l)"); - }} - - -BOILERPLATE -tlm2error( tlm::tlm_generic_payload& trans, const char* ref, bool warning ) -{ - txt << "\n\nRefer to IEEE Std 1666-2011, clause " << ref; - txt << "\n\nChecker instance: " << this->name(); - txt << "\n\nTransaction details:"; - txt << "\n has_mm = " << dec << trans.has_mm() << " (bool)"; - txt << "\n ref_count = " << dec << trans.get_ref_count() << " (int)"; - txt << "\n\n gp_option = " << - (trans.get_gp_option() == tlm::TLM_MIN_PAYLOAD ? "TLM_MIN_PAYLOAD" - :trans.get_gp_option() == tlm::TLM_FULL_PAYLOAD ? "TLM_FULL_PAYLOAD" - : "TLM_FULL_PAYLOAD_ACCEPTED"); - txt << "\n command = " << - (trans.get_command() == tlm::TLM_READ_COMMAND ? "TLM_READ_COMMAND" - :trans.get_command() == tlm::TLM_WRITE_COMMAND ? "TLM_WRITE_COMMAND" - : "TLM_IGNORE_COMMAND"); - txt << "\n address = " << hex << trans.get_address() << " (hex)"; - txt << "\n data_ptr = " << hex - << reinterpret_cast(trans.get_data_ptr()) << " (hex)"; - txt << "\n data_length = " << hex << trans.get_data_length() << " (hex)"; - txt << "\n streaming_width = " << hex << trans.get_streaming_width() << " (hex)"; - txt << "\n byte_enable_ptr = " << hex - << reinterpret_cast(trans.get_byte_enable_ptr()) << " (hex)"; - txt << "\n byte_enable_length = " << hex << trans.get_byte_enable_length() << " (hex)"; - txt << "\n dmi_allowed = " << dec << trans.is_dmi_allowed() << " (bool)"; - txt << "\n response_status = " << trans.get_response_string(); - - bool extensions_present = false; - for (unsigned int i = 0; i < tlm::max_num_extensions(); i++) - { - tlm::tlm_extension_base* ext = trans.get_extension(i); - if (ext) - { - if (!extensions_present) - txt << "\n\n extensions:"; - txt << "\n index = " << i << " type = " << typeid(*ext).name(); - extensions_present = true; - } - } - - txt << "\n\n"; - if (warning) - SC_REPORT_WARNING("tlm2_protocol_checker", txt.str().c_str()); - else - SC_REPORT_ERROR("tlm2_protocol_checker", txt.str().c_str()); -} - - - -} // namespace tlm_utils - -#endif // __tlm2_base_protocol_checker__ + +// Filename: tlm2_base_protocol_checker.h + +//---------------------------------------------------------------------- +// Copyright (c) 2008-2013 by Doulos Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +//---------------------------------------------------------------------- + +// Author: John Aynsley, Doulos + +// Version 1, 11 July 2008 +// Version 2, 16 July 2008 Only generate ref_count > 1 warning from 1st checker of path +// Version 3, 17 July 2008 Support compilation under SystemC 2.1.v1 +// Version 4, 12 Aug 2008 Add header #include +// Version 5, 08 Sep 2008 Fix bugs in message text +// Version 6, 01 Aug 2010 Update messages to refer to OSCI TLM-2.0 LRM of July 2009 +// Version 7, 25 Oct 2011 Minor bug fix for certain compilers: replace u_char with uchar_t +// Version 8, 02 Nov 2011 Support the endianness conversion functions by excluding the +// tlm_endian_context extension from the protocol checks +// Version 9, 17 Aug 2012 Fix LRM reference on line 805 (should be 8.2.11 a) [NOT YET RELEASED] +// Version 10, 3 Jan 2013 Updated messages to refer to IEEE Std 1666-2011, the combined SystemC + TLM-2.0 LRM +// Added checks related to the generic payload option attribute +// Version 11, 14 Mar 2016 Fix minor bug - start_phase should be a copy, not a reference + +// TLM-2.0 Base Protocol Compliance Checker + +/* +Instantiate this checker module in-line between initiator and target, initiator and interconnect, +or interconnect and target by binding the target_socket and initiator_socket +Binding two checkers either side of an interconnect component, or interleaving a series of +checkers with interconnect components, will enable some deeper checks as against having just +a single checker + +For example + + Initiator *initiator; + Bus *bus; + Memory *memory; + ... + initiator->socket.bind(bus->target_socket); + bus->initiator_socket.bind(memory->socket); + +might become + + tlm_utils::tlm2_base_protocol_checker<32> *checker1; + tlm_utils::tlm2_base_protocol_checker<32> *checker2; + ... + initiator->socket.bind(checker1->target_socket); + checker1->initiator_socket.bind(bus->target_socket); + bus->initiator_socket.bind(checker2->target_socket); + checker2->initiator_socket.bind(memory->socket); + + +GENERAL FEATURES OF THE BASE PROTOCOL CHECKER + +The checks are relatively expensive, hence by default the number of checks is limited. +A maximum number can be set explicitly by calling set_num_checks(max) +Checking can be deactivated at any time by calling set_num_checks(0) +All checkers decrement a single global count, because having some checkers running and +others not can cause bogus violation reports +It is not permitted to turn checks on by calling set_num_checks() once checking has been +deactivated, because this could cause bogus violation reports + +The DMI and debug checks are unaffected by the num_checks count (because they are cheap) + +The error messages contain User Manual references + +The checker is designed to be used with a transaction pool: otherwise it could consume +a lot of memory. The checker keeps a local copy of each transaction object +Failures are reported with a severity of SC_ERROR. The actions may be overridden by calling: + sc_report_handler::set_actions("tlm2_protocol_checker", ...); + +SPECIFIC CHECKS + +nb_transport: phase sequence BEGIN_REQ -> END_REQ -> BEGIN_RESP -> END_RESP +Must not have two outstanding requests or responses (exclusion rules) +Must not have decreasing timing annotations on calls to or returns from nb_transport_fw/bw +Phase extensions permitted and ignored +Must not call b_transport during nb_transport phase sequence and vice-versa + +nb_transport: memory manager must be set +nb_transport: reference count must be non-zero +First checker in BEGIN_REQ path should see ref_count == 1 (warning only) +An interconnect component that sets a memory manager should also clear it +An interconnect component that sets extensions with no memory manager should also clear them +(Does not bother with these memory manager checks for DMI and debug) + +Transaction object must be properly initialized +Many generic payload attributes must not be modified during the transaction lifetime +Transaction object must not be re-allocated for a new transaction while still in use +DMI descriptor must be properly initialized +Debug transaction must be properly initialized +Debug byte count must be less than data_length + +Checks that require multiple checkers to be instantiated along a transaction path: +The BEGIN_RESP path must be the reverse of the BEGIN_REQ path +Transaction object must not be sent with BEGIN_REQ while participating in a previous response +Interconnect component must not set response status attribute to TLM_OK_RESPONSE +Interconnect component must not modify data array on the response path + +Generic payload option attribute (IEEE Std 1666-2011, SystemC 2.3.x) +gp_option must be properly initialized and only used for DMI and debug transport +When gp_option is used, other gp attributes must be initalized and used as per the transport interfaces +*/ + + +// ******************** PREAMBLE ******************** + + +#ifndef __tlm2_base_protocol_checker__ +#define __tlm2_base_protocol_checker__ + +#include "systemc" +using std::cout; +using std::endl; +using std::dec; +using std::hex; + +#include "tlm.h" +#include +#include + + +namespace tlm_utils { + + +// Number of checks remaining +const sc_dt::uint64 default_num_checks = 100000; +static sc_dt::uint64 num_checks = default_num_checks; + + +// Types used when building a trace of the transaction path +typedef unsigned char uchar_t; +typedef std::deque deque_t; + +struct path_t { + path_t () + { + response_in_progress = false; + ok_response = false; + resp_data_ptr = 0; + } + + bool response_in_progress; + bool ok_response; + deque_t path; + uchar_t *resp_data_ptr; // Copy of data on response path +}; + +// Global variable used for checks involving multiple checkers along a transaction path +static std::map shared_map; + + +// ******************** CLASS DEFINITION ******************** + + +template +class tlm2_base_protocol_checker + + : public sc_core::sc_module + , public tlm::tlm_fw_transport_if + , public tlm::tlm_bw_transport_if +{ +public: + + // Instantiate and bind checker inline between an existing pair of initiator and target sockets + + tlm::tlm_target_socket + target_socket; + tlm::tlm_initiator_socket + initiator_socket; + + SC_CTOR(tlm2_base_protocol_checker) + : m_request_in_progress(0), m_response_in_progress(0) + { + target_socket .bind( *this ); + initiator_socket.bind( *this ); + } + + + // Access methods for num_checks count + + static void set_num_checks(sc_dt::uint64 n) + { + if (num_checks == 0) + SC_REPORT_FATAL("tlm2_protocol_checker", + "Method set_num_checks called after checking has stopped due to maximum number of checks being reached"); + num_checks = n; + } + + static sc_dt::uint64 get_num_checks() + { + return num_checks; + } + + + // TLM-2.0 interface methods for initiator and target sockets, instrumented with checks + + virtual tlm::tlm_sync_enum nb_transport_fw( + tlm::tlm_generic_payload &trans, tlm::tlm_phase &phase, sc_core::sc_time &delay) + { + tlm::tlm_phase start_phase = phase; + + if (num_checks) + nb_transport_fw_pre_checks( trans, phase, delay ); + + tlm::tlm_sync_enum status; + status = initiator_socket->nb_transport_fw( trans, phase, delay ); + + if (num_checks) + nb_transport_fw_post_checks( trans, start_phase, phase, delay, status ); + + return status; + } + + virtual tlm::tlm_sync_enum nb_transport_bw( + tlm::tlm_generic_payload &trans, tlm::tlm_phase &phase, sc_core::sc_time &delay) + { + if (num_checks) + nb_transport_bw_pre_checks( trans, phase, delay ); + + tlm::tlm_sync_enum status; + status = target_socket->nb_transport_bw( trans, phase, delay ); + + if (num_checks) + nb_transport_bw_post_checks( trans, phase, delay, status ); + + return status; + } + + virtual void b_transport( tlm::tlm_generic_payload &trans, + sc_core::sc_time &delay ) + { + if (num_checks) + b_transport_pre_checks( trans, delay ); + + initiator_socket->b_transport( trans, delay ); + + if (num_checks) + b_transport_post_checks( trans, delay ); + } + + virtual bool get_direct_mem_ptr(tlm::tlm_generic_payload &trans, + tlm::tlm_dmi &dmi_data) + { + get_direct_mem_ptr_pre_checks( trans, dmi_data ); + + bool status; + status = initiator_socket->get_direct_mem_ptr( trans, dmi_data ); + + get_direct_mem_ptr_post_checks( trans, dmi_data ); + return status; + } + + virtual void invalidate_direct_mem_ptr(sc_dt::uint64 start_range, + sc_dt::uint64 end_range) + { + target_socket->invalidate_direct_mem_ptr(start_range, end_range); + } + + virtual unsigned int transport_dbg(tlm::tlm_generic_payload &trans) + { + transport_dbg_pre_checks( trans ); + + unsigned int count; + count = initiator_socket->transport_dbg( trans ); + + transport_dbg_post_checks( trans, count ); + return count; + } + + +private: + void b_transport_pre_checks( tlm::tlm_generic_payload &trans, + sc_core::sc_time &delay); + + void b_transport_post_checks( tlm::tlm_generic_payload &trans, + sc_core::sc_time &delay); + + void nb_transport_fw_pre_checks( + tlm::tlm_generic_payload &trans, tlm::tlm_phase &phase, + sc_core::sc_time &delay); + + void nb_transport_fw_post_checks( + tlm::tlm_generic_payload &trans, tlm::tlm_phase &start_phase, + tlm::tlm_phase &phase, + sc_core::sc_time &delay, tlm::tlm_sync_enum status); + + void nb_transport_bw_pre_checks( + tlm::tlm_generic_payload &trans, tlm::tlm_phase &phase, + sc_core::sc_time &delay); + + void nb_transport_bw_post_checks( + tlm::tlm_generic_payload &trans, tlm::tlm_phase &phase, sc_core::sc_time &delay, + tlm::tlm_sync_enum status); + + void nb_transport_response_checks( + tlm::tlm_generic_payload &trans, tlm::tlm_phase &phase, sc_core::sc_time &delay, + const char *txt2, const char *txt3, const char *txt4); + + void check_initial_state( tlm::tlm_generic_payload &trans, + const char *txt2 ); + void check_trans_not_modified( tlm::tlm_generic_payload &trans, + const char *txt2 ); + void check_response_path( tlm::tlm_generic_payload &trans, + const char *txt2 ); + void remember_gp_option( tlm::tlm_generic_payload &trans ); + + void get_direct_mem_ptr_pre_checks( tlm::tlm_generic_payload &trans, + tlm::tlm_dmi &dmi_data ); + + void get_direct_mem_ptr_post_checks( tlm::tlm_generic_payload &trans, + tlm::tlm_dmi &dmi_data ); + + void transport_dbg_pre_checks( tlm::tlm_generic_payload &trans ); + + void transport_dbg_post_checks( tlm::tlm_generic_payload &trans, + unsigned int count ); + + void tlm2error( tlm::tlm_generic_payload &trans, const char *ref, + bool warning = false ); + +private: + + struct state_t { + state_t() + { + b_call = 0; + ph = tlm::UNINITIALIZED_PHASE; + gp = 0; + } + + bool has_mm; + unsigned int b_call; // Number of b_transport calls in progress + tlm::tlm_phase ph; + sc_core::sc_time time; // Current time + annotated delay + tlm::tlm_generic_payload + *gp; // Points to new data and byte enable buffers + uchar_t *data_ptr; // Stores original pointers + uchar_t *byte_enable_ptr; + }; + + // Transaction state for the specific hop where this checker is inlined + std::map m_map; + + // Flags for exclusion rules + tlm::tlm_generic_payload *m_request_in_progress; + tlm::tlm_generic_payload *m_response_in_progress; + + std::ostringstream txt; + +}; + + + +// ******************** MEMBER FUNCTION DEFINITIONS ******************** + + +#define BOILERPLATE \ +template \ +void tlm2_base_protocol_checker:: + + +BOILERPLATE +b_transport_pre_checks( + tlm::tlm_generic_payload &trans, sc_core::sc_time & /*delay*/) +{ + ++ m_map[&trans].b_call; + + if ( trans.has_mm() && trans.get_ref_count() == 0) { + txt << "Transaction passed to b_transport with memory manager and reference count of 0"; + tlm2error(trans, "14.5 t)"); + } + check_initial_state(trans, "b_transport"); + +#if !(defined SYSTEMC_VERSION & SYSTEMC_VERSION <= 20050714) + if (sc_core::sc_get_current_process_handle().proc_kind() == + sc_core::SC_METHOD_PROC_) { + txt << "b_transport called from method process"; + tlm2error(trans, "11.1.1.4 b)"); + } +#endif + + if (m_map[&trans].ph > 0 && m_map[&trans].ph < 4) { + txt << "b_transport called during a sequence of nb_transport calls"; + tlm2error(trans, "15.2.10 c)"); + } +} + + +BOILERPLATE +b_transport_post_checks( + tlm::tlm_generic_payload &trans, sc_core::sc_time & /*delay*/) +{ + check_response_path(trans, "b_transport"); + check_trans_not_modified(trans, "b_transport"); + -- m_map[&trans].b_call; +} + + +BOILERPLATE +nb_transport_fw_pre_checks( + tlm::tlm_generic_payload &trans, tlm::tlm_phase &phase, sc_core::sc_time &delay) +{ + if ( !trans.has_mm() ) { + txt << "Transaction passed to nb_transport_fw with no memory manager set"; + tlm2error(trans, "14.5 i)"); + } + if ( trans.get_ref_count() == 0) { + txt << "Transaction passed to nb_transport_fw with reference count of 0"; + tlm2error(trans, "14.5 t)"); + } + + switch (phase) { + case tlm::BEGIN_REQ: + check_initial_state(trans, "nb_transport_fw"); + + if (m_map[&trans].ph > 0 + && m_map[&trans].ph < 4) { // END_RESP -> BEGIN_REQ is legal + txt << "Phase " << phase << + " sent out-of-sequence on forward path, detected in nb_transport_fw"; + tlm2error(trans, "15.2.4"); + } + + if (m_request_in_progress) { + txt << "Transaction violates BEGIN_REQ exclusion rule, detected in nb_transport_fw"; + tlm2error(trans, "15.2.6 e)"); + } + m_request_in_progress = &trans; + + if (m_map[&trans].b_call) { + txt << "nb_transport_fw called during a b_transport call"; + tlm2error(trans, "15.2.10 c)"); + } + break; + + case tlm::END_REQ: + case tlm::BEGIN_RESP: + case tlm::UNINITIALIZED_PHASE: + txt << "Phase " << phase << + " sent on forward path, detected in nb_transport_fw"; + tlm2error(trans, " 15.2.3 c)"); + break; + + case tlm::END_RESP: + if (m_map[&trans].ph != tlm::BEGIN_RESP) { + txt << "Phase " << phase << + " sent out-of-sequence on forward path, detected in nb_transport_fw"; + tlm2error(trans, "15.2.4"); + } + m_response_in_progress = 0; + break; + } + + if (phase < 5) // Ignore extended phases + m_map[&trans].ph = phase; + + if (sc_core::sc_time_stamp() + delay < m_map[&trans].time) { + txt << "nb_transport_fw called with decreasing timing annotation:" + << " delay = " << delay + << ", sc_time_stamp() + delay from previous call = " << m_map[&trans].time; + tlm2error(trans, "15.2.7 c)"); + } + m_map[&trans].time = sc_core::sc_time_stamp() + delay; +} + + +BOILERPLATE +nb_transport_fw_post_checks( + tlm::tlm_generic_payload &trans, tlm::tlm_phase &start_phase, + tlm::tlm_phase &phase, + sc_core::sc_time &delay, tlm::tlm_sync_enum status) +{ + if (status == tlm::TLM_UPDATED) { + nb_transport_response_checks( + trans, phase, delay, "(forward) return", "Return from nb_transport_fw", + "nb_transport_fw"); + } else if (status == tlm::TLM_COMPLETED) { + if (start_phase == tlm::BEGIN_REQ) + check_response_path(trans, "nb_transport_fw"); + m_request_in_progress = 0; + m_map[&trans].ph = tlm::UNINITIALIZED_PHASE; + } + + // Transaction object should not be re-allocated, even during the END_RESP phase + //if (phase != tlm::END_RESP) + { + std::ostringstream txt; + txt << "nb_transport_fw, phase = " << phase; + check_trans_not_modified(trans, txt.str().c_str()); + } +} + + +BOILERPLATE +nb_transport_bw_pre_checks( + tlm::tlm_generic_payload &trans, tlm::tlm_phase &phase, sc_core::sc_time &delay) +{ + if ( !trans.has_mm() ) { + txt << "Transaction passed to nb_transport_bw with no memory manager set"; + tlm2error(trans, "14.5 i)"); + } + if ( trans.get_ref_count() == 0) { + txt << "Transaction passed to nb_transport_bw with reference count of 0"; + tlm2error(trans, "14.5 t)"); + } + nb_transport_response_checks( + trans, phase, delay, "backward", "nb_transport_bw called", "nb_transport_bw"); +} + + +BOILERPLATE +nb_transport_bw_post_checks( + tlm::tlm_generic_payload &trans, tlm::tlm_phase &phase, sc_core::sc_time &delay, + tlm::tlm_sync_enum status) +{ + if (status == tlm::TLM_UPDATED) { + switch (phase) { + case tlm::BEGIN_REQ: + txt << "Phase " << phase << + " sent out-of-sequence on (backward) return path, detected in nb_transport_bw"; + tlm2error(trans, "15.2.4"); + break; + + case tlm::END_REQ: + case tlm::BEGIN_RESP: + case tlm::UNINITIALIZED_PHASE: + txt << "Phase " << phase << + " sent on (backward) return path, detected in nb_transport_bw"; + tlm2error(trans, "15.2.3 c)"); + break; + + case tlm::END_RESP: + if (m_map[&trans].ph != tlm::BEGIN_RESP) { + txt << "Phase " << phase << + " sent out-of-sequence on (backward) return path, detected in nb_transport_bw"; + tlm2error(trans, "15.2.4"); + } + + m_response_in_progress = 0; + break; + } + + if (phase < 5) // Ignore extended phases + m_map[&trans].ph = phase; + + if (sc_core::sc_time_stamp() + delay < m_map[&trans].time) { + txt << "Return from nb_transport_bw with decreasing timing annotation:" + << " delay = " << delay + << ", sc_time_stamp() + delay from previous call = " << m_map[&trans].time; + tlm2error(trans, "15.2.7 c)"); + } + m_map[&trans].time = sc_core::sc_time_stamp() + delay; + } else if (status == tlm::TLM_COMPLETED) { + m_response_in_progress = 0; + m_map[&trans].ph = tlm::UNINITIALIZED_PHASE; + } + + // Transaction object should not be re-allocated, even during the END_RESP phase + //if (phase != tlm::END_RESP) + { + std::ostringstream txt; + txt << "nb_transport_bw, phase = " << phase; + check_trans_not_modified(trans, txt.str().c_str()); + } +} + + +BOILERPLATE +nb_transport_response_checks( + tlm::tlm_generic_payload &trans, tlm::tlm_phase &phase, sc_core::sc_time &delay, + const char *txt2, const char *txt3, const char *txt4) +{ + if (trans.is_response_ok()) + if (shared_map[&trans].response_in_progress + && !shared_map[&trans].ok_response) { + txt << "Interconnect component sets response status attribute to TLM_OK_RESPONSE" + << ", detected in " << txt4; + tlm2error(trans, "14.7"); + + } + + switch (phase) { + case tlm::BEGIN_REQ: + case tlm::END_RESP: + case tlm::UNINITIALIZED_PHASE: + txt << "Phase " << phase << " sent on " << txt2 << " path" + << ", detected in " << txt4; + tlm2error(trans, "15.2.3 c)"); + break; + + case tlm::END_REQ: + if (m_map[&trans].ph != tlm::BEGIN_REQ) { + txt << "Phase " << phase << " sent out-of-sequence on " << txt2 << " path" + << ", detected in " << txt4; + tlm2error(trans, "15.2.4"); + } + + m_request_in_progress = 0; + break; + + case tlm::BEGIN_RESP: + if (m_map[&trans].ph != tlm::BEGIN_REQ && m_map[&trans].ph != tlm::END_REQ) { + txt << "Phase " << phase << " sent out-of-sequence on " << txt2 << " path" + << ", detected in " << txt4; + tlm2error(trans, "15.2.4"); + } + + if (&trans == m_request_in_progress) + m_request_in_progress = 0; + + if (m_response_in_progress) { + txt << "Transaction violates BEGIN_RESP exclusion rule" + << ", detected in " << txt4; + tlm2error(trans, "15.2.6 f)"); + } + m_response_in_progress = &trans; + + check_response_path(trans, txt4); + break; + } + + if (phase < 5) // Ignore extended phases + m_map[&trans].ph = phase; + + if (sc_core::sc_time_stamp() + delay < m_map[&trans].time) { + txt << txt3 << " with decreasing timing annotation:" + << " delay = " << delay + << ", sc_time_stamp() + delay from previous call = " << m_map[&trans].time; + tlm2error(trans, "15.2.7 c)"); + } + m_map[&trans].time = sc_core::sc_time_stamp() + delay; +} + + +BOILERPLATE +check_initial_state( + tlm::tlm_generic_payload &trans, const char *txt2 ) +{ + if (num_checks > 0) { + --num_checks; + if (num_checks == 0) + SC_REPORT_INFO("tlm2_protocol_checker", + "Checkers deactivated after executing the set number of checks"); + } + + if ( trans.has_mm() && trans.get_ref_count() > 1 + && shared_map[&trans].path.empty() ) { + txt << "New transaction passed to " << txt2 << " with reference count = " + << trans.get_ref_count(); + tlm2error(trans, "14.5 t)", true); + } + if (trans.get_data_ptr() == 0 + && trans.get_command() != tlm::TLM_IGNORE_COMMAND) { + txt << "Transaction not properly initialized: data_ptr == 0, detected in " << + txt2; + tlm2error(trans, "14.11 e)"); + } + if (trans.get_data_length() == 0 + && trans.get_command() != tlm::TLM_IGNORE_COMMAND) { + txt << "Transaction not properly initialized: data_langth == 0, detected in " << + txt2; + tlm2error(trans, "14.12 d)"); + } + if (trans.get_byte_enable_ptr() != 0 && trans.get_byte_enable_length() == 0) { + txt << "Transaction not properly initialized: " + << "byte_enable_ptr != 0 and byte_enable_length == 0, detected in " << txt2; + tlm2error(trans, "14.14 f)"); + } + if (trans.get_streaming_width() == 0) { + txt << "Transaction not properly initialized: streaming_width == 0, detected in " + << txt2; + tlm2error(trans, "14.15 f)"); + } + if (trans.is_dmi_allowed()) { + txt << "Transaction not properly initialized: dmi_allowed == true, detected in " + << txt2; + tlm2error(trans, "14.16"); + } + if (trans.get_response_status() != tlm::TLM_INCOMPLETE_RESPONSE) { + txt << "Transaction not properly initialized: response_status != TLM_INCOMPLETE_RESPONSE, detected in " + << txt2; + tlm2error(trans, "14.17 e)"); + } + if (trans.get_gp_option() != tlm::TLM_MIN_PAYLOAD) { + txt << "Transaction not properly initialized: gp_option != TLM_MIN_PAYLOAD, detected in " + << txt2; + tlm2error(trans, "14.8 g)"); + } + + // Setup clones of transaction and buffers in map + tlm::tlm_generic_payload *gp = m_map[&trans].gp; + if (gp == 0) + gp = new tlm::tlm_generic_payload; // Memory leak: transactions are never cleared from map + else { + delete [] gp->get_data_ptr(); + gp->free_all_extensions(); + } + gp->set_data_ptr( new uchar_t[trans.get_data_length()] ); + m_map[&trans].data_ptr = trans.get_data_ptr(); + + if (gp->get_byte_enable_ptr()) + delete [] gp->get_byte_enable_ptr(); + if (trans.get_byte_enable_ptr()) + gp->set_byte_enable_ptr( new uchar_t[trans.get_byte_enable_length()] ); + else + gp->set_byte_enable_ptr(0); + m_map[&trans].byte_enable_ptr = trans.get_byte_enable_ptr(); + + gp->deep_copy_from(trans); + m_map[&trans].gp = gp; + m_map[&trans].time = sc_core::SC_ZERO_TIME; + m_map[&trans].has_mm = trans.has_mm(); + + // Store request path checker sequence + if (shared_map[&trans].resp_data_ptr) { + delete [] shared_map[&trans].resp_data_ptr; + shared_map[&trans].resp_data_ptr = 0; + } + if (shared_map[&trans].response_in_progress) { + txt << "Transaction object sent with BEGIN_REQ while still being used on a previous response path, detected in " + << txt2; + tlm2error(trans, "14.5 x)"); + } + shared_map[&trans].ok_response = false; + shared_map[&trans].path.push_back(this); +} + + +BOILERPLATE +remember_gp_option( + tlm::tlm_generic_payload &trans) +{ + // Setup clone of transaction in map in order to check gp_option only + tlm::tlm_generic_payload *gp = m_map[&trans].gp; + if (gp == 0) + gp = new tlm::tlm_generic_payload; // Memory leak: transactions are never cleared from map + gp->set_gp_option( trans.get_gp_option() ); + m_map[&trans].gp = gp; +} + + +BOILERPLATE +check_trans_not_modified( + tlm::tlm_generic_payload &trans, const char *txt2 ) +{ + tlm::tlm_generic_payload *init = m_map[&trans].gp; + + if (trans.get_command() != init->get_command()) { + txt << "Command attribute modified during transaction lifetime, detected in " << + txt2; + tlm2error(trans, "14.7"); + } + if (trans.get_data_ptr() != m_map[&trans].data_ptr) { + txt << "Data pointer attribute modified during transaction lifetime, detected in " + << txt2; + tlm2error(trans, "14.7"); + } + if (trans.get_data_length() != init->get_data_length()) { + txt << "Data length attribute modified during transaction lifetime, detected in " + << txt2; + tlm2error(trans, "14.7"); + } + if (trans.get_command() == tlm::TLM_WRITE_COMMAND) + for (unsigned int i = 0; i < init->get_data_length(); i++) + if (trans.get_data_ptr()[i] != init->get_data_ptr()[i]) { + txt << "Data array modified during transaction lifetime, detected in " << txt2; + tlm2error(trans, "14.7"); + } + if (trans.get_byte_enable_ptr() != m_map[&trans].byte_enable_ptr) { + txt << "Byte enable pointer attribute modified during transaction lifetime, detected in " + << txt2; + tlm2error(trans, "14.7"); + } + if (trans.get_byte_enable_length() != init->get_byte_enable_length()) { + txt << "Byte enable length attribute modified during transaction lifetime, detected in " + << txt2; + tlm2error(trans, "14.7"); + } + if (trans.get_byte_enable_ptr()) + for (unsigned int i = 0; i < init->get_byte_enable_length(); i++) + if (trans.get_byte_enable_ptr()[i] != init->get_byte_enable_ptr()[i]) { + txt << "Byte enable array modified during transaction lifetime, detected in " << + txt2; + tlm2error(trans, "14.7"); + } + if (trans.get_streaming_width() != init->get_streaming_width()) { + txt << "Streaming width attribute modified during transaction lifetime, detected in " + << txt2; + tlm2error(trans, "14.7"); + } + if (init->get_gp_option() == tlm::TLM_MIN_PAYLOAD + && trans.get_gp_option() != tlm::TLM_MIN_PAYLOAD) { + txt << "Generic payload option attribute modified during transaction lifetime, detected in " + << txt2; + tlm2error(trans, "14.8 g)"); + } + if ( !m_map[&trans].has_mm ) { + if (trans.has_mm()) { + txt << "Interconnect component sets a memory manager, but does not clear it on return, detected in " + << txt2; + tlm2error(trans, "14.5 aa)"); + } + + for (unsigned int i = 0; i < tlm::max_num_extensions(); i++) + // Exclude tlm_endian_context extension from the check because it is not cloned in m_map + if (i != tlm::tlm_endian_context::ID) + if (trans.get_extension(i)) + if ( !m_map[&trans].gp->get_extension(i) ) { + txt << "Extension set (index = " << i << + ") without also being deleted in the absence of a memory manager, detected in " + << txt2; + tlm2error(trans, "14.5 aa)"); + } + } + + uchar_t *resp_data_ptr = shared_map[&trans].resp_data_ptr; + if (resp_data_ptr) + for (unsigned int i = 0; i < trans.get_data_length(); i++) + if (trans.get_data_ptr()[i] != resp_data_ptr[i]) { + txt << "Transaction data array modified in interconnect component on response path, detected in " + << txt2; + tlm2error(trans, "14.7"); + } +} + + +BOILERPLATE +check_response_path( + tlm::tlm_generic_payload &trans, const char *txt2 ) +{ + if ( !shared_map[&trans].path.empty() ) { + if ( this != shared_map[&trans].path.back() ) { + txt << "BEGIN_RESP path is not the reverse of the BEGIN_REQ path."; + txt << "\nBEGIN_REQ path includes these checkers: -> "; + deque_t path = shared_map[&trans].path; + for (deque_t::iterator i = path.begin(); i < path.end(); i++) + txt << (*i)->name() << " -> "; + txt << "\nDetected in " << txt2; + tlm2error(trans, "15.2.11 a)"); + } + shared_map[&trans].path.pop_back(); + shared_map[&trans].response_in_progress = !shared_map[&trans].path.empty(); + shared_map[&trans].ok_response = trans.is_response_ok(); + + // Create a copy of the data array for comparison on the response path + if ( !shared_map[&trans].resp_data_ptr ) { + shared_map[&trans].resp_data_ptr = new uchar_t[trans.get_data_length()]; + memcpy(shared_map[&trans].resp_data_ptr, trans.get_data_ptr(), + trans.get_data_length()); + } + } +} + + +BOILERPLATE +get_direct_mem_ptr_pre_checks( + tlm::tlm_generic_payload &trans, tlm::tlm_dmi &dmi_data ) +{ + remember_gp_option(trans); + + if (dmi_data.get_dmi_ptr() != 0) { + txt << "DMI descriptor not properly initialized: dmi_ptr != 0"; + tlm2error(trans, "11.2.5 f)"); + } + if (!dmi_data.is_none_allowed()) { + txt << "DMI descriptor not properly initialized: granted_access != DMI_ACCESS_NONE"; + tlm2error(trans, "11.2.5 a)"); + } + if (dmi_data.get_start_address() != 0) { + txt << "DMI descriptor not properly initialized: start_address != 0"; + tlm2error(trans, "11.2.5 u)"); + } + if (dmi_data.get_end_address() != (sc_dt::uint64)(-1)) { + txt << "DMI descriptor not properly initialized: end_address != 0"; + tlm2error(trans, "11.2.5 u)"); + } + if (dmi_data.get_read_latency() != sc_core::SC_ZERO_TIME) { + txt << "DMI descriptor not properly initialized: read_latency != SC_ZERO_TIME"; + tlm2error(trans, "11.2.5 ac)"); + } + if (dmi_data.get_write_latency() != sc_core::SC_ZERO_TIME) { + txt << "DMI descriptor not properly initialized: write_latency != SC_ZERO_TIME"; + tlm2error(trans, "11.2.5 ac)"); + } + + if (trans.get_gp_option() == tlm::TLM_FULL_PAYLOAD) { + /* + if (trans.is_dmi_allowed()) // Would be rather brutal to flag dmi_allowed as an arror for a DMI transaction! + { + txt << "DMI transaction not properly initialized: dmi_allowed == true"; + tlm2error(trans, "14.8 e) & 14.16"); + } + */ + if (trans.get_response_status() != tlm::TLM_INCOMPLETE_RESPONSE) { + txt << "DMI transaction not properly initialized: response_status != TLM_INCOMPLETE_RESPONSE"; + tlm2error(trans, "14.8 e) & 14.17 e)"); + } + } else if (trans.get_gp_option() == tlm::TLM_FULL_PAYLOAD_ACCEPTED) { + txt << "DMI transaction not properly initialized: gp_option == TLM_FULL_PAYLOAD_ACCEPTED"; + tlm2error(trans, "14.8 c) & e) & j)"); + } +} + + +BOILERPLATE +get_direct_mem_ptr_post_checks( tlm::tlm_generic_payload &trans, + tlm::tlm_dmi & /*dmi_data*/ ) +{ + tlm::tlm_generic_payload *init = m_map[&trans].gp; + + if (init->get_gp_option() == tlm::TLM_MIN_PAYLOAD + && trans.get_gp_option() != tlm::TLM_MIN_PAYLOAD) { + txt << "DMI transaction gp_option attribute value TLM_MIN_PAYLOAD modified during transaction lifetime"; + tlm2error(trans, "14.8 h)"); + } else if (init->get_gp_option() == tlm::TLM_FULL_PAYLOAD + && trans.get_gp_option() == tlm::TLM_MIN_PAYLOAD) { + txt << "DMI transaction gp_option attribute value changed from TLM_FULL_PAYLOAD to TLM_MIN_PAYLOAD"; + tlm2error(trans, "14.8 j)"); + } +} + + +BOILERPLATE +transport_dbg_pre_checks( tlm::tlm_generic_payload &trans ) +{ + remember_gp_option(trans); + + if (trans.get_data_length() > 0 && trans.get_data_ptr() == 0) { + txt << "Debug transaction has data_ptr == 0"; + tlm2error(trans, "11.3.4 l)"); + } + + if (trans.get_gp_option() == tlm::TLM_FULL_PAYLOAD) { + if (trans.get_byte_enable_ptr() != 0 && trans.get_byte_enable_length() == 0) { + txt << "Debug transaction not properly initialized: " + << "byte_enable_ptr != 0 and byte_enable_length == 0"; + tlm2error(trans, "14.8 f) & 14.14 f)"); + } + if (trans.get_streaming_width() == 0) { + txt << "Debug transaction not properly initialized: streaming_width == 0"; + tlm2error(trans, "14.8 f) & 14.15 f)"); + } + if (trans.is_dmi_allowed()) { + txt << "Debug transaction not properly initialized: dmi_allowed == true"; + tlm2error(trans, "14.8 f) & 14.16"); + } + if (trans.get_response_status() != tlm::TLM_INCOMPLETE_RESPONSE) { + txt << "Debug transaction not properly initialized: response_status != TLM_INCOMPLETE_RESPONSE"; + tlm2error(trans, "14.8 f) & 14.17 e)"); + } + } else if (trans.get_gp_option() == tlm::TLM_FULL_PAYLOAD_ACCEPTED) { + txt << "Debug transaction not properly initialized: gp_option == TLM_FULL_PAYLOAD_ACCEPTED"; + tlm2error(trans, "14.8 c) & f) & l)"); + } +} + + +BOILERPLATE +transport_dbg_post_checks( tlm::tlm_generic_payload &trans, unsigned int count ) +{ + tlm::tlm_generic_payload *init = m_map[&trans].gp; + + if (trans.get_data_length() > 0 && trans.get_data_ptr() == 0) { + txt << "Debug transaction has data_ptr == 0"; + tlm2error(trans, "11.3.4 l)"); + } + if (count > trans.get_data_length()) { + txt << "Count returned from transport_dbg is greater than data_length"; + tlm2error(trans, "11.3.4 s)"); + } + + if (init->get_gp_option() == tlm::TLM_MIN_PAYLOAD + && trans.get_gp_option() != tlm::TLM_MIN_PAYLOAD) { + txt << "Debug transaction gp_option attribute value TLM_MIN_PAYLOAD modified during transaction lifetime"; + tlm2error(trans, "14.8 h)"); + } else if (init->get_gp_option() == tlm::TLM_FULL_PAYLOAD + && trans.get_gp_option() == tlm::TLM_MIN_PAYLOAD) { + txt << "Debug transaction gp_option attribute value changed from TLM_FULL_PAYLOAD to TLM_MIN_PAYLOAD"; + tlm2error(trans, "14.8 l)"); + } +} + + +BOILERPLATE +tlm2error( tlm::tlm_generic_payload &trans, const char *ref, bool warning ) +{ + txt << "\n\nRefer to IEEE Std 1666-2011, clause " << ref; + txt << "\n\nChecker instance: " << this->name(); + txt << "\n\nTransaction details:"; + txt << "\n has_mm = " << dec << trans.has_mm() << " (bool)"; + txt << "\n ref_count = " << dec << trans.get_ref_count() << " (int)"; + txt << "\n\n gp_option = " << + (trans.get_gp_option() == tlm::TLM_MIN_PAYLOAD ? "TLM_MIN_PAYLOAD" + : trans.get_gp_option() == tlm::TLM_FULL_PAYLOAD ? "TLM_FULL_PAYLOAD" + : "TLM_FULL_PAYLOAD_ACCEPTED"); + txt << "\n command = " << + (trans.get_command() == tlm::TLM_READ_COMMAND ? "TLM_READ_COMMAND" + : trans.get_command() == tlm::TLM_WRITE_COMMAND ? "TLM_WRITE_COMMAND" + : "TLM_IGNORE_COMMAND"); + txt << "\n address = " << hex << trans.get_address() << " (hex)"; + txt << "\n data_ptr = " << hex + << reinterpret_cast(trans.get_data_ptr()) << " (hex)"; + txt << "\n data_length = " << hex << trans.get_data_length() << + " (hex)"; + txt << "\n streaming_width = " << hex << trans.get_streaming_width() << + " (hex)"; + txt << "\n byte_enable_ptr = " << hex + << reinterpret_cast(trans.get_byte_enable_ptr()) << " (hex)"; + txt << "\n byte_enable_length = " << hex << trans.get_byte_enable_length() << + " (hex)"; + txt << "\n dmi_allowed = " << dec << trans.is_dmi_allowed() << + " (bool)"; + txt << "\n response_status = " << trans.get_response_string(); + + bool extensions_present = false; + for (unsigned int i = 0; i < tlm::max_num_extensions(); i++) { + tlm::tlm_extension_base *ext = trans.get_extension(i); + if (ext) { + if (!extensions_present) + txt << "\n\n extensions:"; + txt << "\n index = " << i << " type = " << typeid(*ext).name(); + extensions_present = true; + } + } + + txt << "\n\n"; + if (warning) + SC_REPORT_WARNING("tlm2_protocol_checker", txt.str().c_str()); + else + SC_REPORT_ERROR("tlm2_protocol_checker", txt.str().c_str()); +} + + + +} // namespace tlm_utils + +#endif // __tlm2_base_protocol_checker__ diff --git a/DRAMSys/library/src/common/xmlAddressdecoder.cpp b/DRAMSys/library/src/common/xmlAddressdecoder.cpp index 639631fa..d0264cea 100644 --- a/DRAMSys/library/src/common/xmlAddressdecoder.cpp +++ b/DRAMSys/library/src/common/xmlAddressdecoder.cpp @@ -53,18 +53,16 @@ void xmlAddressDecoder::setConfiguration(std::string addressConfigURI) { tinyxml2::XMLDocument doc; loadXML(addressConfigURI, doc); - tinyxml2::XMLElement* addressMap = doc.RootElement(); + tinyxml2::XMLElement *addressMap = doc.RootElement(); string xmlNodeName(addressMap->Name()); - if( xmlNodeName != "addressmapping") - { + if ( xmlNodeName != "addressmapping") { reportFatal("AddressDecorder", "addressmap node expected"); } - for(XMLElement* child = addressMap->FirstChildElement(); - child != NULL; - child = child->NextSiblingElement()) - { + for (XMLElement *child = addressMap->FirstChildElement(); + child != NULL; + child = child->NextSiblingElement()) { int from; int to; @@ -85,7 +83,8 @@ DecodedAddress xmlAddressDecoder::decodeAddress(sc_dt::uint64 addr) //result.rank = (addr & masks["rank"]) >> shifts["rank"]; //result.bankgroup = (addr & masks["bankgroup"]) >> shifts["bankgroup"]; result.bank = (addr & masks["bank"]) >> shifts["bank"]; - result.bankgroup = result.bank % Configuration::getInstance().memSpec.NumberOfBankGroups; + result.bankgroup = result.bank % + Configuration::getInstance().memSpec.NumberOfBankGroups; result.rank = result.bank % Configuration::getInstance().memSpec.NumberOfRanks; result.row = (addr & masks["row"]) >> shifts["row"]; result.column = (addr & masks["column"]) >> shifts["column"]; @@ -96,21 +95,20 @@ DecodedAddress xmlAddressDecoder::decodeAddress(sc_dt::uint64 addr) sc_dt::uint64 xmlAddressDecoder::encodeAddress(DecodedAddress n) { return n.channel << shifts["channel"] | - n.rank << shifts["rank"] | - n.bankgroup << shifts["bankgroup"] | - n.row << shifts["row"] | - n.bank << shifts["bank"] | - n.column << shifts["column"] | - n.bytes << shifts["bytes"]; + n.rank << shifts["rank"] | + n.bankgroup << shifts["bankgroup"] | + n.row << shifts["row"] | + n.bank << shifts["bank"] | + n.column << shifts["column"] | + n.bytes << shifts["bytes"]; } void xmlAddressDecoder::print() { cout << "Used addressmapping:" << endl; cout << headline << endl; - for(auto& pair : masks) - { - cout<(pair.second)<(pair.second) << endl; } - cout<<"\n"< masks; std::map shifts; - tinyxml2::XMLElement* addressmapping; + tinyxml2::XMLElement *addressmapping; - public: +public: virtual DecodedAddress decodeAddress(sc_dt::uint64 addr); virtual sc_dt::uint64 encodeAddress(DecodedAddress n); diff --git a/DRAMSys/library/src/controller/Command.cpp b/DRAMSys/library/src/controller/Command.cpp index 4c5f4aa2..448941b9 100644 --- a/DRAMSys/library/src/controller/Command.cpp +++ b/DRAMSys/library/src/controller/Command.cpp @@ -41,8 +41,7 @@ std::string commandToString(Command command) { - switch (command) - { + switch (command) { case Command::Read: return "RD"; break; @@ -99,19 +98,19 @@ std::string commandToString(Command command) return ""; } -const std::vector& getAllCommands() +const std::vector &getAllCommands() { static std::vector allCommands( { Command::Precharge, Command::PrechargeAll, Command::Activate, Command::Read, Command::Write, Command::ReadA, Command::WriteA, Command::AutoRefresh, Command::PDNA, Command::PDNAX, Command::PDNP, Command::PDNPX, - Command::SREF, Command::SREFX }); + Command::SREF, Command::SREFX + }); return allCommands; } bool commandIsIn(Command command, std::vector commands) { - for (Command c : commands) - { + for (Command c : commands) { if (c == command) return true; } diff --git a/DRAMSys/library/src/controller/Command.h b/DRAMSys/library/src/controller/Command.h index ff95fc2c..e8b5ee3f 100644 --- a/DRAMSys/library/src/controller/Command.h +++ b/DRAMSys/library/src/controller/Command.h @@ -42,7 +42,7 @@ enum class Command {NOP, Precharge, PrechargeAll, Activate, Read, Write, ReadA, WriteA, AutoRefresh, PDNA, PDNAX, PDNP, PDNPX, SREF, SREFX}; std::string commandToString(Command command); -const std::vector& getAllCommands(); +const std::vector &getAllCommands(); bool commandIsIn(Command command, std::vector commands); #endif /* COMMAND_H_ */ diff --git a/DRAMSys/library/src/controller/Controller.cpp b/DRAMSys/library/src/controller/Controller.cpp index 1c4b2333..3d0e6c58 100644 --- a/DRAMSys/library/src/controller/Controller.cpp +++ b/DRAMSys/library/src/controller/Controller.cpp @@ -43,29 +43,19 @@ void Controller::buildScheduler() string selectedScheduler = Configuration::getInstance().Scheduler; std::cout << "Selected Scheduler: " << selectedScheduler << std::endl; - if (selectedScheduler == "FIFO") - { + if (selectedScheduler == "FIFO") { scheduler = new Fifo(*controllerCore); - } - else if (selectedScheduler == "FIFO_STRICT") - { + } else if (selectedScheduler == "FIFO_STRICT") { scheduler = new FifoStrict(*this, *controllerCore); - } - else if (selectedScheduler == "FR_FCFS") - { + } else if (selectedScheduler == "FR_FCFS") { scheduler = new FR_FCFS(*controllerCore); - } - else if (selectedScheduler == "FR_FCFS_RP") - { + } else if (selectedScheduler == "FR_FCFS_RP") { scheduler = new FR_FCFS_RP(*controllerCore); - } - else if (selectedScheduler == "FR_FCFS_GRP") - { - scheduler = new FR_FCFS_GRP(*controllerCore,this); - } - else if (selectedScheduler == "SMS") - { - scheduler = new SMS("SMS", *controllerCore, Configuration::getInstance().SJFProbability); + } else if (selectedScheduler == "FR_FCFS_GRP") { + scheduler = new FR_FCFS_GRP(*controllerCore, this); + } else if (selectedScheduler == "SMS") { + scheduler = new SMS("SMS", *controllerCore, + Configuration::getInstance().SJFProbability); } //else if (selectedScheduler == "PAR_BS") //{ @@ -81,98 +71,105 @@ void Controller::buildScheduler() } //Send the next scheduled command to the DRAM -void Controller::send(const ScheduledCommand &command, tlm_generic_payload &payload) +void Controller::send(const ScheduledCommand &command, + tlm_generic_payload &payload) { sc_assert(command.getStart() >= sc_time_stamp()); TimeInterval dataStrobe; - switch (command.getCommand()) - { + switch (command.getCommand()) { //TODO: refactor tlm recorder case Command::Read: dataStrobe = command.getIntervalOnDataStrobe(); tlmRecorder->updateDataStrobe(dataStrobe.start, dataStrobe.end, payload); - controllerCorePEQ.notify(payload, BEGIN_RD, command.getStart() - sc_time_stamp()); + controllerCorePEQ.notify(payload, BEGIN_RD, + command.getStart() - sc_time_stamp()); break; case Command::ReadA: dataStrobe = command.getIntervalOnDataStrobe(); tlmRecorder->updateDataStrobe(dataStrobe.start, dataStrobe.end, payload); - controllerCorePEQ.notify(payload, BEGIN_RDA, command.getStart() - sc_time_stamp()); + controllerCorePEQ.notify(payload, BEGIN_RDA, + command.getStart() - sc_time_stamp()); break; case Command::Write: dataStrobe = command.getIntervalOnDataStrobe(); tlmRecorder->updateDataStrobe(dataStrobe.start, dataStrobe.end, payload); - controllerCorePEQ.notify(payload, BEGIN_WR, command.getStart() - sc_time_stamp()); + controllerCorePEQ.notify(payload, BEGIN_WR, + command.getStart() - sc_time_stamp()); break; case Command::WriteA: dataStrobe = command.getIntervalOnDataStrobe(); tlmRecorder->updateDataStrobe(dataStrobe.start, dataStrobe.end, payload); - controllerCorePEQ.notify(payload, BEGIN_WRA, command.getStart() - sc_time_stamp()); + controllerCorePEQ.notify(payload, BEGIN_WRA, + command.getStart() - sc_time_stamp()); break; case Command::AutoRefresh: - if(!Configuration::getInstance().BankwiseLogic) - { - controllerCorePEQ.notify(payload, BEGIN_REFA, command.getStart() - sc_time_stamp()); - } - else - controllerCorePEQ.notify(payload, BEGIN_REFB, command.getStart() - sc_time_stamp()); + if (!Configuration::getInstance().BankwiseLogic) { + controllerCorePEQ.notify(payload, BEGIN_REFA, + command.getStart() - sc_time_stamp()); + } else + controllerCorePEQ.notify(payload, BEGIN_REFB, + command.getStart() - sc_time_stamp()); break; case Command::Activate: - controllerCorePEQ.notify(payload, BEGIN_ACT, command.getStart() - sc_time_stamp()); + controllerCorePEQ.notify(payload, BEGIN_ACT, + command.getStart() - sc_time_stamp()); break; case Command::Precharge: - controllerCorePEQ.notify(payload, BEGIN_PRE, command.getStart() - sc_time_stamp()); + controllerCorePEQ.notify(payload, BEGIN_PRE, + command.getStart() - sc_time_stamp()); break; case Command::PrechargeAll: - controllerCorePEQ.notify(payload, BEGIN_PRE_ALL, command.getStart() - sc_time_stamp()); + controllerCorePEQ.notify(payload, BEGIN_PRE_ALL, + command.getStart() - sc_time_stamp()); break; case Command::PDNA: - if(!Configuration::getInstance().BankwiseLogic) - { - controllerCorePEQ.notify(payload, BEGIN_PDNA, command.getStart() - sc_time_stamp()); - } - else - controllerCorePEQ.notify(payload, BEGIN_PDNAB, command.getStart() - sc_time_stamp()); + if (!Configuration::getInstance().BankwiseLogic) { + controllerCorePEQ.notify(payload, BEGIN_PDNA, + command.getStart() - sc_time_stamp()); + } else + controllerCorePEQ.notify(payload, BEGIN_PDNAB, + command.getStart() - sc_time_stamp()); break; case Command::PDNAX: - if(!Configuration::getInstance().BankwiseLogic) - { - controllerCorePEQ.notify(payload, END_PDNA, command.getStart() - sc_time_stamp()); - } - else - controllerCorePEQ.notify(payload, END_PDNAB, command.getStart() - sc_time_stamp()); + if (!Configuration::getInstance().BankwiseLogic) { + controllerCorePEQ.notify(payload, END_PDNA, + command.getStart() - sc_time_stamp()); + } else + controllerCorePEQ.notify(payload, END_PDNAB, + command.getStart() - sc_time_stamp()); break; case Command::PDNP: - if(!Configuration::getInstance().BankwiseLogic) - { - controllerCorePEQ.notify(payload, BEGIN_PDNP, command.getStart() - sc_time_stamp()); - } - else - controllerCorePEQ.notify(payload, BEGIN_PDNPB, command.getStart() - sc_time_stamp()); + if (!Configuration::getInstance().BankwiseLogic) { + controllerCorePEQ.notify(payload, BEGIN_PDNP, + command.getStart() - sc_time_stamp()); + } else + controllerCorePEQ.notify(payload, BEGIN_PDNPB, + command.getStart() - sc_time_stamp()); break; case Command::PDNPX: - if(!Configuration::getInstance().BankwiseLogic) - { - controllerCorePEQ.notify(payload, END_PDNP, command.getStart() - sc_time_stamp()); - } - else - controllerCorePEQ.notify(payload, END_PDNPB, command.getStart() - sc_time_stamp()); + if (!Configuration::getInstance().BankwiseLogic) { + controllerCorePEQ.notify(payload, END_PDNP, + command.getStart() - sc_time_stamp()); + } else + controllerCorePEQ.notify(payload, END_PDNPB, + command.getStart() - sc_time_stamp()); break; case Command::SREF: - if(!Configuration::getInstance().BankwiseLogic) - { - controllerCorePEQ.notify(payload, BEGIN_SREF, command.getStart() - sc_time_stamp()); - } - else - controllerCorePEQ.notify(payload, BEGIN_SREFB, command.getStart() - sc_time_stamp()); + if (!Configuration::getInstance().BankwiseLogic) { + controllerCorePEQ.notify(payload, BEGIN_SREF, + command.getStart() - sc_time_stamp()); + } else + controllerCorePEQ.notify(payload, BEGIN_SREFB, + command.getStart() - sc_time_stamp()); break; case Command::SREFX: - if(!Configuration::getInstance().BankwiseLogic) - { - controllerCorePEQ.notify(payload, END_SREF, command.getStart() - sc_time_stamp()); - } - else - controllerCorePEQ.notify(payload, END_SREFB, command.getStart() - sc_time_stamp()); + if (!Configuration::getInstance().BankwiseLogic) { + controllerCorePEQ.notify(payload, END_SREF, + command.getStart() - sc_time_stamp()); + } else + controllerCorePEQ.notify(payload, END_SREFB, + command.getStart() - sc_time_stamp()); break; default: SC_REPORT_FATAL(0, "unsupported command was sent by controller"); @@ -181,65 +178,61 @@ void Controller::send(const ScheduledCommand &command, tlm_generic_payload &payl } //Trigger the next planned refresh or the power down mode on the DRAM -void Controller::send(Trigger trigger, sc_time time, tlm_generic_payload &payload) +void Controller::send(Trigger trigger, sc_time time, + tlm_generic_payload &payload) { sc_assert(time >= sc_time_stamp()); sc_time delay = time - sc_time_stamp(); - if (trigger == Trigger::REFTrigger) - { + if (trigger == Trigger::REFTrigger) { controllerCorePEQ.notify(payload, REF_TRIGGER, delay); - } - else if (trigger == Trigger::PDNTrigger) - { + } else if (trigger == Trigger::PDNTrigger) { controllerCorePEQ.notify(payload, PDN_TRIGGER, delay); - } - else - { + } else { SC_REPORT_FATAL("controller wrapper", "unknown trigger"); } } -void Controller::controllerCorePEQCallback(tlm_generic_payload &payload, const tlm_phase &phase) +void Controller::controllerCorePEQCallback(tlm_generic_payload &payload, + const tlm_phase &phase) { - if (phase == REF_TRIGGER) - { + if (phase == REF_TRIGGER) { controllerCore->triggerRefresh(payload); - } - else if (phase == PDN_TRIGGER) - { - controllerCore->powerDownManager->sleep(DramExtension::getExtension(payload).getBank(),sc_time_stamp()); - } - else - { + } else if (phase == PDN_TRIGGER) { + controllerCore->powerDownManager->sleep(DramExtension::getExtension( + payload).getBank(), sc_time_stamp()); + } else { Bank bank = DramExtension::getBank(payload); sendToDram(payload, phase, SC_ZERO_TIME); - if (phase == BEGIN_RD || phase == BEGIN_WR) - { + if (phase == BEGIN_RD || phase == BEGIN_WR) { scheduleNextFromScheduler(DramExtension::getBank(payload)); - } - else if (phase == BEGIN_REFB) + } else if (phase == BEGIN_REFB) printDebugMessage("Entering REFB on bank " + to_string(bank.ID())); else if (phase == BEGIN_REFA) printDebugMessage("Entering REFA"); else if (containsPhase(phase, { BEGIN_PDNAB, BEGIN_PDNPB, BEGIN_SREFB })) - printDebugMessage("Entering PowerDown " + phaseNameToString(phase) + " on bank " + to_string(bank.ID())); + printDebugMessage("Entering PowerDown " + phaseNameToString( + phase) + " on bank " + to_string(bank.ID())); else if (containsPhase(phase, { END_PDNAB, END_PDNPB, END_SREFB })) - printDebugMessage("Leaving PowerDown " + phaseNameToString(phase) + " on bank " + to_string(bank.ID())); + printDebugMessage("Leaving PowerDown " + phaseNameToString( + phase) + " on bank " + to_string(bank.ID())); else if (containsPhase(phase, { BEGIN_PDNA, BEGIN_PDNP, BEGIN_SREF })) - printDebugMessage("Entering PowerDown " + phaseNameToString(phase) + " on all banks"); + printDebugMessage("Entering PowerDown " + phaseNameToString( + phase) + " on all banks"); else if (containsPhase(phase, { END_PDNA, END_PDNP, END_SREF })) - printDebugMessage("Leaving PowerDown " + phaseNameToString(phase) + " on all banks" ); - else if (containsPhase(phase, { BEGIN_RD, BEGIN_WR, BEGIN_ACT, BEGIN_PRE, BEGIN_PRE_ALL, BEGIN_RDA, BEGIN_WRA })) - { + printDebugMessage("Leaving PowerDown " + phaseNameToString( + phase) + " on all banks" ); + else if (containsPhase(phase, { BEGIN_RD, BEGIN_WR, BEGIN_ACT, BEGIN_PRE, BEGIN_PRE_ALL, BEGIN_RDA, BEGIN_WRA })) { } else - SC_REPORT_FATAL(0, "refreshTriggerPEQCallback queue in controller wrapper was triggered with unsupported phase"); + SC_REPORT_FATAL(0, + "refreshTriggerPEQCallback queue in controller wrapper was triggered with unsupported phase"); } } -tlm_sync_enum Controller::nb_transport_fw(tlm_generic_payload &payload, tlm_phase &phase, sc_time &fwDelay) +tlm_sync_enum Controller::nb_transport_fw(tlm_generic_payload &payload, + tlm_phase &phase, sc_time &fwDelay) { sc_time recTime; sc_time notDelay; @@ -251,31 +244,39 @@ tlm_sync_enum Controller::nb_transport_fw(tlm_generic_payload &payload, tlm_phas unsigned int row = DramExtension::getExtension(payload).getRow().ID(); unsigned int col = DramExtension::getExtension(payload).getColumn().ID(); - if (phase == BEGIN_REQ) - { + if (phase == BEGIN_REQ) { recTime = fwDelay + sc_time_stamp(); - notDelay = clkAlign(sc_time_stamp() + fwDelay) - (sc_time_stamp() + fwDelay) + Configuration::getInstance().memSpec.clk; + notDelay = clkAlign(sc_time_stamp() + fwDelay) - (sc_time_stamp() + fwDelay) + + Configuration::getInstance().memSpec.clk; - printDebugMessage("[fw] Recording " + phaseNameToString(phase) + " thread " + to_string(thr) + " channel " + to_string(ch) + " bank group " + to_string(bg) + " bank " + to_string(bank) + " row " + to_string(row) + " column " + to_string(col) + " at " + recTime.to_string() + " notification in " + notDelay.to_string()); + printDebugMessage("[fw] Recording " + phaseNameToString( + phase) + " thread " + to_string(thr) + " channel " + to_string( + ch) + " bank group " + to_string(bg) + " bank " + to_string( + bank) + " row " + to_string(row) + " column " + to_string( + col) + " at " + recTime.to_string() + " notification in " + + notDelay.to_string()); tlmRecorder->recordPhase(payload, phase, recTime); frontendPEQ.notify(payload, phase, notDelay); //Bandwidth IDLE - if ((getTotalNumberOfPayloadsInSystem()== 0)&& idleState){ + if ((getTotalNumberOfPayloadsInSystem() == 0) && idleState) { endBandwidthIdleCollector(); } - } - else if (phase == END_RESP) - { + } else if (phase == END_RESP) { recTime = fwDelay + sc_time_stamp() + Configuration::getInstance().memSpec.clk; notDelay = clkAlign(sc_time_stamp() + fwDelay) - (sc_time_stamp() + fwDelay); - printDebugMessage("[fw] Recording " + phaseNameToString(phase) + " thread " + to_string(thr) + " channel " + to_string(ch) + " bank group " + to_string(bg) + " bank " + to_string(bank) + " row " + to_string(row) + " column " + to_string(col) + " at " + recTime.to_string() + " notification in " + notDelay.to_string()); + printDebugMessage("[fw] Recording " + phaseNameToString( + phase) + " thread " + to_string(thr) + " channel " + to_string( + ch) + " bank group " + to_string(bg) + " bank " + to_string( + bank) + " row " + to_string(row) + " column " + to_string( + col) + " at " + recTime.to_string() + " notification in " + + notDelay.to_string()); // Badnwith IDLE - if (getTotalNumberOfPayloadsInSystem()==1){ + if (getTotalNumberOfPayloadsInSystem() == 1) { startBandwidthIdleCollector(); } @@ -286,20 +287,21 @@ tlm_sync_enum Controller::nb_transport_fw(tlm_generic_payload &payload, tlm_phas return TLM_ACCEPTED; } -unsigned int Controller::transport_dbg(tlm::tlm_generic_payload& trans) +unsigned int Controller::transport_dbg(tlm::tlm_generic_payload &trans) { return iSocket->transport_dbg(trans); } -void Controller::frontendPEQCallback(tlm_generic_payload &payload, const tlm_phase &phase) +void Controller::frontendPEQCallback(tlm_generic_payload &payload, + const tlm_phase &phase) { - if (phase == BEGIN_REQ) - { - printDebugMessage(string("Payload in system: ") + to_string(getTotalNumberOfPayloadsInSystem())); + if (phase == BEGIN_REQ) { + printDebugMessage(string("Payload in system: ") + to_string( + getTotalNumberOfPayloadsInSystem())); payload.acquire(); payloadEntersSystem(payload); - if (getTotalNumberOfPayloadsInSystem() > controllerCore->config.MaxNrOfTransactions) - { + if (getTotalNumberOfPayloadsInSystem() > + controllerCore->config.MaxNrOfTransactions) { printDebugMessage("##Backpressure: Max number of transactions in system reached"); backpressure = &payload; return; @@ -309,16 +311,11 @@ void Controller::frontendPEQCallback(tlm_generic_payload &payload, const tlm_pha scheduler->schedule(&payload); scheduleNextFromScheduler(DramExtension::getExtension(payload).getBank()); - } - else if (phase == PendingRequest) - { - // Schedule a pending request. - scheduleNextFromScheduler(DramExtension::getExtension(payload).getBank()); - } - else if (phase == END_RESP) - { - if (backpressure != NULL) - { + } else if (phase == PendingRequest) { + // Schedule a pending request. + scheduleNextFromScheduler(DramExtension::getExtension(payload).getBank()); + } else if (phase == END_RESP) { + if (backpressure != NULL) { printDebugMessage("##Backpressure released"); backpressure->set_response_status(tlm::TLM_OK_RESPONSE); sendToFrontend(*backpressure, END_REQ, SC_ZERO_TIME); @@ -330,10 +327,9 @@ void Controller::frontendPEQCallback(tlm_generic_payload &payload, const tlm_pha payloadLeavesSystem(payload); payload.release(); - } - else - { - SC_REPORT_FATAL(0, "Frontend PEQ event queue in controller wrapper was triggered with unknown phase"); + } else { + SC_REPORT_FATAL(0, + "Frontend PEQ event queue in controller wrapper was triggered with unknown phase"); } } @@ -341,13 +337,14 @@ void Controller::payloadEntersSystem(tlm_generic_payload &payload) { Bank bank = DramExtension::getExtension(payload).getBank(); printDebugMessage( - "Payload enters system on bank " + to_string(bank.ID()) + ". Total number of payloads in Controller: " - + to_string(getTotalNumberOfPayloadsInSystem())); + "Payload enters system on bank " + to_string(bank.ID()) + + ". Total number of payloads in Controller: " + + to_string(getTotalNumberOfPayloadsInSystem())); numberOfPayloadsInSystem[bank]++; // Set Start Time for Simulation - if (startTimeSet == false){ + if (startTimeSet == false) { printDebugMessage("Simulation Timer Start"); - startTime = sc_time_stamp()-Configuration::getInstance().memSpec.clk; + startTime = sc_time_stamp() - Configuration::getInstance().memSpec.clk; startTimeSet = true; } } @@ -357,16 +354,16 @@ void Controller::payloadLeavesSystem(tlm_generic_payload &payload) Bank bank = DramExtension::getExtension(payload).getBank(); numberOfPayloadsInSystem[bank]--; printDebugMessage( - "Payload left system on bank " + to_string(bank.ID()) + ". Total number of payloads in Controller: " - + to_string(getTotalNumberOfPayloadsInSystem())); + "Payload left system on bank " + to_string(bank.ID()) + + ". Total number of payloads in Controller: " + + to_string(getTotalNumberOfPayloadsInSystem())); controllerCore->powerDownManager->triggerSleep(bank, sc_time_stamp()); } unsigned int Controller::getTotalNumberOfPayloadsInSystem() { unsigned int sum = 0; - for (Bank bank : controllerCore->getBanks()) - { + for (Bank bank : controllerCore->getBanks()) { sum += numberOfPayloadsInSystem[bank]; } return sum; @@ -375,27 +372,26 @@ unsigned int Controller::getTotalNumberOfPayloadsInSystem() void Controller::scheduleNextFromScheduler(Bank bank) { - if(controllerCore->bankIsBusy(bank)) - { + if (controllerCore->bankIsBusy(bank)) { return; } bool rescheduled = true; - pair nextRequest = scheduler->getNextRequest(bank); - if(nextRequest.second != NULL) - { - controllerCore->powerDownManager->wakeUp(DramExtension::getExtension(nextRequest.second).getBank(), sc_time_stamp()); + pair nextRequest = + scheduler->getNextRequest(bank); + if (nextRequest.second != NULL) { + controllerCore->powerDownManager->wakeUp(DramExtension::getExtension( + nextRequest.second).getBank(), sc_time_stamp()); controllerCore->scheduleRequest(nextRequest.first, *nextRequest.second); - printDebugMessage("\t-> Next payload was scheduled by core [" + commandToString(nextRequest.first) + "]"); - } - else - { - gp* pendingRequest = scheduler->getPendingRequest(bank); - if (pendingRequest != NULL) - { - rescheduled = true; - frontendPEQ.notify(*(pendingRequest), PendingRequest, Configuration::getInstance().memSpec.clk); - } + printDebugMessage("\t-> Next payload was scheduled by core [" + commandToString( + nextRequest.first) + "]"); + } else { + gp *pendingRequest = scheduler->getPendingRequest(bank); + if (pendingRequest != NULL) { + rescheduled = true; + frontendPEQ.notify(*(pendingRequest), PendingRequest, + Configuration::getInstance().memSpec.clk); + } } queue blocked; @@ -403,24 +399,23 @@ void Controller::scheduleNextFromScheduler(Bank bank) bank = blockedRequests.front(); blockedRequests.pop(); - pair nextRequest = scheduler->getNextRequest(bank); + pair nextRequest = + scheduler->getNextRequest(bank); if (nextRequest.second != NULL) { - controllerCore->powerDownManager->wakeUp(DramExtension::getExtension(nextRequest.second).getBank(), sc_time_stamp()); + controllerCore->powerDownManager->wakeUp(DramExtension::getExtension( + nextRequest.second).getBank(), sc_time_stamp()); controllerCore->scheduleRequest(nextRequest.first, *nextRequest.second); - printDebugMessage("\t-> Next payload was scheduled by core [" + commandToString(nextRequest.first) + "] (unblocked)"); - } - else - { - gp* pendingRequest = scheduler->getPendingRequest(bank); - if(pendingRequest != NULL) - { + printDebugMessage("\t-> Next payload was scheduled by core [" + commandToString( + nextRequest.first) + "] (unblocked)"); + } else { + gp *pendingRequest = scheduler->getPendingRequest(bank); + if (pendingRequest != NULL) { //Pending request - if(!rescheduled) - { + if (!rescheduled) { rescheduled = true; - frontendPEQ.notify(*(pendingRequest), PendingRequest, Configuration::getInstance().memSpec.clk); - } - else + frontendPEQ.notify(*(pendingRequest), PendingRequest, + Configuration::getInstance().memSpec.clk); + } else blocked.push(bank); } } @@ -428,14 +423,16 @@ void Controller::scheduleNextFromScheduler(Bank bank) blockedRequests = blocked; } -void Controller::sendToFrontend(tlm_generic_payload &payload, const tlm_phase &phase, const sc_time &delay) +void Controller::sendToFrontend(tlm_generic_payload &payload, + const tlm_phase &phase, const sc_time &delay) { tlm_phase TPhase = phase; sc_time TDelay = delay; tSocket->nb_transport_bw(payload, TPhase, TDelay); } -tlm_sync_enum Controller::nb_transport_bw(tlm_generic_payload &payload, tlm_phase &phase, sc_time &bwDelay) +tlm_sync_enum Controller::nb_transport_bw(tlm_generic_payload &payload, + tlm_phase &phase, sc_time &bwDelay) { sc_time recTime = bwDelay + sc_time_stamp(); sc_time notDelay = bwDelay; @@ -447,7 +444,12 @@ tlm_sync_enum Controller::nb_transport_bw(tlm_generic_payload &payload, tlm_phas unsigned int row = DramExtension::getExtension(payload).getRow().ID(); unsigned int col = DramExtension::getExtension(payload).getColumn().ID(); - printDebugMessage("[bw] Recording " + phaseNameToString(phase) + " thread " + to_string(thr) + " channel " + to_string(ch) + " bank group " + to_string(bg) + " bank " + to_string(bank) + " row " + to_string(row) + " column " + to_string(col) + " at " + recTime.to_string() + " notification in " + notDelay.to_string()); + printDebugMessage("[bw] Recording " + phaseNameToString( + phase) + " thread " + to_string(thr) + " channel " + to_string( + ch) + " bank group " + to_string(bg) + " bank " + to_string( + bank) + " row " + to_string(row) + " column " + to_string( + col) + " at " + recTime.to_string() + " notification in " + + notDelay.to_string()); dramPEQ.notify(payload, phase, notDelay); tlmRecorder->recordPhase(payload, phase, recTime); @@ -455,71 +457,57 @@ tlm_sync_enum Controller::nb_transport_bw(tlm_generic_payload &payload, tlm_phas return TLM_ACCEPTED; } -void Controller::dramPEQCallback(tlm_generic_payload &payload, const tlm_phase &phase) +void Controller::dramPEQCallback(tlm_generic_payload &payload, + const tlm_phase &phase) { Bank bank = DramExtension::getExtension(payload).getBank(); - printDebugMessage("Received " + phaseNameToString(phase) + " on bank " + to_string(bank.ID()) + " from DRAM"); + printDebugMessage("Received " + phaseNameToString(phase) + " on bank " + + to_string(bank.ID()) + " from DRAM"); - if (phase == END_RD || phase == END_WR) - { + if (phase == END_RD || phase == END_WR) { sendToFrontend(payload, BEGIN_RESP, SC_ZERO_TIME); - } - else if (phase == END_RDA || phase == END_WRA) - { + } else if (phase == END_RDA || phase == END_WRA) { sendToFrontend(payload, BEGIN_RESP, SC_ZERO_TIME); scheduleNextFromScheduler(bank); - } - else if (phase == END_REFA) - { + } else if (phase == END_REFA) { printDebugMessage("Finished auto refresh on all banks "); bool sleepy = true; - for(Bank bank : controllerCore->getBanks()) - { - if(numberOfPayloadsInSystem[bank] != 0) - { + for (Bank bank : controllerCore->getBanks()) { + if (numberOfPayloadsInSystem[bank] != 0) { sleepy = false; scheduleNextFromScheduler(bank); } } - if(sleepy == true) - { - controllerCore->powerDownManager->sleep(0,sc_time_stamp()); + if (sleepy == true) { + controllerCore->powerDownManager->sleep(0, sc_time_stamp()); } - } - else if(phase == END_REFB) - { + } else if (phase == END_REFB) { printDebugMessage("Finished auto refresh on bank " + to_string(bank.ID())); - if(numberOfPayloadsInSystem[bank] == 0) - { - controllerCore->powerDownManager->sleep(bank,sc_time_stamp()); - } - else - { + if (numberOfPayloadsInSystem[bank] == 0) { + controllerCore->powerDownManager->sleep(bank, sc_time_stamp()); + } else { scheduleNextFromScheduler(bank); } scheduleNextFromScheduler(bank); - } - else if (containsPhase(phase, { END_PRE, END_ACT })) - { + } else if (containsPhase(phase, { END_PRE, END_ACT })) { scheduleNextFromScheduler(bank); } - else if(phase == END_PRE_ALL) - { + else if (phase == END_PRE_ALL) { // No need to trigger anything for a END_PRE_ALL. It is followed by a AUTO_REFRESH anyway (in our current // scheduler implementation) - } - else - { - string str = string("dramPEQCallback queue in controller wrapper was triggered with unsupported phase ") - + phaseNameToString(phase); + } else { + string str = + string("dramPEQCallback queue in controller wrapper was triggered with unsupported phase ") + + phaseNameToString(phase); SC_REPORT_FATAL(0, str.c_str()); } } -void Controller::sendToDram(tlm_generic_payload &payload, const tlm_phase &phase, const sc_time &delay) +void Controller::sendToDram(tlm_generic_payload &payload, + const tlm_phase &phase, const sc_time &delay) { tlm_phase TPhase = phase; sc_time TDelay = delay; @@ -533,8 +521,7 @@ void Controller::printDebugMessage(string message) bool Controller::containsPhase(tlm_phase phase, std::vector phases) { - for (tlm_phase p : phases) - { + for (tlm_phase p : phases) { if (p == phase) return true; } @@ -548,15 +535,11 @@ void Controller::end_of_simulation() void Controller::terminateSimulation() { - if(Configuration::getInstance().BankwiseLogic) - { - for (Bank bank : controllerCore->getBanks()) - { + if (Configuration::getInstance().BankwiseLogic) { + for (Bank bank : controllerCore->getBanks()) { controllerCore->powerDownManager->wakeUp(bank, clkAlign(sc_time_stamp())); } - } - else - { + } else { controllerCore->powerDownManager->wakeUp(0, clkAlign(sc_time_stamp())); } @@ -574,24 +557,25 @@ void Controller::startBandwidthIdleCollector() void Controller::endBandwidthIdleCollector() { printDebugMessage("IDLE End"); - idleTime += sc_time_stamp()-idleStart+ Configuration::getInstance().memSpec.clk; + idleTime += sc_time_stamp() - idleStart + + Configuration::getInstance().memSpec.clk; idleState = false; } sc_time Controller::getIdleTime() { - printDebugMessage("IDLE Time: "+idleTime.to_string()); + printDebugMessage("IDLE Time: " + idleTime.to_string()); return idleTime; } sc_time Controller::getEndTime() { - printDebugMessage("End Time: "+endTime.to_string()); + printDebugMessage("End Time: " + endTime.to_string()); return endTime; } sc_time Controller::getStartTime() { - printDebugMessage("Start Time: "+startTime.to_string()); + printDebugMessage("Start Time: " + startTime.to_string()); return startTime; } diff --git a/DRAMSys/library/src/controller/Controller.h b/DRAMSys/library/src/controller/Controller.h index d280b9cf..90c787f3 100644 --- a/DRAMSys/library/src/controller/Controller.h +++ b/DRAMSys/library/src/controller/Controller.h @@ -81,7 +81,10 @@ class Controller: public sc_module, public IController { public: Controller(sc_module_name /*name*/, TlmRecorder *rec) : - frontendPEQ(this, &Controller::frontendPEQCallback), dramPEQ(this, &Controller::dramPEQCallback), controllerCorePEQ(this, &Controller::controllerCorePEQCallback), debugManager(DebugManager::getInstance()), tlmRecorder(rec) + frontendPEQ(this, &Controller::frontendPEQCallback), dramPEQ(this, + &Controller::dramPEQCallback), controllerCorePEQ(this, + &Controller::controllerCorePEQCallback), + debugManager(DebugManager::getInstance()), tlmRecorder(rec) { controllerCore = new ControllerCore("core", *this, numberOfPayloadsInSystem); buildScheduler(); @@ -103,51 +106,61 @@ public: sc_time getStartTime(); // ------- CONTROLLER CORE --------- - virtual void send(const ScheduledCommand& command, tlm_generic_payload& payload) override; - virtual void send(Trigger trigger, sc_time time, tlm_generic_payload& payload) override; + virtual void send(const ScheduledCommand &command, + tlm_generic_payload &payload) override; + virtual void send(Trigger trigger, sc_time time, + tlm_generic_payload &payload) override; tlm_utils::simple_initiator_socket iSocket; tlm_utils::simple_target_socket tSocket; unsigned int getTotalNumberOfPayloadsInSystem(); void scheduleNextFromScheduler(Bank bank) override; - static unsigned int ControllerThreadId() {return controllerThreadId;} + static unsigned int ControllerThreadId() + { + return controllerThreadId; + } private: void buildScheduler(); - void payloadEntersSystem(tlm_generic_payload& payload); - void payloadLeavesSystem(tlm_generic_payload& payload); + void payloadEntersSystem(tlm_generic_payload &payload); + void payloadLeavesSystem(tlm_generic_payload &payload); // --- FRONTEND ------ - tlm_sync_enum nb_transport_fw(tlm_generic_payload& payload, tlm_phase& phase, sc_time& fwDelay); - virtual unsigned int transport_dbg(tlm::tlm_generic_payload& trans); - void frontendPEQCallback(tlm_generic_payload& payload, const tlm_phase& phase); - void sendToFrontend(tlm_generic_payload& payload, const tlm_phase& phase, const sc_time& delay); + tlm_sync_enum nb_transport_fw(tlm_generic_payload &payload, tlm_phase &phase, + sc_time &fwDelay); + virtual unsigned int transport_dbg(tlm::tlm_generic_payload &trans); + void frontendPEQCallback(tlm_generic_payload &payload, const tlm_phase &phase); + void sendToFrontend(tlm_generic_payload &payload, const tlm_phase &phase, + const sc_time &delay); // --- DRAM ------ - tlm_sync_enum nb_transport_bw(tlm_generic_payload& payload, tlm_phase& phase, sc_time& bwDelay); - void dramPEQCallback(tlm_generic_payload& payload, const tlm_phase& phase); - void sendToDram(tlm_generic_payload& payload, const tlm_phase& phase, const sc_time& delay); + tlm_sync_enum nb_transport_bw(tlm_generic_payload &payload, tlm_phase &phase, + sc_time &bwDelay); + void dramPEQCallback(tlm_generic_payload &payload, const tlm_phase &phase); + void sendToDram(tlm_generic_payload &payload, const tlm_phase &phase, + const sc_time &delay); // ------- CONTROLLER CORE --------- - void controllerCorePEQCallback(tlm_generic_payload& payload, const tlm_phase& phase); + void controllerCorePEQCallback(tlm_generic_payload &payload, + const tlm_phase &phase); // Helpers TODO move them void printDebugMessage(string message); bool containsPhase(tlm_phase phase, std::vector phases); - ControllerCore* controllerCore; + ControllerCore *controllerCore; //Scheduler* scheduler; - IScheduler* scheduler; + IScheduler *scheduler; std::map numberOfPayloadsInSystem; - std::vector refreshCollisionRequets; - tlm::tlm_generic_payload* backpressure = NULL; + std::vector refreshCollisionRequets; + tlm::tlm_generic_payload *backpressure = NULL; tlm_utils::peq_with_cb_and_phase frontendPEQ; tlm_utils::peq_with_cb_and_phase dramPEQ; tlm_utils::peq_with_cb_and_phase controllerCorePEQ; - DebugManager& debugManager; + DebugManager &debugManager; TlmRecorder *tlmRecorder; // Bandwidth realted: diff --git a/DRAMSys/library/src/controller/ControllerState.cpp b/DRAMSys/library/src/controller/ControllerState.cpp index 56149e0f..14e19b23 100644 --- a/DRAMSys/library/src/controller/ControllerState.cpp +++ b/DRAMSys/library/src/controller/ControllerState.cpp @@ -41,7 +41,8 @@ using namespace std; -const ScheduledCommand ControllerState::getLastCommand(Command command, Bank bank) //TODO const reference? and make const +const ScheduledCommand ControllerState::getLastCommand(Command command, + Bank bank) //TODO const reference? and make const { return lastScheduledByCommandAndBank[command][bank]; } @@ -50,8 +51,7 @@ const ScheduledCommand ControllerState::getLastCommand(Command command) { ScheduledCommand max; - for (unsigned int i = 0; i < config->memSpec.NumberOfBanks; ++i) - { + for (unsigned int i = 0; i < config->memSpec.NumberOfBanks; ++i) { ScheduledCommand current = getLastCommand(command, Bank(i)); if (current.getStart() > max.getStart()) max = current; @@ -64,17 +64,16 @@ const ScheduledCommand ControllerState::getLastScheduledCommand() { ScheduledCommand lastCommand; - for(Command cmd : getAllCommands()) - { - for(Bank bank : Configuration::getInstance().memSpec.getBanks()) - { - ScheduledCommand& current = lastScheduledByCommandAndBank[cmd][bank]; + for (Command cmd : getAllCommands()) { + for (Bank bank : Configuration::getInstance().memSpec.getBanks()) { + ScheduledCommand ¤t = lastScheduledByCommandAndBank[cmd][bank]; if (current.getStart() > lastCommand.getStart()) lastCommand = current; } } - printDebugMessage("Last scheduled command was " + commandToString(lastCommand.getCommand())); + printDebugMessage("Last scheduled command was " + commandToString( + lastCommand.getCommand())); return lastCommand; } @@ -83,27 +82,29 @@ const ScheduledCommand ControllerState::getLastScheduledCommand(Bank bank) { ScheduledCommand lastCommand; - for(Command cmd : getAllCommands()) - { - ScheduledCommand& current = lastScheduledByCommandAndBank[cmd][bank]; + for (Command cmd : getAllCommands()) { + ScheduledCommand ¤t = lastScheduledByCommandAndBank[cmd][bank]; if (current.getStart() > lastCommand.getStart()) lastCommand = current; } - printDebugMessage("Last scheduled command on bank " + to_string(bank.ID()) + " was " + commandToString(lastCommand.getCommand())); + printDebugMessage("Last scheduled command on bank " + to_string( + bank.ID()) + " was " + commandToString(lastCommand.getCommand())); return lastCommand; } -void ControllerState::change(const ScheduledCommand& scheduledCommand) +void ControllerState::change(const ScheduledCommand &scheduledCommand) { bus.blockSlot(scheduledCommand.getStart()); - printDebugMessage("Changing state on bank " + to_string(scheduledCommand.getBank().ID()) + " command is " + commandToString(scheduledCommand.getCommand())); - lastScheduledByCommandAndBank[scheduledCommand.getCommand()][scheduledCommand.getBank()] = scheduledCommand; + printDebugMessage("Changing state on bank " + to_string( + scheduledCommand.getBank().ID()) + " command is " + commandToString( + scheduledCommand.getCommand())); + lastScheduledByCommandAndBank[scheduledCommand.getCommand()][scheduledCommand.getBank()] + = scheduledCommand; - switch (scheduledCommand.getCommand()) - { + switch (scheduledCommand.getCommand()) { case Command::Read: lastDataStrobeCommands.emplace_back(scheduledCommand); break; @@ -121,7 +122,8 @@ void ControllerState::change(const ScheduledCommand& scheduledCommand) case Command::AutoRefresh: break; case Command::Activate: - rowBufferStates->openRowInRowBuffer(scheduledCommand.getBank(), scheduledCommand.getRow()); + rowBufferStates->openRowInRowBuffer(scheduledCommand.getBank(), + scheduledCommand.getRow()); lastActivates.emplace(scheduledCommand.getStart(), scheduledCommand); break; case Command::Precharge: @@ -142,18 +144,19 @@ void ControllerState::cleanUp(sc_time time) { bus.cleanUpSlots(time); vector tmp; - for(ScheduledCommand& command: lastDataStrobeCommands) - { - if(command.getEnd() >= time || getDistance(command.getEnd(), time) <= config->memSpec.tDataStrobeHistory()) + for (ScheduledCommand &command : lastDataStrobeCommands) { + if (command.getEnd() >= time + || getDistance(command.getEnd(), time) <= config->memSpec.tDataStrobeHistory()) tmp.push_back(command); } lastDataStrobeCommands = tmp; - if(time >= config->memSpec.tActHistory()) - lastActivates.erase(lastActivates.begin(), lastActivates.lower_bound(time - config->memSpec.tActHistory())); + if (time >= config->memSpec.tActHistory()) + lastActivates.erase(lastActivates.begin(), + lastActivates.lower_bound(time - config->memSpec.tActHistory())); } void ControllerState::printDebugMessage(std::string message) { - DebugManager::getInstance().printDebugMessage(ownerName, message); + DebugManager::getInstance().printDebugMessage(ownerName, message); } diff --git a/DRAMSys/library/src/controller/ControllerState.h b/DRAMSys/library/src/controller/ControllerState.h index 38f1941b..f4eeb36c 100644 --- a/DRAMSys/library/src/controller/ControllerState.h +++ b/DRAMSys/library/src/controller/ControllerState.h @@ -48,24 +48,27 @@ class ControllerState { public: - ControllerState(std::string ownerName, Configuration *config) : bus(config->memSpec.clk), ownerName(ownerName), config(config) + ControllerState(std::string ownerName, + Configuration *config) : bus(config->memSpec.clk), ownerName(ownerName), + config(config) { - rowBufferStates = new RowBufferState(ownerName); + rowBufferStates = new RowBufferState(ownerName); } - virtual ~ControllerState(){} + virtual ~ControllerState() {} const ScheduledCommand getLastCommand(Command command, Bank bank); const ScheduledCommand getLastCommand(Command command); const ScheduledCommand getLastScheduledCommand(Bank bank); const ScheduledCommand getLastScheduledCommand(); - void change(const ScheduledCommand& scheduledCommand); + void change(const ScheduledCommand &scheduledCommand); void cleanUp(sc_time time); RowBufferState *rowBufferStates; //used by the various checkers - std::map > lastScheduledByCommandAndBank; + std::map > + lastScheduledByCommandAndBank; std::map lastScheduledByCommand; std::map lastScheduledByBank; ScheduledCommand lastScheduled; @@ -76,7 +79,7 @@ public: private: std::string ownerName; - Configuration* config; + Configuration *config; void printDebugMessage(std::string message); }; diff --git a/DRAMSys/library/src/controller/IController.h b/DRAMSys/library/src/controller/IController.h index 46a534b7..ded2de7b 100644 --- a/DRAMSys/library/src/controller/IController.h +++ b/DRAMSys/library/src/controller/IController.h @@ -51,8 +51,10 @@ class IController { public: virtual ~IController() {} - virtual void send(const ScheduledCommand& command,tlm::tlm_generic_payload& payload) = 0; - virtual void send(Trigger trigger, sc_time time, tlm::tlm_generic_payload& payload) = 0; + virtual void send(const ScheduledCommand &command, + tlm::tlm_generic_payload &payload) = 0; + virtual void send(Trigger trigger, sc_time time, + tlm::tlm_generic_payload &payload) = 0; virtual void scheduleNextFromScheduler(Bank bank) = 0; std::queue blockedRequests; diff --git a/DRAMSys/library/src/controller/RowBufferStates.cpp b/DRAMSys/library/src/controller/RowBufferStates.cpp index a8ab5aa1..2948203a 100644 --- a/DRAMSys/library/src/controller/RowBufferStates.cpp +++ b/DRAMSys/library/src/controller/RowBufferStates.cpp @@ -43,7 +43,7 @@ using namespace std; RowBufferState::RowBufferState(std::string ownerName) : ownerName(ownerName) { - closeAllRowBuffers(); + closeAllRowBuffers(); } RowBufferState::~RowBufferState() @@ -52,31 +52,33 @@ RowBufferState::~RowBufferState() bool RowBufferState::rowBufferIsOpen(Bank bank) const { - return getElementFromMap(rowsInRowBuffers,bank) != Row::NO_ROW; + return getElementFromMap(rowsInRowBuffers, bank) != Row::NO_ROW; } Row RowBufferState::getRowInRowBuffer(Bank bank) const { - return getElementFromMap(rowsInRowBuffers,bank); + return getElementFromMap(rowsInRowBuffers, bank); } -void RowBufferState::openRowInRowBuffer(Bank bank,Row row) +void RowBufferState::openRowInRowBuffer(Bank bank, Row row) { - printDebugMessage("Row buffer for bank " + to_string(bank.ID()) + " is now open"); + printDebugMessage("Row buffer for bank " + to_string(bank.ID()) + + " is now open"); rowsInRowBuffers[bank] = row; } void RowBufferState::closeRowBuffer(Bank bank) { - printDebugMessage("Row buffer for bank " + to_string(bank.ID()) + " is now closed"); + printDebugMessage("Row buffer for bank " + to_string(bank.ID()) + + " is now closed"); rowsInRowBuffers[bank] = Row::NO_ROW; } bool RowBufferState::allRowBuffersAreClosed() const { - for(unsigned int i=0; i #include "../common/dramExtension.h" -class RowBufferState { +class RowBufferState +{ public: RowBufferState(std::string ownerName); virtual ~RowBufferState(); @@ -55,7 +56,7 @@ public: private: std::string ownerName; - std::map rowsInRowBuffers; + std::map rowsInRowBuffers; void printDebugMessage(std::string message); }; diff --git a/DRAMSys/library/src/controller/core/ControllerCore.cpp b/DRAMSys/library/src/controller/core/ControllerCore.cpp index 6fc50917..eb9c5914 100644 --- a/DRAMSys/library/src/controller/core/ControllerCore.cpp +++ b/DRAMSys/library/src/controller/core/ControllerCore.cpp @@ -57,8 +57,10 @@ #include "powerdown/NoPowerDown.h" #include "../../common/DebugManager.h" -ControllerCore::ControllerCore(sc_module_name /*name*/, IController& wrapperConnector, std::map& numberOfPayloads) : - config(Configuration::getInstance()), controller(wrapperConnector), numberOfPayloads(numberOfPayloads), commandChecker() +ControllerCore::ControllerCore(sc_module_name /*name*/, + IController &wrapperConnector, std::map &numberOfPayloads) : + config(Configuration::getInstance()), controller(wrapperConnector), + numberOfPayloads(numberOfPayloads), commandChecker() { state = new ControllerState(name(), &config); @@ -78,36 +80,28 @@ ControllerCore::ControllerCore(sc_module_name /*name*/, IController& wrapperConn commandChecker[Command::PDNPX] = commandChecker[Command::PDNA]; commandChecker[Command::SREFX] = commandChecker[Command::PDNA]; - if (config.BankwiseLogic) - { + if (config.BankwiseLogic) { refreshManager = new RefreshManagerBankwise("refManagerBw", *this); - } - else - { + } else { refreshManager = new RefreshManager("refManager", *this); } - if(config.PowerDownMode == EPowerDownMode::Staggered) - { + if (config.PowerDownMode == EPowerDownMode::Staggered) { if (config.BankwiseLogic) powerDownManager = new PowerDownManagerBankwise("pdnManagerBw", *this); else powerDownManager = new PowerDownManager("pdnManager", *this); - } - else if(config.PowerDownMode == EPowerDownMode::TimeoutPDN || config.PowerDownMode == EPowerDownMode::TimeoutSREF) - { + } else if (config.PowerDownMode == EPowerDownMode::TimeoutPDN + || config.PowerDownMode == EPowerDownMode::TimeoutSREF) { if (config.BankwiseLogic) powerDownManager = new PowerDownManagerTimeoutBankwise("pdnManagerBw", *this); else powerDownManager = new PowerDownManagerTimeout("pdnManager", *this); - } - else if(config.PowerDownMode == EPowerDownMode::NoPowerDown) - { + } else if (config.PowerDownMode == EPowerDownMode::NoPowerDown) { powerDownManager = new NoPowerDown(); - } - else - { - SC_REPORT_FATAL(0, "Unsupported powerdown mode in constructor of controller core"); + } else { + SC_REPORT_FATAL(0, + "Unsupported powerdown mode in constructor of controller core"); } } @@ -125,7 +119,7 @@ ControllerCore::~ControllerCore() delete state; } -void ControllerCore::triggerRefresh(tlm::tlm_generic_payload& payload) +void ControllerCore::triggerRefresh(tlm::tlm_generic_payload &payload) { /* Refresh can be disabled for tests purpose */ if (config.ControllerCoreDisableRefresh == false) { @@ -134,28 +128,27 @@ void ControllerCore::triggerRefresh(tlm::tlm_generic_payload& payload) state->cleanUp(time); - if (!refreshManager->isInvalidated(payload, time) && !powerDownManager->isInSelfRefresh(bank)) - { + if (!refreshManager->isInvalidated(payload, time) + && !powerDownManager->isInSelfRefresh(bank)) { printDebugMessage("Triggering refresh on bank " + to_string(bank.ID())); - powerDownManager->wakeUpForRefresh(bank, time); //expects PDNA and PDNP to exit without delay + powerDownManager->wakeUpForRefresh(bank, + time); //expects PDNA and PDNP to exit without delay bool pdnpToSrefTransition = false; - if (config.PowerDownMode == EPowerDownMode::Staggered) - { - pdnpToSrefTransition = state->getLastCommand(Command::PDNPX,bank).getStart() >= time; + if (config.PowerDownMode == EPowerDownMode::Staggered) { + pdnpToSrefTransition = state->getLastCommand(Command::PDNPX, + bank).getStart() >= time; } - if (pdnpToSrefTransition) - { - powerDownManager->sleep(bank,time); - } - else - { + if (pdnpToSrefTransition) { + powerDownManager->sleep(bank, time); + } else { refreshManager->scheduleRefresh(payload, time); } } } } -void ControllerCore::scheduleRequest(Command command, tlm::tlm_generic_payload &payload) +void ControllerCore::scheduleRequest(Command command, + tlm::tlm_generic_payload &payload) { sc_time start = clkAlign(sc_time_stamp()); state->cleanUp(start); @@ -164,9 +157,8 @@ void ControllerCore::scheduleRequest(Command command, tlm::tlm_generic_payload & state->change(scheduledCommand); controller.send(scheduledCommand, payload); } else { - if(!((command == Command::Precharge || command == Command::Activate) - && refreshManager->hasCollision(scheduledCommand))) - { + if (!((command == Command::Precharge || command == Command::Activate) + && refreshManager->hasCollision(scheduledCommand))) { state->change(scheduledCommand); controller.send(scheduledCommand, payload); } @@ -174,20 +166,21 @@ void ControllerCore::scheduleRequest(Command command, tlm::tlm_generic_payload & } ScheduledCommand ControllerCore::schedule(Command command, sc_time start, - tlm::tlm_generic_payload& payload) + tlm::tlm_generic_payload &payload) { - ControllerCore::printDebugMessage("Scheduling command " + commandToString(command) + " on " + DramExtension::getBank(payload).toString()); - ICommandChecker& checker = getCommandChecker(command); - sc_time executionTime = getExecutionTime(command, payload); - ScheduledCommand scheduledCommand(command, start, executionTime, DramExtension::getExtension(payload)); - checker.delayToSatisfyConstraints(scheduledCommand); - return scheduledCommand; + ControllerCore::printDebugMessage("Scheduling command " + commandToString( + command) + " on " + DramExtension::getBank(payload).toString()); + ICommandChecker &checker = getCommandChecker(command); + sc_time executionTime = getExecutionTime(command, payload); + ScheduledCommand scheduledCommand(command, start, executionTime, + DramExtension::getExtension(payload)); + checker.delayToSatisfyConstraints(scheduledCommand); + return scheduledCommand; } bool ControllerCore::hasPendingRequests() { - for (Bank bank : getBanks()) - { + for (Bank bank : getBanks()) { if (numberOfPayloads[bank] != 0) return true; } @@ -202,40 +195,33 @@ bool ControllerCore::bankIsBusy(Bank bank) if (lastScheduledCommand.isNoCommand()) return false; - else if (lastScheduledCommand.commandIsIn( { Command::Write, Command::Read })) - { + else if (lastScheduledCommand.commandIsIn( { Command::Write, Command::Read })) { // Read and writes can overlap, so the bank should not be busy during a rd/wr return (time < lastScheduledCommand.getStart()); } - else if (lastScheduledCommand.commandIsIn( { Command::WriteA, Command::ReadA, Command::Precharge, Command::PrechargeAll, Command::Activate })) - { + else if (lastScheduledCommand.commandIsIn( { Command::WriteA, Command::ReadA, Command::Precharge, Command::PrechargeAll, Command::Activate })) { return (time < lastScheduledCommand.getEnd()); } - else if (lastScheduledCommand.getCommand() == Command::AutoRefresh) - { + else if (lastScheduledCommand.getCommand() == Command::AutoRefresh) { return (time < lastScheduledCommand.getEnd()); - } - else if (lastScheduledCommand.commandIsIn( { Command::SREFX, Command::PDNPX, Command::PDNAX, Command::SREF, Command::PDNP, - Command::PDNA })) - { + } else if (lastScheduledCommand.commandIsIn( { Command::SREFX, Command::PDNPX, Command::PDNAX, Command::SREF, Command::PDNP, + Command::PDNA + })) { return false; } - else - { + else { SC_REPORT_FATAL("Core", "Last command unkown"); return false; } } -const std::vector& ControllerCore::getBanks() +const std::vector &ControllerCore::getBanks() { static std::vector banks; - if (banks.size() == 0) - { - for (unsigned int i = 0; i < config.memSpec.NumberOfBanks; i++) - { + if (banks.size() == 0) { + for (unsigned int i = 0; i < config.memSpec.NumberOfBanks; i++) { banks.push_back(Bank(i)); } } @@ -246,15 +232,14 @@ const std::vector& ControllerCore::getBanks() std::vector ControllerCore::getFreeBanks() { std::vector freeBanks; - for(Bank bank: getBanks()) - { - if(!bankIsBusy(bank)) + for (Bank bank : getBanks()) { + if (!bankIsBusy(bank)) freeBanks.push_back(bank); } return freeBanks; } -ICommandChecker& ControllerCore::getCommandChecker(Command command) +ICommandChecker &ControllerCore::getCommandChecker(Command command) { return *getElementFromMap(commandChecker, command); } diff --git a/DRAMSys/library/src/controller/core/ControllerCore.h b/DRAMSys/library/src/controller/core/ControllerCore.h index b05a3788..405b25f6 100644 --- a/DRAMSys/library/src/controller/core/ControllerCore.h +++ b/DRAMSys/library/src/controller/core/ControllerCore.h @@ -54,31 +54,36 @@ using namespace std; class ControllerCore : public sc_module { public: - ControllerCore(sc_module_name /*name*/, IController& controller, std::map& numberOfPayloads); + ControllerCore(sc_module_name /*name*/, IController &controller, + std::map &numberOfPayloads); virtual ~ControllerCore(); - void scheduleRequest(Command command, tlm::tlm_generic_payload& payload); - void triggerRefresh(tlm::tlm_generic_payload& payload); + void scheduleRequest(Command command, tlm::tlm_generic_payload &payload); + void triggerRefresh(tlm::tlm_generic_payload &payload); - const std::vector& getBanks(); + const std::vector &getBanks(); std::vector getFreeBanks(); - const RowBufferState& getRowBufferStates(){return *(state->rowBufferStates);} + const RowBufferState &getRowBufferStates() + { + return *(state->rowBufferStates); + } bool hasPendingRequests(); bool bankIsBusy(Bank bank); - ICommandChecker& getCommandChecker(Command command); + ICommandChecker &getCommandChecker(Command command); Configuration config; ControllerState *state; - IController& controller; - IPowerDownManager* powerDownManager; - IRefreshManager* refreshManager; - std::map& numberOfPayloads; + IController &controller; + IPowerDownManager *powerDownManager; + IRefreshManager *refreshManager; + std::map &numberOfPayloads; private: - ScheduledCommand schedule(Command command, sc_time start, tlm::tlm_generic_payload &payload); - std::map commandChecker; + ScheduledCommand schedule(Command command, sc_time start, + tlm::tlm_generic_payload &payload); + std::map commandChecker; void printDebugMessage(string message); }; diff --git a/DRAMSys/library/src/controller/core/Slots.cpp b/DRAMSys/library/src/controller/core/Slots.cpp index 87909571..20126eab 100644 --- a/DRAMSys/library/src/controller/core/Slots.cpp +++ b/DRAMSys/library/src/controller/core/Slots.cpp @@ -39,7 +39,7 @@ Slots::Slots(sc_time clk) : - clk(clk) + clk(clk) { } @@ -48,41 +48,40 @@ Slots::~Slots() { } -void Slots::moveCommandToNextFreeSlot(ScheduledCommand& command) +void Slots::moveCommandToNextFreeSlot(ScheduledCommand &command) { - while(!isFree(command.getStart())) - command.delayStart(clk); + while (!isFree(command.getStart())) + command.delayStart(clk); } void Slots::cleanUpSlots(sc_time time) { - slotSet.erase(slotSet.begin(), slotSet.lower_bound(time)); + slotSet.erase(slotSet.begin(), slotSet.lower_bound(time)); } void Slots::blockSlot(sc_time time) { - sc_assert(isClkAligned(time, clk)); - slotSet.insert(time); + sc_assert(isClkAligned(time, clk)); + slotSet.insert(time); } bool Slots::isFree(sc_time time) { - return (slotSet.count(time) == 0); + return (slotSet.count(time) == 0); } void Slots::blockSlots(sc_time begin, sc_time end, bool excludeBorders) { - sc_assert(isClkAligned(begin, clk)); - sc_assert(isClkAligned(end, clk)); + sc_assert(isClkAligned(begin, clk)); + sc_assert(isClkAligned(end, clk)); - if (excludeBorders) - { - begin += clk; - end -= clk; - } + if (excludeBorders) { + begin += clk; + end -= clk; + } - for (sc_time time = begin; time <= end; time += clk) { - blockSlot(time); - } + for (sc_time time = begin; time <= end; time += clk) { + blockSlot(time); + } } diff --git a/DRAMSys/library/src/controller/core/Slots.h b/DRAMSys/library/src/controller/core/Slots.h index 49b03b5b..5a821a4b 100644 --- a/DRAMSys/library/src/controller/core/Slots.h +++ b/DRAMSys/library/src/controller/core/Slots.h @@ -47,7 +47,7 @@ public: Slots(sc_time clk); virtual ~Slots(); - void moveCommandToNextFreeSlot(ScheduledCommand& command); + void moveCommandToNextFreeSlot(ScheduledCommand &command); void cleanUpSlots(sc_time time); void blockSlot(sc_time time); bool isFree(sc_time); diff --git a/DRAMSys/library/src/controller/core/TimingCalculation.cpp b/DRAMSys/library/src/controller/core/TimingCalculation.cpp index d20e7ba9..da1db258 100644 --- a/DRAMSys/library/src/controller/core/TimingCalculation.cpp +++ b/DRAMSys/library/src/controller/core/TimingCalculation.cpp @@ -43,7 +43,8 @@ -sc_time getDelayToMeetConstraint(sc_time previous, sc_time start, sc_time constraint) +sc_time getDelayToMeetConstraint(sc_time previous, sc_time start, + sc_time constraint) { if (previous + constraint > start) return previous + constraint - start; @@ -66,49 +67,33 @@ const sc_time clkAlign(sc_time time, Alignment alignment) } // Returns the execution time for commands that have a fixed execution time -sc_time getExecutionTime(Command command, tlm::tlm_generic_payload& payload) +sc_time getExecutionTime(Command command, tlm::tlm_generic_payload &payload) { - MemSpec& config = Configuration::getInstance().memSpec; + MemSpec &config = Configuration::getInstance().memSpec; - if (command == Command::Precharge || command == Command::PrechargeAll) - { + if (command == Command::Precharge || command == Command::PrechargeAll) { return config.tRP; - } - else if (command == Command::Activate) - { + } else if (command == Command::Activate) { return config.tRCD; - } - else if (command == Command::Read) - { + } else if (command == Command::Read) { return config.tRL + getReadAccessTime(); - } - else if (command == Command::ReadA) - { + } else if (command == Command::ReadA) { return config.tRTP + config.tRP; - } - else if (command == Command::Write) - { + } else if (command == Command::Write) { return config.tWL + getWriteAccessTime(); - } - else if (command == Command::WriteA) - { + } else if (command == Command::WriteA) { return config.tWL + getWriteAccessTime() + config.tWR + config.tRP; - } - else if (command == Command::PrechargeAll) - { + } else if (command == Command::PrechargeAll) { return config.tRP; - } - else if (command == Command::AutoRefresh) - { - return getElementFromMap(config.refreshTimings, DramExtension::getExtension(payload).getBank()).tRFC; - } - else if (command == Command::PDNAX || command == Command::PDNPX || command == Command::SREFX) - { + } else if (command == Command::AutoRefresh) { + return getElementFromMap(config.refreshTimings, + DramExtension::getExtension(payload).getBank()).tRFC; + } else if (command == Command::PDNAX || command == Command::PDNPX + || command == Command::SREFX) { return config.clk; - } - else - { - SC_REPORT_FATAL("getExecutionTime", "command not known or command doesn't have a fixed execution time"); + } else { + SC_REPORT_FATAL("getExecutionTime", + "command not known or command doesn't have a fixed execution time"); return SC_ZERO_TIME; } } @@ -116,18 +101,14 @@ sc_time getExecutionTime(Command command, tlm::tlm_generic_payload& payload) // Returns the minimum execution time for commands that have a variable execution time sc_time getMinExecutionTimeForPowerDownCmd(Command command) { - MemSpec& config = Configuration::getInstance().memSpec; - if (command == Command::PDNA || command == Command::PDNP) - { + MemSpec &config = Configuration::getInstance().memSpec; + if (command == Command::PDNA || command == Command::PDNP) { return config.tCKE; - } - else if (command == Command::SREF) - { + } else if (command == Command::SREF) { return config.tCKESR; - } - else - { - SC_REPORT_FATAL("getMinimalExecutionTime", "command is not know or command has a fixed execution time"); + } else { + SC_REPORT_FATAL("getMinimalExecutionTime", + "command is not know or command has a fixed execution time"); return SC_ZERO_TIME; } } @@ -140,21 +121,20 @@ bool isClkAligned(sc_time time, sc_time clk) sc_time getReadAccessTime() { - Configuration& config = Configuration::getInstance(); - return (config.memSpec.BurstLength / config.memSpec.DataRate)*config.memSpec.clk; + Configuration &config = Configuration::getInstance(); + return (config.memSpec.BurstLength / config.memSpec.DataRate) * + config.memSpec.clk; } sc_time getWriteAccessTime() { - Configuration& config = Configuration::getInstance(); + Configuration &config = Configuration::getInstance(); - if (config.memSpec.DataRate == 1) - { + if (config.memSpec.DataRate == 1) { return config.memSpec.clk * (config.memSpec.BurstLength); - } - else - { - return config.memSpec.clk * (config.memSpec.BurstLength / config.memSpec.DataRate); + } else { + return config.memSpec.clk * (config.memSpec.BurstLength / + config.memSpec.DataRate); } } diff --git a/DRAMSys/library/src/controller/core/TimingCalculation.h b/DRAMSys/library/src/controller/core/TimingCalculation.h index 0f37dacf..03fa1918 100644 --- a/DRAMSys/library/src/controller/core/TimingCalculation.h +++ b/DRAMSys/library/src/controller/core/TimingCalculation.h @@ -44,11 +44,12 @@ sc_time getMinExecutionTimeForPowerDownCmd(Command command); -sc_time getExecutionTime(Command command, tlm::tlm_generic_payload& payload); +sc_time getExecutionTime(Command command, tlm::tlm_generic_payload &payload); sc_time getReadAccessTime(); sc_time getWriteAccessTime(); -sc_time getDelayToMeetConstraint(sc_time previous, sc_time start, sc_time constraint); +sc_time getDelayToMeetConstraint(sc_time previous, sc_time start, + sc_time constraint); enum Alignment {UP, DOWN}; const sc_time clkAlign(sc_time time, Alignment alignment = UP); diff --git a/DRAMSys/library/src/controller/core/configuration/Configuration.cpp b/DRAMSys/library/src/controller/core/configuration/Configuration.cpp index d7070107..d2653b39 100644 --- a/DRAMSys/library/src/controller/core/configuration/Configuration.cpp +++ b/DRAMSys/library/src/controller/core/configuration/Configuration.cpp @@ -53,16 +53,11 @@ Configuration::Configuration() bool string2bool(string s) { - if(s.compare("0") == 0) - { + if (s.compare("0") == 0) { return false; - } - else if(s.compare("1") == 0) - { + } else if (s.compare("1") == 0) { return true; - } - else - { + } else { SC_REPORT_FATAL("Configuration", ("Could not convert to bool: " + s).c_str()); return false; } @@ -80,14 +75,13 @@ unsigned long long string2ull(string s) StorageMode string2StoreMode(string s) { - if(s == "NoStorage") + if (s == "NoStorage") return StorageMode::NoStorage; - else if(s == "Store") + else if (s == "Store") return StorageMode::Store; else if (s == "ErrorModel") return StorageMode::ErrorModel; - else - { + else { SC_REPORT_FATAL("Configuration", ("Unknown StorageMode: " + s).c_str()); throw; } @@ -95,16 +89,15 @@ StorageMode string2StoreMode(string s) EPowerDownMode string2PDNMode(string s) { - if(s == "NoPowerDown") + if (s == "NoPowerDown") return EPowerDownMode::NoPowerDown; - else if(s == "Staggered") + else if (s == "Staggered") return EPowerDownMode::Staggered; else if (s == "TimeoutPDN") return EPowerDownMode::TimeoutPDN; else if (s == "TimeoutSREF") return EPowerDownMode::TimeoutSREF; - else - { + else { SC_REPORT_FATAL("Configuration", ("Unknown PowerDownMode: " + s).c_str()); throw; } @@ -112,15 +105,14 @@ EPowerDownMode string2PDNMode(string s) ECCControllerMode string2ECCControllerMode(string s) { - if(s == "Disabled") - return ECCControllerMode::Disabled; - else if(s == "Hamming") - return ECCControllerMode::Hamming; - else - { - SC_REPORT_FATAL("Configuration", ("Unknown ECCControllerMode: " + s).c_str()); - throw; - } + if (s == "Disabled") + return ECCControllerMode::Disabled; + else if (s == "Hamming") + return ECCControllerMode::Hamming; + else { + SC_REPORT_FATAL("Configuration", ("Unknown ECCControllerMode: " + s).c_str()); + throw; + } } enum sc_time_unit string2TimeUnit(string s) @@ -138,131 +130,133 @@ enum sc_time_unit string2TimeUnit(string s) else if (s == "fs") return SC_FS; else { - SC_REPORT_FATAL("Configuration", ("Could not convert to enum sc_time_unit: " + s).c_str()); + SC_REPORT_FATAL("Configuration", + ("Could not convert to enum sc_time_unit: " + s).c_str()); throw; } } void Configuration::setParameter(std::string name, std::string value) { - if(name == "BankwiseLogic") + if (name == "BankwiseLogic") BankwiseLogic = string2bool(value); - else if(name == "OpenPagePolicy") + else if (name == "OpenPagePolicy") OpenPagePolicy = string2bool(value); - else if(name == "MaxNrOfTransactions") + else if (name == "MaxNrOfTransactions") MaxNrOfTransactions = string2int(value); - else if(name == "Scheduler") + else if (name == "Scheduler") Scheduler = value; - else if(name == "SJFProbability") - if (string2int(value) > 100 || string2int(value) < 0) { - SC_REPORT_FATAL("Configuration", ("Invalid value for parameter " + name + ". This parameter must be between 0 and 100.").c_str()); - } else { - SJFProbability = string2int(value); - } + else if (name == "SJFProbability") + if (string2int(value) > 100 || string2int(value) < 0) { + SC_REPORT_FATAL("Configuration", + ("Invalid value for parameter " + name + + ". This parameter must be between 0 and 100.").c_str()); + } else { + SJFProbability = string2int(value); + } else if (name == "RequestBufferSize") - RequestBufferSize = string2int(value); - else if(name == "Capsize") + RequestBufferSize = string2int(value); + else if (name == "Capsize") Capsize = string2int(value); - else if(name == "PowerDownTimeout") + else if (name == "PowerDownTimeout") powerDownTimeoutInClk = string2int(value); - else if(name == "PowerDownMode") + else if (name == "PowerDownMode") PowerDownMode = string2PDNMode(value); - else if(name == "ReadWriteGrouping") + else if (name == "ReadWriteGrouping") ReadWriteGrouping = string2bool(value); - else if(name == "ReorderBuffer") + else if (name == "ReorderBuffer") ReorderBuffer = string2bool(value); //SimConfig------------------------------------------------ - else if(name == "SimulationName") + else if (name == "SimulationName") SimulationName = value; - else if(name == "DatabaseRecording") + else if (name == "DatabaseRecording") DatabaseRecording = string2bool(value); - else if(name == "PowerAnalysis") + else if (name == "PowerAnalysis") PowerAnalysis = string2bool(value); else if (name == "EnableWindowing") EnableWindowing = string2bool(value); - else if(name == "WindowSize") - if(string2int(value) < 1) { - SC_REPORT_FATAL("Configuration", ("Invalid value for parameter " + name + ". This parameter must be at least one.").c_str()); - } - else + else if (name == "WindowSize") + if (string2int(value) < 1) { + SC_REPORT_FATAL("Configuration", + ("Invalid value for parameter " + name + + ". This parameter must be at least one.").c_str()); + } else WindowSize = string2int(value); - else if(name == "Debug") + else if (name == "Debug") Debug = string2bool(value); else if (name == "NumberOfMemChannels") { NumberOfMemChannels = string2int(value); - unsigned int maxNumberofMemChannels = AddressDecoder::getInstance().amount["channel"]; - if (NumberOfMemChannels > maxNumberofMemChannels) { + unsigned int maxNumberofMemChannels = + AddressDecoder::getInstance().amount["channel"]; + if (NumberOfMemChannels > maxNumberofMemChannels) { SC_REPORT_FATAL("Configuration", ("Invalid value for parameter " + name + ". Value is out of range. The maximum value according to " + "the address mapping configuration file is " + std::to_string(maxNumberofMemChannels) + ".").c_str()); - } - } - else if (name == "ControllerCoreDisableRefresh") + } + } else if (name == "ControllerCoreDisableRefresh") ControllerCoreDisableRefresh = string2bool(value); else if (name == "ControllerCoreForceMaxRefBurst") ControllerCoreForceMaxRefBurst = string2bool(value); - else if (name == "ControllerCoreEnableRefPostpone") - { + else if (name == "ControllerCoreEnableRefPostpone") { ControllerCoreEnableRefPostpone = string2bool(value); // Refresh postpone feature available for DDR3 only in the current // version of DRAMsys. if (ControllerCoreEnableRefPostpone && memSpec.MemoryType != "DDR3") { - SC_REPORT_FATAL("Configuration", (name + " requires memory type DDR3.").c_str()); + SC_REPORT_FATAL("Configuration", + (name + " requires memory type DDR3.").c_str()); } - } - else if (name == "ControllerCoreEnableRefPullIn") - { + } else if (name == "ControllerCoreEnableRefPullIn") { ControllerCoreEnableRefPullIn = string2bool(value); // Refresh pull-in feature available for DDR3 only in the current // version of DRAMsys. if (ControllerCoreEnableRefPullIn && memSpec.MemoryType != "DDR3") { - SC_REPORT_FATAL("Configuration", (name + " requires memory type DDR3.").c_str()); + SC_REPORT_FATAL("Configuration", + (name + " requires memory type DDR3.").c_str()); } - } - else if (name == "ControllerCoreMaxPostponedARCmd") + } else if (name == "ControllerCoreMaxPostponedARCmd") ControllerCoreMaxPostponedARCmd = string2int(value); else if (name == "ControllerCoreMaxPulledInARCmd") ControllerCoreMaxPulledInARCmd = string2int(value); else if (name == "ThermalSimulation") ThermalSimulation = string2bool(value); - else if(name == "SimulationProgressBar") + else if (name == "SimulationProgressBar") SimulationProgressBar = string2bool(value); - else if(name == "NumberOfDevicesOnDIMM") - if (string2int(value) < 1) { - SC_REPORT_FATAL("Configuration", ("Invalid value for parameter " + name + ". This parameter must be at least one.").c_str()); - } else - NumberOfDevicesOnDIMM = string2int(value); - else if(name == "AddressOffset") - { + else if (name == "NumberOfDevicesOnDIMM") + if (string2int(value) < 1) { + SC_REPORT_FATAL("Configuration", + ("Invalid value for parameter " + name + + ". This parameter must be at least one.").c_str()); + } else + NumberOfDevicesOnDIMM = string2int(value); + else if (name == "AddressOffset") { #ifdef DRAMSYS_GEM5 AddressOffset = string2ull(value); #else AddressOffset = 0; #endif cout << "Address Offset: " << AddressOffset << endl; - } - else if(name == "CheckTLM2Protocol") + } else if (name == "CheckTLM2Protocol") CheckTLM2Protocol = string2bool(value); - else if(name == "ECCControllerMode") - ECCMode = string2ECCControllerMode(value); + else if (name == "ECCControllerMode") + ECCMode = string2ECCControllerMode(value); // Specification for ErrorChipSeed, ErrorCSVFile path and StoreMode - else if(name == "ErrorChipSeed") + else if (name == "ErrorChipSeed") ErrorChipSeed = string2int(value); - else if(name == "ErrorCSVFile") + else if (name == "ErrorCSVFile") ErrorCSVFile = value; - else if(name == "StoreMode") + else if (name == "StoreMode") StoreMode = string2StoreMode(value); // Temperature Simulation related else if (name == "TemperatureScale") { if (value != "Celsius" && value != "Fahrenheit" && value != "Kelvin") { - SC_REPORT_FATAL("Configuration", ("Invalid value for parameter " + name + ".").c_str()); + SC_REPORT_FATAL("Configuration", + ("Invalid value for parameter " + name + ".").c_str()); } temperatureSim.TemperatureScale = value; - } - else if (name == "StaticTemperatureDefaultValue") + } else if (name == "StaticTemperatureDefaultValue") temperatureSim.StaticTemperatureDefaultValue = string2int(value); else if (name == "ThermalSimPeriod") temperatureSim.ThermalSimPeriod = std::stod(value.c_str()); @@ -271,8 +265,7 @@ void Configuration::setParameter(std::string name, std::string value) else if (name == "PowerInfoFile") { temperatureSim.powerInfoFile = value; temperatureSim.parsePowerInfoFile(); - } - else if (name == "IceServerIp") + } else if (name == "IceServerIp") temperatureSim.IceServerIp = value; else if (name == "IceServerPort") temperatureSim.IceServerPort = string2int(value); @@ -284,9 +277,9 @@ void Configuration::setParameter(std::string name, std::string value) temperatureSim.GenerateTemperatureMap = string2bool(value); else if (name == "GeneratePowerMap") temperatureSim.GeneratePowerMap = string2bool(value); - else - { - SC_REPORT_FATAL("Configuration", ("Parameter " + name + " not defined in Configuration").c_str()); + else { + SC_REPORT_FATAL("Configuration", + ("Parameter " + name + " not defined in Configuration").c_str()); } } @@ -301,10 +294,10 @@ std::string Configuration::getPathToResources() return pathToResources; } -void Configuration::setParameters(std::map parameterMap) +void Configuration::setParameters(std::map + parameterMap) { - for(auto item : parameterMap) - { + for (auto item : parameterMap) { setParameter(item.first, item.second); } } @@ -349,7 +342,8 @@ unsigned int Configuration::getBytesPerBurst() // The least significant bits of the physical address are the byte // offset of the N-byte-wide memory module (DIMM) (a single data word // or burst element has N bytes. N = 2^(# bits for byte offset)). - unsigned int burstElementSizeInBytes = AddressDecoder::getInstance().amount["bytes"]; + unsigned int burstElementSizeInBytes = + AddressDecoder::getInstance().amount["bytes"]; assert(bytesPerBurst == (burstElementSizeInBytes * memSpec.BurstLength)); } @@ -359,12 +353,11 @@ unsigned int Configuration::getBytesPerBurst() // Changes the number of bytes depeding on the ECC Controller. This function is needed for modules which get data directly or indirectly from the ECC Controller unsigned int Configuration::adjustNumBytesAfterECC(unsigned nBytes) { - // Manipulate the number of bytes only if there is an ECC Controller selected - if(ECCMode == ECCControllerMode::Disabled) - return nBytes; - else - { - assert(pECC != nullptr); - return pECC->AllocationSize(nBytes); - } + // Manipulate the number of bytes only if there is an ECC Controller selected + if (ECCMode == ECCControllerMode::Disabled) + return nBytes; + else { + assert(pECC != nullptr); + return pECC->AllocationSize(nBytes); + } } diff --git a/DRAMSys/library/src/controller/core/configuration/Configuration.h b/DRAMSys/library/src/controller/core/configuration/Configuration.h index a0c449be..ea179604 100644 --- a/DRAMSys/library/src/controller/core/configuration/Configuration.h +++ b/DRAMSys/library/src/controller/core/configuration/Configuration.h @@ -47,14 +47,13 @@ #include "../../../error/eccbaseclass.h" -enum class StorageMode{NoStorage, Store, ErrorModel}; +enum class StorageMode {NoStorage, Store, ErrorModel}; -enum class EPowerDownMode{NoPowerDown, Staggered, TimeoutPDN, TimeoutSREF}; +enum class EPowerDownMode {NoPowerDown, Staggered, TimeoutPDN, TimeoutSREF}; -enum class ECCControllerMode{Disabled, Hamming}; +enum class ECCControllerMode {Disabled, Hamming}; -struct Configuration -{ +struct Configuration { static std::string memspecUri; static std::string mcconfigUri; std::string pathToResources; @@ -69,7 +68,10 @@ struct Configuration unsigned int SJFProbability; unsigned int RequestBufferSize; unsigned int Capsize = 5; - sc_time getPowerDownTimeout(){return powerDownTimeoutInClk*memSpec.clk;} + sc_time getPowerDownTimeout() + { + return powerDownTimeoutInClk * memSpec.clk; + } EPowerDownMode PowerDownMode = EPowerDownMode::Staggered; bool ReadWriteGrouping = false; bool ReorderBuffer = false; @@ -92,8 +94,8 @@ struct Configuration bool SimulationProgressBar = false; unsigned int NumberOfDevicesOnDIMM = 1; bool CheckTLM2Protocol = false; - ECCControllerMode ECCMode = ECCControllerMode::Disabled; - ECCBaseClass* pECC = nullptr; + ECCControllerMode ECCMode = ECCControllerMode::Disabled; + ECCBaseClass *pECC = nullptr; bool gem5 = false; unsigned long long int AddressOffset = 0; @@ -105,7 +107,7 @@ struct Configuration //Configs for Seed, csv file and StorageMode unsigned int ErrorChipSeed; - std::string ErrorCSVFile ="not defined."; + std::string ErrorCSVFile = "not defined."; StorageMode StoreMode; // Temperature Simulation related @@ -114,7 +116,7 @@ struct Configuration std::uint64_t getSimMemSizeInBytes(); unsigned int getDataBusWidth(); unsigned int getBytesPerBurst(); - unsigned int adjustNumBytesAfterECC(unsigned bytes); + unsigned int adjustNumBytesAfterECC(unsigned bytes); void setPathToResources(std::string path); std::string getPathToResources(); diff --git a/DRAMSys/library/src/controller/core/configuration/ConfigurationLoader.cpp b/DRAMSys/library/src/controller/core/configuration/ConfigurationLoader.cpp index 7388d2e0..86588d2d 100644 --- a/DRAMSys/library/src/controller/core/configuration/ConfigurationLoader.cpp +++ b/DRAMSys/library/src/controller/core/configuration/ConfigurationLoader.cpp @@ -41,19 +41,20 @@ using namespace tinyxml2; using namespace std; -void ConfigurationLoader::loadSimConfig(Configuration& config, string simconfigUri) +void ConfigurationLoader::loadSimConfig(Configuration &config, + string simconfigUri) { tinyxml2::XMLDocument doc; loadXML(simconfigUri, doc); - XMLElement* simconfig = doc.FirstChildElement("simconfig"); + XMLElement *simconfig = doc.FirstChildElement("simconfig"); loadConfig(config, simconfig); } -void ConfigurationLoader::loadSimConfig(Configuration& config, XMLElement* simconfig) +void ConfigurationLoader::loadSimConfig(Configuration &config, + XMLElement *simconfig) { - if(simconfig->Attribute("src")) - { + if (simconfig->Attribute("src")) { XMLDocument doc; string src(simconfig->Attribute("src")); loadXML(src, doc); @@ -62,12 +63,14 @@ void ConfigurationLoader::loadSimConfig(Configuration& config, XMLElement* simco loadConfig(config, simconfig); } -void ConfigurationLoader::loadTemperatureSimConfig(Configuration &config, std::string thermalsimconfigUri) +void ConfigurationLoader::loadTemperatureSimConfig(Configuration &config, + std::string thermalsimconfigUri) { loadConfigFromUri(config, thermalsimconfigUri, "thermalsimconfig"); } -void ConfigurationLoader::loadTemperatureSimConfig(Configuration &config, XMLElement *thermalsimconfig) +void ConfigurationLoader::loadTemperatureSimConfig(Configuration &config, + XMLElement *thermalsimconfig) { if (thermalsimconfig->Attribute("src")) { // Configuration is inside another a file @@ -78,18 +81,19 @@ void ConfigurationLoader::loadTemperatureSimConfig(Configuration &config, XMLEle } } -void ConfigurationLoader::loadConfig(Configuration& config, XMLElement* configNode) +void ConfigurationLoader::loadConfig(Configuration &config, + XMLElement *configNode) { - XMLElement* element; + XMLElement *element; for (element = configNode->FirstChildElement(); element != NULL; - element = element->NextSiblingElement()) - { + element = element->NextSiblingElement()) { config.setParameter(element->Name(), element->Attribute("value")); } } -void ConfigurationLoader::loadConfigFromUri(Configuration &config, std::string uri, std::string first_element) +void ConfigurationLoader::loadConfigFromUri(Configuration &config, + std::string uri, std::string first_element) { tinyxml2::XMLDocument doc; loadXML(uri, doc); @@ -97,75 +101,66 @@ void ConfigurationLoader::loadConfigFromUri(Configuration &config, std::string u loadConfig(config, e); } -void ConfigurationLoader::loadMemSpec(Configuration& config, string memspecUri) +void ConfigurationLoader::loadMemSpec(Configuration &config, string memspecUri) { tinyxml2::XMLDocument doc; config.memspecUri = memspecUri; loadXML(memspecUri, doc); - XMLElement* memspec = doc.FirstChildElement("memspec"); + XMLElement *memspec = doc.FirstChildElement("memspec"); loadMemSpec(config, memspec); } -void ConfigurationLoader::loadMemSpec(Configuration& config, XMLElement* memspec) +void ConfigurationLoader::loadMemSpec(Configuration &config, + XMLElement *memspec) { config.memSpec.MemoryId = queryStringParameter(memspec, "memoryId"); config.memSpec.MemoryType = queryStringParameter(memspec, "memoryType"); std::cout << "Memtype: " << config.memSpec.MemoryType << std::endl; - if (config.memSpec.MemoryType == "DDR4") - { + if (config.memSpec.MemoryType == "DDR4") { loadDDR4(config, memspec); - } - else if (config.memSpec.MemoryType == "DDR3") - { + } else if (config.memSpec.MemoryType == "DDR3") { loadDDR3(config, memspec); - } - else if (config.memSpec.MemoryType == "LPDDR4") - { + } else if (config.memSpec.MemoryType == "LPDDR4") { loadLPDDR4(config, memspec); - } - else if (config.memSpec.MemoryType == "WIDEIO_SDR") - { + } else if (config.memSpec.MemoryType == "WIDEIO_SDR") { loadWideIO(config, memspec); - } - else - { + } else { reportFatal("ConfigurationLoader", "Unsupported DRAM type"); } } -void ConfigurationLoader::loadMCConfig(Configuration& config, string mcconfigUri) +void ConfigurationLoader::loadMCConfig(Configuration &config, + string mcconfigUri) { tinyxml2::XMLDocument doc; config.mcconfigUri = mcconfigUri; loadXML(mcconfigUri, doc); - XMLElement* mcconfig = doc.FirstChildElement("mcconfig"); + XMLElement *mcconfig = doc.FirstChildElement("mcconfig"); loadConfig(config, mcconfig); } -void ConfigurationLoader::loadMCConfig(Configuration& config, XMLElement* mcconfig) +void ConfigurationLoader::loadMCConfig(Configuration &config, + XMLElement *mcconfig) { - if(mcconfig->Attribute("src")) - { + if (mcconfig->Attribute("src")) { XMLDocument doc; string src(mcconfig->Attribute("src")); config.mcconfigUri = src; loadXML(src, doc); loadMCConfig(config, doc.FirstChildElement("mcconfig")); - } - else - { + } else { loadConfig(config, mcconfig); } } -void ConfigurationLoader::loadDDR3(Configuration& config, XMLElement* memspec) +void ConfigurationLoader::loadDDR3(Configuration &config, XMLElement *memspec) { //MemArchitecture - XMLElement* architecture = memspec->FirstChildElement("memarchitecturespec"); + XMLElement *architecture = memspec->FirstChildElement("memarchitecturespec"); config.memSpec.NumberOfBanks = queryUIntParameter(architecture, "nbrOfBanks"); config.memSpec.NumberOfBankGroups = 1; @@ -174,13 +169,14 @@ void ConfigurationLoader::loadDDR3(Configuration& config, XMLElement* memspec) config.memSpec.nActivate = 4; config.memSpec.DataRate = queryUIntParameter(architecture, "dataRate"); config.memSpec.NumberOfRows = queryUIntParameter(architecture, "nbrOfRows"); - config.memSpec.NumberOfColumns = queryUIntParameter(architecture, "nbrOfColumns"); + config.memSpec.NumberOfColumns = queryUIntParameter(architecture, + "nbrOfColumns"); config.memSpec.bitWidth = queryUIntParameter(architecture, "width"); config.memSpec.DLL = true; config.memSpec.termination = true; //MemTimings - XMLElement* timings = memspec->FirstChildElement("memtimingspec"); + XMLElement *timings = memspec->FirstChildElement("memtimingspec"); double clkMhz = queryDoubleParameter(timings, "clkMhz"); config.memSpec.clk = FrequencyToClk(clkMhz); sc_time clk = config.memSpec.clk; @@ -211,13 +207,13 @@ void ConfigurationLoader::loadDDR3(Configuration& config, XMLElement* memspec) config.memSpec.tDQSCK = clk * queryUIntParameter(timings, "DQSCK"); config.memSpec.refreshTimings.clear(); - for (unsigned int i = 0; i < config.memSpec.NumberOfBanks; ++i) - { - config.memSpec.refreshTimings[Bank(i)] = RefreshTiming(config.memSpec.tRFC, config.memSpec.tREFI); + for (unsigned int i = 0; i < config.memSpec.NumberOfBanks; ++i) { + config.memSpec.refreshTimings[Bank(i)] = RefreshTiming(config.memSpec.tRFC, + config.memSpec.tREFI); } // Currents and Volatages: TODO Check if this is correct. - XMLElement* powers = memspec->FirstChildElement("mempowerspec"); + XMLElement *powers = memspec->FirstChildElement("mempowerspec"); config.memSpec.iDD0 = queryDoubleParameter(powers, "idd0"); config.memSpec.iDD02 = queryDoubleParameter(powers, "idd0"); config.memSpec.iDD2P0 = queryDoubleParameter(powers, "idd2p0"); @@ -236,25 +232,27 @@ void ConfigurationLoader::loadDDR3(Configuration& config, XMLElement* memspec) } -void ConfigurationLoader::loadDDR4(Configuration& config, XMLElement* memspec) +void ConfigurationLoader::loadDDR4(Configuration &config, XMLElement *memspec) { //MemArchitecture - XMLElement* architecture = memspec->FirstChildElement("memarchitecturespec"); + XMLElement *architecture = memspec->FirstChildElement("memarchitecturespec"); config.memSpec.NumberOfBanks = queryUIntParameter(architecture, "nbrOfBanks"); - config.memSpec.NumberOfBankGroups = queryUIntParameter(architecture, "nbrOfBankGroups"); + config.memSpec.NumberOfBankGroups = queryUIntParameter(architecture, + "nbrOfBankGroups"); config.memSpec.NumberOfRanks = queryUIntParameter(architecture, "nbrOfRanks"); config.memSpec.BurstLength = queryUIntParameter(architecture, "burstLength"); config.memSpec.nActivate = 4; config.memSpec.DataRate = queryUIntParameter(architecture, "dataRate"); config.memSpec.NumberOfRows = queryUIntParameter(architecture, "nbrOfRows"); - config.memSpec.NumberOfColumns = queryUIntParameter(architecture, "nbrOfColumns"); + config.memSpec.NumberOfColumns = queryUIntParameter(architecture, + "nbrOfColumns"); config.memSpec.bitWidth = queryUIntParameter(architecture, "width"); config.memSpec.DLL = true; config.memSpec.termination = true; //MemTimings - XMLElement* timings = memspec->FirstChildElement("memtimingspec"); + XMLElement *timings = memspec->FirstChildElement("memtimingspec"); double clkMhz = queryDoubleParameter(timings, "clkMhz"); config.memSpec.clk = FrequencyToClk(clkMhz); sc_time clk = config.memSpec.clk; @@ -285,13 +283,13 @@ void ConfigurationLoader::loadDDR4(Configuration& config, XMLElement* memspec) config.memSpec.tDQSCK = clk * queryUIntParameter(timings, "DQSCK"); config.memSpec.refreshTimings.clear(); - for (unsigned int i = 0; i < config.memSpec.NumberOfBanks; ++i) - { - config.memSpec.refreshTimings[Bank(i)] = RefreshTiming(config.memSpec.tRFC, config.memSpec.tREFI); + for (unsigned int i = 0; i < config.memSpec.NumberOfBanks; ++i) { + config.memSpec.refreshTimings[Bank(i)] = RefreshTiming(config.memSpec.tRFC, + config.memSpec.tREFI); } // Currents and Volatages: - XMLElement* powers = memspec->FirstChildElement("mempowerspec"); + XMLElement *powers = memspec->FirstChildElement("mempowerspec"); config.memSpec.iDD0 = queryDoubleParameter(powers, "idd0"); config.memSpec.iDD02 = queryDoubleParameter(powers, "idd02"); config.memSpec.iDD2P0 = queryDoubleParameter(powers, "idd2p0"); @@ -310,10 +308,10 @@ void ConfigurationLoader::loadDDR4(Configuration& config, XMLElement* memspec) } // TODO: fix this for LPDDR4 -void ConfigurationLoader::loadLPDDR4(Configuration& config, XMLElement* memspec) +void ConfigurationLoader::loadLPDDR4(Configuration &config, XMLElement *memspec) { //MemArchitecture: - XMLElement* architecture = memspec->FirstChildElement("memarchitecturespec"); + XMLElement *architecture = memspec->FirstChildElement("memarchitecturespec"); config.memSpec.NumberOfBanks = queryUIntParameter(architecture, "nbrOfBanks"); config.memSpec.NumberOfBankGroups = 1; @@ -322,13 +320,14 @@ void ConfigurationLoader::loadLPDDR4(Configuration& config, XMLElement* memspec) config.memSpec.nActivate = 4; config.memSpec.DataRate = queryUIntParameter(architecture, "dataRate"); config.memSpec.NumberOfRows = queryUIntParameter(architecture, "nbrOfRows"); - config.memSpec.NumberOfColumns = queryUIntParameter(architecture, "nbrOfColumns"); + config.memSpec.NumberOfColumns = queryUIntParameter(architecture, + "nbrOfColumns"); config.memSpec.bitWidth = queryUIntParameter(architecture, "width"); config.memSpec.DLL = false; // TODO: Correct? config.memSpec.termination = true; // TODO: Correct? //MemTimings - XMLElement* timings = memspec->FirstChildElement("memtimingspec"); + XMLElement *timings = memspec->FirstChildElement("memtimingspec"); double clkMhz = queryDoubleParameter(timings, "clkMhz"); config.memSpec.clk = FrequencyToClk(clkMhz); sc_time clk = config.memSpec.clk; @@ -362,13 +361,13 @@ void ConfigurationLoader::loadLPDDR4(Configuration& config, XMLElement* memspec) config.memSpec.tDQSCK = clk * queryUIntParameter(timings, "DQSCK"); config.memSpec.refreshTimings.clear(); - for (unsigned int i = 0; i < config.memSpec.NumberOfBanks; ++i) - { - config.memSpec.refreshTimings[Bank(i)] = RefreshTiming(config.memSpec.tRFC, config.memSpec.tREFI); + for (unsigned int i = 0; i < config.memSpec.NumberOfBanks; ++i) { + config.memSpec.refreshTimings[Bank(i)] = RefreshTiming(config.memSpec.tRFC, + config.memSpec.tREFI); } // Currents and Volatages: - XMLElement* powers = memspec->FirstChildElement("mempowerspec"); + XMLElement *powers = memspec->FirstChildElement("mempowerspec"); config.memSpec.iDD0 = queryDoubleParameter(powers, "idd0"); config.memSpec.iDD02 = queryDoubleParameter(powers, "idd02"); config.memSpec.iDD2P0 = queryDoubleParameter(powers, "idd2p"); @@ -386,10 +385,10 @@ void ConfigurationLoader::loadLPDDR4(Configuration& config, XMLElement* memspec) config.memSpec.vDD2 = queryDoubleParameter(powers, "vdd2"); } -void ConfigurationLoader::loadWideIO(Configuration& config, XMLElement* memspec) +void ConfigurationLoader::loadWideIO(Configuration &config, XMLElement *memspec) { //MemSpecification - XMLElement* architecture = memspec->FirstChildElement("memarchitecturespec"); + XMLElement *architecture = memspec->FirstChildElement("memarchitecturespec"); config.memSpec.NumberOfBanks = queryUIntParameter(architecture, "nbrOfBanks"); config.memSpec.NumberOfBankGroups = 1; @@ -398,13 +397,14 @@ void ConfigurationLoader::loadWideIO(Configuration& config, XMLElement* memspec) config.memSpec.nActivate = 2; config.memSpec.DataRate = queryUIntParameter(architecture, "dataRate"); config.memSpec.NumberOfRows = queryUIntParameter(architecture, "nbrOfRows"); - config.memSpec.NumberOfColumns = queryUIntParameter(architecture, "nbrOfColumns"); + config.memSpec.NumberOfColumns = queryUIntParameter(architecture, + "nbrOfColumns"); config.memSpec.bitWidth = queryUIntParameter(architecture, "width"); config.memSpec.DLL = false; config.memSpec.termination = false; //MemTimings - XMLElement* timings = memspec->FirstChildElement("memtimingspec"); + XMLElement *timings = memspec->FirstChildElement("memtimingspec"); double clkMhz = queryDoubleParameter(timings, "clkMhz"); config.memSpec.clk = FrequencyToClk(clkMhz); sc_time clk = config.memSpec.clk; @@ -434,13 +434,13 @@ void ConfigurationLoader::loadWideIO(Configuration& config, XMLElement* memspec) config.memSpec.tREFI = clk * queryUIntParameter(timings, "REFI"); config.memSpec.refreshTimings.clear(); - for (unsigned int i = 0; i < config.memSpec.NumberOfBanks; ++i) - { - config.memSpec.refreshTimings[Bank(i)] = RefreshTiming(config.memSpec.tRFC, config.memSpec.tREFI); + for (unsigned int i = 0; i < config.memSpec.NumberOfBanks; ++i) { + config.memSpec.refreshTimings[Bank(i)] = RefreshTiming(config.memSpec.tRFC, + config.memSpec.tREFI); } // Currents and Volatages: - XMLElement* powers = memspec->FirstChildElement("mempowerspec"); + XMLElement *powers = memspec->FirstChildElement("mempowerspec"); config.memSpec.iDD0 = queryDoubleParameter(powers, "idd0"); config.memSpec.iDD02 = queryDoubleParameter(powers, "idd02"); config.memSpec.iDD2P0 = queryDoubleParameter(powers, "idd2p0"); diff --git a/DRAMSys/library/src/controller/core/configuration/ConfigurationLoader.h b/DRAMSys/library/src/controller/core/configuration/ConfigurationLoader.h index 309b25f8..8334cb4e 100644 --- a/DRAMSys/library/src/controller/core/configuration/ConfigurationLoader.h +++ b/DRAMSys/library/src/controller/core/configuration/ConfigurationLoader.h @@ -46,27 +46,31 @@ class ConfigurationLoader { public: - static void loadMCConfig(Configuration& config, std::string amconfigUri); - static void loadMCConfig(Configuration& config, tinyxml2::XMLElement* mcconfig); + static void loadMCConfig(Configuration &config, std::string amconfigUri); + static void loadMCConfig(Configuration &config, tinyxml2::XMLElement *mcconfig); - static void loadSimConfig(Configuration& config, std::string simconfigUri); - static void loadSimConfig(Configuration& config,tinyxml2::XMLElement* simconfig); + static void loadSimConfig(Configuration &config, std::string simconfigUri); + static void loadSimConfig(Configuration &config, + tinyxml2::XMLElement *simconfig); - static void loadMemSpec(Configuration& config, std::string memspecUri); - static void loadMemSpec(Configuration& config, tinyxml2::XMLElement* memspec); + static void loadMemSpec(Configuration &config, std::string memspecUri); + static void loadMemSpec(Configuration &config, tinyxml2::XMLElement *memspec); - static void loadTemperatureSimConfig(Configuration &config, std::string simconfigUri); - static void loadTemperatureSimConfig(Configuration& config, tinyxml2::XMLElement *simconfig); + static void loadTemperatureSimConfig(Configuration &config, + std::string simconfigUri); + static void loadTemperatureSimConfig(Configuration &config, + tinyxml2::XMLElement *simconfig); private: - ConfigurationLoader(){} - static void loadConfig(Configuration& config, tinyxml2::XMLElement* configNode); - static void loadConfigFromUri(Configuration &config, std::string uri, std::string first_element); + ConfigurationLoader() {} + static void loadConfig(Configuration &config, tinyxml2::XMLElement *configNode); + static void loadConfigFromUri(Configuration &config, std::string uri, + std::string first_element); //specific loader - static void loadDDR3(Configuration& config, tinyxml2::XMLElement* memspec); - static void loadDDR4(Configuration& config, tinyxml2::XMLElement* memspec); - static void loadLPDDR4(Configuration& config, tinyxml2::XMLElement* memspec); - static void loadWideIO(Configuration& config, tinyxml2::XMLElement* memspec); + static void loadDDR3(Configuration &config, tinyxml2::XMLElement *memspec); + static void loadDDR4(Configuration &config, tinyxml2::XMLElement *memspec); + static void loadLPDDR4(Configuration &config, tinyxml2::XMLElement *memspec); + static void loadWideIO(Configuration &config, tinyxml2::XMLElement *memspec); }; diff --git a/DRAMSys/library/src/controller/core/configuration/MemSpec.h b/DRAMSys/library/src/controller/core/configuration/MemSpec.h index a14f2b57..b954e4b2 100644 --- a/DRAMSys/library/src/controller/core/configuration/MemSpec.h +++ b/DRAMSys/library/src/controller/core/configuration/MemSpec.h @@ -42,28 +42,24 @@ #include "../../../common/dramExtension.h" -struct RefreshTiming -{ +struct RefreshTiming { RefreshTiming() {} RefreshTiming(sc_time tRFC, sc_time tREFI) : tRFC(tRFC), tREFI(tREFI) {} - sc_time tRFC; - sc_time tREFI; + sc_time tRFC; + sc_time tREFI; }; -struct MemSpec -{ +struct MemSpec { MemSpec() - { + { //default DDR4 - } + } - const std::vector& getBanks() const + const std::vector &getBanks() const { static std::vector banks; - if (banks.size() == 0) - { - for (unsigned int i = 0; i < NumberOfBanks; i++) - { + if (banks.size() == 0) { + for (unsigned int i = 0; i < NumberOfBanks; i++) { banks.push_back(Bank(i)); } } @@ -87,34 +83,34 @@ struct MemSpec bool termination; // Memspec Variables: - sc_time clk; - sc_time tRP; //precharge-time (pre -> act same bank) - sc_time tRPAB; //precharge-all time only for LPDDR4 - sc_time tRAS; //active-time (act -> pre same bank) - sc_time tRC; //RAS-cycle-time (min time bw 2 succesive ACT to same bank) - sc_time tCCD_S; //max(bl, tCCD) is relevant for rd->rd - sc_time tCCD_L; - sc_time tRTP; //Read to precharge - sc_time tRRD_S; //min time bw 2 succesive ACT to different banks (different bank group) - sc_time tRRD_L; //.. (same bank group) - sc_time tRCD; //act -> read/write - sc_time tNAW; //n activate window - sc_time tRL; //read latency (read command start to data strobe) - sc_time tWL; //write latency - sc_time tWR; //write recovery (write to precharge) - sc_time tWTR_S; //write to read (different bank group) - sc_time tWTR_L; //.. (same bank group) - sc_time tCKESR; //min time in sref - sc_time tCKE; //min time in pdna or pdnp - sc_time tXP; //min delay to row access command after pdnpx pdnax - sc_time tXPDLL; //min delay to row access command after pdnpx pdnax for dll commands - sc_time tXSR; //min delay to row access command after srefx - sc_time tXSRDLL; //min delay to row access command after srefx for dll commands - sc_time tAL; //additive delay (delayed execution in dram) + sc_time clk; + sc_time tRP; //precharge-time (pre -> act same bank) + sc_time tRPAB; //precharge-all time only for LPDDR4 + sc_time tRAS; //active-time (act -> pre same bank) + sc_time tRC; //RAS-cycle-time (min time bw 2 succesive ACT to same bank) + sc_time tCCD_S; //max(bl, tCCD) is relevant for rd->rd + sc_time tCCD_L; + sc_time tRTP; //Read to precharge + sc_time tRRD_S; //min time bw 2 succesive ACT to different banks (different bank group) + sc_time tRRD_L; //.. (same bank group) + sc_time tRCD; //act -> read/write + sc_time tNAW; //n activate window + sc_time tRL; //read latency (read command start to data strobe) + sc_time tWL; //write latency + sc_time tWR; //write recovery (write to precharge) + sc_time tWTR_S; //write to read (different bank group) + sc_time tWTR_L; //.. (same bank group) + sc_time tCKESR; //min time in sref + sc_time tCKE; //min time in pdna or pdnp + sc_time tXP; //min delay to row access command after pdnpx pdnax + sc_time tXPDLL; //min delay to row access command after pdnpx pdnax for dll commands + sc_time tXSR; //min delay to row access command after srefx + sc_time tXSRDLL; //min delay to row access command after srefx for dll commands + sc_time tAL; //additive delay (delayed execution in dram) sc_time tDQSCK; - sc_time tRFC; //min ref->act delay - sc_time tREFI; //auto refresh must be issued at an average periodic interval tREFI + sc_time tRFC; //min ref->act delay + sc_time tREFI; //auto refresh must be issued at an average periodic interval tREFI // Currents and Voltages: double iDD0; @@ -143,11 +139,18 @@ struct MemSpec double vDD2; - std::map refreshTimings;//ensure that map is populated completely in memspecloader + std::map + refreshTimings;//ensure that map is populated completely in memspecloader - //act and read/write commands remain for this timespan in history - sc_time tActHistory(){return tNAW;} - sc_time tDataStrobeHistory(){return tWTR_L;} + //act and read/write commands remain for this timespan in history + sc_time tActHistory() + { + return tNAW; + } + sc_time tDataStrobeHistory() + { + return tWTR_L; + } }; #endif /* MemSpec_H_ */ diff --git a/DRAMSys/library/src/controller/core/configuration/thermalSimConfig.h b/DRAMSys/library/src/controller/core/configuration/thermalSimConfig.h index 167b0e11..6d202dbc 100644 --- a/DRAMSys/library/src/controller/core/configuration/thermalSimConfig.h +++ b/DRAMSys/library/src/controller/core/configuration/thermalSimConfig.h @@ -79,8 +79,8 @@ struct TemperatureSimConfig { printDebugMessage("Power Info File: " + powerInfoFile); powerInfoFile = pathToResources - + "/configs/thermalsim/" - + powerInfoFile; + + "/configs/thermalsim/" + + powerInfoFile; // Load the XML file into memory and parse it tinyxml2::XMLDocument xml; @@ -94,7 +94,8 @@ struct TemperatureSimConfig { SC_REPORT_FATAL("Temperature Sim Config", errormsg.c_str()); } - for (tinyxml2::XMLElement *e = powInfoElem->FirstChildElement(); e != NULL; e = e->NextSiblingElement()) { + for (tinyxml2::XMLElement *e = powInfoElem->FirstChildElement(); e != NULL; + e = e->NextSiblingElement()) { // Load initial power values for all devices std::string init_pow_str = e->Attribute("init_pow"); @@ -114,17 +115,20 @@ struct TemperatureSimConfig { { int i = 0; for (auto e : powerInitialValues) { - printDebugMessage("powerInitialValues[" + std::to_string(i++) + "]: " + std::to_string(e)); + printDebugMessage("powerInitialValues[" + std::to_string( + i++) + "]: " + std::to_string(e)); } i = 0; for (auto e : powerThresholds) { - printDebugMessage("powerThreshold[" + std::to_string(i++) + "]: " + std::to_string(e)); + printDebugMessage("powerThreshold[" + std::to_string(i++) + "]: " + + std::to_string(e)); } } void printDebugMessage(std::string message) { - DebugManager::getInstance().printDebugMessage("Temperature Sim Config", message); + DebugManager::getInstance().printDebugMessage("Temperature Sim Config", + message); } }; diff --git a/DRAMSys/library/src/controller/core/powerdown/IPowerDownManager.h b/DRAMSys/library/src/controller/core/powerdown/IPowerDownManager.h index 48972149..1de77427 100644 --- a/DRAMSys/library/src/controller/core/powerdown/IPowerDownManager.h +++ b/DRAMSys/library/src/controller/core/powerdown/IPowerDownManager.h @@ -42,89 +42,87 @@ #include "../../Command.h" -enum class PowerDownState -{ - Awake, AwakeForRefresh, PDNActive, PDNPrecharge, PDNSelfRefresh +enum class PowerDownState { + Awake, AwakeForRefresh, PDNActive, PDNPrecharge, PDNSelfRefresh }; class IPowerDownManager { public: - virtual ~IPowerDownManager() {} + virtual ~IPowerDownManager() {} - virtual void sleep(Bank bank, sc_time time) = 0; - virtual void triggerSleep(Bank bank, sc_time time) = 0; + virtual void sleep(Bank bank, sc_time time) = 0; + virtual void triggerSleep(Bank bank, sc_time time) = 0; - virtual void wakeUp(Bank bank, sc_time time) = 0; - virtual void wakeUpForRefresh(Bank bank, sc_time time) = 0; + virtual void wakeUp(Bank bank, sc_time time) = 0; + virtual void wakeUpForRefresh(Bank bank, sc_time time) = 0; - virtual bool isInSelfRefresh(Bank bank) = 0; + virtual bool isInSelfRefresh(Bank bank) = 0; protected: - Command getSleepCommand(PowerDownState state); - Command getWakeUpCommand(PowerDownState state); + Command getSleepCommand(PowerDownState state); + Command getWakeUpCommand(PowerDownState state); }; inline Command IPowerDownManager::getSleepCommand(PowerDownState state) { - Command cmd(Command::NOP); - switch (state) - { - case PowerDownState::PDNActive: - cmd = Command::PDNA; - break; - case PowerDownState::PDNPrecharge: - cmd = Command::PDNP; - break; - case PowerDownState::PDNSelfRefresh: - cmd = Command::SREF; - break; - default: - SC_REPORT_FATAL("In PowerDownManager sendPowerdownBegin", "invalid powerDownState"); - break; - } - return cmd; + Command cmd(Command::NOP); + switch (state) { + case PowerDownState::PDNActive: + cmd = Command::PDNA; + break; + case PowerDownState::PDNPrecharge: + cmd = Command::PDNP; + break; + case PowerDownState::PDNSelfRefresh: + cmd = Command::SREF; + break; + default: + SC_REPORT_FATAL("In PowerDownManager sendPowerdownBegin", + "invalid powerDownState"); + break; + } + return cmd; } inline Command IPowerDownManager::getWakeUpCommand(PowerDownState state) { - Command cmd(Command::NOP); - switch (state) - { - case PowerDownState::PDNActive: - cmd = Command::PDNAX; - break; - case PowerDownState::PDNPrecharge: - cmd = Command::PDNPX; - break; - case PowerDownState::PDNSelfRefresh: - cmd = Command::SREFX; - break; - default: - SC_REPORT_FATAL("In PowerDownManager sendPowerdownEnd", "invalid powerDownState"); - } - return cmd; + Command cmd(Command::NOP); + switch (state) { + case PowerDownState::PDNActive: + cmd = Command::PDNAX; + break; + case PowerDownState::PDNPrecharge: + cmd = Command::PDNPX; + break; + case PowerDownState::PDNSelfRefresh: + cmd = Command::SREFX; + break; + default: + SC_REPORT_FATAL("In PowerDownManager sendPowerdownEnd", + "invalid powerDownState"); + } + return cmd; } inline std::string powerDownStateToString(PowerDownState powerDownState) { - switch (powerDownState) - { - case PowerDownState::Awake: - return "Awake"; - case PowerDownState::AwakeForRefresh: - return "Awake for refresh"; - case PowerDownState::PDNActive: - return "PDN Active"; - case PowerDownState::PDNPrecharge: - return "PDN Precharged"; - case PowerDownState::PDNSelfRefresh: - return "PDN Self refresh"; - default: - return "unknown state"; - } + switch (powerDownState) { + case PowerDownState::Awake: + return "Awake"; + case PowerDownState::AwakeForRefresh: + return "Awake for refresh"; + case PowerDownState::PDNActive: + return "PDN Active"; + case PowerDownState::PDNPrecharge: + return "PDN Precharged"; + case PowerDownState::PDNSelfRefresh: + return "PDN Self refresh"; + default: + return "unknown state"; + } } diff --git a/DRAMSys/library/src/controller/core/powerdown/NoPowerDown.h b/DRAMSys/library/src/controller/core/powerdown/NoPowerDown.h index e4a01115..13b9db16 100644 --- a/DRAMSys/library/src/controller/core/powerdown/NoPowerDown.h +++ b/DRAMSys/library/src/controller/core/powerdown/NoPowerDown.h @@ -48,8 +48,8 @@ class NoPowerDown: public IPowerDownManager { public: - NoPowerDown(){} - virtual ~NoPowerDown(){} + NoPowerDown() {} + virtual ~NoPowerDown() {} virtual void triggerSleep(Bank bank, sc_time time) override; virtual void sleep(Bank bank, sc_time time) override; diff --git a/DRAMSys/library/src/controller/core/powerdown/PowerDownManager.cpp b/DRAMSys/library/src/controller/core/powerdown/PowerDownManager.cpp index 7c1f59e6..45923fdd 100644 --- a/DRAMSys/library/src/controller/core/powerdown/PowerDownManager.cpp +++ b/DRAMSys/library/src/controller/core/powerdown/PowerDownManager.cpp @@ -48,12 +48,12 @@ using namespace tlm; using namespace std; -PowerDownManager::PowerDownManager(sc_module_name /*name*/, ControllerCore& controller) : - controllerCore(controller) +PowerDownManager::PowerDownManager(sc_module_name /*name*/, + ControllerCore &controller) : + controllerCore(controller) { powerDownState = PowerDownState::Awake; - for (Bank bank : controller.getBanks()) - { + for (Bank bank : controller.getBanks()) { setUpDummy(powerDownPayloads[bank], bank); } //controllerCore.controller.send(PDNTrigger, sc_time_stamp(), powerDownPayloads[Bank(0)]); @@ -71,35 +71,31 @@ void PowerDownManager::sleep(Bank /*bank*/, sc_time time) PowerDownState state = powerDownState; - if (state == PowerDownState::Awake) //coming from active - { - state = controllerCore.state->rowBufferStates->allRowBuffersAreClosed() ? PowerDownState::PDNPrecharge : PowerDownState::PDNActive; - } - else if (state == PowerDownState::AwakeForRefresh) //coming from refresh interrupting power down - { + if (state == PowerDownState::Awake) { //coming from active + state = controllerCore.state->rowBufferStates->allRowBuffersAreClosed() ? + PowerDownState::PDNPrecharge : PowerDownState::PDNActive; + } else if (state == + PowerDownState::AwakeForRefresh) { //coming from refresh interrupting power down sc_assert(controllerCore.state->rowBufferStates->allRowBuffersAreClosed()); if (controllerCore.state->getLastCommand(Command::PDNA).getStart() >= controllerCore.state->getLastCommand(Command::PDNP).getStart()) state = PowerDownState::PDNPrecharge; - else - { + else { state = PowerDownState::PDNSelfRefresh; } } Command cmd = IPowerDownManager::getSleepCommand(state); ScheduledCommand pdn(cmd, time, getMinExecutionTimeForPowerDownCmd(cmd), - DramExtension::getExtension(powerDownPayloads[Bank(0)])); + DramExtension::getExtension(powerDownPayloads[Bank(0)])); controllerCore.getCommandChecker(cmd).delayToSatisfyConstraints(pdn); - if (state != PowerDownState::PDNSelfRefresh && controllerCore.refreshManager->hasCollision(pdn)) - { + if (state != PowerDownState::PDNSelfRefresh + && controllerCore.refreshManager->hasCollision(pdn)) { return; - } - else - { + } else { setPowerDownState(state); sendPowerDownPayload(pdn); } @@ -107,86 +103,95 @@ void PowerDownManager::sleep(Bank /*bank*/, sc_time time) void PowerDownManager::wakeUp(Bank bank, sc_time time) { - printDebugMessage("Waking up at " + time.to_string() + " current power down state is " + powerDownStateToString(powerDownState)); + printDebugMessage("Waking up at " + time.to_string() + + " current power down state is " + powerDownStateToString(powerDownState)); - if (isAwakeForRefresh()) //Request enters system during Refresh - { + if (isAwakeForRefresh()) { //Request enters system during Refresh setPowerDownState(PowerDownState::Awake); - } - else if (isInPowerDown()) //Request wakes up power down - { + } else if (isInPowerDown()) { //Request wakes up power down Command cmd = IPowerDownManager::getWakeUpCommand(powerDownState); - ScheduledCommand pdn(cmd, time, getExecutionTime(cmd, powerDownPayloads[Bank(0)]), - DramExtension::getExtension(powerDownPayloads[Bank(0)])); + ScheduledCommand pdn(cmd, time, getExecutionTime(cmd, + powerDownPayloads[Bank(0)]), + DramExtension::getExtension(powerDownPayloads[Bank(0)])); controllerCore.getCommandChecker(cmd).delayToSatisfyConstraints(pdn); if (cmd == Command::SREFX) { // Leaving Self Refresh. Plan the next refresh. controllerCore.refreshManager->reInitialize(bank, pdn.getEnd()); - printDebugMessage("Waking up. Leaving Self Refresh at " + time.to_string() + " next refresh planned to " + pdn.getEnd().to_string()); + printDebugMessage("Waking up. Leaving Self Refresh at " + time.to_string() + + " next refresh planned to " + pdn.getEnd().to_string()); } setPowerDownState(PowerDownState::Awake); - printDebugMessage("Sending power down exit command " + commandToString(cmd) + " on all banks"); + printDebugMessage("Sending power down exit command " + commandToString( + cmd) + " on all banks"); sendPowerDownPayload(pdn); } - printDebugMessage("Awaken at " + time.to_string() + " current power down state is " + powerDownStateToString(powerDownState)); + printDebugMessage("Awaken at " + time.to_string() + + " current power down state is " + powerDownStateToString(powerDownState)); } void PowerDownManager::wakeUpForRefresh(Bank /*bank*/, sc_time time) { - printDebugMessage("Waking up for refresh at " + time.to_string() + " current power down state is " + powerDownStateToString(powerDownState)); + printDebugMessage("Waking up for refresh at " + time.to_string() + + " current power down state is " + powerDownStateToString(powerDownState)); - if (isInPowerDown()) - { + if (isInPowerDown()) { Command cmd = IPowerDownManager::getWakeUpCommand(powerDownState); - ScheduledCommand pdn(cmd, time, getExecutionTime(cmd, powerDownPayloads[Bank(0)]), - DramExtension::getExtension(powerDownPayloads[Bank(0)])); + ScheduledCommand pdn(cmd, time, getExecutionTime(cmd, + powerDownPayloads[Bank(0)]), + DramExtension::getExtension(powerDownPayloads[Bank(0)])); setPowerDownState(PowerDownState::AwakeForRefresh); - printDebugMessage("Sending power down exit command " + commandToString(cmd) + " on all banks"); + printDebugMessage("Sending power down exit command " + commandToString( + cmd) + " on all banks"); sendPowerDownPayload(pdn); } - printDebugMessage("Awaken for refresh at " + time.to_string() + " current power down state is " + powerDownStateToString(powerDownState)); + printDebugMessage("Awaken for refresh at " + time.to_string() + + " current power down state is " + powerDownStateToString(powerDownState)); } -void PowerDownManager::sendPowerDownPayload(ScheduledCommand& pdnToSend) +void PowerDownManager::sendPowerDownPayload(ScheduledCommand &pdnToSend) { controllerCore.state->bus.moveCommandToNextFreeSlot(pdnToSend); - for (size_t bank = 1; bank < controllerCore.getBanks().size(); bank++) - { - tlm_generic_payload& payloadToSend = powerDownPayloads[bank]; + for (size_t bank = 1; bank < controllerCore.getBanks().size(); bank++) { + tlm_generic_payload &payloadToSend = powerDownPayloads[bank]; - ScheduledCommand pdn(pdnToSend.getCommand(), pdnToSend.getStart(), pdnToSend.getExecutionTime(), DramExtension::getExtension(payloadToSend)); + ScheduledCommand pdn(pdnToSend.getCommand(), pdnToSend.getStart(), + pdnToSend.getExecutionTime(), DramExtension::getExtension(payloadToSend)); controllerCore.state->change(pdn); } controllerCore.state->change(pdnToSend); controllerCore.controller.send(pdnToSend, powerDownPayloads[Bank(0)]); - printDebugMessage("Sending power down command " + commandToString(pdnToSend.getCommand()) + " on bank " + to_string(pdnToSend.getBank().ID()) + " start time " + pdnToSend.getStart().to_string() + " end time " + pdnToSend.getEnd().to_string()); + printDebugMessage("Sending power down command " + commandToString( + pdnToSend.getCommand()) + " on bank " + to_string(pdnToSend.getBank().ID()) + + " start time " + pdnToSend.getStart().to_string() + " end time " + + pdnToSend.getEnd().to_string()); } void PowerDownManager::setPowerDownState(PowerDownState state) { powerDownState = state; - printDebugMessage("Is now in state " + powerDownStateToString(powerDownState) + " on all banks"); + printDebugMessage("Is now in state " + powerDownStateToString( + powerDownState) + " on all banks"); } bool PowerDownManager::isInPowerDown() { - return (powerDownState == PowerDownState::PDNActive || powerDownState == PowerDownState::PDNPrecharge + return (powerDownState == PowerDownState::PDNActive + || powerDownState == PowerDownState::PDNPrecharge || powerDownState == PowerDownState::PDNSelfRefresh); } bool PowerDownManager::canSleep() { - for (Bank bank : controllerCore.getBanks()) - { + for (Bank bank : controllerCore.getBanks()) { if (!controllerCore.numberOfPayloads[bank] == 0) return false; } diff --git a/DRAMSys/library/src/controller/core/powerdown/PowerDownManager.h b/DRAMSys/library/src/controller/core/powerdown/PowerDownManager.h index 9a4a2484..a8a77e20 100644 --- a/DRAMSys/library/src/controller/core/powerdown/PowerDownManager.h +++ b/DRAMSys/library/src/controller/core/powerdown/PowerDownManager.h @@ -45,7 +45,7 @@ class ControllerCore; class PowerDownManager: public IPowerDownManager, public sc_module { public: - PowerDownManager(sc_module_name /*name*/, ControllerCore& controllerCore); + PowerDownManager(sc_module_name /*name*/, ControllerCore &controllerCore); virtual ~PowerDownManager(); virtual void triggerSleep(Bank bank, sc_time time) override; @@ -55,7 +55,7 @@ public: virtual bool isInSelfRefresh(Bank bank) override; protected: - void sendPowerDownPayload(ScheduledCommand& pdnToSend); + void sendPowerDownPayload(ScheduledCommand &pdnToSend); bool isInPowerDown(); void setPowerDownState(PowerDownState state); bool canSleep(); @@ -63,7 +63,7 @@ protected: PowerDownState powerDownState; std::map powerDownPayloads; - ControllerCore& controllerCore; + ControllerCore &controllerCore; void printDebugMessage(std::string message); }; diff --git a/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerBankwise.cpp b/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerBankwise.cpp index cf2d02a5..57490c88 100644 --- a/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerBankwise.cpp +++ b/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerBankwise.cpp @@ -42,10 +42,10 @@ using namespace tlm; -PowerDownManagerBankwise::PowerDownManagerBankwise(sc_module_name /*name*/, ControllerCore& controllerCore) : controllerCore(controllerCore) +PowerDownManagerBankwise::PowerDownManagerBankwise(sc_module_name /*name*/, + ControllerCore &controllerCore) : controllerCore(controllerCore) { - for (Bank bank : controllerCore.getBanks()) - { + for (Bank bank : controllerCore.getBanks()) { setUpDummy(powerDownPayloads[bank], bank); powerDownStates[bank] = PowerDownState::Awake; //controllerCore.controller.send(PDNTrigger, sc_time_stamp(), powerDownPayloads[bank]); @@ -57,36 +57,33 @@ void PowerDownManagerBankwise::sleep(Bank bank, sc_time time) if (!canSleep(bank) || isInPowerDown(bank)) return; - tlm_generic_payload& payload = powerDownPayloads[bank]; + tlm_generic_payload &payload = powerDownPayloads[bank]; PowerDownState state = powerDownStates[bank]; - if (state == PowerDownState::Awake) //coming from active - { - state = controllerCore.state->rowBufferStates->rowBufferIsOpen(bank) ? PowerDownState::PDNActive : PowerDownState::PDNPrecharge; - } - else if (state == PowerDownState::AwakeForRefresh) //coming from refresh interrupting power down - { + if (state == PowerDownState::Awake) { //coming from active + state = controllerCore.state->rowBufferStates->rowBufferIsOpen( + bank) ? PowerDownState::PDNActive : PowerDownState::PDNPrecharge; + } else if (state == + PowerDownState::AwakeForRefresh) { //coming from refresh interrupting power down sc_assert(!controllerCore.state->rowBufferStates->rowBufferIsOpen(bank)); if (controllerCore.state->getLastCommand(Command::PDNA, bank).getStart() >= controllerCore.state->getLastCommand(Command::PDNP, bank).getStart()) state = PowerDownState::PDNPrecharge; - else - { + else { state = PowerDownState::PDNSelfRefresh; } } Command cmd = IPowerDownManager::getSleepCommand(state); - ScheduledCommand pdn(cmd, time, getMinExecutionTimeForPowerDownCmd(cmd), DramExtension::getExtension(payload)); + ScheduledCommand pdn(cmd, time, getMinExecutionTimeForPowerDownCmd(cmd), + DramExtension::getExtension(payload)); controllerCore.getCommandChecker(cmd).delayToSatisfyConstraints(pdn); - if (state != PowerDownState::PDNSelfRefresh && controllerCore.refreshManager->hasCollision(pdn)) - { + if (state != PowerDownState::PDNSelfRefresh + && controllerCore.refreshManager->hasCollision(pdn)) { return; - } - else - { + } else { setPowerDownState(state, bank); sendPowerDownPayload(pdn); } @@ -94,37 +91,50 @@ void PowerDownManagerBankwise::sleep(Bank bank, sc_time time) void PowerDownManagerBankwise::wakeUp(Bank bank, sc_time time) { - printDebugMessage("Waking up on bank " + to_string(bank.ID()) + " at " + time.to_string() + " current power down state is " + powerDownStateToString(powerDownStates[bank])); + printDebugMessage("Waking up on bank " + to_string(bank.ID()) + " at " + + time.to_string() + " current power down state is " + powerDownStateToString( + powerDownStates[bank])); if (isAwakeForRefresh(bank)) { - printDebugMessage("It was already awake for refresh on bank " + to_string(bank.ID()) + " at " + time.to_string()); + printDebugMessage("It was already awake for refresh on bank " + to_string( + bank.ID()) + " at " + time.to_string()); setPowerDownState(PowerDownState::Awake, bank); } else if (isInPowerDown(bank)) { // Request wake up from power down. A Power Down Exit request will be generated (PDNAX, PDNPX, SREFX). Command pdnExitCmd = IPowerDownManager::getWakeUpCommand(powerDownStates[bank]); // Mount the command to be scheduled - ScheduledCommand pdnExit(pdnExitCmd, time, getExecutionTime(pdnExitCmd, powerDownPayloads[bank]), DramExtension::getExtension(powerDownPayloads[bank])); + ScheduledCommand pdnExit(pdnExitCmd, time, getExecutionTime(pdnExitCmd, + powerDownPayloads[bank]), DramExtension::getExtension(powerDownPayloads[bank])); // Ensure that time constraints are respected controllerCore.getCommandChecker(pdnExitCmd).delayToSatisfyConstraints(pdnExit); if (pdnExitCmd == Command::SREFX) { // Leaving Self Refresh. Plan the next refresh. controllerCore.refreshManager->reInitialize(bank, pdnExit.getEnd()); - printDebugMessage("Waking up. Leaving Self Refresh on Bank " + to_string(bank.ID()) + " at " + time.to_string() + " next refresh planned to " + pdnExit.getEnd().to_string()); + printDebugMessage("Waking up. Leaving Self Refresh on Bank " + to_string( + bank.ID()) + " at " + time.to_string() + " next refresh planned to " + + pdnExit.getEnd().to_string()); } setPowerDownState(PowerDownState::Awake, bank); - printDebugMessage("Sending power down exit command " + commandToString(pdnExitCmd) + " on bank " + to_string(bank.ID()) + " at " + time.to_string() + " start time " + pdnExit.getStart().to_string() + " end time " + pdnExit.getEnd().to_string()); + printDebugMessage("Sending power down exit command " + commandToString( + pdnExitCmd) + " on bank " + to_string(bank.ID()) + " at " + time.to_string() + + " start time " + pdnExit.getStart().to_string() + " end time " + + pdnExit.getEnd().to_string()); sendPowerDownPayload(pdnExit); } - printDebugMessage("Awaken on bank " + to_string(bank.ID()) + " at " + time.to_string() + " current power down state is " + powerDownStateToString(powerDownStates[bank])); + printDebugMessage("Awaken on bank " + to_string(bank.ID()) + " at " + + time.to_string() + " current power down state is " + powerDownStateToString( + powerDownStates[bank])); } void PowerDownManagerBankwise::wakeUpForRefresh(Bank bank, sc_time time) { - printDebugMessage("Waking up for refresh on bank " + to_string(bank.ID()) + " at " + time.to_string() + " current power down state is " + powerDownStateToString(powerDownStates[bank])); + printDebugMessage("Waking up for refresh on bank " + to_string( + bank.ID()) + " at " + time.to_string() + " current power down state is " + + powerDownStateToString(powerDownStates[bank])); if (isInPowerDown(bank)) { // A Power Down Exit request will be generated (PDNAX, PDNPX, SREFX). @@ -132,15 +142,21 @@ void PowerDownManagerBankwise::wakeUpForRefresh(Bank bank, sc_time time) // Get the execution time for this request sc_time executionTime = getExecutionTime(pdnExitCmd, powerDownPayloads[bank]); // Mount the command to be scheduled - ScheduledCommand pdnExit(pdnExitCmd, time, executionTime, DramExtension::getExtension(powerDownPayloads[bank])); + ScheduledCommand pdnExit(pdnExitCmd, time, executionTime, + DramExtension::getExtension(powerDownPayloads[bank])); setPowerDownState(PowerDownState::AwakeForRefresh, bank); - printDebugMessage("Sending power down exit command " + commandToString(pdnExitCmd) + " on bank " + to_string(bank.ID()) + " at " + time.to_string() + " start time " + pdnExit.getStart().to_string() + " end time " + pdnExit.getEnd().to_string()); + printDebugMessage("Sending power down exit command " + commandToString( + pdnExitCmd) + " on bank " + to_string(bank.ID()) + " at " + time.to_string() + + " start time " + pdnExit.getStart().to_string() + " end time " + + pdnExit.getEnd().to_string()); sendPowerDownPayload(pdnExit); } - printDebugMessage("Awaken for refresh on bank " + to_string(bank.ID()) + " at " + time.to_string() + " current power down state is " + powerDownStateToString(powerDownStates[bank])); + printDebugMessage("Awaken for refresh on bank " + to_string( + bank.ID()) + " at " + time.to_string() + " current power down state is " + + powerDownStateToString(powerDownStates[bank])); } bool PowerDownManagerBankwise::isInPowerDown(Bank bank) @@ -163,18 +179,22 @@ bool PowerDownManagerBankwise::isAwake(Bank bank) return powerDownStates[bank] == PowerDownState::Awake; } -void PowerDownManagerBankwise::setPowerDownState(PowerDownState state, Bank bank) +void PowerDownManagerBankwise::setPowerDownState(PowerDownState state, + Bank bank) { - PowerDownState& bankstate = powerDownStates[bank]; + PowerDownState &bankstate = powerDownStates[bank]; bankstate = state; - printDebugMessage("Is now in state " + powerDownStateToString(state) + " on Bank " + to_string(bank.ID())); + printDebugMessage("Is now in state " + powerDownStateToString( + state) + " on Bank " + to_string(bank.ID())); } void PowerDownManagerBankwise::sendPowerDownPayload(ScheduledCommand &pdn) { controllerCore.state->bus.moveCommandToNextFreeSlot(pdn); controllerCore.state->change(pdn); - printDebugMessage("Sending power down command " + commandToString(pdn.getCommand()) + " on bank " + to_string(pdn.getBank().ID()) + " start time " + pdn.getStart().to_string() + " end time " + pdn.getEnd().to_string()); + printDebugMessage("Sending power down command " + commandToString( + pdn.getCommand()) + " on bank " + to_string(pdn.getBank().ID()) + " start time " + + pdn.getStart().to_string() + " end time " + pdn.getEnd().to_string()); controllerCore.controller.send(pdn, powerDownPayloads[pdn.getBank()]); } diff --git a/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerBankwise.h b/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerBankwise.h index bbe8b1f3..5f532b00 100644 --- a/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerBankwise.h +++ b/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerBankwise.h @@ -52,8 +52,9 @@ class ControllerCore; class PowerDownManagerBankwise : public sc_module, public IPowerDownManager { public: - PowerDownManagerBankwise(sc_module_name /*name*/, ControllerCore& controllerCore); - virtual ~PowerDownManagerBankwise(){} + PowerDownManagerBankwise(sc_module_name /*name*/, + ControllerCore &controllerCore); + virtual ~PowerDownManagerBankwise() {} virtual void triggerSleep(Bank bank, sc_time time) override; virtual void sleep(Bank bank, sc_time time) override; virtual void wakeUp(Bank bank, sc_time time) override; diff --git a/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerTimeout.cpp b/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerTimeout.cpp index 3b68008e..c694d13f 100644 --- a/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerTimeout.cpp +++ b/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerTimeout.cpp @@ -44,7 +44,8 @@ using namespace tlm; -PowerDownManagerTimeout::PowerDownManagerTimeout(sc_module_name name, ControllerCore& controllerCore): +PowerDownManagerTimeout::PowerDownManagerTimeout(sc_module_name name, + ControllerCore &controllerCore): PowerDownManager(name, controllerCore) { //controllerCore.controller.send(PDNTrigger, Configuration::getInstance().getPowerDownTimeout(), powerDownPayloads[Bank(0)]); @@ -58,56 +59,51 @@ PowerDownManagerTimeout::~PowerDownManagerTimeout() void PowerDownManagerTimeout::sleep(Bank /*bank*/, sc_time time) { bool timeoutTest; - if(!isAwakeForRefresh()) - { + if (!isAwakeForRefresh()) { sc_time lastReadScheduled; sc_time lastWriteScheduled; - if(Configuration::getInstance().OpenPagePolicy) - { - lastReadScheduled= controllerCore.state->getLastCommand(Command::Read).getEnd(); - lastWriteScheduled = controllerCore.state->getLastCommand(Command::Write).getEnd(); + if (Configuration::getInstance().OpenPagePolicy) { + lastReadScheduled = controllerCore.state->getLastCommand( + Command::Read).getEnd(); + lastWriteScheduled = controllerCore.state->getLastCommand( + Command::Write).getEnd(); + } else { + lastReadScheduled = controllerCore.state->getLastCommand( + Command::ReadA).getEnd(); + lastWriteScheduled = controllerCore.state->getLastCommand( + Command::WriteA).getEnd(); } - else - { - lastReadScheduled = controllerCore.state->getLastCommand(Command::ReadA).getEnd(); - lastWriteScheduled = controllerCore.state->getLastCommand(Command::WriteA).getEnd(); - } - sc_time lastScheduledCommand = max(lastReadScheduled,lastWriteScheduled); - timeoutTest = (time - lastScheduledCommand) >= Configuration::getInstance().getPowerDownTimeout(); - } - else - { + sc_time lastScheduledCommand = max(lastReadScheduled, lastWriteScheduled); + timeoutTest = (time - lastScheduledCommand) >= + Configuration::getInstance().getPowerDownTimeout(); + } else { timeoutTest = true; } //test_awakeForRefresh = false; - if( canSleep() && !isInPowerDown() && timeoutTest) - { + if ( canSleep() && !isInPowerDown() && timeoutTest) { PowerDownState newState; - if(Configuration::getInstance().PowerDownMode == EPowerDownMode::TimeoutPDN) - { - newState = controllerCore.state->rowBufferStates->allRowBuffersAreClosed() ? PowerDownState::PDNPrecharge : PowerDownState::PDNActive; - } - else // PowerDownMode == TimeoutSREF - { - if(!controllerCore.state->rowBufferStates->allRowBuffersAreClosed()) - { - ScheduledCommand prechargeAllMaster(Command::PrechargeAll, time, getExecutionTime(Command::PrechargeAll, powerDownPayloads[Bank(0)]), DramExtension::getExtension(powerDownPayloads[Bank(0)])); + if (Configuration::getInstance().PowerDownMode == EPowerDownMode::TimeoutPDN) { + newState = controllerCore.state->rowBufferStates->allRowBuffersAreClosed() ? + PowerDownState::PDNPrecharge : PowerDownState::PDNActive; + } else { // PowerDownMode == TimeoutSREF + if (!controllerCore.state->rowBufferStates->allRowBuffersAreClosed()) { + ScheduledCommand prechargeAllMaster(Command::PrechargeAll, time, + getExecutionTime(Command::PrechargeAll, powerDownPayloads[Bank(0)]), + DramExtension::getExtension(powerDownPayloads[Bank(0)])); - controllerCore.getCommandChecker(Command::PrechargeAll).delayToSatisfyConstraints(prechargeAllMaster); + controllerCore.getCommandChecker( + Command::PrechargeAll).delayToSatisfyConstraints(prechargeAllMaster); - if (controllerCore.refreshManager->hasCollision(prechargeAllMaster)) - { + if (controllerCore.refreshManager->hasCollision(prechargeAllMaster)) { return; - } - else - { - for (size_t i = 1; i < controllerCore.getBanks().size(); i++) - { - ScheduledCommand prechargeAll(Command::PrechargeAll, prechargeAllMaster.getStart(), prechargeAllMaster.getExecutionTime(), - powerDownPayloads[Bank(i)]); + } else { + for (size_t i = 1; i < controllerCore.getBanks().size(); i++) { + ScheduledCommand prechargeAll(Command::PrechargeAll, + prechargeAllMaster.getStart(), prechargeAllMaster.getExecutionTime(), + powerDownPayloads[Bank(i)]); controllerCore.state->change(prechargeAll); } controllerCore.state->change(prechargeAllMaster); @@ -125,12 +121,9 @@ void PowerDownManagerTimeout::sleep(Bank /*bank*/, sc_time time) controllerCore.getCommandChecker(cmd).delayToSatisfyConstraints(pdn); - if (controllerCore.refreshManager->hasCollision(pdn)) - { + if (controllerCore.refreshManager->hasCollision(pdn)) { return; - } - else - { + } else { setPowerDownState(newState); sendPowerDownPayload(pdn); } @@ -139,9 +132,9 @@ void PowerDownManagerTimeout::sleep(Bank /*bank*/, sc_time time) void PowerDownManagerTimeout::triggerSleep(Bank /*bank*/, sc_time time) { - if(canSleep() && !isInPowerDown()) - { - controllerCore.controller.send(PDNTrigger, time + controllerCore.config.getPowerDownTimeout(), powerDownPayloads[Bank(0)]); + if (canSleep() && !isInPowerDown()) { + controllerCore.controller.send(PDNTrigger, + time + controllerCore.config.getPowerDownTimeout(), powerDownPayloads[Bank(0)]); } } diff --git a/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerTimeout.h b/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerTimeout.h index 39c206ca..538df00c 100644 --- a/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerTimeout.h +++ b/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerTimeout.h @@ -50,7 +50,8 @@ class ControllerCore; class PowerDownManagerTimeout: public PowerDownManager { public: - PowerDownManagerTimeout(sc_module_name /*name*/, ControllerCore& controllerCore); + PowerDownManagerTimeout(sc_module_name /*name*/, + ControllerCore &controllerCore); virtual ~PowerDownManagerTimeout(); virtual void triggerSleep(Bank /*bank*/, sc_time time); diff --git a/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerTimeoutBankwise.cpp b/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerTimeoutBankwise.cpp index e520243a..56a8b9b3 100644 --- a/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerTimeoutBankwise.cpp +++ b/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerTimeoutBankwise.cpp @@ -44,7 +44,8 @@ using namespace tlm; -PowerDownManagerTimeoutBankwise::PowerDownManagerTimeoutBankwise(sc_module_name name, ControllerCore& controllerCore): +PowerDownManagerTimeoutBankwise::PowerDownManagerTimeoutBankwise( + sc_module_name name, ControllerCore &controllerCore): PowerDownManagerBankwise(name, controllerCore) { /*for (Bank bank : controllerCore.getBanks()) @@ -61,49 +62,44 @@ PowerDownManagerTimeoutBankwise::~PowerDownManagerTimeoutBankwise() void PowerDownManagerTimeoutBankwise::sleep(Bank bank, sc_time time) { bool timeoutTest; - if(!isAwakeForRefresh(bank)) - { + if (!isAwakeForRefresh(bank)) { sc_time lastReadScheduled; sc_time lastWriteScheduled; - if(Configuration::getInstance().OpenPagePolicy) - { - lastReadScheduled= controllerCore.state->getLastCommand(Command::Read, bank).getEnd(); - lastWriteScheduled = controllerCore.state->getLastCommand(Command::Write, bank).getEnd(); + if (Configuration::getInstance().OpenPagePolicy) { + lastReadScheduled = controllerCore.state->getLastCommand(Command::Read, + bank).getEnd(); + lastWriteScheduled = controllerCore.state->getLastCommand(Command::Write, + bank).getEnd(); + } else { + lastReadScheduled = controllerCore.state->getLastCommand(Command::ReadA, + bank).getEnd(); + lastWriteScheduled = controllerCore.state->getLastCommand(Command::WriteA, + bank).getEnd(); } - else - { - lastReadScheduled = controllerCore.state->getLastCommand(Command::ReadA, bank).getEnd(); - lastWriteScheduled = controllerCore.state->getLastCommand(Command::WriteA, bank).getEnd(); - } - sc_time lastScheduledCommand = max(lastReadScheduled,lastWriteScheduled); - timeoutTest = (time - lastScheduledCommand) >= Configuration::getInstance().getPowerDownTimeout(); - } - else - { + sc_time lastScheduledCommand = max(lastReadScheduled, lastWriteScheduled); + timeoutTest = (time - lastScheduledCommand) >= + Configuration::getInstance().getPowerDownTimeout(); + } else { timeoutTest = true; } - if( canSleep(bank) && !isInPowerDown(bank) && timeoutTest) - { + if ( canSleep(bank) && !isInPowerDown(bank) && timeoutTest) { PowerDownState newState; - if(Configuration::getInstance().PowerDownMode == EPowerDownMode::TimeoutPDN) - { - newState = controllerCore.state->rowBufferStates->rowBufferIsOpen(bank) ? PowerDownState::PDNActive : PowerDownState::PDNPrecharge; - } - else // PowerDownMode == TimeoutSREF - { - if(controllerCore.state->rowBufferStates->rowBufferIsOpen(bank)) - { - ScheduledCommand precharge(Command::Precharge, time, getExecutionTime(Command::Precharge, powerDownPayloads[bank]), DramExtension::getExtension(powerDownPayloads[bank])); + if (Configuration::getInstance().PowerDownMode == EPowerDownMode::TimeoutPDN) { + newState = controllerCore.state->rowBufferStates->rowBufferIsOpen( + bank) ? PowerDownState::PDNActive : PowerDownState::PDNPrecharge; + } else { // PowerDownMode == TimeoutSREF + if (controllerCore.state->rowBufferStates->rowBufferIsOpen(bank)) { + ScheduledCommand precharge(Command::Precharge, time, + getExecutionTime(Command::Precharge, powerDownPayloads[bank]), + DramExtension::getExtension(powerDownPayloads[bank])); - controllerCore.getCommandChecker(Command::Precharge).delayToSatisfyConstraints(precharge); + controllerCore.getCommandChecker(Command::Precharge).delayToSatisfyConstraints( + precharge); - if (controllerCore.refreshManager->hasCollision(precharge)) - { + if (controllerCore.refreshManager->hasCollision(precharge)) { return; - } - else - { + } else { controllerCore.state->change(precharge); controllerCore.controller.send(precharge, powerDownPayloads[bank]); } @@ -120,12 +116,9 @@ void PowerDownManagerTimeoutBankwise::sleep(Bank bank, sc_time time) controllerCore.getCommandChecker(cmd).delayToSatisfyConstraints(pdn); - if (controllerCore.refreshManager->hasCollision(pdn)) - { + if (controllerCore.refreshManager->hasCollision(pdn)) { return; - } - else - { + } else { setPowerDownState(newState, bank); sendPowerDownPayload(pdn); } @@ -134,8 +127,8 @@ void PowerDownManagerTimeoutBankwise::sleep(Bank bank, sc_time time) void PowerDownManagerTimeoutBankwise::triggerSleep(Bank bank, sc_time time) { - if(canSleep(bank) && !isInPowerDown(bank)) - { - controllerCore.controller.send(PDNTrigger, time + controllerCore.config.getPowerDownTimeout(), powerDownPayloads[bank]); + if (canSleep(bank) && !isInPowerDown(bank)) { + controllerCore.controller.send(PDNTrigger, + time + controllerCore.config.getPowerDownTimeout(), powerDownPayloads[bank]); } } diff --git a/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerTimeoutBankwise.h b/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerTimeoutBankwise.h index 8383a0b8..3c1fb76b 100644 --- a/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerTimeoutBankwise.h +++ b/DRAMSys/library/src/controller/core/powerdown/PowerDownManagerTimeoutBankwise.h @@ -50,7 +50,8 @@ class ControllerCore; class PowerDownManagerTimeoutBankwise: public PowerDownManagerBankwise { public: - PowerDownManagerTimeoutBankwise(sc_module_name /*name*/, ControllerCore& controllerCore); + PowerDownManagerTimeoutBankwise(sc_module_name /*name*/, + ControllerCore &controllerCore); virtual ~PowerDownManagerTimeoutBankwise(); virtual void triggerSleep(Bank bank, sc_time time); diff --git a/DRAMSys/library/src/controller/core/refresh/IRefreshManager.h b/DRAMSys/library/src/controller/core/refresh/IRefreshManager.h index 1bfb4d31..5ab46989 100644 --- a/DRAMSys/library/src/controller/core/refresh/IRefreshManager.h +++ b/DRAMSys/library/src/controller/core/refresh/IRefreshManager.h @@ -45,13 +45,14 @@ class IRefreshManager { public: - virtual ~IRefreshManager(){}; - virtual bool hasCollision(const ScheduledCommand& command) = 0; - virtual void scheduleRefresh(tlm::tlm_generic_payload& payload, sc_time time) = 0; - virtual void reInitialize(Bank bank, sc_time time) = 0; + virtual ~IRefreshManager() {}; + virtual bool hasCollision(const ScheduledCommand &command) = 0; + virtual void scheduleRefresh(tlm::tlm_generic_payload &payload, + sc_time time) = 0; + virtual void reInitialize(Bank bank, sc_time time) = 0; - virtual bool isInvalidated(tlm::tlm_generic_payload& payload, sc_time time) = 0; + virtual bool isInvalidated(tlm::tlm_generic_payload &payload, sc_time time) = 0; }; diff --git a/DRAMSys/library/src/controller/core/refresh/RefreshManager.cpp b/DRAMSys/library/src/controller/core/refresh/RefreshManager.cpp index 8b410019..78688699 100644 --- a/DRAMSys/library/src/controller/core/refresh/RefreshManager.cpp +++ b/DRAMSys/library/src/controller/core/refresh/RefreshManager.cpp @@ -44,19 +44,19 @@ using namespace tlm; -RefreshManager::RefreshManager(sc_module_name /*name*/, ControllerCore& controller) : - controllerCore(controller), timing(controller.config.memSpec.refreshTimings[Bank(0)]), nextPlannedRefresh(SC_ZERO_TIME) +RefreshManager::RefreshManager(sc_module_name /*name*/, + ControllerCore &controller) : + controllerCore(controller), + timing(controller.config.memSpec.refreshTimings[Bank(0)]), + nextPlannedRefresh(SC_ZERO_TIME) { - if (controllerCore.config.ControllerCoreEnableRefPostpone) - { + if (controllerCore.config.ControllerCoreEnableRefPostpone) { maxpostpone = controllerCore.config.ControllerCoreMaxPostponedARCmd; } - if (controllerCore.config.ControllerCoreEnableRefPullIn) - { + if (controllerCore.config.ControllerCoreEnableRefPullIn) { maxpullin = controllerCore.config.ControllerCoreMaxPulledInARCmd; } - for (Bank bank : controller.getBanks()) - { + for (Bank bank : controller.getBanks()) { setUpDummy(refreshPayloads[bank], bank); } planNextRefresh(timing.tREFI); @@ -67,33 +67,38 @@ RefreshManager::~RefreshManager() } //Check if a command will be scheduled during the next refresh period -bool RefreshManager::hasCollision(const ScheduledCommand& command) +bool RefreshManager::hasCollision(const ScheduledCommand &command) { - bool collisionWithPreviousRefEnd = command.getStart() < controllerCore.state->getLastCommand(Command::AutoRefresh).getEnd(); + bool collisionWithPreviousRefEnd = command.getStart() < + controllerCore.state->getLastCommand(Command::AutoRefresh).getEnd(); bool collisionWithNextRefStart = command.getEnd() >= nextPlannedRefresh; - if (controllerCore.config.ControllerCoreEnableRefPostpone && (arCmdCounter < maxpostpone)) // Flexible refresh is on and have "credits" to postpone - { - collisionWithNextRefStart = false; // Then there will not be a collision with next refresh because nextPlannedRefresh will be updated + if (controllerCore.config.ControllerCoreEnableRefPostpone + && (arCmdCounter < + maxpostpone)) { // Flexible refresh is on and have "credits" to postpone + collisionWithNextRefStart = + false; // Then there will not be a collision with next refresh because nextPlannedRefresh will be updated } return collisionWithPreviousRefEnd || collisionWithNextRefStart; } -void RefreshManager::doRefresh(tlm::tlm_generic_payload& payload __attribute__((unused)), sc_time time) +void RefreshManager::doRefresh(tlm::tlm_generic_payload &payload __attribute__(( + unused)), sc_time time) { sc_assert(!isInvalidated(payload, time)); //Check if any row on all banks is activated and if so, a PrechargeAll command must be scheduled before the refresh command. - if (!controllerCore.state->rowBufferStates->allRowBuffersAreClosed()) - { - ScheduledCommand prechargeAllMaster(Command::PrechargeAll, time, getExecutionTime(Command::PrechargeAll, refreshPayloads[Bank(0)]), - refreshPayloads[Bank(0)]); - controllerCore.getCommandChecker(Command::PrechargeAll).delayToSatisfyConstraints(prechargeAllMaster); + if (!controllerCore.state->rowBufferStates->allRowBuffersAreClosed()) { + ScheduledCommand prechargeAllMaster(Command::PrechargeAll, time, + getExecutionTime(Command::PrechargeAll, refreshPayloads[Bank(0)]), + refreshPayloads[Bank(0)]); + controllerCore.getCommandChecker( + Command::PrechargeAll).delayToSatisfyConstraints(prechargeAllMaster); - for (size_t i = 1;i < controllerCore.getBanks().size(); i++) - { - ScheduledCommand prechargeAll(Command::PrechargeAll, prechargeAllMaster.getStart(), prechargeAllMaster.getExecutionTime(), - refreshPayloads[Bank(i)]); + for (size_t i = 1; i < controllerCore.getBanks().size(); i++) { + ScheduledCommand prechargeAll(Command::PrechargeAll, + prechargeAllMaster.getStart(), prechargeAllMaster.getExecutionTime(), + refreshPayloads[Bank(i)]); controllerCore.state->change(prechargeAll); } controllerCore.state->change(prechargeAllMaster); @@ -101,13 +106,15 @@ void RefreshManager::doRefresh(tlm::tlm_generic_payload& payload __attribute__(( } //Otherwise just the AutoRefresh command is scheduled. - ScheduledCommand refreshAllMaster(Command::AutoRefresh, time, getExecutionTime(Command::AutoRefresh, refreshPayloads[Bank(0)]), - DramExtension::getExtension(refreshPayloads[Bank(0)])); - controllerCore.getCommandChecker(Command::AutoRefresh).delayToSatisfyConstraints(refreshAllMaster); + ScheduledCommand refreshAllMaster(Command::AutoRefresh, time, + getExecutionTime(Command::AutoRefresh, refreshPayloads[Bank(0)]), + DramExtension::getExtension(refreshPayloads[Bank(0)])); + controllerCore.getCommandChecker( + Command::AutoRefresh).delayToSatisfyConstraints(refreshAllMaster); - for (size_t i = 1;i < controllerCore.getBanks().size(); i++) - { - ScheduledCommand refresh(Command::AutoRefresh, refreshAllMaster.getStart(), refreshAllMaster.getExecutionTime(),refreshPayloads[Bank(i)]); + for (size_t i = 1; i < controllerCore.getBanks().size(); i++) { + ScheduledCommand refresh(Command::AutoRefresh, refreshAllMaster.getStart(), + refreshAllMaster.getExecutionTime(), refreshPayloads[Bank(i)]); controllerCore.state->change(refresh); DramExtension::getExtension(refreshPayloads[Bank(i)]).incrementRow(); } @@ -117,7 +124,8 @@ void RefreshManager::doRefresh(tlm::tlm_generic_payload& payload __attribute__(( } -void RefreshManager::scheduleRefresh(tlm::tlm_generic_payload& payload __attribute__((unused)), sc_time time) +void RefreshManager::scheduleRefresh(tlm::tlm_generic_payload &payload + __attribute__((unused)), sc_time time) { sc_time nextRefTiming; bool pendingReq = controllerCore.hasPendingRequests(); @@ -127,121 +135,103 @@ void RefreshManager::scheduleRefresh(tlm::tlm_generic_payload& payload __attribu previousState = currentState; currentState = nextState; - switch(currentState) - { - case ST_REFRESH: + switch (currentState) { + case ST_REFRESH: // Regular Refresh. It's possible to migrate from this to the flexible refresh states - assert(arCmdCounter == 0); // The arCmdCounter should always be equal to zero here + assert(arCmdCounter == + 0); // The arCmdCounter should always be equal to zero here - if(canPostpone) - { - nextState = ST_POSTPONE; - nextRefTiming = SC_ZERO_TIME; - } - else if(canPullIn) - { - nextState = ST_PULLIN; - nextRefTiming = SC_ZERO_TIME; // Attempt to burst pull-in - } - else - { - doRefresh(payload, time); - nextRefTiming = timing.tREFI; - nextState = ST_REFRESH; - } - break; + if (canPostpone) { + nextState = ST_POSTPONE; + nextRefTiming = SC_ZERO_TIME; + } else if (canPullIn) { + nextState = ST_PULLIN; + nextRefTiming = SC_ZERO_TIME; // Attempt to burst pull-in + } else { + doRefresh(payload, time); + nextRefTiming = timing.tREFI; + nextState = ST_REFRESH; + } + break; - case ST_PULLIN: + case ST_PULLIN: // Pull-In Refresh. Try to pull-in refreshes as long as the limit hasn't been reached yet and has credits - if(canPullIn) - { - doRefresh(payload, time); - arCmdCounter++; - nextState = ST_PULLIN; - nextRefTiming = timing.tRFC; - } - else - { - alignValue = arCmdCounter; // Saving value to be used by ST_ALIGN - nextState = ST_ALIGN; - nextRefTiming = SC_ZERO_TIME; - } - break; + if (canPullIn) { + doRefresh(payload, time); + arCmdCounter++; + nextState = ST_PULLIN; + nextRefTiming = timing.tRFC; + } else { + alignValue = arCmdCounter; // Saving value to be used by ST_ALIGN + nextState = ST_ALIGN; + nextRefTiming = SC_ZERO_TIME; + } + break; - case ST_SKIP: + case ST_SKIP: // Skip Refresh. The arCmdCounter is used to skip the correct amount of refreshes - arCmdCounter--; - if(arCmdCounter == 0) - { - nextState = ST_REFRESH; - nextRefTiming = SC_ZERO_TIME; - } - else - { - nextState = ST_SKIP; - nextRefTiming = timing.tREFI; - } - break; + arCmdCounter--; + if (arCmdCounter == 0) { + nextState = ST_REFRESH; + nextRefTiming = SC_ZERO_TIME; + } else { + nextState = ST_SKIP; + nextRefTiming = timing.tREFI; + } + break; - case ST_POSTPONE: + case ST_POSTPONE: // Postpone Refresh. Delaying refreshes as long as there are pending requests and credits to postpone. Should be followed by a burst refresh - if((arCmdCounter == maxpostpone) || ((!pendingReq) && !controllerCore.config.ControllerCoreForceMaxRefBurst)) // Burst conditions met - { - if(arCmdCounter < maxpostpone) // In case the burst was started by inactivity, need to also count the current REF - { - arCmdCounter++; - } - alignValue = arCmdCounter; // Will start a burst next, so the value is saved to be used by ST_ALIGN - nextState = ST_BURST; - nextRefTiming = SC_ZERO_TIME; - } - else - { + if ((arCmdCounter == maxpostpone) || ((!pendingReq) + && !controllerCore.config.ControllerCoreForceMaxRefBurst)) { // Burst conditions met + if (arCmdCounter < + maxpostpone) { // In case the burst was started by inactivity, need to also count the current REF arCmdCounter++; - nextState = ST_POSTPONE; - nextRefTiming = timing.tREFI; } - break; + alignValue = + arCmdCounter; // Will start a burst next, so the value is saved to be used by ST_ALIGN + nextState = ST_BURST; + nextRefTiming = SC_ZERO_TIME; + } else { + arCmdCounter++; + nextState = ST_POSTPONE; + nextRefTiming = timing.tREFI; + } + break; - case ST_BURST: + case ST_BURST: // Burst Refresh. The arCmdCounter is used to issue the correct amount of refreshes - arCmdCounter--; - doRefresh(payload, time); - if(arCmdCounter == 0) // All bursts issued, next state will align to tREFI - { - nextState = ST_ALIGN; - nextRefTiming = SC_ZERO_TIME; - } - else - { - nextState = ST_BURST; - nextRefTiming = timing.tRFC; - } - break; + arCmdCounter--; + doRefresh(payload, time); + if (arCmdCounter == 0) { // All bursts issued, next state will align to tREFI + nextState = ST_ALIGN; + nextRefTiming = SC_ZERO_TIME; + } else { + nextState = ST_BURST; + nextRefTiming = timing.tRFC; + } + break; - case ST_ALIGN: + case ST_ALIGN: // Align Refresh. Adjusting the timing so the next REF timing will be a in a time multiple of tREFI - if(previousState == ST_PULLIN) - { - nextRefTiming = timing.tREFI-(timing.tRFC*(alignValue)); - nextState = ST_SKIP; - } - else - { - nextRefTiming = timing.tREFI-(timing.tRFC*(alignValue-1)); - nextState = ST_REFRESH; - } - break; + if (previousState == ST_PULLIN) { + nextRefTiming = timing.tREFI - (timing.tRFC * (alignValue)); + nextState = ST_SKIP; + } else { + nextRefTiming = timing.tREFI - (timing.tRFC * (alignValue - 1)); + nextState = ST_REFRESH; + } + break; - default: - SC_REPORT_FATAL(this->name(),"Invalid State in Flexible Refresh FSM. Stop."); - break; + default: + SC_REPORT_FATAL(this->name(), "Invalid State in Flexible Refresh FSM. Stop."); + break; } planNextRefresh(nextRefTiming); @@ -250,7 +240,8 @@ void RefreshManager::scheduleRefresh(tlm::tlm_generic_payload& payload __attribu void RefreshManager::planNextRefresh(sc_time nextRefTiming) { nextPlannedRefresh += nextRefTiming; - controllerCore.controller.send(REFTrigger, nextPlannedRefresh, refreshPayloads[Bank(0)]); + controllerCore.controller.send(REFTrigger, nextPlannedRefresh, + refreshPayloads[Bank(0)]); } void RefreshManager::reInitialize(Bank /*bank*/, sc_time time) @@ -259,7 +250,8 @@ void RefreshManager::reInitialize(Bank /*bank*/, sc_time time) planNextRefresh(timing.tREFI); } -bool RefreshManager::isInvalidated(tlm::tlm_generic_payload& payload __attribute__((unused)), sc_time time) +bool RefreshManager::isInvalidated(tlm::tlm_generic_payload &payload + __attribute__((unused)), sc_time time) { return nextPlannedRefresh > time; } diff --git a/DRAMSys/library/src/controller/core/refresh/RefreshManager.h b/DRAMSys/library/src/controller/core/refresh/RefreshManager.h index 32216527..ee28c25f 100644 --- a/DRAMSys/library/src/controller/core/refresh/RefreshManager.h +++ b/DRAMSys/library/src/controller/core/refresh/RefreshManager.h @@ -40,8 +40,7 @@ #include "IRefreshManager.h" #include "../configuration/MemSpec.h" -typedef enum -{ +typedef enum { ST_REFRESH = 0, ST_PULLIN, ST_POSTPONE, @@ -55,17 +54,19 @@ class ControllerCore; class RefreshManager : public IRefreshManager, public sc_module { public: - RefreshManager(sc_module_name /*name*/, ControllerCore& controllerCore); + RefreshManager(sc_module_name /*name*/, ControllerCore &controllerCore); virtual ~RefreshManager(); - virtual bool hasCollision(const ScheduledCommand& command) override; - virtual void scheduleRefresh(tlm::tlm_generic_payload& payload, sc_time time) override; + virtual bool hasCollision(const ScheduledCommand &command) override; + virtual void scheduleRefresh(tlm::tlm_generic_payload &payload, + sc_time time) override; void reInitialize(Bank bank, sc_time time) override; - virtual bool isInvalidated(tlm::tlm_generic_payload& payload, sc_time time) override; + virtual bool isInvalidated(tlm::tlm_generic_payload &payload, + sc_time time) override; private: - ControllerCore& controllerCore; - RefreshTiming& timing; + ControllerCore &controllerCore; + RefreshTiming &timing; sc_time nextPlannedRefresh; std::map refreshPayloads; unsigned int maxpostpone = 0; @@ -77,7 +78,7 @@ private: ref_fsm_state_t previousState = ST_REFRESH; ref_fsm_state_t nextState = ST_REFRESH; - void doRefresh(tlm::tlm_generic_payload& payload, sc_time time); + void doRefresh(tlm::tlm_generic_payload &payload, sc_time time); void planNextRefresh(sc_time time); void printDebugMessage(std::string message); }; diff --git a/DRAMSys/library/src/controller/core/refresh/RefreshManagerBankwise.cpp b/DRAMSys/library/src/controller/core/refresh/RefreshManagerBankwise.cpp index 3aac9feb..3d71980f 100644 --- a/DRAMSys/library/src/controller/core/refresh/RefreshManagerBankwise.cpp +++ b/DRAMSys/library/src/controller/core/refresh/RefreshManagerBankwise.cpp @@ -42,10 +42,10 @@ using namespace std; -RefreshManagerBankwise::RefreshManagerBankwise(sc_module_name /*name*/, ControllerCore& controller) : controllerCore(controller) +RefreshManagerBankwise::RefreshManagerBankwise(sc_module_name /*name*/, + ControllerCore &controller) : controllerCore(controller) { - for (Bank bank : controller.getBanks()) - { + for (Bank bank : controller.getBanks()) { setUpDummy(refreshPayloads[bank], bank); planNextRefresh(bank); } @@ -55,50 +55,60 @@ RefreshManagerBankwise::~RefreshManagerBankwise() { } -bool RefreshManagerBankwise::hasCollision(const ScheduledCommand& command) +bool RefreshManagerBankwise::hasCollision(const ScheduledCommand &command) { - Bank bank = command.getBank(); - // Get the last AutoRefresh command for this bank and the time of its end - ScheduledCommand lastAutoRefreshCmd = controllerCore.state->getLastCommand(Command::AutoRefresh, bank); - sc_time endTimeLastAutoRefreshCmd = lastAutoRefreshCmd.getEnd(); - // Get the time of the next planned refresh for this bank - sc_time timeNextPlannedRefresh = nextPlannedRefreshs[command.getBank()]; - // Collision: - // - the start time of the command is before the end time of the last auto refresh command for this bank - // - the end time of the command is after the next planned refresh for this bank - return command.getStart() < endTimeLastAutoRefreshCmd || command.getEnd() > timeNextPlannedRefresh; + Bank bank = command.getBank(); + // Get the last AutoRefresh command for this bank and the time of its end + ScheduledCommand lastAutoRefreshCmd = controllerCore.state->getLastCommand( + Command::AutoRefresh, bank); + sc_time endTimeLastAutoRefreshCmd = lastAutoRefreshCmd.getEnd(); + // Get the time of the next planned refresh for this bank + sc_time timeNextPlannedRefresh = nextPlannedRefreshs[command.getBank()]; + // Collision: + // - the start time of the command is before the end time of the last auto refresh command for this bank + // - the end time of the command is after the next planned refresh for this bank + return command.getStart() < endTimeLastAutoRefreshCmd + || command.getEnd() > timeNextPlannedRefresh; } -void RefreshManagerBankwise::scheduleRefresh(tlm::tlm_generic_payload& payload, sc_time time) +void RefreshManagerBankwise::scheduleRefresh(tlm::tlm_generic_payload &payload, + sc_time time) { sc_assert(!isInvalidated(payload, time)); - tlm::tlm_generic_payload& refreshPayload = refreshPayloads[DramExtension::getExtension(payload).getBank()]; + tlm::tlm_generic_payload &refreshPayload = + refreshPayloads[DramExtension::getExtension(payload).getBank()]; - DramExtension& extension = DramExtension::getExtension(refreshPayload); + DramExtension &extension = DramExtension::getExtension(refreshPayload); - if (controllerCore.state->rowBufferStates->rowBufferIsOpen(extension.getBank())) - { - ScheduledCommand precharge(Command::Precharge, time, getExecutionTime(Command::Precharge, refreshPayload), extension); + if (controllerCore.state->rowBufferStates->rowBufferIsOpen( + extension.getBank())) { + ScheduledCommand precharge(Command::Precharge, time, + getExecutionTime(Command::Precharge, refreshPayload), extension); - controllerCore.getCommandChecker(Command::Precharge).delayToSatisfyConstraints(precharge); + controllerCore.getCommandChecker(Command::Precharge).delayToSatisfyConstraints( + precharge); controllerCore.state->change(precharge); controllerCore.controller.send(precharge, refreshPayload); } - ScheduledCommand refresh(Command::AutoRefresh, time, getExecutionTime(Command::AutoRefresh, refreshPayload), extension); - controllerCore.getCommandChecker(Command::AutoRefresh).delayToSatisfyConstraints(refresh); + ScheduledCommand refresh(Command::AutoRefresh, time, + getExecutionTime(Command::AutoRefresh, refreshPayload), extension); + controllerCore.getCommandChecker( + Command::AutoRefresh).delayToSatisfyConstraints(refresh); controllerCore.state->change(refresh); extension.incrementRow(); controllerCore.controller.send(refresh, refreshPayload); - planNextRefresh(extension.getBank()); + planNextRefresh(extension.getBank()); } void RefreshManagerBankwise::planNextRefresh(Bank bank) { - nextPlannedRefreshs[bank] += Configuration::getInstance().memSpec.refreshTimings[bank].tREFI; - controllerCore.controller.send(REFTrigger, nextPlannedRefreshs[bank], refreshPayloads[bank]); + nextPlannedRefreshs[bank] += + Configuration::getInstance().memSpec.refreshTimings[bank].tREFI; + controllerCore.controller.send(REFTrigger, nextPlannedRefreshs[bank], + refreshPayloads[bank]); } void RefreshManagerBankwise::reInitialize(Bank bank, sc_time time) @@ -107,13 +117,15 @@ void RefreshManagerBankwise::reInitialize(Bank bank, sc_time time) planNextRefresh(bank); } -bool RefreshManagerBankwise::isInvalidated(tlm::tlm_generic_payload& payload, sc_time time) +bool RefreshManagerBankwise::isInvalidated(tlm::tlm_generic_payload &payload, + sc_time time) { - return nextPlannedRefreshs[DramExtension::getExtension(payload).getBank()] > time; + return nextPlannedRefreshs[DramExtension::getExtension(payload).getBank()] > + time; } void RefreshManagerBankwise::printDebugMessage(std::string message) { - DebugManager::getInstance().printDebugMessage(this->name(), message); + DebugManager::getInstance().printDebugMessage(this->name(), message); } diff --git a/DRAMSys/library/src/controller/core/refresh/RefreshManagerBankwise.h b/DRAMSys/library/src/controller/core/refresh/RefreshManagerBankwise.h index a026aae8..f0f57070 100644 --- a/DRAMSys/library/src/controller/core/refresh/RefreshManagerBankwise.h +++ b/DRAMSys/library/src/controller/core/refresh/RefreshManagerBankwise.h @@ -47,25 +47,26 @@ class ControllerCore; class RefreshManagerBankwise : public IRefreshManager, public sc_module { public: - RefreshManagerBankwise(sc_module_name /*name*/, ControllerCore& controllerCore); - virtual ~RefreshManagerBankwise(); + RefreshManagerBankwise(sc_module_name /*name*/, ControllerCore &controllerCore); + virtual ~RefreshManagerBankwise(); - virtual bool hasCollision(const ScheduledCommand& command) override; - virtual void scheduleRefresh(tlm::tlm_generic_payload& payload, sc_time time) override; + virtual bool hasCollision(const ScheduledCommand &command) override; + virtual void scheduleRefresh(tlm::tlm_generic_payload &payload, + sc_time time) override; - void reInitialize(Bank bank, sc_time time) override; + void reInitialize(Bank bank, sc_time time) override; - bool isInvalidated(tlm::tlm_generic_payload& payload,sc_time time) override; + bool isInvalidated(tlm::tlm_generic_payload &payload, sc_time time) override; private: - ControllerCore &controllerCore; + ControllerCore &controllerCore; - std::map refreshPayloads; - std::map nextPlannedRefreshs; + std::map refreshPayloads; + std::map nextPlannedRefreshs; - void planNextRefresh(Bank bank); + void planNextRefresh(Bank bank); - void printDebugMessage(std::string message); + void printDebugMessage(std::string message); }; #endif /* BANKWISEREFRESHMANAGER_H_ */ diff --git a/DRAMSys/library/src/controller/core/scheduling/ScheduledCommand.cpp b/DRAMSys/library/src/controller/core/scheduling/ScheduledCommand.cpp index a4e73400..34ed336e 100644 --- a/DRAMSys/library/src/controller/core/scheduling/ScheduledCommand.cpp +++ b/DRAMSys/library/src/controller/core/scheduling/ScheduledCommand.cpp @@ -41,7 +41,8 @@ bool ScheduledCommand::isNoCommand() const { - return (command == Command::NOP && start == SC_ZERO_TIME && executionTime == SC_ZERO_TIME && end == SC_ZERO_TIME); + return (command == Command::NOP && start == SC_ZERO_TIME + && executionTime == SC_ZERO_TIME && end == SC_ZERO_TIME); } @@ -63,12 +64,13 @@ void ScheduledCommand::setStart(sc_time newStart) void ScheduledCommand::delayStart(sc_time delay) { - setStart(start+delay); + setStart(start + delay); } // Delays the command so that its start is at least value(constraint) from timepoint previous apart. // If passed a constraint of 0ns, method will make sure that command starts no earlier than at timepoint previous -void ScheduledCommand::establishMinDistanceFromStart(sc_time previous, sc_time constraint) +void ScheduledCommand::establishMinDistanceFromStart(sc_time previous, + sc_time constraint) { delayStart(getDelayToMeetConstraint(previous, start, constraint)); } @@ -108,12 +110,13 @@ unsigned int ScheduledCommand::getBurstLength() const return extension.getBurstlength(); } -bool ScheduledCommand::operator ==(const ScheduledCommand& b) const +bool ScheduledCommand::operator ==(const ScheduledCommand &b) const { - return b.command == command && b.start == start && b.executionTime == executionTime && b.end == end; + return b.command == command && b.start == start + && b.executionTime == executionTime && b.end == end; } -bool ScheduledCommand::commandIsIn(const std::vector& commandSet) const +bool ScheduledCommand::commandIsIn(const std::vector &commandSet) const { return isIn(command, commandSet); } @@ -122,17 +125,16 @@ TimeInterval ScheduledCommand::getIntervalOnDataStrobe() const { //only read and write commands have an assoicated time on the data strobe sc_assert(getCommand() == Command::Read || getCommand() == Command::ReadA - || getCommand() == Command::Write - || getCommand() == Command::WriteA); + || getCommand() == Command::Write + || getCommand() == Command::WriteA); - MemSpec& timings = Configuration::getInstance().memSpec; + MemSpec &timings = Configuration::getInstance().memSpec; - if (getCommand() == Command::Read || getCommand() == Command::ReadA) - { - return TimeInterval(getStart() + timings.tRL, getStart() + timings.tRL + getReadAccessTime()); - } - else - { - return TimeInterval(getStart() + timings.tWL - timings.clk / 2, getStart() + timings.tWL + getWriteAccessTime() - timings.clk / 2); + if (getCommand() == Command::Read || getCommand() == Command::ReadA) { + return TimeInterval(getStart() + timings.tRL, + getStart() + timings.tRL + getReadAccessTime()); + } else { + return TimeInterval(getStart() + timings.tWL - timings.clk / 2, + getStart() + timings.tWL + getWriteAccessTime() - timings.clk / 2); } } diff --git a/DRAMSys/library/src/controller/core/scheduling/ScheduledCommand.h b/DRAMSys/library/src/controller/core/scheduling/ScheduledCommand.h index e0265737..8bb57653 100644 --- a/DRAMSys/library/src/controller/core/scheduling/ScheduledCommand.h +++ b/DRAMSys/library/src/controller/core/scheduling/ScheduledCommand.h @@ -47,20 +47,25 @@ class ScheduledCommand { public: - ScheduledCommand(Command command, sc_time start, sc_time executionTime, const DramExtension& extension) : - command(command), start(start), executionTime(executionTime),end(start+executionTime), - extension(extension) + ScheduledCommand(Command command, sc_time start, sc_time executionTime, + const DramExtension &extension) : + command(command), start(start), executionTime(executionTime), + end(start + executionTime), + extension(extension) { } - ScheduledCommand(Command command, sc_time start, sc_time executionTime, const tlm::tlm_generic_payload& payload) : - ScheduledCommand(command, start, executionTime, DramExtension::getExtension(payload)) + ScheduledCommand(Command command, sc_time start, sc_time executionTime, + const tlm::tlm_generic_payload &payload) : + ScheduledCommand(command, start, executionTime, + DramExtension::getExtension(payload)) { } ScheduledCommand() : - command(Command::NOP), start(SC_ZERO_TIME), executionTime(SC_ZERO_TIME), end(SC_ZERO_TIME), extension() + command(Command::NOP), start(SC_ZERO_TIME), executionTime(SC_ZERO_TIME), + end(SC_ZERO_TIME), extension() { } @@ -81,8 +86,8 @@ public: Row getRow() const; unsigned int getBurstLength() const; - bool operator ==(const ScheduledCommand& b) const; - bool commandIsIn(const std::vector& commandSet) const; + bool operator ==(const ScheduledCommand &b) const; + bool commandIsIn(const std::vector &commandSet) const; TimeInterval getIntervalOnDataStrobe() const; diff --git a/DRAMSys/library/src/controller/core/scheduling/checker/ActivateChecker.cpp b/DRAMSys/library/src/controller/core/scheduling/checker/ActivateChecker.cpp index 170bca70..4ce4b249 100644 --- a/DRAMSys/library/src/controller/core/scheduling/checker/ActivateChecker.cpp +++ b/DRAMSys/library/src/controller/core/scheduling/checker/ActivateChecker.cpp @@ -45,67 +45,67 @@ using namespace std; -void ActivateChecker::delayToSatisfyConstraints(ScheduledCommand& command) const +void ActivateChecker::delayToSatisfyConstraints(ScheduledCommand &command) const { sc_assert(command.getCommand() == Command::Activate); - ScheduledCommand lastCommandOnBank = state.getLastScheduledCommand(command.getBank()); - if (lastCommandOnBank.isValidCommand()) - { - if (lastCommandOnBank.getCommand() == Command::Precharge || lastCommandOnBank.getCommand() == Command::PrechargeAll) - { - command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), config.memSpec.tRP); - } - else if (lastCommandOnBank.getCommand() == Command::ReadA) - { - command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), config.memSpec.tRTP + config.memSpec.tRP); - } - else if (lastCommandOnBank.getCommand() == Command::WriteA) - { + ScheduledCommand lastCommandOnBank = state.getLastScheduledCommand( + command.getBank()); + if (lastCommandOnBank.isValidCommand()) { + if (lastCommandOnBank.getCommand() == Command::Precharge + || lastCommandOnBank.getCommand() == Command::PrechargeAll) { command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), - config.memSpec.tWL + getWriteAccessTime() + config.memSpec.tWR + config.memSpec.tRP); - } - else if (lastCommandOnBank.getCommand() == Command::AutoRefresh) - { - command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), config.memSpec.tRFC); - } - else if (lastCommandOnBank.getCommand() == Command::PDNPX || lastCommandOnBank.getCommand() == Command::PDNAX) - { - command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), config.memSpec.tXP); - } - else if (lastCommandOnBank.getCommand() == Command::SREFX) - { - command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), config.memSpec.tXSR); - } - else - reportFatal("Activate Checker", "Activate can not follow " + commandToString(lastCommandOnBank.getCommand())); + config.memSpec.tRP); + } else if (lastCommandOnBank.getCommand() == Command::ReadA) { + command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), + config.memSpec.tRTP + config.memSpec.tRP); + } else if (lastCommandOnBank.getCommand() == Command::WriteA) { + command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), + config.memSpec.tWL + getWriteAccessTime() + config.memSpec.tWR + + config.memSpec.tRP); + } else if (lastCommandOnBank.getCommand() == Command::AutoRefresh) { + command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), + config.memSpec.tRFC); + } else if (lastCommandOnBank.getCommand() == Command::PDNPX + || lastCommandOnBank.getCommand() == Command::PDNAX) { + command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), + config.memSpec.tXP); + } else if (lastCommandOnBank.getCommand() == Command::SREFX) { + command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), + config.memSpec.tXSR); + } else + reportFatal("Activate Checker", + "Activate can not follow " + commandToString(lastCommandOnBank.getCommand())); } delay_to_satisfy_activateToActivate_sameBank(command); - while (!(state.bus.isFree(command.getStart()) && satsfies_activateToActivate_differentBank(command) - && satisfies_nActivateWindow(command))) - { + while (!(state.bus.isFree(command.getStart()) + && satsfies_activateToActivate_differentBank(command) + && satisfies_nActivateWindow(command))) { command.delayStart(config.memSpec.clk); } } -void ActivateChecker::delay_to_satisfy_activateToActivate_sameBank(ScheduledCommand& command) const +void ActivateChecker::delay_to_satisfy_activateToActivate_sameBank( + ScheduledCommand &command) const { - ScheduledCommand lastActivateOnBank = state.getLastCommand(Command::Activate, command.getBank()); - if (lastActivateOnBank.isValidCommand()) - { - command.establishMinDistanceFromStart(lastActivateOnBank.getStart(), config.memSpec.tRC); + ScheduledCommand lastActivateOnBank = state.getLastCommand(Command::Activate, + command.getBank()); + if (lastActivateOnBank.isValidCommand()) { + command.establishMinDistanceFromStart(lastActivateOnBank.getStart(), + config.memSpec.tRC); } } -bool ActivateChecker::satsfies_activateToActivate_differentBank(ScheduledCommand& command) const +bool ActivateChecker::satsfies_activateToActivate_differentBank( + ScheduledCommand &command) const { - for (auto act : state.lastActivates) - { + for (auto act : state.lastActivates) { sc_time time = act.first; - sc_time tRRD = (command.getBankGroup() == act.second.getBankGroup()) ? config.memSpec.tRRD_L : config.memSpec.tRRD_S; + sc_time tRRD = (command.getBankGroup() == act.second.getBankGroup()) ? + config.memSpec.tRRD_L : config.memSpec.tRRD_S; if ((time < command.getStart() && command.getStart() - time < tRRD) || (command.getStart() <= time && time - command.getStart() < tRRD)) @@ -114,23 +114,21 @@ bool ActivateChecker::satsfies_activateToActivate_differentBank(ScheduledCommand return true; } -bool ActivateChecker::satisfies_nActivateWindow(ScheduledCommand& command) const +bool ActivateChecker::satisfies_nActivateWindow(ScheduledCommand &command) const { /* * there may be activates scheduled in the future, so emplace * command in a copied set (not necessarily the last in time), * and check if the n-act constraint holds for the whole set. */ - if (state.lastActivates.size() >= config.memSpec.nActivate) - { + if (state.lastActivates.size() >= config.memSpec.nActivate) { map lastActivates = state.lastActivates; lastActivates.emplace(command.getStart(), command); auto upper = lastActivates.begin(); advance(upper, config.memSpec.nActivate); auto lower = lastActivates.begin(); - while (upper != lastActivates.end()) - { + while (upper != lastActivates.end()) { if (upper->first - lower->first < config.memSpec.tNAW) return false; ++upper; diff --git a/DRAMSys/library/src/controller/core/scheduling/checker/ActivateChecker.h b/DRAMSys/library/src/controller/core/scheduling/checker/ActivateChecker.h index 22c5886f..ed62f98d 100644 --- a/DRAMSys/library/src/controller/core/scheduling/checker/ActivateChecker.h +++ b/DRAMSys/library/src/controller/core/scheduling/checker/ActivateChecker.h @@ -45,17 +45,20 @@ class ActivateChecker: public ICommandChecker { public: - ActivateChecker(const Configuration& config, ControllerState& state) : config(config), state(state){} - virtual ~ActivateChecker(){} + ActivateChecker(const Configuration &config, + ControllerState &state) : config(config), state(state) {} + virtual ~ActivateChecker() {} - virtual void delayToSatisfyConstraints(ScheduledCommand& command) const override; + virtual void delayToSatisfyConstraints(ScheduledCommand &command) const + override; private: - const Configuration& config; - ControllerState& state;//TODO make const + const Configuration &config; + ControllerState &state;//TODO make const - void delay_to_satisfy_activateToActivate_sameBank(ScheduledCommand& command) const; - bool satsfies_activateToActivate_differentBank(ScheduledCommand& command) const; - bool satisfies_nActivateWindow(ScheduledCommand& command) const; + void delay_to_satisfy_activateToActivate_sameBank(ScheduledCommand &command) + const; + bool satsfies_activateToActivate_differentBank(ScheduledCommand &command) const; + bool satisfies_nActivateWindow(ScheduledCommand &command) const; }; #endif /* ACTIVATESCHEDULER_H_ */ diff --git a/DRAMSys/library/src/controller/core/scheduling/checker/ICommandChecker.h b/DRAMSys/library/src/controller/core/scheduling/checker/ICommandChecker.h index a82350d5..833077cb 100644 --- a/DRAMSys/library/src/controller/core/scheduling/checker/ICommandChecker.h +++ b/DRAMSys/library/src/controller/core/scheduling/checker/ICommandChecker.h @@ -44,8 +44,8 @@ class ICommandChecker { public: - virtual ~ICommandChecker() {} - virtual void delayToSatisfyConstraints(ScheduledCommand& command) const = 0; + virtual ~ICommandChecker() {} + virtual void delayToSatisfyConstraints(ScheduledCommand &command) const = 0; }; diff --git a/DRAMSys/library/src/controller/core/scheduling/checker/PowerDownChecker.cpp b/DRAMSys/library/src/controller/core/scheduling/checker/PowerDownChecker.cpp index a85179da..d4c22c36 100644 --- a/DRAMSys/library/src/controller/core/scheduling/checker/PowerDownChecker.cpp +++ b/DRAMSys/library/src/controller/core/scheduling/checker/PowerDownChecker.cpp @@ -38,77 +38,86 @@ #include "PowerDownChecker.h" #include "../../TimingCalculation.h" -sc_time PowerDownChecker::getTimeConstraintToEnterPowerDown(Command lastCmd, Command pdnCmd) const +sc_time PowerDownChecker::getTimeConstraintToEnterPowerDown(Command lastCmd, + Command pdnCmd) const { - sc_assert(pdnCmd == Command::SREF || pdnCmd == Command::PDNA || pdnCmd == Command::PDNP); + sc_assert(pdnCmd == Command::SREF || pdnCmd == Command::PDNA + || pdnCmd == Command::PDNP); - sc_time constraint; + sc_time constraint; - if (lastCmd == Command::Read || lastCmd == Command::ReadA) { - constraint = config.memSpec.tRL + getReadAccessTime() + config.memSpec.clk; - } else if (lastCmd == Command::Write) { - constraint = config.memSpec.tWL + getWriteAccessTime() + config.memSpec.tWR; - } else if (lastCmd == Command::WriteA) { - constraint = config.memSpec.tWL + getWriteAccessTime() + config.memSpec.tWR + config.memSpec.clk; - } else if (lastCmd == Command::AutoRefresh) { - constraint = config.memSpec.tRFC; - } else if (lastCmd == Command::PDNPX || lastCmd == Command::PDNAX) { - constraint = config.memSpec.tXP; - } else if (lastCmd == Command::SREFX) { - constraint = config.memSpec.tXSR; - } else if(lastCmd == Command::Precharge || lastCmd == Command::PrechargeAll) { - constraint = config.memSpec.tRP; - } else { - reportFatal("Powerdown checker", commandToString(pdnCmd) + " can not follow " + commandToString(lastCmd)); - } + if (lastCmd == Command::Read || lastCmd == Command::ReadA) { + constraint = config.memSpec.tRL + getReadAccessTime() + config.memSpec.clk; + } else if (lastCmd == Command::Write) { + constraint = config.memSpec.tWL + getWriteAccessTime() + config.memSpec.tWR; + } else if (lastCmd == Command::WriteA) { + constraint = config.memSpec.tWL + getWriteAccessTime() + config.memSpec.tWR + + config.memSpec.clk; + } else if (lastCmd == Command::AutoRefresh) { + constraint = config.memSpec.tRFC; + } else if (lastCmd == Command::PDNPX || lastCmd == Command::PDNAX) { + constraint = config.memSpec.tXP; + } else if (lastCmd == Command::SREFX) { + constraint = config.memSpec.tXSR; + } else if (lastCmd == Command::Precharge || lastCmd == Command::PrechargeAll) { + constraint = config.memSpec.tRP; + } else { + reportFatal("Powerdown checker", + commandToString(pdnCmd) + " can not follow " + commandToString(lastCmd)); + } - return constraint; + return constraint; } -void PowerDownChecker::delayToSatisfyConstraints(ScheduledCommand &command) const +void PowerDownChecker::delayToSatisfyConstraints(ScheduledCommand &command) +const { - sc_assert(command.commandIsIn({Command::PDNA, Command::PDNP, Command::SREF, Command::PDNAX, Command::PDNPX, Command::SREFX})); + sc_assert(command.commandIsIn({Command::PDNA, Command::PDNP, Command::SREF, Command::PDNAX, Command::PDNPX, Command::SREFX})); - // Power Down commmand (one of the listed above) - Command pdnCmd = command.getCommand(); - Bank bank = command.getBank(); + // Power Down commmand (one of the listed above) + Command pdnCmd = command.getCommand(); + Bank bank = command.getBank(); - sc_time timeConstraint; + sc_time timeConstraint; - if (pdnCmd == Command::PDNA || pdnCmd == Command::PDNP || pdnCmd == Command::SREF) { - // Entering in one of the Power Down modes: - // PDNA - Active Power Down - // PDNP - Precharge Power Down - // SREF - Self Refresh + if (pdnCmd == Command::PDNA || pdnCmd == Command::PDNP + || pdnCmd == Command::SREF) { + // Entering in one of the Power Down modes: + // PDNA - Active Power Down + // PDNP - Precharge Power Down + // SREF - Self Refresh - // Get the last scheduled command on this bank - ScheduledCommand lastSchedCmdOnBank = state.getLastScheduledCommand(bank); + // Get the last scheduled command on this bank + ScheduledCommand lastSchedCmdOnBank = state.getLastScheduledCommand(bank); if (lastSchedCmdOnBank.isValidCommand()) { - // Get the start time for the last scheduled command on this bank - sc_time lastSchedCmdOnBankStart = lastSchedCmdOnBank.getStart(); - // Get the last command on this bank itself - Command lastCmdBank = lastSchedCmdOnBank.getCommand(); + // Get the start time for the last scheduled command on this bank + sc_time lastSchedCmdOnBankStart = lastSchedCmdOnBank.getStart(); + // Get the last command on this bank itself + Command lastCmdBank = lastSchedCmdOnBank.getCommand(); - timeConstraint = getTimeConstraintToEnterPowerDown(lastCmdBank, pdnCmd); + timeConstraint = getTimeConstraintToEnterPowerDown(lastCmdBank, pdnCmd); - command.establishMinDistanceFromStart(lastSchedCmdOnBankStart, timeConstraint); + command.establishMinDistanceFromStart(lastSchedCmdOnBankStart, timeConstraint); } } else if (pdnCmd == Command::PDNAX) { // Leaving Active Power Down timeConstraint = config.memSpec.tCKE; - command.establishMinDistanceFromStart(state.getLastCommand(Command::PDNA, bank).getStart(), timeConstraint); + command.establishMinDistanceFromStart(state.getLastCommand(Command::PDNA, + bank).getStart(), timeConstraint); } else if (pdnCmd == Command::PDNPX) { // Leaving Precharge Power Down timeConstraint = config.memSpec.tCKE; - command.establishMinDistanceFromStart(state.getLastCommand(Command::PDNP, bank).getStart(), timeConstraint); + command.establishMinDistanceFromStart(state.getLastCommand(Command::PDNP, + bank).getStart(), timeConstraint); } else if (pdnCmd == Command::SREFX) { // Leaving Self Refresh timeConstraint = config.memSpec.tCKESR; - command.establishMinDistanceFromStart(state.getLastCommand(Command::SREF, bank).getStart(), timeConstraint); + command.establishMinDistanceFromStart(state.getLastCommand(Command::SREF, + bank).getStart(), timeConstraint); } - state.bus.moveCommandToNextFreeSlot(command); + state.bus.moveCommandToNextFreeSlot(command); } diff --git a/DRAMSys/library/src/controller/core/scheduling/checker/PowerDownChecker.h b/DRAMSys/library/src/controller/core/scheduling/checker/PowerDownChecker.h index 222ae31e..df7a2a9a 100644 --- a/DRAMSys/library/src/controller/core/scheduling/checker/PowerDownChecker.h +++ b/DRAMSys/library/src/controller/core/scheduling/checker/PowerDownChecker.h @@ -46,15 +46,18 @@ class PowerDownChecker : public ICommandChecker { public: - PowerDownChecker(const Configuration &config, ControllerState &state) : config(config), state(state) {} - virtual ~PowerDownChecker() {} + PowerDownChecker(const Configuration &config, + ControllerState &state) : config(config), state(state) {} + virtual ~PowerDownChecker() {} - virtual void delayToSatisfyConstraints(ScheduledCommand& command) const override; + virtual void delayToSatisfyConstraints(ScheduledCommand &command) const + override; private: - const Configuration &config; - ControllerState &state; - sc_time getTimeConstraintToEnterPowerDown(Command lastCmd, Command pdnCmd) const; + const Configuration &config; + ControllerState &state; + sc_time getTimeConstraintToEnterPowerDown(Command lastCmd, + Command pdnCmd) const; }; #endif /* POWERDOWNCHECKER_H_ */ diff --git a/DRAMSys/library/src/controller/core/scheduling/checker/PrechargeAllChecker.cpp b/DRAMSys/library/src/controller/core/scheduling/checker/PrechargeAllChecker.cpp index aaf0f661..297ad105 100644 --- a/DRAMSys/library/src/controller/core/scheduling/checker/PrechargeAllChecker.cpp +++ b/DRAMSys/library/src/controller/core/scheduling/checker/PrechargeAllChecker.cpp @@ -39,62 +39,55 @@ #include "../../TimingCalculation.h" -void PrechargeAllChecker::delayToSatisfyConstraints(ScheduledCommand& command) const +void PrechargeAllChecker::delayToSatisfyConstraints(ScheduledCommand &command) +const { sc_assert(command.getCommand() == Command::PrechargeAll); // Consider all banks for the constraints, since precharge all command is supposed to happen at the same time on all banks - for (unsigned int bank = 0; bank < config.memSpec.NumberOfBanks; ++bank) - { + for (unsigned int bank = 0; bank < config.memSpec.NumberOfBanks; ++bank) { ScheduledCommand lastCommand = state.getLastScheduledCommand(Bank(bank)); - if (lastCommand.isValidCommand()) - { - if(lastCommand.getCommand() == Command::Precharge) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tRP); - } - else if(lastCommand.getCommand() == Command::Activate) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tRCD); - } - else if (lastCommand.getCommand() == Command::Read) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tRTP); - } - else if (lastCommand.getCommand() == Command::ReadA) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tRTP + config.memSpec.tRP); - } - else if (lastCommand.getCommand() == Command::Write) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tWL + getWriteAccessTime() + config.memSpec.tWR); - } - else if(lastCommand.getCommand() == Command::WriteA) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tWL + getWriteAccessTime() + config.memSpec.tWR + config.memSpec.tRP); - } - else if (lastCommand.getCommand() == Command::AutoRefresh) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tRFC); - } - else if (lastCommand.getCommand() == Command::PDNAX || lastCommand.getCommand() == Command::PDNPX) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tXP); - } - else if (lastCommand.getCommand() == Command::SREFX) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tXSR); - } - else + if (lastCommand.isValidCommand()) { + if (lastCommand.getCommand() == Command::Precharge) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tRP); + } else if (lastCommand.getCommand() == Command::Activate) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tRCD); + } else if (lastCommand.getCommand() == Command::Read) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tRTP); + } else if (lastCommand.getCommand() == Command::ReadA) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tRTP + config.memSpec.tRP); + } else if (lastCommand.getCommand() == Command::Write) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tWL + getWriteAccessTime() + config.memSpec.tWR); + } else if (lastCommand.getCommand() == Command::WriteA) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tWL + getWriteAccessTime() + config.memSpec.tWR + + config.memSpec.tRP); + } else if (lastCommand.getCommand() == Command::AutoRefresh) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tRFC); + } else if (lastCommand.getCommand() == Command::PDNAX + || lastCommand.getCommand() == Command::PDNPX) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tXP); + } else if (lastCommand.getCommand() == Command::SREFX) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tXSR); + } else reportFatal("Precharge All Checker", - "Precharge All can not follow " + commandToString(lastCommand.getCommand())); + "Precharge All can not follow " + commandToString(lastCommand.getCommand())); } } - ScheduledCommand lastActivate = state.getLastCommand(Command::Activate, command.getBank()); - if (lastActivate.isValidCommand()) - { - command.establishMinDistanceFromStart(lastActivate.getStart(), config.memSpec.tRAS); + ScheduledCommand lastActivate = state.getLastCommand(Command::Activate, + command.getBank()); + if (lastActivate.isValidCommand()) { + command.establishMinDistanceFromStart(lastActivate.getStart(), + config.memSpec.tRAS); } state.bus.moveCommandToNextFreeSlot(command); diff --git a/DRAMSys/library/src/controller/core/scheduling/checker/PrechargeAllChecker.h b/DRAMSys/library/src/controller/core/scheduling/checker/PrechargeAllChecker.h index 8863c27f..62e8a0f2 100644 --- a/DRAMSys/library/src/controller/core/scheduling/checker/PrechargeAllChecker.h +++ b/DRAMSys/library/src/controller/core/scheduling/checker/PrechargeAllChecker.h @@ -45,19 +45,20 @@ class PrechargeAllChecker: public ICommandChecker { public: - PrechargeAllChecker(const Configuration& config, ControllerState& state) : - config(config), state(state) - { - } - virtual ~PrechargeAllChecker() - { - } + PrechargeAllChecker(const Configuration &config, ControllerState &state) : + config(config), state(state) + { + } + virtual ~PrechargeAllChecker() + { + } - virtual void delayToSatisfyConstraints(ScheduledCommand& command) const override; + virtual void delayToSatisfyConstraints(ScheduledCommand &command) const + override; private: - const Configuration& config; - ControllerState& state; + const Configuration &config; + ControllerState &state; }; diff --git a/DRAMSys/library/src/controller/core/scheduling/checker/PrechargeChecker.cpp b/DRAMSys/library/src/controller/core/scheduling/checker/PrechargeChecker.cpp index fa53958f..d6bfd8fd 100644 --- a/DRAMSys/library/src/controller/core/scheduling/checker/PrechargeChecker.cpp +++ b/DRAMSys/library/src/controller/core/scheduling/checker/PrechargeChecker.cpp @@ -38,47 +38,45 @@ #include "../../TimingCalculation.h" -void PrechargeChecker::delayToSatisfyConstraints(ScheduledCommand& command) const +void PrechargeChecker::delayToSatisfyConstraints(ScheduledCommand &command) +const { //return; sc_assert(command.getCommand() == Command::Precharge); ScheduledCommand lastCommand = state.getLastScheduledCommand(command.getBank()); - if (lastCommand.isValidCommand()) - { + if (lastCommand.isValidCommand()) { // the first two cases happen when a resfresh interrups the command sequence of a transaction // (e.g. commands to process transaction are PRE-ACT-RD and refresh happens after the PRE or after the ACT) - if(lastCommand.getCommand() == Command::Precharge) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tRP); - } - else if(lastCommand.getCommand() == Command::Activate) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tRCD); + if (lastCommand.getCommand() == Command::Precharge) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tRP); + } else if (lastCommand.getCommand() == Command::Activate) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tRCD); } - else if (lastCommand.getCommand() == Command::Read) - { - command.establishMinDistanceFromStart(lastCommand.getStart(),config.memSpec.tRTP); - } - else if (lastCommand.getCommand() == Command::Write) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tWL + getWriteAccessTime() + config.memSpec.tWR); + else if (lastCommand.getCommand() == Command::Read) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tRTP); + } else if (lastCommand.getCommand() == Command::Write) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tWL + getWriteAccessTime() + config.memSpec.tWR); - } - else if (lastCommand.getCommand() == Command::PDNAX) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tXP); - } - else - reportFatal("Precharge Checker", "Precharge can not follow " + commandToString(lastCommand.getCommand())); + } else if (lastCommand.getCommand() == Command::PDNAX) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tXP); + } else + reportFatal("Precharge Checker", + "Precharge can not follow " + commandToString(lastCommand.getCommand())); } - ScheduledCommand lastActivate = state.getLastCommand(Command::Activate, command.getBank()); - if (lastActivate.isValidCommand()) - { - command.establishMinDistanceFromStart(lastActivate.getStart(), config.memSpec.tRAS); + ScheduledCommand lastActivate = state.getLastCommand(Command::Activate, + command.getBank()); + if (lastActivate.isValidCommand()) { + command.establishMinDistanceFromStart(lastActivate.getStart(), + config.memSpec.tRAS); } state.bus.moveCommandToNextFreeSlot(command); diff --git a/DRAMSys/library/src/controller/core/scheduling/checker/PrechargeChecker.h b/DRAMSys/library/src/controller/core/scheduling/checker/PrechargeChecker.h index 6bed3e4a..4977dd55 100644 --- a/DRAMSys/library/src/controller/core/scheduling/checker/PrechargeChecker.h +++ b/DRAMSys/library/src/controller/core/scheduling/checker/PrechargeChecker.h @@ -45,13 +45,15 @@ class PrechargeChecker: public ICommandChecker { public: - PrechargeChecker(const Configuration& config, ControllerState& state) : config(config), state(state) {} - virtual ~PrechargeChecker() {} - virtual void delayToSatisfyConstraints(ScheduledCommand& command) const override; + PrechargeChecker(const Configuration &config, + ControllerState &state) : config(config), state(state) {} + virtual ~PrechargeChecker() {} + virtual void delayToSatisfyConstraints(ScheduledCommand &command) const + override; private: - const Configuration& config; - ControllerState& state; + const Configuration &config; + ControllerState &state; }; diff --git a/DRAMSys/library/src/controller/core/scheduling/checker/ReadChecker.cpp b/DRAMSys/library/src/controller/core/scheduling/checker/ReadChecker.cpp index e0746d24..78c3cfe9 100644 --- a/DRAMSys/library/src/controller/core/scheduling/checker/ReadChecker.cpp +++ b/DRAMSys/library/src/controller/core/scheduling/checker/ReadChecker.cpp @@ -41,44 +41,40 @@ using namespace std; -void ReadChecker::delayToSatisfyConstraints(ScheduledCommand& command) const +void ReadChecker::delayToSatisfyConstraints(ScheduledCommand &command) const { - sc_assert(command.getCommand() == Command::Read || command.getCommand() == Command::ReadA); + sc_assert(command.getCommand() == Command::Read + || command.getCommand() == Command::ReadA); delayToSatisfyDLL(command); ScheduledCommand lastCommand = state.getLastScheduledCommand(command.getBank()); - if (lastCommand.isValidCommand()) - { - if (lastCommand.getCommand() == Command::Activate) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tRCD); - } - else if (lastCommand.getCommand() == Command::Read) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), ReadChecker::readToRead(lastCommand,command)); - } - else if (lastCommand.getCommand() == Command::Write) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), ReadChecker::writeToRead(lastCommand, command)); - } - else if (lastCommand.getCommand() == Command::PDNPX || lastCommand.getCommand() == Command::PDNAX) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tXP); - } - else - reportFatal("Read Checker", "Read can not follow " + commandToString(lastCommand.getCommand())); + if (lastCommand.isValidCommand()) { + if (lastCommand.getCommand() == Command::Activate) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tRCD); + } else if (lastCommand.getCommand() == Command::Read) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + ReadChecker::readToRead(lastCommand, command)); + } else if (lastCommand.getCommand() == Command::Write) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + ReadChecker::writeToRead(lastCommand, command)); + } else if (lastCommand.getCommand() == Command::PDNPX + || lastCommand.getCommand() == Command::PDNAX) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tXP); + } else + reportFatal("Read Checker", + "Read can not follow " + commandToString(lastCommand.getCommand())); } - while (!state.bus.isFree(command.getStart()) || collidesOnDataStrobe(command)) - { + while (!state.bus.isFree(command.getStart()) || collidesOnDataStrobe(command)) { command.delayStart(config.memSpec.clk); } } -bool ReadChecker::collidesOnDataStrobe(ScheduledCommand& read) const +bool ReadChecker::collidesOnDataStrobe(ScheduledCommand &read) const { - for (ScheduledCommand& strobeCommand : state.lastDataStrobeCommands) - { + for (ScheduledCommand &strobeCommand : state.lastDataStrobeCommands) { if (collidesWithStrobeCommand(read, strobeCommand)) return true; } @@ -86,51 +82,63 @@ bool ReadChecker::collidesOnDataStrobe(ScheduledCommand& read) const return false; } -bool ReadChecker::collidesWithStrobeCommand(ScheduledCommand& read, ScheduledCommand& strobeCommand) const +bool ReadChecker::collidesWithStrobeCommand(ScheduledCommand &read, + ScheduledCommand &strobeCommand) const { - if (strobeCommand.getCommand() == Command::Read || strobeCommand.getCommand() == Command::ReadA) - { - return getDistance(read.getStart(),strobeCommand.getStart()) < ReadChecker::readToRead(strobeCommand,read); - } - else if (strobeCommand.getCommand() == Command::Write || strobeCommand.getCommand() == Command::WriteA) - { + if (strobeCommand.getCommand() == Command::Read + || strobeCommand.getCommand() == Command::ReadA) { + return getDistance(read.getStart(), + strobeCommand.getStart()) < ReadChecker::readToRead(strobeCommand, read); + } else if (strobeCommand.getCommand() == Command::Write + || strobeCommand.getCommand() == Command::WriteA) { if (strobeCommand.getStart() >= read.getStart()) - return getDistance(read.getStart(), strobeCommand.getStart()) < WriteChecker::readToWrite(read,strobeCommand); + return getDistance(read.getStart(), + strobeCommand.getStart()) < WriteChecker::readToWrite(read, strobeCommand); else - return getDistance(strobeCommand.getStart(), read.getStart()) < ReadChecker::writeToRead(strobeCommand, read); - } - else - { + return getDistance(strobeCommand.getStart(), + read.getStart()) < ReadChecker::writeToRead(strobeCommand, read); + } else { reportFatal("Read Checker", - "Invalid strobeCommand in data strobe commands " + commandToString(strobeCommand.getCommand())); + "Invalid strobeCommand in data strobe commands " + commandToString( + strobeCommand.getCommand())); return true; } } -void ReadChecker::delayToSatisfyDLL(ScheduledCommand& read) const +void ReadChecker::delayToSatisfyDLL(ScheduledCommand &read) const { - ScheduledCommand lastSREFX = state.getLastCommand(Command::SREFX, read.getBank()); + ScheduledCommand lastSREFX = state.getLastCommand(Command::SREFX, + read.getBank()); if (lastSREFX.isValidCommand()) - read.establishMinDistanceFromStart(lastSREFX.getStart(), config.memSpec.tXSRDLL); + read.establishMinDistanceFromStart(lastSREFX.getStart(), + config.memSpec.tXSRDLL); } -sc_time ReadChecker::readToRead(ScheduledCommand& firstRead, ScheduledCommand& secondRead) +sc_time ReadChecker::readToRead(ScheduledCommand &firstRead, + ScheduledCommand &secondRead) { - sc_assert(firstRead.getCommand() == Command::Read || firstRead.getCommand() == Command::ReadA); - sc_assert(secondRead.getCommand() == Command::Read || secondRead.getCommand() == Command::ReadA); + sc_assert(firstRead.getCommand() == Command::Read + || firstRead.getCommand() == Command::ReadA); + sc_assert(secondRead.getCommand() == Command::Read + || secondRead.getCommand() == Command::ReadA); - MemSpec& config = Configuration::getInstance().memSpec; - sc_time tCCD = (firstRead.getBankGroup() == secondRead.getBankGroup()) ? config.tCCD_L : config.tCCD_S; + MemSpec &config = Configuration::getInstance().memSpec; + sc_time tCCD = (firstRead.getBankGroup() == secondRead.getBankGroup()) ? + config.tCCD_L : config.tCCD_S; return max(tCCD, getReadAccessTime()); } -sc_time ReadChecker::writeToRead(ScheduledCommand& write, ScheduledCommand& read) +sc_time ReadChecker::writeToRead(ScheduledCommand &write, + ScheduledCommand &read) { - sc_assert(read.getCommand() == Command::Read || read.getCommand() == Command::ReadA); - sc_assert(write.getCommand() == Command::Write || write.getCommand() == Command::WriteA); + sc_assert(read.getCommand() == Command::Read + || read.getCommand() == Command::ReadA); + sc_assert(write.getCommand() == Command::Write + || write.getCommand() == Command::WriteA); - MemSpec& config = Configuration::getInstance().memSpec; - sc_time tWTR = (write.getBankGroup() == read.getBankGroup()) ? config.tWTR_L : config.tWTR_S; + MemSpec &config = Configuration::getInstance().memSpec; + sc_time tWTR = (write.getBankGroup() == read.getBankGroup()) ? config.tWTR_L : + config.tWTR_S; return config.tWL + getWriteAccessTime() + tWTR; } diff --git a/DRAMSys/library/src/controller/core/scheduling/checker/ReadChecker.h b/DRAMSys/library/src/controller/core/scheduling/checker/ReadChecker.h index 7b4ebede..1fd31f2b 100644 --- a/DRAMSys/library/src/controller/core/scheduling/checker/ReadChecker.h +++ b/DRAMSys/library/src/controller/core/scheduling/checker/ReadChecker.h @@ -44,21 +44,25 @@ class ReadChecker: public ICommandChecker { public: - ReadChecker(Configuration& config, ControllerState& state) : config(config), state(state) {} - virtual ~ReadChecker() {} + ReadChecker(Configuration &config, ControllerState &state) : config(config), + state(state) {} + virtual ~ReadChecker() {} - virtual void delayToSatisfyConstraints(ScheduledCommand& command) const override; + virtual void delayToSatisfyConstraints(ScheduledCommand &command) const + override; - static sc_time readToRead(ScheduledCommand& firstRead, ScheduledCommand& secondRead); - static sc_time writeToRead(ScheduledCommand& write, ScheduledCommand& read); + static sc_time readToRead(ScheduledCommand &firstRead, + ScheduledCommand &secondRead); + static sc_time writeToRead(ScheduledCommand &write, ScheduledCommand &read); private: - const Configuration& config; - ControllerState& state; + const Configuration &config; + ControllerState &state; - void delayToSatisfyDLL(ScheduledCommand& read) const; - bool collidesOnDataStrobe(ScheduledCommand& read) const; - bool collidesWithStrobeCommand(ScheduledCommand& read, ScheduledCommand& strobeCommand) const; + void delayToSatisfyDLL(ScheduledCommand &read) const; + bool collidesOnDataStrobe(ScheduledCommand &read) const; + bool collidesWithStrobeCommand(ScheduledCommand &read, + ScheduledCommand &strobeCommand) const; }; #endif /* READCHECKER_H_ */ diff --git a/DRAMSys/library/src/controller/core/scheduling/checker/RefreshChecker.cpp b/DRAMSys/library/src/controller/core/scheduling/checker/RefreshChecker.cpp index dd6d3869..f05f308d 100644 --- a/DRAMSys/library/src/controller/core/scheduling/checker/RefreshChecker.cpp +++ b/DRAMSys/library/src/controller/core/scheduling/checker/RefreshChecker.cpp @@ -38,81 +38,71 @@ #include "RefreshChecker.h" #include "../../TimingCalculation.h" -void RefreshChecker::delayToSatisfyConstraints(ScheduledCommand& command) const +void RefreshChecker::delayToSatisfyConstraints(ScheduledCommand &command) const { sc_assert(command.getCommand() == Command::AutoRefresh); - if(config.BankwiseLogic) - { - ScheduledCommand lastCommandOnBank = state.getLastScheduledCommand(command.getBank()); + if (config.BankwiseLogic) { + ScheduledCommand lastCommandOnBank = state.getLastScheduledCommand( + command.getBank()); - if (lastCommandOnBank.isValidCommand()) - { - if (lastCommandOnBank.getCommand() == Command::Precharge || lastCommandOnBank.getCommand() == Command::PrechargeAll) - { - command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), config.memSpec.tRP); - } - else if (lastCommandOnBank.getCommand() == Command::ReadA) - { - command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), config.memSpec.tRTP + config.memSpec.tRP); - } - else if (lastCommandOnBank.getCommand() == Command::WriteA) - { - command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), config.memSpec.tWL + getWriteAccessTime() + config.memSpec.tWR + config.memSpec.tRP); - } - else if (lastCommandOnBank.getCommand() == Command::PDNPX || lastCommandOnBank.getCommand() == Command::PDNAX) - { - command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), config.memSpec.tXP); - } - else if (lastCommandOnBank.getCommand() == Command::SREFX) - { - command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), config.memSpec.tXSR); - } - else if (lastCommandOnBank.getCommand() == Command::AutoRefresh) - { - command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), config.memSpec.tRFC); - } - else - reportFatal("Refresh Checker", "Refresh can not follow " + commandToString(lastCommandOnBank.getCommand())); + if (lastCommandOnBank.isValidCommand()) { + if (lastCommandOnBank.getCommand() == Command::Precharge + || lastCommandOnBank.getCommand() == Command::PrechargeAll) { + command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), + config.memSpec.tRP); + } else if (lastCommandOnBank.getCommand() == Command::ReadA) { + command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), + config.memSpec.tRTP + config.memSpec.tRP); + } else if (lastCommandOnBank.getCommand() == Command::WriteA) { + command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), + config.memSpec.tWL + getWriteAccessTime() + config.memSpec.tWR + + config.memSpec.tRP); + } else if (lastCommandOnBank.getCommand() == Command::PDNPX + || lastCommandOnBank.getCommand() == Command::PDNAX) { + command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), + config.memSpec.tXP); + } else if (lastCommandOnBank.getCommand() == Command::SREFX) { + command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), + config.memSpec.tXSR); + } else if (lastCommandOnBank.getCommand() == Command::AutoRefresh) { + command.establishMinDistanceFromStart(lastCommandOnBank.getStart(), + config.memSpec.tRFC); + } else + reportFatal("Refresh Checker", + "Refresh can not follow " + commandToString(lastCommandOnBank.getCommand())); } - } - else - { - for (unsigned int bank = 0; bank < config.memSpec.NumberOfBanks; ++bank) - { + } else { + for (unsigned int bank = 0; bank < config.memSpec.NumberOfBanks; ++bank) { ScheduledCommand lastCommand = state.getLastScheduledCommand(Bank(bank)); - if (lastCommand.isValidCommand()) - { - if(lastCommand.getCommand() == Command::Precharge || lastCommand.getCommand() == Command::PrechargeAll) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tRP); - } - else if(lastCommand.getCommand() == Command::Activate) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tRCD); - } - else if (lastCommand.getCommand() == Command::ReadA) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tRTP + config.memSpec.tRP); - } - else if(lastCommand.getCommand() == Command::WriteA) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tWL + getWriteAccessTime() + config.memSpec.tWR + config.memSpec.tRP); - } - else if (lastCommand.getCommand() == Command::PDNAX || lastCommand.getCommand() == Command::PDNPX) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tXP); - } - else if (lastCommand.getCommand() == Command::SREFX) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tXSR); - } - else if (lastCommand.getCommand() == Command::AutoRefresh) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tRFC); - } - else - reportFatal("Refresh Checker", "Refresh can not follow " + commandToString(lastCommand.getCommand())); + if (lastCommand.isValidCommand()) { + if (lastCommand.getCommand() == Command::Precharge + || lastCommand.getCommand() == Command::PrechargeAll) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tRP); + } else if (lastCommand.getCommand() == Command::Activate) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tRCD); + } else if (lastCommand.getCommand() == Command::ReadA) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tRTP + config.memSpec.tRP); + } else if (lastCommand.getCommand() == Command::WriteA) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tWL + getWriteAccessTime() + config.memSpec.tWR + + config.memSpec.tRP); + } else if (lastCommand.getCommand() == Command::PDNAX + || lastCommand.getCommand() == Command::PDNPX) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tXP); + } else if (lastCommand.getCommand() == Command::SREFX) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tXSR); + } else if (lastCommand.getCommand() == Command::AutoRefresh) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tRFC); + } else + reportFatal("Refresh Checker", + "Refresh can not follow " + commandToString(lastCommand.getCommand())); } } } diff --git a/DRAMSys/library/src/controller/core/scheduling/checker/RefreshChecker.h b/DRAMSys/library/src/controller/core/scheduling/checker/RefreshChecker.h index 1e0a72ad..1dd8655d 100644 --- a/DRAMSys/library/src/controller/core/scheduling/checker/RefreshChecker.h +++ b/DRAMSys/library/src/controller/core/scheduling/checker/RefreshChecker.h @@ -46,19 +46,20 @@ class RefreshChecker: public ICommandChecker { public: - RefreshChecker(const Configuration& config, ControllerState& state) : - config(config), state(state) - { - } - virtual ~RefreshChecker() - { - } + RefreshChecker(const Configuration &config, ControllerState &state) : + config(config), state(state) + { + } + virtual ~RefreshChecker() + { + } - virtual void delayToSatisfyConstraints(ScheduledCommand& command) const override; + virtual void delayToSatisfyConstraints(ScheduledCommand &command) const + override; private: - const Configuration& config; - ControllerState& state; + const Configuration &config; + ControllerState &state; }; diff --git a/DRAMSys/library/src/controller/core/scheduling/checker/WriteChecker.cpp b/DRAMSys/library/src/controller/core/scheduling/checker/WriteChecker.cpp index e02130bb..a356caa8 100644 --- a/DRAMSys/library/src/controller/core/scheduling/checker/WriteChecker.cpp +++ b/DRAMSys/library/src/controller/core/scheduling/checker/WriteChecker.cpp @@ -41,88 +41,93 @@ using namespace std; -void WriteChecker::delayToSatisfyConstraints(ScheduledCommand& command) const +void WriteChecker::delayToSatisfyConstraints(ScheduledCommand &command) const { - sc_assert(command.getCommand() == Command::Write || command.getCommand() == Command::WriteA); + sc_assert(command.getCommand() == Command::Write + || command.getCommand() == Command::WriteA); - ScheduledCommand lastCommand = state.getLastScheduledCommand(command.getBank()); + ScheduledCommand lastCommand = state.getLastScheduledCommand(command.getBank()); - if (lastCommand.isValidCommand()) - { - if (lastCommand.getCommand() == Command::Activate) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tRCD); - } - else if (lastCommand.getCommand() == Command::Read) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), WriteChecker::readToWrite(lastCommand, command)); - } - else if (lastCommand.getCommand() == Command::Write) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), WriteChecker::writeToWrite(lastCommand, command)); - } - else if (lastCommand.getCommand() == Command::PDNPX || lastCommand.getCommand() == Command::PDNAX) - { - command.establishMinDistanceFromStart(lastCommand.getStart(), config.memSpec.tXP); - } - else - reportFatal("Write Checker", "Write can not follow " + commandToString(lastCommand.getCommand())); - } + if (lastCommand.isValidCommand()) { + if (lastCommand.getCommand() == Command::Activate) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tRCD); + } else if (lastCommand.getCommand() == Command::Read) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + WriteChecker::readToWrite(lastCommand, command)); + } else if (lastCommand.getCommand() == Command::Write) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + WriteChecker::writeToWrite(lastCommand, command)); + } else if (lastCommand.getCommand() == Command::PDNPX + || lastCommand.getCommand() == Command::PDNAX) { + command.establishMinDistanceFromStart(lastCommand.getStart(), + config.memSpec.tXP); + } else + reportFatal("Write Checker", + "Write can not follow " + commandToString(lastCommand.getCommand())); + } - while (!state.bus.isFree(command.getStart()) || collidesOnDataStrobe(command)) - { - command.delayStart(config.memSpec.clk); - } + while (!state.bus.isFree(command.getStart()) || collidesOnDataStrobe(command)) { + command.delayStart(config.memSpec.clk); + } } -bool WriteChecker::collidesOnDataStrobe(ScheduledCommand& write) const +bool WriteChecker::collidesOnDataStrobe(ScheduledCommand &write) const { - for (ScheduledCommand& strobeCommand : state.lastDataStrobeCommands) - { - if (collidesWithStrobeCommand(write, strobeCommand)) - return true; - } + for (ScheduledCommand &strobeCommand : state.lastDataStrobeCommands) { + if (collidesWithStrobeCommand(write, strobeCommand)) + return true; + } - return false; + return false; } -bool WriteChecker::collidesWithStrobeCommand(ScheduledCommand& write, ScheduledCommand& strobeCommand) const +bool WriteChecker::collidesWithStrobeCommand(ScheduledCommand &write, + ScheduledCommand &strobeCommand) const { - if (strobeCommand.getCommand() == Command::Write || strobeCommand.getCommand() == Command::WriteA) - { - return getDistance(write.getStart(),strobeCommand.getStart()) < WriteChecker::writeToWrite(strobeCommand,write); - } - else if (strobeCommand.getCommand() == Command::Read || strobeCommand.getCommand() == Command::ReadA) - { - if (strobeCommand.getStart() >= write.getStart()) - return getDistance(write.getStart(),strobeCommand.getStart()) < ReadChecker::writeToRead(write, strobeCommand); - else - return getDistance(strobeCommand.getStart(), write.getStart()) < WriteChecker::readToWrite(strobeCommand, write); - } - else - { - reportFatal("Write Checker", - "Invalid strobeCommand in data strobe commands " + commandToString(strobeCommand.getCommand())); - return true; - } + if (strobeCommand.getCommand() == Command::Write + || strobeCommand.getCommand() == Command::WriteA) { + return getDistance(write.getStart(), + strobeCommand.getStart()) < WriteChecker::writeToWrite(strobeCommand, write); + } else if (strobeCommand.getCommand() == Command::Read + || strobeCommand.getCommand() == Command::ReadA) { + if (strobeCommand.getStart() >= write.getStart()) + return getDistance(write.getStart(), + strobeCommand.getStart()) < ReadChecker::writeToRead(write, strobeCommand); + else + return getDistance(strobeCommand.getStart(), + write.getStart()) < WriteChecker::readToWrite(strobeCommand, write); + } else { + reportFatal("Write Checker", + "Invalid strobeCommand in data strobe commands " + commandToString( + strobeCommand.getCommand())); + return true; + } } -sc_time WriteChecker::writeToWrite(ScheduledCommand& firstWrite, ScheduledCommand& secondWrite) +sc_time WriteChecker::writeToWrite(ScheduledCommand &firstWrite, + ScheduledCommand &secondWrite) { - sc_assert(firstWrite.getCommand() == Command::Write || firstWrite.getCommand() == Command::WriteA); - sc_assert(secondWrite.getCommand() == Command::Write || secondWrite.getCommand() == Command::WriteA); + sc_assert(firstWrite.getCommand() == Command::Write + || firstWrite.getCommand() == Command::WriteA); + sc_assert(secondWrite.getCommand() == Command::Write + || secondWrite.getCommand() == Command::WriteA); - MemSpec& config = Configuration::getInstance().memSpec; - sc_time tCCD = (firstWrite.getBankGroup() == secondWrite.getBankGroup()) ? config.tCCD_L : config.tCCD_S; - return max(tCCD, getWriteAccessTime()); + MemSpec &config = Configuration::getInstance().memSpec; + sc_time tCCD = (firstWrite.getBankGroup() == secondWrite.getBankGroup()) ? + config.tCCD_L : config.tCCD_S; + return max(tCCD, getWriteAccessTime()); } -sc_time WriteChecker::readToWrite(ScheduledCommand& read __attribute__((unused)), ScheduledCommand& write __attribute__((unused))) +sc_time WriteChecker::readToWrite(ScheduledCommand &read __attribute__(( + unused)), ScheduledCommand &write __attribute__((unused))) { - sc_assert(read.getCommand() == Command::Read || read.getCommand() == Command::ReadA); - sc_assert(write.getCommand() == Command::Write || write.getCommand() == Command::WriteA); + sc_assert(read.getCommand() == Command::Read + || read.getCommand() == Command::ReadA); + sc_assert(write.getCommand() == Command::Write + || write.getCommand() == Command::WriteA); - MemSpec& config = Configuration::getInstance().memSpec; - return config.tRL + getReadAccessTime() - config.tWL + config.clk * 2; + MemSpec &config = Configuration::getInstance().memSpec; + return config.tRL + getReadAccessTime() - config.tWL + config.clk * 2; } diff --git a/DRAMSys/library/src/controller/core/scheduling/checker/WriteChecker.h b/DRAMSys/library/src/controller/core/scheduling/checker/WriteChecker.h index d2831a29..5b8c46f8 100644 --- a/DRAMSys/library/src/controller/core/scheduling/checker/WriteChecker.h +++ b/DRAMSys/library/src/controller/core/scheduling/checker/WriteChecker.h @@ -45,18 +45,22 @@ class WriteChecker: public ICommandChecker { public: - WriteChecker(const Configuration& config, ControllerState& state) : config(config), state(state) {} - virtual ~WriteChecker() {} + WriteChecker(const Configuration &config, + ControllerState &state) : config(config), state(state) {} + virtual ~WriteChecker() {} - virtual void delayToSatisfyConstraints(ScheduledCommand& command) const override; + virtual void delayToSatisfyConstraints(ScheduledCommand &command) const + override; - static sc_time writeToWrite(ScheduledCommand& firstWrite, ScheduledCommand& secondWrite); - static sc_time readToWrite(ScheduledCommand& read, ScheduledCommand& write); + static sc_time writeToWrite(ScheduledCommand &firstWrite, + ScheduledCommand &secondWrite); + static sc_time readToWrite(ScheduledCommand &read, ScheduledCommand &write); private: - bool collidesOnDataStrobe(ScheduledCommand& write) const; - bool collidesWithStrobeCommand(ScheduledCommand& write, ScheduledCommand& strobeCommand) const; - const Configuration& config; - ControllerState& state; + bool collidesOnDataStrobe(ScheduledCommand &write) const; + bool collidesWithStrobeCommand(ScheduledCommand &write, + ScheduledCommand &strobeCommand) const; + const Configuration &config; + ControllerState &state; }; diff --git a/DRAMSys/library/src/controller/scheduler/Fifo.cpp b/DRAMSys/library/src/controller/scheduler/Fifo.cpp index 60aecf5b..fe041319 100644 --- a/DRAMSys/library/src/controller/scheduler/Fifo.cpp +++ b/DRAMSys/library/src/controller/scheduler/Fifo.cpp @@ -38,31 +38,30 @@ using namespace std; -void Fifo::schedule(gp* payload) +void Fifo::schedule(gp *payload) { buffer[DramExtension::getExtension(payload).getBank()].emplace_back(payload); } -pair Fifo::getNextRequest(Bank bank) +pair Fifo::getNextRequest(Bank bank) { - if(!buffer[bank].empty()) - { - gp* payload = buffer[bank].front(); + if (!buffer[bank].empty()) { + gp *payload = buffer[bank].front(); Command command = IScheduler::getNextCommand(*payload); - if(command == Command::Read || command == Command::ReadA || command == Command::Write || command == Command::WriteA) - { + if (command == Command::Read || command == Command::ReadA + || command == Command::Write || command == Command::WriteA) { buffer[bank].pop_front(); } - return pair(command, payload); + return pair(command, payload); } - return pair(Command::NOP, NULL); + return pair(Command::NOP, NULL); } -gp* Fifo::getPendingRequest(Bank /*bank*/) +gp *Fifo::getPendingRequest(Bank /*bank*/) { - return NULL; + return NULL; } diff --git a/DRAMSys/library/src/controller/scheduler/Fifo.h b/DRAMSys/library/src/controller/scheduler/Fifo.h index 1b060b12..7194fad6 100644 --- a/DRAMSys/library/src/controller/scheduler/Fifo.h +++ b/DRAMSys/library/src/controller/scheduler/Fifo.h @@ -50,12 +50,13 @@ public: Fifo(ControllerCore &controllerCore) : IScheduler(controllerCore) {} virtual ~Fifo() {} - void schedule(gp* payload) override; - std::pair getNextRequest(Bank bank) override; - virtual gp* getPendingRequest(Bank bank) override; + void schedule(gp *payload) override; + std::pair getNextRequest( + Bank bank) override; + virtual gp *getPendingRequest(Bank bank) override; private: - std::map> buffer; + std::map> buffer; }; #endif /* FIFO_H_ */ diff --git a/DRAMSys/library/src/controller/scheduler/FifoStrict.cpp b/DRAMSys/library/src/controller/scheduler/FifoStrict.cpp index 6b6b1caa..035031d0 100644 --- a/DRAMSys/library/src/controller/scheduler/FifoStrict.cpp +++ b/DRAMSys/library/src/controller/scheduler/FifoStrict.cpp @@ -44,7 +44,8 @@ void FifoStrict::schedule(tlm::tlm_generic_payload *payload) buffer.push_back(std::pair(bank, payload)); } -std::pair FifoStrict::getNextRequest(Bank bank) +std::pair FifoStrict::getNextRequest( + Bank bank) { if (!buffer.empty()) { @@ -76,7 +77,7 @@ std::pair FifoStrict::getNextRequest(Bank b // Command command = IScheduler::getNextCommand(*payload); - if(commandIsIn(command, {Command::Read, Command::Write, Command::ReadA, Command::WriteA})) { + if (commandIsIn(command, {Command::Read, Command::Write, Command::ReadA, Command::WriteA})) { buffer.pop_front(); // Check if the next transaction is a blocked read or write @@ -91,7 +92,7 @@ std::pair FifoStrict::getNextRequest(Bank b } } - return pair(command, payload); + return pair(command, payload); } else { // The next request in the FIFO is NOT for the bank passed as parameter. @@ -115,20 +116,21 @@ std::pair FifoStrict::getNextRequest(Bank b // the next command for this request is read or write // NOP will be returned and no operation will be // performed. - return pair(Command::NOP, NULL); - } else { + return pair(Command::NOP, NULL); + } + else { // Commands other than read and write are issued normally. - return pair(command, payload); + return pair(command, payload); } } } } } - return pair(Command::NOP, NULL); + return pair(Command::NOP, NULL); } -gp* FifoStrict::getPendingRequest(Bank /*bank*/) +gp *FifoStrict::getPendingRequest(Bank /*bank*/) { - return NULL; + return NULL; } diff --git a/DRAMSys/library/src/controller/scheduler/FifoStrict.h b/DRAMSys/library/src/controller/scheduler/FifoStrict.h index 855f7ff3..74e85b2e 100644 --- a/DRAMSys/library/src/controller/scheduler/FifoStrict.h +++ b/DRAMSys/library/src/controller/scheduler/FifoStrict.h @@ -51,12 +51,15 @@ class FifoStrict : public IScheduler { public: IController &controller; - FifoStrict(IController &controller, ControllerCore &controllerCore) : IScheduler(controllerCore), controller(controller) {} + FifoStrict(IController &controller, + ControllerCore &controllerCore) : IScheduler(controllerCore), + controller(controller) {} virtual ~FifoStrict() {} - void schedule(gp* payload) override; - std::pair getNextRequest(Bank bank) override; - virtual gp* getPendingRequest(Bank bank) override; + void schedule(gp *payload) override; + std::pair getNextRequest( + Bank bank) override; + virtual gp *getPendingRequest(Bank bank) override; private: std::deque> buffer; diff --git a/DRAMSys/library/src/controller/scheduler/Fr_Fcfs.cpp b/DRAMSys/library/src/controller/scheduler/Fr_Fcfs.cpp index dec43cd2..a50212e6 100644 --- a/DRAMSys/library/src/controller/scheduler/Fr_Fcfs.cpp +++ b/DRAMSys/library/src/controller/scheduler/Fr_Fcfs.cpp @@ -65,32 +65,30 @@ void FR_FCFS::schedule(gp *payload) // should provide a true or false when the placement into the buffer worked // out or not (?). buffer[DramExtension::getExtension(payload).getBank()] - .emplace_back(payload); + .emplace_back(payload); } -std::pair FR_FCFS::getNextRequest(Bank bank) +std::pair FR_FCFS::getNextRequest(Bank bank) { // If the bank is empty like Bank0 in the example we do nothing - if(buffer[bank].empty()) - { - return pair(Command::NOP, NULL); + if (buffer[bank].empty()) { + return pair(Command::NOP, NULL); } // In FR_FCFS row hits have always the highest priority, therefore we search // for row hits. If we find a row hit, we remove the transaction from the // queue and send it to the DRAM. - deque::iterator it = FindRowHit(bank); - if(it != buffer[bank].end()) - { - gp* payload = *it; + deque::iterator it = FindRowHit(bank); + if (it != buffer[bank].end()) { + gp *payload = *it; buffer[bank].erase(it); - return pair(getReadWriteCommand(*payload), payload); + return pair(getReadWriteCommand(*payload), payload); } // If there is no row hit, the FR_FCFS takes always the oldest transaction // in the buffer, i.e. the transaction in the front. - return pair(getNextCommand(buffer[bank].front()), - buffer[bank].front()); + return pair(getNextCommand(buffer[bank].front()), + buffer[bank].front()); } // This function searches for a row hit in the scheduling queue of the specific @@ -100,21 +98,19 @@ std::pair FR_FCFS::getNextRequest(Bank bank) // deque container. The past-the-end element is the theoretical element that // would follow the last element in the deque container. It does not point to // any element, and thus shall not be dereferenced. -deque::iterator FR_FCFS::FindRowHit(Bank bank) +deque::iterator FR_FCFS::FindRowHit(Bank bank) { - deque &queue = buffer[bank]; + deque &queue = buffer[bank]; - if(!controllerCore.getRowBufferStates().rowBufferIsOpen(bank)) + if (!controllerCore.getRowBufferStates().rowBufferIsOpen(bank)) return queue.end(); // Traverse the scheduling queue of the specific bank: - for(auto it = queue.begin(); it!=queue.end(); it++) - { - gp* payload = *it; + for (auto it = queue.begin(); it != queue.end(); it++) { + gp *payload = *it; //Found row-hit and return the according iterator - if(DramExtension::getRow(payload) - == controllerCore.getRowBufferStates().getRowInRowBuffer(bank)) - { + if (DramExtension::getRow(payload) + == controllerCore.getRowBufferStates().getRowInRowBuffer(bank)) { return it; } } @@ -122,7 +118,7 @@ deque::iterator FR_FCFS::FindRowHit(Bank bank) return queue.end(); } -gp* FR_FCFS::getPendingRequest(Bank /*bank*/) +gp *FR_FCFS::getPendingRequest(Bank /*bank*/) { - return NULL; + return NULL; } diff --git a/DRAMSys/library/src/controller/scheduler/Fr_Fcfs.h b/DRAMSys/library/src/controller/scheduler/Fr_Fcfs.h index ece2b5b4..02b46ca0 100644 --- a/DRAMSys/library/src/controller/scheduler/Fr_Fcfs.h +++ b/DRAMSys/library/src/controller/scheduler/Fr_Fcfs.h @@ -48,16 +48,17 @@ class FR_FCFS : public IScheduler { public: - FR_FCFS(ControllerCore &controllerCore) : IScheduler(controllerCore){} - virtual ~FR_FCFS(){} + FR_FCFS(ControllerCore &controllerCore) : IScheduler(controllerCore) {} + virtual ~FR_FCFS() {} - void schedule(gp* payload) override; - std::pair getNextRequest(Bank bank) override; - virtual gp* getPendingRequest(Bank bank) override; + void schedule(gp *payload) override; + std::pair getNextRequest( + Bank bank) override; + virtual gp *getPendingRequest(Bank bank) override; protected: - std::map> buffer; - std::deque::iterator FindRowHit(Bank bank); + std::map> buffer; + std::deque::iterator FindRowHit(Bank bank); private: diff --git a/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_grouper.cpp b/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_grouper.cpp index 735c0045..40a8258e 100644 --- a/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_grouper.cpp +++ b/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_grouper.cpp @@ -40,56 +40,43 @@ // TODO: what is missed is a check if the buffers are full. This will only work // if we have buffers with a fixed size (Prado's future patch). -std::pair FR_FCFS_GRP::getNextRequest(Bank bank) +std::pair FR_FCFS_GRP::getNextRequest(Bank bank) { // If the bank is empty we do nothing: - if(buffer[bank].empty()) - { - return pair(Command::NOP, NULL); + if (buffer[bank].empty()) { + return pair(Command::NOP, NULL); } // If we are in write mode we should check if we should switch to read mode // because there are no writes anymore in the buffer. - if(readMode == false) - { - if(getNumberOfRequest(tlm::TLM_WRITE_COMMAND) == 0) - { + if (readMode == false) { + if (getNumberOfRequest(tlm::TLM_WRITE_COMMAND) == 0) { readMode = true; } - } - else // If we are in read mode but all reads are served we switch to write - { - if(getNumberOfRequest(tlm::TLM_READ_COMMAND) == 0) - { + } else { // If we are in read mode but all reads are served we switch to write + if (getNumberOfRequest(tlm::TLM_READ_COMMAND) == 0) { readMode = false; } } // Now lets search for read and write commands. However keep in mind that // readMode is a shared variable for all the banks! - if(readMode == true) - { + if (readMode == true) { // 1. Seach for read hit: - for(auto it = buffer[bank].begin(); it!=buffer[bank].end(); it++) - { - gp* read = *it; + for (auto it = buffer[bank].begin(); it != buffer[bank].end(); it++) { + gp *read = *it; - if(read->get_command() == tlm::TLM_READ_COMMAND) - { + if (read->get_command() == tlm::TLM_READ_COMMAND) { // If there is a row hit: - if(DramExtension::getRow(read) - == controllerCore.getRowBufferStates() - .getRowInRowBuffer(bank)) - { - if(hazardDetection(bank, it) == false) - { + if (DramExtension::getRow(read) + == controllerCore.getRowBufferStates() + .getRowInRowBuffer(bank)) { + if (hazardDetection(bank, it) == false) { buffer[bank].erase(it); printDebugMessage("Read Hit found"); - return pair(getReadWriteCommand(*read), - read); - } - else - { + return pair(getReadWriteCommand(*read), + read); + } else { // If there was a hazard, switch the mode and try again: readMode = false; return getNextRequest(bank); @@ -99,68 +86,55 @@ std::pair FR_FCFS_GRP::getNextRequest(Bank bank) } // 2. Search for read miss: - for(auto it = buffer[bank].begin(); it!=buffer[bank].end(); it++) - { - gp* read = *it; + for (auto it = buffer[bank].begin(); it != buffer[bank].end(); it++) { + gp *read = *it; - if(read->get_command() == tlm::TLM_READ_COMMAND) - { - if(hazardDetection(bank, it) == false) - { + if (read->get_command() == tlm::TLM_READ_COMMAND) { + if (hazardDetection(bank, it) == false) { printDebugMessage("Read miss found"); - return pair(getNextCommand(read),read); - } - else - { + return pair(getNextCommand(read), read); + } else { // If there was a hazard, switch the mode and try again: readMode = false; return getNextRequest(bank); } } } - } - else // write mode: - { + } else { // write mode: // 3. Search for write hit: - for(auto it = buffer[bank].begin(); it!=buffer[bank].end(); it++) - { - gp* write = *it; + for (auto it = buffer[bank].begin(); it != buffer[bank].end(); it++) { + gp *write = *it; - if(write->get_command() == tlm::TLM_WRITE_COMMAND) - { + if (write->get_command() == tlm::TLM_WRITE_COMMAND) { // If there is a row hit: - if(DramExtension::getRow(write) + if (DramExtension::getRow(write) == controllerCore.getRowBufferStates() - .getRowInRowBuffer(bank)) - { + .getRowInRowBuffer(bank)) { buffer[bank].erase(it); printDebugMessage("Write Hit found"); - return pair(getReadWriteCommand(*write), - write); + return pair(getReadWriteCommand(*write), + write); } } } // 4. Search for write miss: - for(auto it = buffer[bank].begin(); it!=buffer[bank].end(); it++) - { - gp* write = *it; + for (auto it = buffer[bank].begin(); it != buffer[bank].end(); it++) { + gp *write = *it; - if(write->get_command() == tlm::TLM_WRITE_COMMAND) - { + if (write->get_command() == tlm::TLM_WRITE_COMMAND) { printDebugMessage("Write miss found"); - return pair(getNextCommand(write),write); + return pair(getNextCommand(write), write); } } } // If nothing was found we check the other banks before we switch the mode: - pair other(Command::NOP, NULL); + pair other(Command::NOP, NULL); unsigned int B = Configuration::getInstance().memSpec.NumberOfBanks; - for(unsigned int i=1; ischeduleNextFromScheduler(nextBank); } @@ -175,21 +149,18 @@ std::pair FR_FCFS_GRP::getNextRequest(Bank bank) // There is a hazard if a read is found which will be scheduled before a write // to the same column and the same row of the same bank: -bool FR_FCFS_GRP::hazardDetection(Bank bank, std::deque::iterator ext) +bool FR_FCFS_GRP::hazardDetection(Bank bank, std::deque::iterator ext) { - gp* read = *ext; + gp *read = *ext; //for(unsigned long i=0; i < id; i++) - for(auto it = buffer[bank].begin(); it!=ext; it++) - { - gp* write = *it; - if(write->get_command() == tlm::TLM_WRITE_COMMAND) - { - if((DramExtension::getExtension(read).getColumn() - == DramExtension::getExtension(write).getColumn()) - && (DramExtension::getExtension(read).getRow() - == DramExtension::getExtension(write).getRow())) - { + for (auto it = buffer[bank].begin(); it != ext; it++) { + gp *write = *it; + if (write->get_command() == tlm::TLM_WRITE_COMMAND) { + if ((DramExtension::getExtension(read).getColumn() + == DramExtension::getExtension(write).getColumn()) + && (DramExtension::getExtension(read).getRow() + == DramExtension::getExtension(write).getRow())) { printDebugMessage("Hazard Detected"); return true; } @@ -202,15 +173,12 @@ bool FR_FCFS_GRP::hazardDetection(Bank bank, std::deque::iterator ext) unsigned int FR_FCFS_GRP::getNumberOfRequest(tlm::tlm_command cmd) { unsigned int numberOfRequests = 0; - for(unsigned int i = 0; - i < Configuration::getInstance().memSpec.NumberOfBanks; - i++) - { - for(auto it = buffer[i].begin(); it!=buffer[i].end(); it++) - { - gp* trans = *it; - if(trans->get_command()==cmd) - { + for (unsigned int i = 0; + i < Configuration::getInstance().memSpec.NumberOfBanks; + i++) { + for (auto it = buffer[i].begin(); it != buffer[i].end(); it++) { + gp *trans = *it; + if (trans->get_command() == cmd) { numberOfRequests++; } } diff --git a/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_grouper.h b/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_grouper.h index d4db780d..6ae8ff08 100644 --- a/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_grouper.h +++ b/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_grouper.h @@ -44,20 +44,20 @@ class Controller; class FR_FCFS_GRP : public FR_FCFS { public: - FR_FCFS_GRP(ControllerCore &controllerCore, Controller * c) : + FR_FCFS_GRP(ControllerCore &controllerCore, Controller *c) : FR_FCFS(controllerCore), ctrl(c), readMode(true) { } - std::pair - getNextRequest(Bank bank) override; + std::pair + getNextRequest(Bank bank) override; private: - Controller * ctrl; - bool hazardDetection(Bank bank, std::deque::iterator ext); + Controller *ctrl; + bool hazardDetection(Bank bank, std::deque::iterator ext); unsigned int getNumberOfRequest(tlm::tlm_command cmd); void printDebugMessage(std::string message); bool readMode; diff --git a/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_read_priority.cpp b/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_read_priority.cpp index 57a5b7b3..66b1f260 100644 --- a/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_read_priority.cpp +++ b/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_read_priority.cpp @@ -38,12 +38,11 @@ // The FR_FCFS_Read_Priority works exactly like the FR_FCFS but reads are // prioratized over writes. For detailed documentation look into the FR_FCFS. -std::pair FR_FCFS_RP::getNextRequest(Bank bank) +std::pair FR_FCFS_RP::getNextRequest(Bank bank) { // If the bank is empty like Bank0 in the example we do nothing: - if(buffer[bank].empty()) - { - return pair(Command::NOP, NULL); + if (buffer[bank].empty()) { + return pair(Command::NOP, NULL); } // Order of Priority: @@ -53,40 +52,33 @@ std::pair FR_FCFS_RP::getNextRequest(Bank bank) // 4. Write Miss // 1. Seach for read hit: - for(auto it = buffer[bank].begin(); it!=buffer[bank].end(); it++) - { - gp* read = *it; + for (auto it = buffer[bank].begin(); it != buffer[bank].end(); it++) { + gp *read = *it; - if(read->get_command() == tlm::TLM_READ_COMMAND) - { + if (read->get_command() == tlm::TLM_READ_COMMAND) { // If there is a row hit: - if(DramExtension::getRow(read) - == controllerCore.getRowBufferStates().getRowInRowBuffer(bank)) - { - if(hazardDetection(bank, it) == false) - { + if (DramExtension::getRow(read) + == controllerCore.getRowBufferStates().getRowInRowBuffer(bank)) { + if (hazardDetection(bank, it) == false) { buffer[bank].erase(it); printDebugMessage("Read Hit found"); - return pair(getReadWriteCommand(*read),read); + return pair(getReadWriteCommand(*read), read); } } } } // 2. Search for write hit: - for(auto it = buffer[bank].begin(); it!=buffer[bank].end(); it++) - { - gp* write = *it; + for (auto it = buffer[bank].begin(); it != buffer[bank].end(); it++) { + gp *write = *it; - if(write->get_command() == tlm::TLM_WRITE_COMMAND) - { + if (write->get_command() == tlm::TLM_WRITE_COMMAND) { // If there is a row hit: - if(DramExtension::getRow(write) - == controllerCore.getRowBufferStates().getRowInRowBuffer(bank)) - { + if (DramExtension::getRow(write) + == controllerCore.getRowBufferStates().getRowInRowBuffer(bank)) { buffer[bank].erase(it); printDebugMessage("Write Hit found"); - return pair(getReadWriteCommand(*write),write); + return pair(getReadWriteCommand(*write), write); } } } @@ -94,29 +86,24 @@ std::pair FR_FCFS_RP::getNextRequest(Bank bank) // For now return the oldest request but prefere also reads before writes: // 3. Search for read miss: - for(auto it = buffer[bank].begin(); it!=buffer[bank].end(); it++) - { - gp* read = *it; + for (auto it = buffer[bank].begin(); it != buffer[bank].end(); it++) { + gp *read = *it; - if(read->get_command() == tlm::TLM_READ_COMMAND) - { - if(hazardDetection(bank, it) == false) - { + if (read->get_command() == tlm::TLM_READ_COMMAND) { + if (hazardDetection(bank, it) == false) { printDebugMessage("Read miss found"); - return pair(getNextCommand(read),read); + return pair(getNextCommand(read), read); } } } // 3. Search for write miss: - for(auto it = buffer[bank].begin(); it!=buffer[bank].end(); it++) - { - gp* write = *it; + for (auto it = buffer[bank].begin(); it != buffer[bank].end(); it++) { + gp *write = *it; - if(write->get_command() == tlm::TLM_WRITE_COMMAND) - { + if (write->get_command() == tlm::TLM_WRITE_COMMAND) { printDebugMessage("Write miss found"); - return pair(getNextCommand(write),write); + return pair(getNextCommand(write), write); } } @@ -125,21 +112,18 @@ std::pair FR_FCFS_RP::getNextRequest(Bank bank) // There is a hazard if a read is found which will be scheduled before a write // to the same column and the same row of the same bank: -bool FR_FCFS_RP::hazardDetection(Bank bank, std::deque::iterator ext) +bool FR_FCFS_RP::hazardDetection(Bank bank, std::deque::iterator ext) { - gp* read = *ext; + gp *read = *ext; //for(unsigned long i=0; i < id; i++) - for(auto it = buffer[bank].begin(); it!=ext; it++) - { - gp* write = *it; - if(write->get_command() == tlm::TLM_WRITE_COMMAND) - { - if((DramExtension::getExtension(read).getColumn() - == DramExtension::getExtension(write).getColumn()) - && (DramExtension::getExtension(read).getRow() - == DramExtension::getExtension(write).getRow())) - { + for (auto it = buffer[bank].begin(); it != ext; it++) { + gp *write = *it; + if (write->get_command() == tlm::TLM_WRITE_COMMAND) { + if ((DramExtension::getExtension(read).getColumn() + == DramExtension::getExtension(write).getColumn()) + && (DramExtension::getExtension(read).getRow() + == DramExtension::getExtension(write).getRow())) { printDebugMessage("Hazard Detected"); return true; } diff --git a/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_read_priority.h b/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_read_priority.h index 1b00d732..fac0af85 100644 --- a/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_read_priority.h +++ b/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_read_priority.h @@ -43,12 +43,12 @@ class FR_FCFS_RP : public FR_FCFS public: FR_FCFS_RP(ControllerCore &controllerCore) : FR_FCFS(controllerCore) {} - std::pair - getNextRequest(Bank bank) override; + std::pair + getNextRequest(Bank bank) override; private: - bool hazardDetection(Bank bank, std::deque::iterator ext); + bool hazardDetection(Bank bank, std::deque::iterator ext); void printDebugMessage(std::string message); }; diff --git a/DRAMSys/library/src/controller/scheduler/IScheduler.cpp b/DRAMSys/library/src/controller/scheduler/IScheduler.cpp index 1f109d25..09d53b47 100644 --- a/DRAMSys/library/src/controller/scheduler/IScheduler.cpp +++ b/DRAMSys/library/src/controller/scheduler/IScheduler.cpp @@ -47,20 +47,16 @@ void IScheduler::printDebugMessage(std::string message) } // Get the next command that is necessary to process the request representend by the payload -Command IScheduler::getNextCommand(gp& payload) +Command IScheduler::getNextCommand(gp &payload) { Bank bank = DramExtension::getBank(payload); - if(!controllerCore.getRowBufferStates().rowBufferIsOpen(bank)) - { + if (!controllerCore.getRowBufferStates().rowBufferIsOpen(bank)) { return Command::Activate; - } - else if(controllerCore.getRowBufferStates().rowBufferIsOpen(bank) && - controllerCore.getRowBufferStates().getRowInRowBuffer(bank) != DramExtension::getRow(payload)) - { + } else if (controllerCore.getRowBufferStates().rowBufferIsOpen(bank) && + controllerCore.getRowBufferStates().getRowInRowBuffer(bank) != + DramExtension::getRow(payload)) { return Command::Precharge; - } - else - { + } else { return getReadWriteCommand(payload); } } @@ -70,19 +66,16 @@ Command IScheduler::getNextCommand(gp *payload) return getNextCommand(*payload); } -Command IScheduler::getReadWriteCommand(gp& payload) +Command IScheduler::getReadWriteCommand(gp &payload) { - if (payload.get_command() == tlm::TLM_READ_COMMAND) - { - if(Configuration::getInstance().OpenPagePolicy) + if (payload.get_command() == tlm::TLM_READ_COMMAND) { + if (Configuration::getInstance().OpenPagePolicy) return Command::Read; else return Command::ReadA; - } - else - { - if(Configuration::getInstance().OpenPagePolicy) + } else { + if (Configuration::getInstance().OpenPagePolicy) return Command::Write; else return Command::WriteA; diff --git a/DRAMSys/library/src/controller/scheduler/IScheduler.h b/DRAMSys/library/src/controller/scheduler/IScheduler.h index efeebdc4..7d7837a6 100644 --- a/DRAMSys/library/src/controller/scheduler/IScheduler.h +++ b/DRAMSys/library/src/controller/scheduler/IScheduler.h @@ -49,12 +49,12 @@ typedef tlm::tlm_generic_payload gp; class IScheduler { public: - virtual ~IScheduler(){} - IScheduler(ControllerCore &controllerCore) : controllerCore(controllerCore){} + virtual ~IScheduler() {} + IScheduler(ControllerCore &controllerCore) : controllerCore(controllerCore) {} - virtual void schedule(gp* payload) = 0; - virtual std::pair getNextRequest(Bank bank) = 0; - virtual gp* getPendingRequest(Bank bank) = 0; + virtual void schedule(gp *payload) = 0; + virtual std::pair getNextRequest(Bank bank) = 0; + virtual gp *getPendingRequest(Bank bank) = 0; static std::string sendername; protected: diff --git a/DRAMSys/library/src/controller/scheduler/SMS.cpp b/DRAMSys/library/src/controller/scheduler/SMS.cpp index a6547998..9406237a 100644 --- a/DRAMSys/library/src/controller/scheduler/SMS.cpp +++ b/DRAMSys/library/src/controller/scheduler/SMS.cpp @@ -22,27 +22,25 @@ void SMS::schedule(gp *payload) } } -std::pair SMS::getNextRequest(Bank bank) +std::pair SMS::getNextRequest(Bank bank) { - if (bankBuffers[bank].empty()) - { + if (bankBuffers[bank].empty()) { debugManager.printDebugMessage(name(), "Get next request on bank " + to_string(bank.ID()) + " : EMPTY buffer"); - return pair(Command::NOP, NULL); - } - else - { - gp* payload = bankBuffers[bank].front(); + return pair(Command::NOP, NULL); + } else { + gp *payload = bankBuffers[bank].front(); Command command = IScheduler::getNextCommand(*payload); - if (command == Command::Read || command == Command::ReadA || command == Command::Write - || command == Command::WriteA) - { + if (command == Command::Read || command == Command::ReadA + || command == Command::Write + || command == Command::WriteA) { inFlightMemRequestCounter[DramExtension::getExtension(payload).getThread()]--; bankBuffers[bank].pop_front(); } - debugManager.printDebugMessage(name(), "Get next request on bank " + to_string(bank.ID())); - return pair(command, payload); + debugManager.printDebugMessage(name(), + "Get next request on bank " + to_string(bank.ID())); + return pair(command, payload); } } @@ -52,15 +50,15 @@ void SMS::batchScheduler() std::default_random_engine generator; std::bernoulli_distribution distribution((double) SJFprobability / 100.0); - while (true) - { + while (true) { updateMPKCs(memClk); if (isRequestBuffersEmpty()) { wait(newRequest); } else { multiBatchFormation(memClk); if (existReadyBatches()) { - if (!isSystemLightlyLoaded() && (existLowIntensityThread() || distribution(generator))) { + if (!isSystemLightlyLoaded() && (existLowIntensityThread() + || distribution(generator))) { pickSJF(); } else { pickRR(); @@ -82,23 +80,18 @@ bool SMS::pickSJF() { // find threads with ready batches std::vector threadsWithReadyBatches; - for (const auto &each : readyBatchInclusiveEndLocs) - { - if (!each.second.empty()) - { + for (const auto &each : readyBatchInclusiveEndLocs) { + if (!each.second.empty()) { // marked as thread with non-empty request buffer threadsWithReadyBatches.push_back(each.first); } } - if (!threadsWithReadyBatches.empty()) - { + if (!threadsWithReadyBatches.empty()) { // pick shortest-job thread among threads with non-empty request buffer Thread &minThread = threadsWithReadyBatches.front(); - for (const auto &thread : threadsWithReadyBatches) - { - if (inFlightMemRequestCounter[thread] < inFlightMemRequestCounter[minThread]) - { + for (const auto &thread : threadsWithReadyBatches) { + if (inFlightMemRequestCounter[thread] < inFlightMemRequestCounter[minThread]) { minThread = thread; } } @@ -108,9 +101,7 @@ bool SMS::pickSJF() debugManager.printDebugMessage(name(), "[SJF] Select ready batch of thread " + to_string(minThread.ID())); return true; - } - else - { + } else { return false; } } @@ -131,17 +122,16 @@ void SMS::drainOnePayloadFromReadybatch(const sc_time &memClk) const size_t &inclusiveEndLoc = lastSelectedThread->second.front(); assert(inclusiveEndLoc < requestBuffers.size()); - for (size_t i = 0; i <= inclusiveEndLoc; ++i) - { + for (size_t i = 0; i <= inclusiveEndLoc; ++i) { wait(memClk); - Bank bank = DramExtension::getExtension(requestBuffers[selectedThread].front()).getBank(); + Bank bank = DramExtension::getExtension( + requestBuffers[selectedThread].front()).getBank(); bankBuffers[bank].emplace_back(requestBuffers[selectedThread].front()); requestBuffers[selectedThread].pop_front(); // decrement inclusive end locations of ready batches // except this ready batch - for (size_t i = 1; i < readyBatchInclusiveEndLocs[selectedThread].size(); ++i) - { + for (size_t i = 1; i < readyBatchInclusiveEndLocs[selectedThread].size(); ++i) { --readyBatchInclusiveEndLocs[selectedThread][i]; } @@ -160,18 +150,17 @@ void SMS::drainOnePayloadFromReadybatch(const sc_time &memClk) */ bool SMS::pickRR() { - if (lastSelectedThread == readyBatchInclusiveEndLocs.end()) - { + if (lastSelectedThread == readyBatchInclusiveEndLocs.end()) { lastSelectedThread = readyBatchInclusiveEndLocs.begin(); if (!(*lastSelectedThread).second.empty()) { return true; } } - std::map>::iterator savedOriginalNextSelectedThread = lastSelectedThread; + std::map>::iterator savedOriginalNextSelectedThread = + lastSelectedThread; - do - { + do { lastSelectedThread++; if (lastSelectedThread == readyBatchInclusiveEndLocs.end()) { lastSelectedThread = readyBatchInclusiveEndLocs.begin(); @@ -182,11 +171,13 @@ bool SMS::pickRR() } while ((*lastSelectedThread).second.empty()); debugManager.printDebugMessage(name(), - "[RR] Select ready batch of thread " + to_string((*lastSelectedThread).first.ID())); + "[RR] Select ready batch of thread " + to_string(( + *lastSelectedThread).first.ID())); return true; } -bool SMS::isSystemLightlyLoaded() const { +bool SMS::isSystemLightlyLoaded() const +{ unsigned int totalRequest = 0; for (const auto &bankBuffer : bankBuffers) { totalRequest += bankBuffer.second.size(); @@ -194,7 +185,8 @@ bool SMS::isSystemLightlyLoaded() const { return (totalRequest <= LOW_SYSTEM_LOAD); } -bool SMS::existLowIntensityThread() const { +bool SMS::existLowIntensityThread() const +{ for (const auto &mpkcPerThread : MPKCs) { if (mpkcPerThread.second < LOW_MPKC) { return true; @@ -203,12 +195,15 @@ bool SMS::existLowIntensityThread() const { return false; } -bool SMS::isThresholdAgeExceeded(const Thread &thread, sc_time const &memClk, size_t const &inclusiveBeginLoc, size_t const &exclusiveEndLoc) { +bool SMS::isThresholdAgeExceeded(const Thread &thread, sc_time const &memClk, + size_t const &inclusiveBeginLoc, size_t const &exclusiveEndLoc) +{ assert((exclusiveEndLoc - inclusiveBeginLoc) >= 1); // find the oldest request in the thread's batch sc_time oldestGenerationTime = sc_time_stamp(); for (size_t i = inclusiveBeginLoc; i != exclusiveEndLoc; ++i) { - sc_time reqGenerationTime = GenerationExtension::getExtension(requestBuffers[thread][i]).TimeOfGeneration(); + sc_time reqGenerationTime = GenerationExtension::getExtension( + requestBuffers[thread][i]).TimeOfGeneration(); if (reqGenerationTime < oldestGenerationTime) { oldestGenerationTime = reqGenerationTime; } @@ -216,16 +211,19 @@ bool SMS::isThresholdAgeExceeded(const Thread &thread, sc_time const &memClk, si // check threshold age according to the thread's MPKC sc_time oldestRequestAge = sc_time_stamp() - oldestGenerationTime; - if ((MPKCs[thread] <= MEDIUM_MPKC) && (oldestRequestAge > (MEDIUM_THRESHOLD_AGE * memClk))) { + if ((MPKCs[thread] <= MEDIUM_MPKC) + && (oldestRequestAge > (MEDIUM_THRESHOLD_AGE * memClk))) { return true; - } else if ((MPKCs[thread] > MEDIUM_MPKC) && (oldestRequestAge > (HIGH_THRESHOLD_AGE * memClk))) { + } else if ((MPKCs[thread] > MEDIUM_MPKC) + && (oldestRequestAge > (HIGH_THRESHOLD_AGE * memClk))) { return true; } else { return false; } } -void SMS::updateMPKCs(sc_time const &memClk) { +void SMS::updateMPKCs(sc_time const &memClk) +{ if (sc_time_stamp() % (MPKC_RESET_CYCLE * memClk) <= memClk) { // reset for every 10k clk cycles for (const auto &cacheMiss : cacheMisses) { @@ -235,17 +233,20 @@ void SMS::updateMPKCs(sc_time const &memClk) { } else { // update MPKC for every thread for (const auto &cacheMiss : cacheMisses) { - MPKCs[cacheMiss.first] = (cacheMiss.second * 1000.0 * memClk) / (sc_time_stamp()); + MPKCs[cacheMiss.first] = (cacheMiss.second * 1000.0 * memClk) / + (sc_time_stamp()); } debugManager.printDebugMessage(name(), "Update MPKCs"); } } -bool SMS::isExceededReqBufferSize(size_t const &exclusiveEndLoc) { +bool SMS::isExceededReqBufferSize(size_t const &exclusiveEndLoc) +{ return exclusiveEndLoc <= Configuration::getInstance().RequestBufferSize; } -bool SMS::isRequestBuffersEmpty() const { +bool SMS::isRequestBuffersEmpty() const +{ for (const auto &requestBuffer : requestBuffers) { if (!requestBuffer.second.empty()) { return false; @@ -254,7 +255,8 @@ bool SMS::isRequestBuffersEmpty() const { return true; } -bool SMS::existReadyBatches() const { +bool SMS::existReadyBatches() const +{ for (const auto &each : readyBatchInclusiveEndLocs) { if (!each.second.empty()) { return true; @@ -270,51 +272,45 @@ bool SMS::existReadyBatches() const { * @param begin * @return true if this batch is ready, otherwise false */ -bool SMS::batchFormation(sc_time const &memClk, Thread const &thread, std::deque const &requestBuffer, size_t const &inclusiveBeginLoc) +bool SMS::batchFormation(sc_time const &memClk, Thread const &thread, + std::deque const &requestBuffer, size_t const &inclusiveBeginLoc) { - if (requestBuffer.empty()) - { + if (requestBuffer.empty()) { return false; } assert(inclusiveBeginLoc <= requestBuffer.size()); - if (requestBuffer.size() == inclusiveBeginLoc) - { + if (requestBuffer.size() == inclusiveBeginLoc) { return false; } - if (MPKCs[thread] < LOW_MPKC || isSystemLightlyLoaded()) - { + if (MPKCs[thread] < LOW_MPKC || isSystemLightlyLoaded()) { // bypass requests by forming batch with only one request (threshold age is ZERO) readyBatchInclusiveEndLocs[thread].push_back(inclusiveBeginLoc); return true; - } - else - { + } else { // forming batch with FIFO size & threshold age constraints size_t firstDifferentRowAccessReqLoc = inclusiveBeginLoc; Row firstRow = DramExtension::getRow(requestBuffer[inclusiveBeginLoc]); bool isBatchReady = false; size_t bufferSize = requestBuffer.size(); while (firstDifferentRowAccessReqLoc != bufferSize - && DramExtension::getRow(requestBuffer[firstDifferentRowAccessReqLoc]) == firstRow) - { + && DramExtension::getRow(requestBuffer[firstDifferentRowAccessReqLoc]) == + firstRow) { ++firstDifferentRowAccessReqLoc; - if (firstDifferentRowAccessReqLoc < bufferSize) - { - if (DramExtension::getRow(requestBuffer[firstDifferentRowAccessReqLoc]) != firstRow + if (firstDifferentRowAccessReqLoc < bufferSize) { + if (DramExtension::getRow(requestBuffer[firstDifferentRowAccessReqLoc]) != + firstRow || isExceededReqBufferSize(firstDifferentRowAccessReqLoc) - || isThresholdAgeExceeded(thread, memClk, inclusiveBeginLoc, firstDifferentRowAccessReqLoc)) - { + || isThresholdAgeExceeded(thread, memClk, inclusiveBeginLoc, + firstDifferentRowAccessReqLoc)) { isBatchReady = true; break; } - } - else - { + } else { if (isExceededReqBufferSize(firstDifferentRowAccessReqLoc) - || isThresholdAgeExceeded(thread, memClk, inclusiveBeginLoc, firstDifferentRowAccessReqLoc)) - { + || isThresholdAgeExceeded(thread, memClk, inclusiveBeginLoc, + firstDifferentRowAccessReqLoc)) { isBatchReady = true; break; } @@ -322,16 +318,13 @@ bool SMS::batchFormation(sc_time const &memClk, Thread const &thread, std::deque } // store this ready batch location - if (isBatchReady) - { + if (isBatchReady) { --firstDifferentRowAccessReqLoc; readyBatchInclusiveEndLocs[thread].push_back(firstDifferentRowAccessReqLoc); debugManager.printDebugMessage(name(), "Deem batch ready - thread " + to_string(thread.ID())); return true; - } - else - { + } else { return false; } } @@ -339,24 +332,20 @@ bool SMS::batchFormation(sc_time const &memClk, Thread const &thread, std::deque void SMS::multiBatchFormation(sc_time const &memClk) { - for (auto &requestBuffer : requestBuffers) - { + for (auto &requestBuffer : requestBuffers) { bool formed = false; - do - { - if (readyBatchInclusiveEndLocs[requestBuffer.first].empty()) - { + do { + if (readyBatchInclusiveEndLocs[requestBuffer.first].empty()) { formed = batchFormation(memClk, requestBuffer.first, requestBuffer.second, 0); - } - else - { - formed = batchFormation(memClk, requestBuffer.first, requestBuffer.second, readyBatchInclusiveEndLocs[requestBuffer.first].back() + 1); + } else { + formed = batchFormation(memClk, requestBuffer.first, requestBuffer.second, + readyBatchInclusiveEndLocs[requestBuffer.first].back() + 1); } } while (!requestBuffer.second.empty() && formed); } } -gp* SMS::getPendingRequest(Bank bank) +gp *SMS::getPendingRequest(Bank bank) { for (const auto &requestBuffer : requestBuffers) { for (const auto &request : requestBuffer.second) { diff --git a/DRAMSys/library/src/controller/scheduler/SMS.h b/DRAMSys/library/src/controller/scheduler/SMS.h index 1b869cae..0cb18882 100644 --- a/DRAMSys/library/src/controller/scheduler/SMS.h +++ b/DRAMSys/library/src/controller/scheduler/SMS.h @@ -18,7 +18,7 @@ #define MPKC_RESET_CYCLE 10000 using namespace std; -typedef std::deque::iterator gp_deque_iterator; +typedef std::deque::iterator gp_deque_iterator; /** * SMS - Staged Memory Scheduler involves 3 steps: @@ -32,7 +32,9 @@ typedef std::deque::iterator gp_deque_iterator; class SMS: public sc_module, public IScheduler { public: - SMS(sc_module_name /*_name*/, ControllerCore &controllerCore, unsigned int SJFprobability) : IScheduler(controllerCore), SJFprobability(SJFprobability), debugManager(DebugManager::getInstance()) + SMS(sc_module_name /*_name*/, ControllerCore &controllerCore, + unsigned int SJFprobability) : IScheduler(controllerCore), + SJFprobability(SJFprobability), debugManager(DebugManager::getInstance()) { // initialize selected thread iterator lastSelectedThread = readyBatchInclusiveEndLocs.end(); @@ -45,14 +47,14 @@ public: } virtual void schedule(gp *payload) override; - virtual std::pair getNextRequest(Bank bank) override; - virtual gp* getPendingRequest(Bank bank) override; + virtual std::pair getNextRequest(Bank bank) override; + virtual gp *getPendingRequest(Bank bank) override; void batchScheduler(); private: - std::map> requestBuffers; - std::map> bankBuffers; + std::map> requestBuffers; + std::map> bankBuffers; std::map> readyBatchInclusiveEndLocs; std::map inFlightMemRequestCounter; @@ -63,9 +65,10 @@ private: std::map>::iterator lastSelectedThread; sc_event newRequest; - DebugManager& debugManager; + DebugManager &debugManager; - bool batchFormation(sc_time const &memClk, Thread const &thread, const std::deque &requestBuffer, const size_t &inclusiveBeginLoc); + bool batchFormation(sc_time const &memClk, Thread const &thread, + const std::deque &requestBuffer, const size_t &inclusiveBeginLoc); void multiBatchFormation(const sc_time &memClk); bool pickSJF(); bool pickRR(); @@ -73,7 +76,8 @@ private: bool existLowIntensityThread() const; bool isSystemLightlyLoaded() const; - bool isThresholdAgeExceeded(const Thread &thread, const sc_time &memClk, const size_t &inclusiveBeginLoc, const size_t &exclusiveEndLoc); + bool isThresholdAgeExceeded(const Thread &thread, const sc_time &memClk, + const size_t &inclusiveBeginLoc, const size_t &exclusiveEndLoc); bool isExceededReqBufferSize(size_t const &exclusiveEndLoc); void updateMPKCs(const sc_time &memClk); diff --git a/DRAMSys/library/src/controller/scheduler/ThreadLoad.cpp b/DRAMSys/library/src/controller/scheduler/ThreadLoad.cpp index 6abc6a95..1938c1d3 100644 --- a/DRAMSys/library/src/controller/scheduler/ThreadLoad.cpp +++ b/DRAMSys/library/src/controller/scheduler/ThreadLoad.cpp @@ -50,59 +50,59 @@ //ThreadLoad::ThreadLoad() //{ -// // TODO Auto-generated constructor stub +// // TODO Auto-generated constructor stub //} //ThreadLoad::~ThreadLoad() //{ -// // TODO Auto-generated destructor stub +// // TODO Auto-generated destructor stub //} //unsigned int ThreadLoad::getMaxBankLoad() const //{ -// unsigned int maxLoad = 0; -// for (auto& bankVectorPair : load) -// { -// if (bankVectorPair.second.size() > maxLoad) -// maxLoad = bankVectorPair.second.size(); -// } -// return maxLoad; +// unsigned int maxLoad = 0; +// for (auto& bankVectorPair : load) +// { +// if (bankVectorPair.second.size() > maxLoad) +// maxLoad = bankVectorPair.second.size(); +// } +// return maxLoad; //} //unsigned int ThreadLoad::getTotalLoad() const //{ -// unsigned int totalLoad = 0; -// for (auto& bankVectorPair : load) -// { -// totalLoad += bankVectorPair.second.size(); -// } -// return totalLoad; +// unsigned int totalLoad = 0; +// for (auto& bankVectorPair : load) +// { +// totalLoad += bankVectorPair.second.size(); +// } +// return totalLoad; //} //void ThreadLoad::addTransaction(gp* payload) //{ -// load[DramExtension::getExtension(payload).getBank()].push_back(payload); +// load[DramExtension::getExtension(payload).getBank()].push_back(payload); //} //bool operator<(const ThreadLoad& lhs, const ThreadLoad& rhs) //{ -// if (lhs.getMaxBankLoad() < rhs.getMaxBankLoad()) -// return true; -// else if (lhs.getMaxBankLoad() == rhs.getMaxBankLoad()) -// return lhs.getTotalLoad() < rhs.getTotalLoad(); -// else -// return false; +// if (lhs.getMaxBankLoad() < rhs.getMaxBankLoad()) +// return true; +// else if (lhs.getMaxBankLoad() == rhs.getMaxBankLoad()) +// return lhs.getTotalLoad() < rhs.getTotalLoad(); +// else +// return false; //} //vector ThreadLoad::getTransactions() //{ -// vector result; -// for (auto& bankVectorPair : load) -// { -// result.insert(result.end(), bankVectorPair.second.begin(), bankVectorPair.second.end()); -// } -// return result; +// vector result; +// for (auto& bankVectorPair : load) +// { +// result.insert(result.end(), bankVectorPair.second.begin(), bankVectorPair.second.end()); +// } +// return result; //} //} /* namespace scheduler diff --git a/DRAMSys/library/src/controller/scheduler/ThreadLoad.h b/DRAMSys/library/src/controller/scheduler/ThreadLoad.h index 5c6324cc..f4152a05 100644 --- a/DRAMSys/library/src/controller/scheduler/ThreadLoad.h +++ b/DRAMSys/library/src/controller/scheduler/ThreadLoad.h @@ -56,16 +56,16 @@ //{ //public: // ThreadLoad();d -// virtual ~ThreadLoad(); +// virtual ~ThreadLoad(); -// unsigned int getMaxBankLoad() const; -// unsigned int getTotalLoad() const; +// unsigned int getMaxBankLoad() const; +// unsigned int getTotalLoad() const; -// void addTransaction(gp* payload); -// std::vector getTransactions(); +// void addTransaction(gp* payload); +// std::vector getTransactions(); //private: -// std::map> load; +// std::map> load; //}; //bool operator< (const ThreadLoad &lhs, const ThreadLoad &rhs); diff --git a/DRAMSys/library/src/error/ECC/Bit.cpp b/DRAMSys/library/src/error/ECC/Bit.cpp index 55f28ebf..161d690f 100644 --- a/DRAMSys/library/src/error/ECC/Bit.cpp +++ b/DRAMSys/library/src/error/ECC/Bit.cpp @@ -6,7 +6,7 @@ using std::cout; CBit::CBit(VALUE nVal) { - m_nValue = nVal; + m_nValue = nVal; } @@ -16,12 +16,9 @@ CBit::~CBit() void CBit::Print() { - if (m_nValue == ZERO) - { - cout <<"0"; - } - else - { - cout << "1"; - } + if (m_nValue == ZERO) { + cout << "0"; + } else { + cout << "1"; + } } diff --git a/DRAMSys/library/src/error/ECC/Bit.h b/DRAMSys/library/src/error/ECC/Bit.h index bfdda476..f1a90d2a 100644 --- a/DRAMSys/library/src/error/ECC/Bit.h +++ b/DRAMSys/library/src/error/ECC/Bit.h @@ -2,72 +2,68 @@ class CBit { public: - enum VALUE - { - ZERO = 0, - ONE = 1 - }; + enum VALUE { + ZERO = 0, + ONE = 1 + }; protected: - VALUE m_nValue; + VALUE m_nValue; public: - CBit(VALUE nVal = ZERO); - virtual ~CBit(); + CBit(VALUE nVal = ZERO); + virtual ~CBit(); - inline void Set() { m_nValue = ONE; }; - inline void Clear() { m_nValue = ZERO; }; - inline unsigned Get() - { - if(m_nValue == ONE) - return 1; - else - return 0; - }; + inline void Set() + { + m_nValue = ONE; + }; + inline void Clear() + { + m_nValue = ZERO; + }; + inline unsigned Get() + { + if (m_nValue == ONE) + return 1; + else + return 0; + }; - void Print(); + void Print(); - CBit& operator=(unsigned d) - { - if (d == 0 ) - { - m_nValue = ZERO; - } - else - { - m_nValue = ONE; - } - return *this; - } + CBit &operator=(unsigned d) + { + if (d == 0 ) { + m_nValue = ZERO; + } else { + m_nValue = ONE; + } + return *this; + } - friend CBit operator^(CBit l, const CBit& r) - { - if (l.m_nValue == r.m_nValue) - { - return CBit(ZERO); - } - else - { - return CBit(ONE); - } - } + friend CBit operator^(CBit l, const CBit &r) + { + if (l.m_nValue == r.m_nValue) { + return CBit(ZERO); + } else { + return CBit(ONE); + } + } - CBit& operator^=(const CBit& r) - { - if (m_nValue == r.m_nValue) - { - m_nValue = ZERO; - } - else - { - m_nValue = ONE; - } - return *this; - } + CBit &operator^=(const CBit &r) + { + if (m_nValue == r.m_nValue) { + m_nValue = ZERO; + } else { + m_nValue = ONE; + } + return *this; + } - inline bool operator==(const CBit::VALUE& r) - { - return m_nValue == r; - } + inline bool operator==(const CBit::VALUE &r) + { + return m_nValue == r; + } }; diff --git a/DRAMSys/library/src/error/ECC/ECC.cpp b/DRAMSys/library/src/error/ECC/ECC.cpp index 6cfaffe9..a6bc9da6 100644 --- a/DRAMSys/library/src/error/ECC/ECC.cpp +++ b/DRAMSys/library/src/error/ECC/ECC.cpp @@ -5,37 +5,35 @@ // to store the hamming code and parity bit for a SECDED implementation unsigned ECC::GetNumParityBits(unsigned nDataBits) { - unsigned nParityBits = 0; + unsigned nParityBits = 0; // Function to calculate the nube of bits: n = 2^k - k - 1 // ( Source: Hacker's Delight; p. 310; math. function 1 ) - while (nDataBits > ((1 << nParityBits) - nParityBits - 1)) - { - ++nParityBits; - } + while (nDataBits > ((1 << nParityBits) - nParityBits - 1)) { + ++nParityBits; + } - return nParityBits+1; // +1 for the parity bit + return nParityBits + 1; // +1 for the parity bit } // ************************************************************************************************ // Function which extends a given data word to the needed length for a SECDED code -void ECC::ExtendWord(CWord & v) +void ECC::ExtendWord(CWord &v) { - unsigned end = v.GetLength() + ECC::GetNumParityBits(v.GetLength()); + unsigned end = v.GetLength() + ECC::GetNumParityBits(v.GetLength()); // Insert x bits for the hamming code at positions where pos = 2^a; a = [0..N] // In "Hacker's Delight" the smallest index is 1 - But in this beautiful C-Code it's 0 as it // should be. That's why there is a '-1' in the call of v.Insert. - unsigned i = 1; - while (i < end) - { - v.Insert(i-1, CBit()); - i <<= 1; - } + unsigned i = 1; + while (i < end) { + v.Insert(i - 1, CBit()); + i <<= 1; + } // Append one bit for the parity - v.Append(CBit()); + v.Append(CBit()); } // ************************************************************************************************ @@ -43,12 +41,12 @@ void ECC::ExtendWord(CWord & v) // Function ExtendWord must be called before calling this function // The calculated bits are stored in p, so the length of p should be at least // 'GetNumParityBits(#data bits)-1' -void ECC::CalculateCheckbits(CWord & v, CWord & p) +void ECC::CalculateCheckbits(CWord &v, CWord &p) { unsigned i = 1, l = 0; - // Last bit is the parity bit - don't use this in the algorithm for hamming code - unsigned len = v.GetLength()-1; + // Last bit is the parity bit - don't use this in the algorithm for hamming code + unsigned len = v.GetLength() - 1; // Following Graph should show you the behaviour of this algorithm // #Data bits: 11 #Hamming bits: 4 -> SECDED bits: 16 (incl. parity bit) @@ -61,73 +59,67 @@ void ECC::CalculateCheckbits(CWord & v, CWord & p) // ATTENTION: The order of indices is different from the one in the book, // but it doesn't matter in which order your data or check bits are. // But it should be the same for encoding and decoding - while (i < len) - { - for (unsigned j = (i - 1); j < len; j += (i << 1)) - { - for (unsigned k = 0; k < (i); k++) - { - if(j + k >= len) - break; - p[l] ^= v[j + k]; - } - } - l++; - i <<= 1; - } + while (i < len) { + for (unsigned j = (i - 1); j < len; j += (i << 1)) { + for (unsigned k = 0; k < (i); k++) { + if (j + k >= len) + break; + p[l] ^= v[j + k]; + } + } + l++; + i <<= 1; + } } // ************************************************************************************************ // Function which inserts the checkbits which were calculated with 'CalculateCheckbits' in the // extended data word. This is needed to calculate a proper parity of ALL bits to achive a SECDED // behaviour. -void ECC::InsertCheckbits(CWord& v, CWord p) +void ECC::InsertCheckbits(CWord &v, CWord p) { - unsigned i = 1, j = 0; - while (i <= v.GetLength()-1) - { - v[i - 1] = p[j++]; - i <<= 1; - } + unsigned i = 1, j = 0; + while (i <= v.GetLength() - 1) { + v[i - 1] = p[j++]; + i <<= 1; + } } // ************************************************************************************************ // Function which extracts the checkbits out of an extended data word. This is needed to check for // bit error in the data word. -void ECC::ExtractCheckbits(CWord v, CWord & p) +void ECC::ExtractCheckbits(CWord v, CWord &p) { - unsigned i = 1, j = 0; - while(i <= v.GetLength()-1) - { - p[j++] = v[i - 1]; - i <<= 1; - } + unsigned i = 1, j = 0; + while (i <= v.GetLength() - 1) { + p[j++] = v[i - 1]; + i <<= 1; + } } // ************************************************************************************************ // Function which calculates the overal parity // Simply XOR all bits -void ECC::CalculateParityBit(CWord v, CBit & p) +void ECC::CalculateParityBit(CWord v, CBit &p) { - // Paritybit - p = CBit::ZERO; - for (unsigned i = 0; i < v.GetLength(); i++) - { - p ^= v[i]; - } + // Paritybit + p = CBit::ZERO; + for (unsigned i = 0; i < v.GetLength(); i++) { + p ^= v[i]; + } } // ************************************************************************************************ // Function to insert the parity bit into the extended data word -void ECC::InsertParityBit(CWord& v, CBit p) +void ECC::InsertParityBit(CWord &v, CBit p) { - v[v.GetLength() - 1] = p; + v[v.GetLength() - 1] = p; } // ************************************************************************************************ // Function to extract the parity bit out of an extended data word. -void ECC::ExtractParityBit(CWord v, CBit & p) +void ECC::ExtractParityBit(CWord v, CBit &p) { - p = v[v.GetLength() - 1]; + p = v[v.GetLength() - 1]; } diff --git a/DRAMSys/library/src/error/ECC/ECC.h b/DRAMSys/library/src/error/ECC/ECC.h index 3e9b8238..ec42bb14 100644 --- a/DRAMSys/library/src/error/ECC/ECC.h +++ b/DRAMSys/library/src/error/ECC/ECC.h @@ -21,19 +21,18 @@ // For further details read chapter 15 of "Hacker's Delight - second Edition" // ************************************************************************************************ -namespace ECC -{ - unsigned GetNumParityBits(unsigned nDataBits); +namespace ECC { +unsigned GetNumParityBits(unsigned nDataBits); - // Extends the data word that it can be used with hamming code - // Several bits will be included at specific places - void ExtendWord(CWord &v); +// Extends the data word that it can be used with hamming code +// Several bits will be included at specific places +void ExtendWord(CWord &v); - void CalculateCheckbits(CWord &v, CWord & p); - void InsertCheckbits(CWord& v, CWord p); - void ExtractCheckbits(CWord v, CWord& p); +void CalculateCheckbits(CWord &v, CWord &p); +void InsertCheckbits(CWord &v, CWord p); +void ExtractCheckbits(CWord v, CWord &p); - void CalculateParityBit(CWord v, CBit& p); - void InsertParityBit(CWord& v, CBit p); - void ExtractParityBit(CWord v, CBit& p); +void CalculateParityBit(CWord v, CBit &p); +void InsertParityBit(CWord &v, CBit p); +void ExtractParityBit(CWord v, CBit &p); } diff --git a/DRAMSys/library/src/error/ECC/ECC_Test.cpp b/DRAMSys/library/src/error/ECC/ECC_Test.cpp index dcbd884e..5f25662a 100644 --- a/DRAMSys/library/src/error/ECC/ECC_Test.cpp +++ b/DRAMSys/library/src/error/ECC/ECC_Test.cpp @@ -7,121 +7,109 @@ int main() { - // Random number init - srand(time(NULL)); + // Random number init + srand(time(NULL)); - // Erstellen - unsigned size = 4; - CWord p(ECC::GetNumParityBits(size)), v(size); + // Erstellen + unsigned size = 4; + CWord p(ECC::GetNumParityBits(size)), v(size); - // Daten eingeben - for (unsigned a = 0; a < 16; a++) - { - v = a; - v.Rotate(); + // Daten eingeben + for (unsigned a = 0; a < 16; a++) { + v = a; + v.Rotate(); - ECC::ExtendWord(v); - printf("%d:\t", a); + ECC::ExtendWord(v); + printf("%d:\t", a); - p = 0; - ECC::CalculateCheckbits(v, p); - ECC::InsertCheckbits(v, p); - ECC::CalculateParityBit(v, p[3]); - ECC::InsertParityBit(v, p[3]); + p = 0; + ECC::CalculateCheckbits(v, p); + ECC::InsertCheckbits(v, p); + ECC::CalculateParityBit(v, p[3]); + ECC::InsertParityBit(v, p[3]); - v.Print(); + v.Print(); - v.Resize(size); - } + v.Resize(size); + } - printf("\r\n"); + printf("\r\n"); - for (unsigned x = 0; x < 100; x++) - { - //Get random number - unsigned a = rand() % 16; + for (unsigned x = 0; x < 100; x++) { + //Get random number + unsigned a = rand() % 16; - v.Resize(size); - v = a; - v.Rotate(); + v.Resize(size); + v = a; + v.Rotate(); - ECC::ExtendWord(v); + ECC::ExtendWord(v); - p = 0; - ECC::CalculateCheckbits(v, p); - ECC::InsertCheckbits(v, p); - ECC::CalculateParityBit(v, p[3]); - ECC::InsertParityBit(v, p[3]); - v.Print(); + p = 0; + ECC::CalculateCheckbits(v, p); + ECC::InsertCheckbits(v, p); + ECC::CalculateParityBit(v, p[3]); + ECC::InsertParityBit(v, p[3]); + v.Print(); - // Insert error - unsigned pos = rand() % 8; - v[pos] ^= CBit(CBit::ONE); + // Insert error + unsigned pos = rand() % 8; + v[pos] ^= CBit(CBit::ONE); - printf("Data: %d, Error at pos %d: ", a, pos + 1); - v[pos].Print(); - printf("\r\n"); - v.Print(); + printf("Data: %d, Error at pos %d: ", a, pos + 1); + v[pos].Print(); + printf("\r\n"); + v.Print(); - p = 0; - ECC::CalculateCheckbits(v, p); - ECC::CalculateParityBit(v, p[3]); + p = 0; + ECC::CalculateCheckbits(v, p); + ECC::CalculateParityBit(v, p[3]); - printf("%d:\t", a); + printf("%d:\t", a); - p.Print(); + p.Print(); - // Interpreting Data + // Interpreting Data - unsigned syndrome = 0; - for (unsigned i = 0; i < p.GetLength() - 1; i++) - { - if (p[i] == CBit::ONE) - syndrome += (1 << i); - } + unsigned syndrome = 0; + for (unsigned i = 0; i < p.GetLength() - 1; i++) { + if (p[i] == CBit::ONE) + syndrome += (1 << i); + } - if (p[3] == CBit::ZERO) - { - // Parity even + if (p[3] == CBit::ZERO) { + // Parity even - if (syndrome) - { - // Double error - printf("Double error detected.\r\n"); - break; - } - else - { - // No Error - printf("No error detected.\r\n"); - break; - } - } - else - { - // Parity odd + if (syndrome) { + // Double error + printf("Double error detected.\r\n"); + break; + } else { + // No Error + printf("No error detected.\r\n"); + break; + } + } else { + // Parity odd - if (syndrome) - { - // Bit error - printf("Error detected in Bit %d.\r\n", syndrome); - if (syndrome == pos + 1) - continue; - else - break; - } - else - { - // Overall parity Error - printf("Overall parity error detected.\r\n"); - if (pos == 7 || pos == 3 || pos == 1 || pos == 0) - continue; - else - break; - } - } - } - system("pause"); + if (syndrome) { + // Bit error + printf("Error detected in Bit %d.\r\n", syndrome); + if (syndrome == pos + 1) + continue; + else + break; + } else { + // Overall parity Error + printf("Overall parity error detected.\r\n"); + if (pos == 7 || pos == 3 || pos == 1 || pos == 0) + continue; + else + break; + } + } + } + system("pause"); return 0; } diff --git a/DRAMSys/library/src/error/ECC/Word.cpp b/DRAMSys/library/src/error/ECC/Word.cpp index 2edb4879..47794ea0 100644 --- a/DRAMSys/library/src/error/ECC/Word.cpp +++ b/DRAMSys/library/src/error/ECC/Word.cpp @@ -7,9 +7,9 @@ using std::cout; CWord::CWord(unsigned nBitLength) - : m_nBitLength(nBitLength) + : m_nBitLength(nBitLength) { - m_word.resize(nBitLength); + m_word.resize(nBitLength); } @@ -17,141 +17,127 @@ CWord::~CWord() { } -CBit * CWord::GetAt(unsigned nBitPos) +CBit *CWord::GetAt(unsigned nBitPos) { - if (nBitPos < m_nBitLength) - { - return &m_word.at(nBitPos); - } + if (nBitPos < m_nBitLength) { + return &m_word.at(nBitPos); + } - return nullptr; + return nullptr; } void CWord::Set(unsigned data) { - deque::iterator it; - if (m_nBitLength < sizeof(data)) - { - it = m_word.begin(); - for (unsigned i = 0; i < m_nBitLength; i++) - { - (*it++) = data & 1; - data >>= 1; - } - } - else - { - for (it = m_word.begin(); it != m_word.end(); it++) - { - (*it) = data & 1; - data >>= 1; - } - } + deque::iterator it; + if (m_nBitLength < sizeof(data)) { + it = m_word.begin(); + for (unsigned i = 0; i < m_nBitLength; i++) { + (*it++) = data & 1; + data >>= 1; + } + } else { + for (it = m_word.begin(); it != m_word.end(); it++) { + (*it) = data & 1; + data >>= 1; + } + } } -void CWord::Set(const unsigned char* data, unsigned lengthInBits) +void CWord::Set(const unsigned char *data, unsigned lengthInBits) { - deque::iterator it; - if (m_nBitLength < lengthInBits) - { - it = m_word.begin(); - for (unsigned pos = 0; pos < m_nBitLength; pos++) - { - (*it) = data[pos>>3] & (1 << (7-(pos&7))); - it++; - } - } - else - { - unsigned pos = 0; - for (it = m_word.begin(); it != m_word.end(); it++) - { - (*it) = data[pos>>3] & (1 << (7-(pos&7))); - ++pos; - } - } + deque::iterator it; + if (m_nBitLength < lengthInBits) { + it = m_word.begin(); + for (unsigned pos = 0; pos < m_nBitLength; pos++) { + (*it) = data[pos >> 3] & (1 << (7 - (pos & 7))); + it++; + } + } else { + unsigned pos = 0; + for (it = m_word.begin(); it != m_word.end(); it++) { + (*it) = data[pos >> 3] & (1 << (7 - (pos & 7))); + ++pos; + } + } } void CWord::Rotate() { - deque buffer = m_word; - for (unsigned i = 0; i < m_nBitLength; i++) - { - m_word.at(m_nBitLength -i -1) = buffer.at(i); - } + deque buffer = m_word; + for (unsigned i = 0; i < m_nBitLength; i++) { + m_word.at(m_nBitLength - i - 1) = buffer.at(i); + } } bool CWord::Insert(unsigned npos, CBit b) { - if (npos >= m_nBitLength) - return false; + if (npos >= m_nBitLength) + return false; - deque::iterator it = m_word.begin() + npos; - m_word.insert(it, b); + deque::iterator it = m_word.begin() + npos; + m_word.insert(it, b); - m_nBitLength++; + m_nBitLength++; - return true; + return true; } bool CWord::Delete(unsigned npos) { - if (npos >= m_nBitLength) - return false; + if (npos >= m_nBitLength) + return false; - deque::iterator it = m_word.begin() + npos; - m_word.erase(it); + deque::iterator it = m_word.begin() + npos; + m_word.erase(it); - m_nBitLength++; + m_nBitLength++; - return true; + return true; } void CWord::Append(CBit b) { - m_word.push_back(b); + m_word.push_back(b); - m_nBitLength++; + m_nBitLength++; } void CWord::Resize(unsigned nsize) { - m_word.resize(nsize); - m_nBitLength = nsize; + m_word.resize(nsize); + m_nBitLength = nsize; } bool CWord::PartShiftRight(unsigned nPos, unsigned /*nShift*/) { - if(nPos >= m_nBitLength) - return false; + if (nPos >= m_nBitLength) + return false; - /*for (unsigned i = 0; i < nShift; i++) - { - m_word.insert() - }*/ + /*for (unsigned i = 0; i < nShift; i++) + { + m_word.insert() + }*/ - return true; + return true; } void CWord::Print() { - deque::iterator it; - for (it = m_word.begin(); it != m_word.end(); it++) - { - (*it).Print(); - } - cout << "\r\n"; + deque::iterator it; + for (it = m_word.begin(); it != m_word.end(); it++) { + (*it).Print(); + } + cout << "\r\n"; } -void CWord::Copy(unsigned char* ptr) +void CWord::Copy(unsigned char *ptr) { - unsigned len = ceil(m_word.size()/8); + unsigned len = ceil(m_word.size() / 8); memset(ptr, 0, len); - unsigned pos = 0; - for(auto it = m_word.begin(); it != m_word.end(); it++) - { - ptr[pos>>3] |= (*it).Get() << (7-(pos&7)); - ++pos; - } + unsigned pos = 0; + for (auto it = m_word.begin(); it != m_word.end(); it++) { + ptr[pos >> 3] |= (*it).Get() << (7 - (pos & 7)); + ++pos; + } } diff --git a/DRAMSys/library/src/error/ECC/Word.h b/DRAMSys/library/src/error/ECC/Word.h index efcdd981..c3edb1ae 100644 --- a/DRAMSys/library/src/error/ECC/Word.h +++ b/DRAMSys/library/src/error/ECC/Word.h @@ -10,54 +10,56 @@ class CWord { protected: - unsigned m_nBitLength; - deque m_word; + unsigned m_nBitLength; + deque m_word; public: - CWord(unsigned nBitLength); - virtual ~CWord(); + CWord(unsigned nBitLength); + virtual ~CWord(); - CBit* GetAt(unsigned nBitPos); + CBit *GetAt(unsigned nBitPos); - void Set(unsigned data); - void Set(const unsigned char* data, unsigned lengthInBits); - void Rotate(); + void Set(unsigned data); + void Set(const unsigned char *data, unsigned lengthInBits); + void Rotate(); - bool Insert(unsigned npos, CBit b); - bool Delete(unsigned npos); + bool Insert(unsigned npos, CBit b); + bool Delete(unsigned npos); - void Copy(unsigned char* ptr); + void Copy(unsigned char *ptr); - void Append(CBit b); + void Append(CBit b); - void Resize(unsigned nsize); + void Resize(unsigned nsize); - bool PartShiftRight(unsigned nPos, unsigned nShift); + bool PartShiftRight(unsigned nPos, unsigned nShift); - inline unsigned GetLength() const { return m_nBitLength; }; + inline unsigned GetLength() const + { + return m_nBitLength; + }; - void Print(); + void Print(); - CWord& operator=(unsigned d) - { - Set(d); - return *this; - } + CWord &operator=(unsigned d) + { + Set(d); + return *this; + } - CBit& operator[](unsigned nPos) - { - return m_word.at(nPos); - } + CBit &operator[](unsigned nPos) + { + return m_word.at(nPos); + } - friend CWord operator >> (CWord l, const unsigned& r) - { - for (unsigned i = 0; i < r; i++) - { - l.m_word.pop_front(); - l.m_word.push_back(CBit(CBit::VALUE::ZERO)); - } - return l; - } + friend CWord operator >> (CWord l, const unsigned &r) + { + for (unsigned i = 0; i < r; i++) { + l.m_word.pop_front(); + l.m_word.push_back(CBit(CBit::VALUE::ZERO)); + } + return l; + } }; diff --git a/DRAMSys/library/src/error/eccbaseclass.cpp b/DRAMSys/library/src/error/eccbaseclass.cpp index 10deaa02..6c41e6d1 100644 --- a/DRAMSys/library/src/error/eccbaseclass.cpp +++ b/DRAMSys/library/src/error/eccbaseclass.cpp @@ -1,31 +1,30 @@ #include "eccbaseclass.h" -tlm::tlm_sync_enum ECCBaseClass::nb_transport_fw( int id, tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_time& delay ) +tlm::tlm_sync_enum ECCBaseClass::nb_transport_fw( int id, + tlm::tlm_generic_payload &trans, tlm::tlm_phase &phase, sc_time &delay ) { - if(trans.get_command() == TLM_WRITE_COMMAND && phase == BEGIN_REQ) - { + if (trans.get_command() == TLM_WRITE_COMMAND && phase == BEGIN_REQ) { // Allocate memory for encoded data using the size provided by AllocationEncode unsigned nEncodedDataSize = AllocationSize(trans.get_data_length()); assert(nEncodedDataSize != 0); - unsigned char* pEncodedData = new unsigned char[nEncodedDataSize]; + unsigned char *pEncodedData = new unsigned char[nEncodedDataSize]; // Save memory pointer and size m_mDataPointer[pEncodedData].pData = trans.get_data_ptr(); m_mDataPointer[pEncodedData].nDataSize = trans.get_data_length(); // Data Encoding - Encode(trans.get_data_ptr(), trans.get_data_length(), pEncodedData, nEncodedDataSize); + Encode(trans.get_data_ptr(), trans.get_data_length(), pEncodedData, + nEncodedDataSize); // Change transport data length and pointer trans.set_data_length(nEncodedDataSize); trans.set_data_ptr(pEncodedData); - } - else if(trans.get_command() == TLM_READ_COMMAND && phase == BEGIN_REQ) - { + } else if (trans.get_command() == TLM_READ_COMMAND && phase == BEGIN_REQ) { // Allocate memory for reading data using the size provided by AllocationEncode unsigned nReadDataSize = AllocationSize(trans.get_data_length()); assert(nReadDataSize != 0); - unsigned char* pReadData = new unsigned char[nReadDataSize]; + unsigned char *pReadData = new unsigned char[nReadDataSize]; // Save memory pointer and size m_mDataPointer[pReadData].pData = trans.get_data_ptr(); @@ -41,16 +40,17 @@ tlm::tlm_sync_enum ECCBaseClass::nb_transport_fw( int id, tlm::tlm_generic_paylo // Backward interface -tlm::tlm_sync_enum ECCBaseClass::nb_transport_bw( int id, tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_time& delay ) +tlm::tlm_sync_enum ECCBaseClass::nb_transport_bw( int id, + tlm::tlm_generic_payload &trans, tlm::tlm_phase &phase, sc_time &delay ) { - if(trans.get_command() == TLM_READ_COMMAND && phase == BEGIN_RESP) - { + if (trans.get_command() == TLM_READ_COMMAND && phase == BEGIN_RESP) { //Look for the corresponding data pointer for decoding auto it = m_mDataPointer.find(trans.get_data_ptr()); assert(it != m_mDataPointer.end()); // Data Decoding - Decode(trans.get_data_ptr(), trans.get_data_length(), it->second.pData, it->second.nDataSize); + Decode(trans.get_data_ptr(), trans.get_data_length(), it->second.pData, + it->second.nDataSize); // delete data pointer from map m_mDataPointer.erase(it); @@ -61,9 +61,7 @@ tlm::tlm_sync_enum ECCBaseClass::nb_transport_bw( int id, tlm::tlm_generic_paylo // Set data pointer and size for decoded data trans.set_data_ptr(it->second.pData); trans.set_data_length(it->second.nDataSize); - } - else if(trans.get_command() == TLM_WRITE_COMMAND && phase == BEGIN_RESP) - { + } else if (trans.get_command() == TLM_WRITE_COMMAND && phase == BEGIN_RESP) { //Look for the corresponding data pointer for decoding auto it = m_mDataPointer.find(trans.get_data_ptr()); assert(it != m_mDataPointer.end()); diff --git a/DRAMSys/library/src/error/eccbaseclass.h b/DRAMSys/library/src/error/eccbaseclass.h index 1c64f51d..544eb420 100644 --- a/DRAMSys/library/src/error/eccbaseclass.h +++ b/DRAMSys/library/src/error/eccbaseclass.h @@ -17,14 +17,13 @@ using namespace tlm; class ECCBaseClass : sc_module { public: - struct DataStruct - { - unsigned char* pData; + struct DataStruct { + unsigned char *pData; unsigned int nDataSize; }; private: - map m_mDataPointer; + map m_mDataPointer; public: // Function prototype for calculated the size of memory needed for saving the encoded data @@ -37,14 +36,16 @@ protected: // Data pointer is provided in pDataIn, length in Bytes provided in nDataIn // Result should be written in pDataOut, which has a size of nDataOut. // pDataOut is already allocated with a size given by function AllocationEncode - virtual void Encode(const unsigned char* pDataIn, const unsigned nDataIn, unsigned char* pDataOut, const unsigned nDataOut) = 0; + virtual void Encode(const unsigned char *pDataIn, const unsigned nDataIn, + unsigned char *pDataOut, const unsigned nDataOut) = 0; // Function prototype for decoding data. // Data pointer is provided in pDataIn, length in Bytes provided in nDataIn // Result should be written in pDataOut, which has a size of nDataOut. // pDataOut is already allocated with a size given by function AllocationDecode - virtual void Decode(const unsigned char* pDataIn, const unsigned nDataIn, unsigned char* pDataOut, const unsigned nDataOut) = 0; + virtual void Decode(const unsigned char *pDataIn, const unsigned nDataIn, + unsigned char *pDataOut, const unsigned nDataOut) = 0; public: tlm_utils::multi_passthrough_target_socket t_socket; @@ -58,10 +59,12 @@ public: i_socket.register_nb_transport_bw(this, &ECCBaseClass::nb_transport_bw); } // Forward interface - tlm::tlm_sync_enum nb_transport_fw( int id, tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_time& delay ); + tlm::tlm_sync_enum nb_transport_fw( int id, tlm::tlm_generic_payload &trans, + tlm::tlm_phase &phase, sc_time &delay ); // Backward interface - tlm::tlm_sync_enum nb_transport_bw( int id, tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_time& delay ); + tlm::tlm_sync_enum nb_transport_bw( int id, tlm::tlm_generic_payload &trans, + tlm::tlm_phase &phase, sc_time &delay ); }; #endif // ECCBASECLASS_H diff --git a/DRAMSys/library/src/error/ecchamming.cpp b/DRAMSys/library/src/error/ecchamming.cpp index d2d1e466..9bc46efc 100644 --- a/DRAMSys/library/src/error/ecchamming.cpp +++ b/DRAMSys/library/src/error/ecchamming.cpp @@ -8,23 +8,23 @@ unsigned ECCHamming::AllocationSize(unsigned nBytes) return nBytes + ceil(nBytes / m_nDatawordSize) * m_nCodewordSize; } -void ECCHamming::Encode(const unsigned char* pDataIn, const unsigned nDataIn, unsigned char* pDataOut, const unsigned nDataOut) +void ECCHamming::Encode(const unsigned char *pDataIn, const unsigned nDataIn, + unsigned char *pDataOut, const unsigned nDataOut) { // Calculate how many 8 byte blocks are there - unsigned nBlocks = nDataIn/m_nDatawordSize; + unsigned nBlocks = nDataIn / m_nDatawordSize; // No partly filled blocks are supported assert(nDataIn % m_nDatawordSize == 0); // Create ECC data for every block - for(unsigned i = 0; i < nBlocks; i++) - { + for (unsigned i = 0; i < nBlocks; i++) { // Create all variables needed for calulation CWord dataword(InBits(m_nDatawordSize)); // Size in bits CWord codeword(InBits(m_nCodewordSize)); // Size in bits // Fill in current data block - dataword.Set(&pDataIn[i*m_nDatawordSize], InBits(m_nDatawordSize)); + dataword.Set(&pDataIn[i * m_nDatawordSize], InBits(m_nDatawordSize)); // Extend data word. It grows from m_nDatawordSize to m_nDatawordSize + m_nCodewordSize ECC::ExtendWord(dataword); @@ -40,34 +40,38 @@ void ECCHamming::Encode(const unsigned char* pDataIn, const unsigned nDataIn, un ECC::CalculateParityBit(dataword, codeword[7]); // Check if there is enough space in the output array (should always be) - assert((i+1)*(m_nDatawordSize + m_nCodewordSize) <= nDataOut); + assert((i + 1) * (m_nDatawordSize + m_nCodewordSize) <= nDataOut); // Copy old data - memcpy(&pDataOut[i*(m_nDatawordSize + m_nCodewordSize)], &pDataIn[i*m_nDatawordSize], m_nDatawordSize); + memcpy(&pDataOut[i * (m_nDatawordSize + m_nCodewordSize)], + &pDataIn[i * m_nDatawordSize], m_nDatawordSize); // Save hamming code + parity bit in the last byte - codeword.Copy(&pDataOut[i*(m_nDatawordSize + m_nCodewordSize)+m_nDatawordSize]); + codeword.Copy(&pDataOut[i * (m_nDatawordSize + m_nCodewordSize) + + m_nDatawordSize]); } } -void ECCHamming::Decode(const unsigned char* pDataIn, const unsigned nDataIn, unsigned char* pDataOut, const unsigned nDataOut) +void ECCHamming::Decode(const unsigned char *pDataIn, const unsigned nDataIn, + unsigned char *pDataOut, const unsigned nDataOut) { // Calculate how many 9 byte blocks are there - unsigned nBlocks = nDataIn/(m_nDatawordSize + m_nCodewordSize); + unsigned nBlocks = nDataIn / (m_nDatawordSize + m_nCodewordSize); // No partly filled blocks are supported assert(nDataIn % (m_nDatawordSize + m_nCodewordSize) == 0); // Verify ECC data for every block - for(unsigned i = 0; i < nBlocks; i++) - { + for (unsigned i = 0; i < nBlocks; i++) { // Create all variables needed for calulation CWord dataword(InBits(m_nDatawordSize)); // Size in bits CWord codeword(InBits(m_nCodewordSize)); // Size in bits // Fill in current data block - dataword.Set(&pDataIn[i*(m_nDatawordSize + m_nCodewordSize)], InBits(m_nDatawordSize)); - codeword.Set(&pDataIn[i*(m_nDatawordSize + m_nCodewordSize)+m_nDatawordSize], InBits(m_nCodewordSize)); + dataword.Set(&pDataIn[i * (m_nDatawordSize + m_nCodewordSize)], + InBits(m_nDatawordSize)); + codeword.Set(&pDataIn[i * (m_nDatawordSize + m_nCodewordSize) + + m_nDatawordSize], InBits(m_nCodewordSize)); // Extend data word. It grows from m_nDatawordSize to m_nDatawordSize + m_nCodewordSize ECC::ExtendWord(dataword); @@ -76,7 +80,7 @@ void ECCHamming::Decode(const unsigned char* pDataIn, const unsigned nDataIn, un ECC::InsertCheckbits(dataword, codeword); ECC::InsertParityBit(dataword, codeword[7]); - // Reset codeword + // Reset codeword codeword = 0; // Calculate Checkbits again @@ -95,40 +99,32 @@ void ECCHamming::Decode(const unsigned char* pDataIn, const unsigned nDataIn, un c &= 0x7F; // Parity Error? - if(bParity) - { + if (bParity) { // Parity Error - if(c == 0) - { + if (c == 0) { // Only Parity Bit broken - continue cout << "Parity Bit error" << endl; - } - else - { + } else { // Data or Hamming Code Bit broken cout << "Single Error Detected" << endl; } - } - else - { + } else { // No Parity Error - if(c == 0) - { + if (c == 0) { // No error at all - continue - } - else - { + } else { // Double error detected cout << "Double Error Detected (Block " << i << ")." << endl; } } // Check if there is enough space in the output array (should always be) - assert((i+1)*(m_nDatawordSize) <= nDataOut); + assert((i + 1) * (m_nDatawordSize) <= nDataOut); // Copy data - memcpy(&pDataOut[i*m_nDatawordSize], &pDataIn[i*(m_nDatawordSize + m_nCodewordSize)], m_nDatawordSize); + memcpy(&pDataOut[i * m_nDatawordSize], + &pDataIn[i * (m_nDatawordSize + m_nCodewordSize)], m_nDatawordSize); } } diff --git a/DRAMSys/library/src/error/ecchamming.h b/DRAMSys/library/src/error/ecchamming.h index 99c548fb..3378613b 100644 --- a/DRAMSys/library/src/error/ecchamming.h +++ b/DRAMSys/library/src/error/ecchamming.h @@ -11,7 +11,10 @@ private: const unsigned m_nDatawordSize = 8; // bytes const unsigned m_nCodewordSize = 1; // bytes - inline unsigned InBits(unsigned n){return n<<3;}; // use this if constants are needed in bits + inline unsigned InBits(unsigned n) + { + return n << 3; + }; // use this if constants are needed in bits public: // Function prototype for calculated the size of memory needed for saving the encoded data @@ -24,14 +27,16 @@ protected: // Data pointer is provided in pDataIn, length in Bytes provided in nDataIn // Result should be written in pDataOut, which has a size of nDataOut. // pDataOut is already allocated with a size given by function AllocationEncode - virtual void Encode(const unsigned char* pDataIn, const unsigned nDataIn, unsigned char* pDataOut, const unsigned nDataOut); + virtual void Encode(const unsigned char *pDataIn, const unsigned nDataIn, + unsigned char *pDataOut, const unsigned nDataOut); // Function prototype for decoding data. // Data pointer is provided in pDataIn, length in Bytes provided in nDataIn // Result should be written in pDataOut, which has a size of nDataOut. // pDataOut is already allocated with a size given by function AllocationDecode - virtual void Decode(const unsigned char* pDataIn, const unsigned nDataIn, unsigned char* pDataOut, const unsigned nDataOut); + virtual void Decode(const unsigned char *pDataIn, const unsigned nDataIn, + unsigned char *pDataOut, const unsigned nDataOut); public: ECCHamming(::sc_core::sc_module_name name) : ECCBaseClass(name) diff --git a/DRAMSys/library/src/error/errormodel.cpp b/DRAMSys/library/src/error/errormodel.cpp index 9a40a869..eb70a964 100644 --- a/DRAMSys/library/src/error/errormodel.cpp +++ b/DRAMSys/library/src/error/errormodel.cpp @@ -50,17 +50,17 @@ void errorModel::init() numberOfColumns = Configuration::getInstance().memSpec.NumberOfColumns; bytesPerColumn = AddressDecoder::getInstance().amount["bytes"]; - // Adjust number of bytes per column dynamically to the selected ecc controller - bytesPerColumn = Configuration::getInstance().adjustNumBytesAfterECC(bytesPerColumn); + // Adjust number of bytes per column dynamically to the selected ecc controller + bytesPerColumn = Configuration::getInstance().adjustNumBytesAfterECC( + bytesPerColumn); - numberOfRows = Configuration::getInstance().memSpec.NumberOfRows; + numberOfRows = Configuration::getInstance().memSpec.NumberOfRows; numberOfBitErrorEvents = 0; // Initialize the lastRow Access array: lastRowAccess = new sc_time[numberOfRows]; - for(unsigned int i = 0; i < numberOfRows; i++) - { + for (unsigned int i = 0; i < numberOfRows; i++) { lastRowAccess[i] = SC_ZERO_TIME; } @@ -126,8 +126,8 @@ errorModel::errorModel(sc_module_name /*name*/) errorModel::~errorModel() { // Remove all data from the dataMap: - for (std::map::iterator it = dataMap.begin(); it != dataMap.end(); ++it ) - { + for (std::map::iterator it = dataMap.begin(); + it != dataMap.end(); ++it ) { delete it->second; } // Delete all elements from the dataMap: @@ -143,8 +143,7 @@ errorModel::~errorModel() delete [] weakCells; // If an access happened to a bank the numner of error events should be shown: - if(myChannel != -1 && myBank != -1 && myBankgroup != -1 && myRank != -1 ) - { + if (myChannel != -1 && myBank != -1 && myBankgroup != -1 && myRank != -1 ) { std::cout << contextStr << ": Number of Retention Error Events = " << numberOfBitErrorEvents << std::endl; @@ -157,32 +156,32 @@ void errorModel::store(tlm::tlm_generic_payload &trans) markBitFlips(); // Get the key for the dataMap from the transaction's address: - DecodedAddress key = AddressDecoder::getInstance().decodeAddress(trans.get_address()); + DecodedAddress key = AddressDecoder::getInstance().decodeAddress( + trans.get_address()); // Set context: setContext(key); std::stringstream msg; - msg << "bank: " << key.bank << " group: " << key.bankgroup << " bytes: " << key.bytes << " channel: " << key.channel << " column: " << key.column << " rank: " << key.rank << " row: " << key.row; + msg << "bank: " << key.bank << " group: " << key.bankgroup << " bytes: " << + key.bytes << " channel: " << key.channel << " column: " << key.column << + " rank: " << key.rank << " row: " << key.row; printDebugMessage(msg.str()); // Check if the provided data length is correct: assert((bytesPerColumn * burstLenght) == trans.get_data_length()); - printDebugMessage(("Data length: " + std::to_string(trans.get_data_length()) + " bytesPerColumn: " + std::to_string(bytesPerColumn)).c_str()); + printDebugMessage(("Data length: " + std::to_string(trans.get_data_length()) + + " bytesPerColumn: " + std::to_string(bytesPerColumn)).c_str()); // Handle the DRAM burst, - for (unsigned int i = 0; i < trans.get_data_length(); i += bytesPerColumn) - { + for (unsigned int i = 0; i < trans.get_data_length(); i += bytesPerColumn) { unsigned char *data; // Check if address is not already stored: - if(dataMap.count(key) == 0) - { + if (dataMap.count(key) == 0) { // Generate a new data entry data = new unsigned char[bytesPerColumn]; - } - else // In case the address was stored before: - { + } else { // In case the address was stored before: data = dataMap[key]; } @@ -191,18 +190,15 @@ void errorModel::store(tlm::tlm_generic_payload &trans) // Save part of the burst in the dataMap // TODO: Check if we can have double entries, is key unique? - dataMap.insert(std::pair(key, data)); + dataMap.insert(std::pair(key, data)); // Reset flipped weak cells in this area, since they are rewritten now - for (unsigned int j = 0; j < maxNumberOfWeakCells; j++) - { + for (unsigned int j = 0; j < maxNumberOfWeakCells; j++) { // If the current written column in a row has a week cell: - if(weakCells[j].row == key.row && weakCells[j].col == key.column) - { + if (weakCells[j].row == key.row && weakCells[j].col == key.column) { // If the bit was marked as flipped due to a retention error // mark it as unflipped: - if(weakCells[j].flipped == true) - { + if (weakCells[j].flipped == true) { weakCells[j].flipped = false; } } @@ -213,7 +209,8 @@ void errorModel::store(tlm::tlm_generic_payload &trans) // Check that there is no column overfow: std::stringstream msg; - msg << "key.column is " << key.column << " numberOfColumns is " << numberOfColumns; + msg << "key.column is " << key.column << " numberOfColumns is " << + numberOfColumns; printDebugMessage(msg.str()); assert(key.column <= numberOfColumns); } @@ -225,7 +222,8 @@ void errorModel::load(tlm::tlm_generic_payload &trans) markBitFlips(); // Get the key for the dataMap from the transaction's address: - DecodedAddress key = AddressDecoder::getInstance().decodeAddress(trans.get_address()); + DecodedAddress key = AddressDecoder::getInstance().decodeAddress( + trans.get_address()); // Set context: setContext(key); @@ -234,16 +232,14 @@ void errorModel::load(tlm::tlm_generic_payload &trans) assert((bytesPerColumn * burstLenght) == trans.get_data_length()); // Handle the DRAM burst: - for (unsigned int i = 0; i < trans.get_data_length(); i+=bytesPerColumn) - { + for (unsigned int i = 0; i < trans.get_data_length(); i += bytesPerColumn) { // Check if address is not stored: - if(dataMap.count(key) == 0) - { - SC_REPORT_FATAL("errormodel","Reading from an empty memory location"); + if (dataMap.count(key) == 0) { + SC_REPORT_FATAL("errormodel", "Reading from an empty memory location"); } // Copy the dataMap to the transaction data pointer - memcpy(trans.get_data_ptr()+i, dataMap[key], bytesPerColumn); + memcpy(trans.get_data_ptr() + i, dataMap[key], bytesPerColumn); // The next burst element is handled, therfore the column address must be increased key.column++; @@ -256,11 +252,10 @@ void errorModel::load(tlm::tlm_generic_payload &trans) void errorModel::markBitFlips() { double temp = getTemperature(); - for(unsigned int row = 0; row < Configuration::getInstance().memSpec.NumberOfRows; row++) - { + for (unsigned int row = 0; + row < Configuration::getInstance().memSpec.NumberOfRows; row++) { // If the row has never been accessed ignore it and go to the next one - if (lastRowAccess[row] != SC_ZERO_TIME) - { + if (lastRowAccess[row] != SC_ZERO_TIME) { // Get the time interval between now and the last acivate/refresh sc_time interval = sc_time_stamp() - lastRowAccess[row]; @@ -269,11 +264,9 @@ void errorModel::markBitFlips() // Check if the current row is in the range of bit flips for this interval // and temperature, if yes mark it as flipped: - for (unsigned int i=0; i0 transitions are supported) // DRAMs based on anti cells are not supported yet by this model - if(getBit(key,byte,bitInByte) == 1) - { + if (getBit(key, byte, bitInByte) == 1) { // Prepare bit mask: invert mask and AND it later unsigned char mask = pow(2, bitInByte); mask = ~mask; @@ -331,10 +321,9 @@ void errorModel::activate(unsigned int row) // Temporal storage for modification: unsigned char tempByte; - if(weakCells[i].dependent == false) - { + if (weakCells[i].dependent == false) { // Load the affected byte to tempByte - memcpy(&tempByte, dataMap[key]+byte, 1); + memcpy(&tempByte, dataMap[key] + byte, 1); // Flip the bit: tempByte = (tempByte & mask); @@ -350,10 +339,8 @@ void errorModel::activate(unsigned int row) numberOfBitErrorEvents++; // Copy the modified byte back to the dataMap: - memcpy(dataMap[key]+byte, &tempByte, 1); - } - else // if(weakCells[i].dependent == true) - { + memcpy(dataMap[key] + byte, &tempByte, 1); + } else { // if(weakCells[i].dependent == true) // Get the neighbourhood of the bit and store it in the // grid variable: // | 0 1 2 | @@ -362,35 +349,33 @@ void errorModel::activate(unsigned int row) unsigned int grid[9]; - grid[0] = getBit(key.row-1,key.column,byte,bitInByte-1); - grid[1] = getBit(key.row-1,key.column,byte,bitInByte ); - grid[2] = getBit(key.row-1,key.column,byte,bitInByte+1); + grid[0] = getBit(key.row - 1, key.column, byte, bitInByte - 1); + grid[1] = getBit(key.row - 1, key.column, byte, bitInByte ); + grid[2] = getBit(key.row - 1, key.column, byte, bitInByte + 1); - grid[3] = getBit(key.row ,key.column,byte,bitInByte-1); - grid[4] = getBit(key.row ,key.column,byte,bitInByte ); - grid[5] = getBit(key.row ,key.column,byte,bitInByte+1); + grid[3] = getBit(key.row , key.column, byte, bitInByte - 1); + grid[4] = getBit(key.row , key.column, byte, bitInByte ); + grid[5] = getBit(key.row , key.column, byte, bitInByte + 1); - grid[6] = getBit(key.row+1,key.column,byte,bitInByte-1); - grid[7] = getBit(key.row+1,key.column,byte,bitInByte ); - grid[8] = getBit(key.row+1,key.column,byte,bitInByte+1); + grid[6] = getBit(key.row + 1, key.column, byte, bitInByte - 1); + grid[7] = getBit(key.row + 1, key.column, byte, bitInByte ); + grid[8] = getBit(key.row + 1, key.column, byte, bitInByte + 1); unsigned int sum = 0; - for(int s = 0; s < 9; s++) - { + for (int s = 0; s < 9; s++) { sum += grid[s]; } - if(sum <= 4) - { + if (sum <= 4) { // Load the affected byte to tempByte - memcpy(&tempByte, dataMap[key]+byte, 1); + memcpy(&tempByte, dataMap[key] + byte, 1); // Flip the bit: tempByte = (tempByte & mask); numberOfBitErrorEvents++; // Copy the modified byte back to the dataMap: - memcpy(dataMap[key]+byte, &tempByte, 1); + memcpy(dataMap[key] + byte, &tempByte, 1); // Output on the Console: std::stringstream msg; @@ -403,9 +388,7 @@ void errorModel::activate(unsigned int row) << grid[3] << grid[4] << grid[5] << std::endl << grid[6] << grid[7] << grid[8]; printDebugMessage(msg.str()); - } - else - { + } else { // Output on the Console: std::stringstream msg; msg << "Dependent Bit NOT Flipped!" @@ -427,19 +410,17 @@ void errorModel::activate(unsigned int row) } // This method is used to get a bit with a key, usually for independent case: -unsigned int errorModel::getBit(DecodedAddress key, unsigned int byteInColumn, unsigned int bitInByte) +unsigned int errorModel::getBit(DecodedAddress key, unsigned int byteInColumn, + unsigned int bitInByte) { // If the data was not writte by the produce yet it is zero: - if(dataMap.count(key) == 0) - { + if (dataMap.count(key) == 0) { return 0; - } - else // Return the value of the bit - { + } else { // Return the value of the bit unsigned char tempByte; // Copy affected byte to a temporal variable: - memcpy(&tempByte, dataMap[key]+byteInColumn, 1); + memcpy(&tempByte, dataMap[key] + byteInColumn, 1); unsigned char mask = pow(2, bitInByte); unsigned int result = (tempByte & mask) >> bitInByte; std::bitset<8> x(mask); @@ -457,51 +438,40 @@ unsigned int errorModel::getBit(DecodedAddress key, unsigned int byteInColumn, u } // This method is used to get neighbourhoods, for the dependent case: -unsigned int errorModel::getBit(int row, int column, int byteInColumn, int bitInByte) +unsigned int errorModel::getBit(int row, int column, int byteInColumn, + int bitInByte) { // Border-Exception handling: // Switch the byte if bit under/overflow: - if(bitInByte < 0) - { + if (bitInByte < 0) { byteInColumn--; bitInByte = 7; - } - else if(bitInByte >= 8) - { + } else if (bitInByte >= 8) { byteInColumn++; bitInByte = 0; } // Switch the column if byte under/overflow - if(byteInColumn < 0) - { + if (byteInColumn < 0) { column--; byteInColumn = bytesPerColumn; - } - else if(byteInColumn >= int(byteInColumn)) - { + } else if (byteInColumn >= int(byteInColumn)) { column++; byteInColumn = 0; } // If we switch the row we return 0 (culumn under/overflow) - if(column < 0) - { + if (column < 0) { return 0; - } - else if(column >= int(numberOfColumns)) - { + } else if (column >= int(numberOfColumns)) { return 0; } // Row over/underflow return 0 - if(row < 0) - { + if (row < 0) { return 0; - } - else if(row >= int(numberOfRows)) - { + } else if (row >= int(numberOfRows)) { return 0; } @@ -527,12 +497,15 @@ double errorModel::getTemperature() if (thermalSim == true && powerAnalysis == true) { // TODO // check if this is best way to request information to DRAMPower. - unsigned long long clk_cycles = sc_time_stamp().value() / Configuration::getInstance().memSpec.clk.value(); + unsigned long long clk_cycles = sc_time_stamp().value() / + Configuration::getInstance().memSpec.clk.value(); DRAMPower->calcWindowEnergy(clk_cycles); float average_power = (float)DRAMPower->getPower().average_power; - temperature = TemperatureController::getInstance().getTemperature(this->myChannel, average_power); + temperature = TemperatureController::getInstance().getTemperature( + this->myChannel, average_power); } else { - temperature = TemperatureController::getInstance().getTemperature(this->myChannel, 0); + temperature = TemperatureController::getInstance().getTemperature( + this->myChannel, 0); } } @@ -544,11 +517,9 @@ void errorModel::parseInputData() std::string fileName = Configuration::getInstance().ErrorCSVFile; std::ifstream inputFile(fileName); - if(inputFile.is_open()) - { + if (inputFile.is_open()) { std::string line; - while(std::getline(inputFile,line)) - { + while (std::getline(inputFile, line)) { std::istringstream iss(line); std::string str_temperature; std::string str_retentionTime; @@ -566,25 +537,27 @@ void errorModel::parseInputData() >> str_sigma_dependent; double temp = std::stod(str_temperature.c_str(), 0); - sc_time retentionTime = sc_time(std::stod(str_retentionTime.c_str(),0),SC_MS); + sc_time retentionTime = sc_time(std::stod(str_retentionTime.c_str(), 0), + SC_MS); - unsigned int mu_independent = std::stod(str_mu_independent.c_str(),0); - unsigned int sigma_independent = std::stod(str_sigma_independent.c_str(),0); - unsigned int mu_dependent = std::stod(str_mu_dependent.c_str(),0); - unsigned int sigma_dependent = std::stod(str_sigma_dependent.c_str(),0); + unsigned int mu_independent = std::stod(str_mu_independent.c_str(), 0); + unsigned int sigma_independent = std::stod(str_sigma_independent.c_str(), 0); + unsigned int mu_dependent = std::stod(str_mu_dependent.c_str(), 0); + unsigned int sigma_dependent = std::stod(str_sigma_dependent.c_str(), 0); errors e; //calculate normal distribution of # of independent errors unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine generator(seed); - std::normal_distribution distribution(mu_independent,sigma_independent); + std::normal_distribution distribution(mu_independent, + sigma_independent); e.independent = ceil(distribution(generator)); // calculate normal distribution of # of dependent errors unsigned seed2 = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine generator2(seed2); - std::normal_distribution distribution2(mu_dependent,sigma_dependent); + std::normal_distribution distribution2(mu_dependent, sigma_dependent); e.dependent = ceil(distribution2(generator2)); // Store parsed data to the errorMap: @@ -599,10 +572,8 @@ void errorModel::parseInputData() printDebugMessage(msg.str()); } inputFile.close(); - } - else - { - SC_REPORT_FATAL("errormodel","Cannot open ErrorCSVFile"); + } else { + SC_REPORT_FATAL("errormodel", "Cannot open ErrorCSVFile"); } } @@ -611,19 +582,15 @@ void errorModel::prepareWeakCells() // Get the Maxium number of weak cells by iterating over the errorMap: maxNumberOfWeakCells = 0; maxNumberOfDepWeakCells = 0; - for( const auto &i : errorMap ) - { - for( const auto &j : i.second ) - { + for ( const auto &i : errorMap ) { + for ( const auto &j : i.second ) { // Get number of dependent weak cells: - if( j.second.dependent > maxNumberOfDepWeakCells) - { + if ( j.second.dependent > maxNumberOfDepWeakCells) { maxNumberOfDepWeakCells = j.second.dependent; } // Get the total number of weak cells (independet + dependent): - if( j.second.independent + j.second.dependent > maxNumberOfWeakCells) - { + if ( j.second.independent + j.second.dependent > maxNumberOfWeakCells) { maxNumberOfWeakCells = j.second.independent + j.second.dependent; } } @@ -631,22 +598,17 @@ void errorModel::prepareWeakCells() // Get the highest temperature in the error map: maxTemperature = 0; - for( const auto &i : errorMap ) - { - if(i.first > maxTemperature) - { + for ( const auto &i : errorMap ) { + if (i.first > maxTemperature) { maxTemperature = i.first; } } // Get the highest time in the error map: maxTime = SC_ZERO_TIME; - for( const auto &i : errorMap ) - { - for( const auto &j : i.second ) - { - if(j.first > maxTime) - { + for ( const auto &i : errorMap ) { + for ( const auto &j : i.second ) { + if (j.first > maxTime) { maxTime = j.first; } } @@ -656,60 +618,52 @@ void errorModel::prepareWeakCells() weakCells = new weakCell[maxNumberOfWeakCells]; - for (unsigned int i=0; i maxTime) { - SC_REPORT_FATAL("errormodel","time out of range"); + SC_REPORT_FATAL("errormodel", "time out of range"); } // Find nearest temperature: double nearestTemperature = 0; - for( const auto &i : errorMap ) - { - if(i.first >= temp) // for worst case reasons we go to the next bin - { + for ( const auto &i : errorMap ) { + if (i.first >= temp) { // for worst case reasons we go to the next bin nearestTemperature = i.first; break; } @@ -747,10 +699,8 @@ unsigned int errorModel::getNumberOfFlips(double temp, sc_time time) // Find nearest time: sc_time nearestTime; - for( const auto &i : errorMap[nearestTemperature]) - { - if(i.first >= time) // for worst case reasons we go to the next bin - { + for ( const auto &i : errorMap[nearestTemperature]) { + if (i.first >= time) { // for worst case reasons we go to the next bin nearestTime = i.first; break; } @@ -775,14 +725,14 @@ void errorModel::setContext(DecodedAddress addr) { // This function is called the first store ore load to get the context in // which channel, rank or bank the error model is used. - if(myChannel == -1 && myBank == -1 && myBankgroup == -1 && myRank == -1 ) - { + if (myChannel == -1 && myBank == -1 && myBankgroup == -1 && myRank == -1 ) { myChannel = addr.channel; myBank = addr.bank; myBankgroup = addr.bankgroup; myRank = addr.rank; - contextStr = "Channel_" + std::to_string(myChannel) + "_Bank_" + std::to_string(myBank) + " "; + contextStr = "Channel_" + std::to_string(myChannel) + "_Bank_" + std::to_string( + myBank) + " "; } } diff --git a/DRAMSys/library/src/error/errormodel.h b/DRAMSys/library/src/error/errormodel.h index f7efed69..c1f21c6e 100644 --- a/DRAMSys/library/src/error/errormodel.h +++ b/DRAMSys/library/src/error/errormodel.h @@ -45,7 +45,7 @@ class errorModel : public sc_module { - public: +public: errorModel(sc_module_name /*name*/, libDRAMPower *dp); errorModel(sc_module_name /*name*/); ~errorModel(); @@ -58,7 +58,7 @@ class errorModel : public sc_module void setTemperature(double t); double getTemperature(void); - private: +private: void init(void); bool powerAnalysis; libDRAMPower *DRAMPower; @@ -83,13 +83,13 @@ class errorModel : public sc_module void markBitFlips(); unsigned int getNumberOfFlips(double temp, sc_time time); void setContext(DecodedAddress addr); - unsigned int getBit(DecodedAddress key, unsigned int byte, unsigned int bitInByte); + unsigned int getBit(DecodedAddress key, unsigned int byte, + unsigned int bitInByte); unsigned int getBit(int row, int column, int byteInColumn, int bitInByte); // Input related data structures: - struct errors - { + struct errors { double independent; double dependent; }; @@ -104,8 +104,7 @@ class errorModel : public sc_module sc_time maxTime; // Storage of weak cells: - struct weakCell - { + struct weakCell { unsigned int row; unsigned int col; unsigned int bit; @@ -113,12 +112,12 @@ class errorModel : public sc_module bool dependent; }; - weakCell * weakCells; + weakCell *weakCells; // To use a map for storing the data a comparing function must be defined - struct DecodedAddressComparer - { - bool operator()( const DecodedAddress& first , const DecodedAddress& second) const + struct DecodedAddressComparer { + bool operator()( const DecodedAddress &first , + const DecodedAddress &second) const { sc_dt::uint64 addrFirst = AddressDecoder::getInstance().encodeAddress(first); sc_dt::uint64 addrSecond = AddressDecoder::getInstance().encodeAddress(second); @@ -132,7 +131,7 @@ class errorModel : public sc_module std::map dataMap; // An array to save when the last ACT/REF to a row happened: - sc_time * lastRowAccess; + sc_time *lastRowAccess; // Context Variables (will be written by the first dram access) int myChannel; diff --git a/DRAMSys/library/src/simulation/Arbiter.h b/DRAMSys/library/src/simulation/Arbiter.h index fe9ce71e..027184d2 100644 --- a/DRAMSys/library/src/simulation/Arbiter.h +++ b/DRAMSys/library/src/simulation/Arbiter.h @@ -59,7 +59,8 @@ public: tlm_utils::multi_passthrough_initiator_socket iSocket; tlm_utils::multi_passthrough_target_socket tSocket; - SC_CTOR(Arbiter) : payloadEventQueue(this, &Arbiter::peqCallback) { + SC_CTOR(Arbiter) : payloadEventQueue(this, &Arbiter::peqCallback) + { // The arbiter communicates with one or more memory unity through one or more sockets (one or more memory channels). // Each of the arbiter's initiator sockets is bound to a memory controller's target socket. // Anytime an transaction comes from a memory unity to the arbiter the "bw" callback is called. @@ -67,7 +68,7 @@ public: for (size_t i = 0; i < Configuration::getInstance().NumberOfMemChannels; ++i) { channelIsFree.push_back(true); - pendingRequests.push_back(queue()); + pendingRequests.push_back(queue()); } // One or more devices can accesss all the memory units through the arbiter. @@ -78,7 +79,7 @@ public: tSocket.register_transport_dbg(this, &Arbiter::transport_dbg); } - void setTlmRecorders(std::vector recorders) + void setTlmRecorders(std::vector recorders) { tlmRecorders = recorders; } @@ -90,28 +91,32 @@ private: //used to account for the request_accept_delay in the dram controllers // This is a queue of new transactions. The phase of a new request is BEGIN_REQ. - vector> pendingRequests; + vector> pendingRequests; //used to account for the response_accept_delay in the initiators (traceplayer,core etc.) // This is a queue of responses comming from the memory side. The phase of these transactions is BEGIN_RESP. - std::map> receivedResponses; + std::map> receivedResponses; - std::vector tlmRecorders; + std::vector tlmRecorders; //used to map the transaction from devices to the arbiter's target socket ID. - std::map routeMap; + std::map routeMap; // Initiated by dram side // This function is called when an arbiter's initiator socket receives a transaction from a memory controller - tlm_sync_enum nb_transport_bw(int channelId, tlm_generic_payload &payload, tlm_phase &phase, sc_time &bwDelay) + tlm_sync_enum nb_transport_bw(int channelId, tlm_generic_payload &payload, + tlm_phase &phase, sc_time &bwDelay) { // Check channel ID - if ((unsigned int)channelId != DramExtension::getExtension(payload).getChannel().ID()) { + if ((unsigned int)channelId != DramExtension::getExtension( + payload).getChannel().ID()) { SC_REPORT_FATAL("Arbiter", "Payload extension was corrupted"); } sc_time recTime = bwDelay + sc_time_stamp(); sc_time notDelay = bwDelay; - printDebugMessage("[bw] Recording " + phaseNameToString(phase) + " at " + recTime.to_string() + " notification in " + notDelay.to_string()); + printDebugMessage("[bw] Recording " + phaseNameToString( + phase) + " at " + recTime.to_string() + " notification in " + + notDelay.to_string()); tlmRecorders[channelId]->recordPhase(payload, phase, recTime); payloadEventQueue.notify(payload, phase, notDelay); @@ -120,12 +125,13 @@ private: // Initiated by initiator side // This function is called when an arbiter's target socket receives a transaction from a device - tlm_sync_enum nb_transport_fw(int id, tlm_generic_payload& payload, tlm_phase& phase, sc_time& fwDelay) + tlm_sync_enum nb_transport_fw(int id, tlm_generic_payload &payload, + tlm_phase &phase, sc_time &fwDelay) { - if (phase == BEGIN_REQ) - { + if (phase == BEGIN_REQ) { // adjust address offset: - payload.set_address(payload.get_address() - Configuration::getInstance().AddressOffset); + payload.set_address(payload.get_address() - + Configuration::getInstance().AddressOffset); // Map the payload with socket id. routeMap[&payload] = id; @@ -134,9 +140,7 @@ private: // It will extracted from the payload and used later. appendDramExtension(id, payload); payload.acquire(); - } - else if (phase == END_RESP) - { + } else if (phase == END_RESP) { // Erase before the payload is released. routeMap.erase(&payload); payload.release(); @@ -149,15 +153,18 @@ private: virtual unsigned int transport_dbg(int /*id*/, tlm::tlm_generic_payload &trans) { // adjust address offset: - trans.set_address(trans.get_address() - Configuration::getInstance().AddressOffset); + trans.set_address(trans.get_address() - + Configuration::getInstance().AddressOffset); - DecodedAddress decodedAddress = AddressDecoder::getInstance().decodeAddress(trans.get_address()); + DecodedAddress decodedAddress = AddressDecoder::getInstance().decodeAddress( + trans.get_address()); return iSocket[decodedAddress.channel]->transport_dbg(trans); } - void peqCallback(tlm_generic_payload& payload, const tlm_phase& phase) + void peqCallback(tlm_generic_payload &payload, const tlm_phase &phase) { - unsigned int initiatorSocket = DramExtension::getExtension(payload).getThread().ID(); + unsigned int initiatorSocket = DramExtension::getExtension( + payload).getThread().ID(); unsigned int channelId = DramExtension::getExtension(payload).getChannel().ID(); // Check the valid range of initiatorSocket ID and channel Id @@ -215,50 +222,56 @@ private: // The arbiter receives a transaction in BEGIN_RESP phase // (that came from the memory side) and forwards it to the requester // device - if (receivedResponses[initiatorSocket].empty()) - { + if (receivedResponses[initiatorSocket].empty()) { sendToInitiator(initiatorSocket, payload, phase, SC_ZERO_TIME); } // Enqueue the transaction in BEGIN_RESP phase until the initiator // device acknowledge it (phase changes to END_RESP). receivedResponses[initiatorSocket].push(&payload); } else { - SC_REPORT_FATAL(0, "Payload event queue in arbiter was triggered with unknown phase"); + SC_REPORT_FATAL(0, + "Payload event queue in arbiter was triggered with unknown phase"); } } - void sendToChannel(unsigned int channelId, tlm_generic_payload& payload, const tlm_phase& phase, const sc_time& delay) + void sendToChannel(unsigned int channelId, tlm_generic_payload &payload, + const tlm_phase &phase, const sc_time &delay) { tlm_phase TPhase = phase; sc_time TDelay = delay; iSocket[channelId]->nb_transport_fw(payload, TPhase, TDelay); } - void sendToInitiator(unsigned int id, tlm_generic_payload& payload, const tlm_phase& phase, const sc_time& delay) + void sendToInitiator(unsigned int id, tlm_generic_payload &payload, + const tlm_phase &phase, const sc_time &delay) { tlm_phase TPhase = phase; sc_time TDelay = delay; tSocket[id]->nb_transport_bw(payload, TPhase, TDelay); } - void appendDramExtension(int socketId, tlm_generic_payload& payload) + void appendDramExtension(int socketId, tlm_generic_payload &payload) { // Append Generation Extension - GenerationExtension* genExtension = new GenerationExtension(sc_time_stamp()); + GenerationExtension *genExtension = new GenerationExtension(sc_time_stamp()); payload.set_auto_extension(genExtension); unsigned int burstlength = payload.get_streaming_width(); - DecodedAddress decodedAddress = AddressDecoder::getInstance().decodeAddress(payload.get_address()); + DecodedAddress decodedAddress = AddressDecoder::getInstance().decodeAddress( + payload.get_address()); // Check the valid range of decodedAddress if (addressIsValid(decodedAddress)) { - DramExtension* extension = new DramExtension(Thread(socketId), Channel(decodedAddress.channel), Bank(decodedAddress.bank), BankGroup(decodedAddress.bankgroup), Row(decodedAddress.row), Column(decodedAddress.column),burstlength); + DramExtension *extension = new DramExtension(Thread(socketId), + Channel(decodedAddress.channel), Bank(decodedAddress.bank), + BankGroup(decodedAddress.bankgroup), Row(decodedAddress.row), + Column(decodedAddress.column), burstlength); payload.set_auto_extension(extension); } else { - SC_REPORT_FATAL("Arbiter", "Decoded Address are not inside the valid range"); + SC_REPORT_FATAL("Arbiter", "Decoded Address are not inside the valid range"); } } - bool addressIsValid(DecodedAddress& decodedAddress) + bool addressIsValid(DecodedAddress &decodedAddress) { if (decodedAddress.channel >= AddressDecoder::getInstance().amount["channel"]) { return false; @@ -266,7 +279,8 @@ private: if (decodedAddress.bank >= AddressDecoder::getInstance().amount["bank"]) { return false; } - if (decodedAddress.bankgroup > AddressDecoder::getInstance().amount["bankgroup"]) { + if (decodedAddress.bankgroup > + AddressDecoder::getInstance().amount["bankgroup"]) { return false; } if (decodedAddress.column >= AddressDecoder::getInstance().amount["column"]) { diff --git a/DRAMSys/library/src/simulation/DRAMSys.cpp b/DRAMSys/library/src/simulation/DRAMSys.cpp index 3e9211cc..25c93ad6 100644 --- a/DRAMSys/library/src/simulation/DRAMSys.cpp +++ b/DRAMSys/library/src/simulation/DRAMSys.cpp @@ -61,7 +61,7 @@ DRAMSys::DRAMSys(sc_module_name __attribute__((unused)) name, string pathToResources) : tSocket("DRAMSys_tSocket") { // Initialize ecc pointer - ecc = nullptr; + ecc = nullptr; logo(); @@ -85,22 +85,17 @@ DRAMSys::DRAMSys(sc_module_name __attribute__((unused)) name, // ConfigurationLoader because some information from the xmlAddressDecoder // is needed to assure the coherence of the configuration. - if(amconfig.find(".xml") != string::npos) - { + if (amconfig.find(".xml") != string::npos) { AddressDecoder::createInstance(AddressDecoder::Type::XML); AddressDecoder::getInstance().setConfiguration(pathToResources - + "configs/amconfigs/" - + amconfig); - } - else if(amconfig.find(".json") != string::npos) - { + + "configs/amconfigs/" + + amconfig); + } else if (amconfig.find(".json") != string::npos) { AddressDecoder::createInstance(AddressDecoder::Type::JSON); AddressDecoder::getInstance().setConfiguration(pathToResources - + "configs/amconfigs/" - + amconfig); - } - else - { + + "configs/amconfigs/" + + amconfig); + } else { throw std::runtime_error("No address mapping loaded. Unknown file extension"); } @@ -139,8 +134,8 @@ DRAMSys::DRAMSys(sc_module_name __attribute__((unused)) name, void DRAMSys::logo() { - #define REDTXT(s) string(("\033[0;31m"+string((s))+"\033[0m")) - #define BOLDBLUETXT(s) string(("\033[1;34m"+string((s))+"\033[0m")) +#define REDTXT(s) string(("\033[0;31m"+string((s))+"\033[0m")) +#define BOLDBLUETXT(s) string(("\033[1;34m"+string((s))+"\033[0m")) cout << endl; cout << REDTXT(" |||") << endl; cout << REDTXT(" +---+ Microelectronic Systems") << endl; @@ -150,16 +145,16 @@ void DRAMSys::logo() cout << REDTXT(" +---+ ") << endl; cout << REDTXT(" ||| ") << "DRAMSys v3.0" << endl; cout << endl; - #undef REDTXT - #undef BOLDBLUETXT +#undef REDTXT +#undef BOLDBLUETXT } -void DRAMSys::setupDebugManager(const string& traceName) +void DRAMSys::setupDebugManager(const string &traceName) { - auto& dbg = DebugManager::getInstance(); + auto &dbg = DebugManager::getInstance(); dbg.writeToConsole = true; dbg.writeToFile = true; - if(dbg.writeToFile) + if (dbg.writeToFile) dbg.openDebugFile(traceName + ".txt"); } @@ -168,24 +163,23 @@ void DRAMSys::setupTlmRecorders(const string &traceName, { // Create TLM Recorders, one per channel. for (size_t i = 0; - i < Configuration::getInstance().NumberOfMemChannels; - i++) - { + i < Configuration::getInstance().NumberOfMemChannels; + i++) { std::string sqlScriptURI = pathToResources - + string("scripts/createTraceDB.sql"); + + string("scripts/createTraceDB.sql"); std::string dbName = traceName - + string("_channel") - + std::to_string(i) - + ".tdb"; + + string("_channel") + + std::to_string(i) + + ".tdb"; std::string recorderName = "tlmRecorder" + std::to_string(i); TlmRecorder *tlmRecorder = - new TlmRecorder(recorderName.c_str(), - sqlScriptURI.c_str(), - dbName.c_str(), - Configuration::getInstance().DatabaseRecording); + new TlmRecorder(recorderName.c_str(), + sqlScriptURI.c_str(), + dbName.c_str(), + Configuration::getInstance().DatabaseRecording); tlmRecorder->recordMCconfig(Configuration::getInstance().mcconfigUri); tlmRecorder->recordMemspec(Configuration::getInstance().memspecUri); @@ -207,29 +201,27 @@ void DRAMSys::instantiateModules(const string &traceName, // They need to be ready before creating some modules. setupTlmRecorders(traceName, pathToResources); - // Create new ECC Controller - switch (Configuration::getInstance().ECCMode) - { - case ECCControllerMode::Hamming: - ecc = new ECCHamming("ECCHamming"); - break; - default: - ecc = nullptr; - break; - } + // Create new ECC Controller + switch (Configuration::getInstance().ECCMode) { + case ECCControllerMode::Hamming: + ecc = new ECCHamming("ECCHamming"); + break; + default: + ecc = nullptr; + break; + } - // Save ECC Controller into the configuration struct to adjust it dynamically - Configuration::getInstance().pECC = ecc; + // Save ECC Controller into the configuration struct to adjust it dynamically + Configuration::getInstance().pECC = ecc; - // Create arbiter + // Create arbiter arbiter = new Arbiter("arbiter"); arbiter->setTlmRecorders(tlmRecorders); - // Create DRAM + // Create DRAM for (size_t i = 0; - i < Configuration::getInstance().NumberOfMemChannels; - i++) - { + i < Configuration::getInstance().NumberOfMemChannels; + i++) { std::string str = "controller" + std::to_string(i); Controller *controller = new Controller(str.c_str(), tlmRecorders[i]); controllers.push_back(controller); @@ -240,11 +232,10 @@ void DRAMSys::instantiateModules(const string &traceName, dram->setDramController(controllers[i]); drams.push_back(dram); - if(Configuration::getInstance().CheckTLM2Protocol) - { - str = "TLMCheckerController"+ std::to_string(i); - tlm_utils::tlm2_base_protocol_checker<> * controllerTlmChecker = - new tlm_utils::tlm2_base_protocol_checker<>(str.c_str()); + if (Configuration::getInstance().CheckTLM2Protocol) { + str = "TLMCheckerController" + std::to_string(i); + tlm_utils::tlm2_base_protocol_checker<> *controllerTlmChecker = + new tlm_utils::tlm2_base_protocol_checker<>(str.c_str()); controllersTlmCheckers.push_back(controllerTlmChecker); } } @@ -253,35 +244,27 @@ void DRAMSys::instantiateModules(const string &traceName, void DRAMSys::bindSockets() { // If ECC Controller enabled, put it between Trace and arbiter - if(Configuration::getInstance().ECCMode != ECCControllerMode::Disabled) - { - assert(ecc != nullptr); + if (Configuration::getInstance().ECCMode != ECCControllerMode::Disabled) { + assert(ecc != nullptr); tSocket.bind(ecc->t_socket); ecc->i_socket.bind(arbiter->tSocket); - } - else - { + } else { tSocket.bind(arbiter->tSocket); } - if(Configuration::getInstance().CheckTLM2Protocol) - { + if (Configuration::getInstance().CheckTLM2Protocol) { for (size_t i = 0; - i < Configuration::getInstance().NumberOfMemChannels; - i++) - { + i < Configuration::getInstance().NumberOfMemChannels; + i++) { arbiter->iSocket.bind(controllersTlmCheckers[i]->target_socket); controllersTlmCheckers[i]->initiator_socket.bind( - controllers[i]->tSocket); + controllers[i]->tSocket); controllers[i]->iSocket.bind(drams[i]->tSocket); } - } - else - { + } else { for (size_t i = 0; - i < Configuration::getInstance().NumberOfMemChannels; - i++) - { + i < Configuration::getInstance().NumberOfMemChannels; + i++) { arbiter->iSocket.bind(controllers[i]->tSocket); controllers[i]->iSocket.bind(drams[i]->tSocket); } @@ -290,28 +273,24 @@ void DRAMSys::bindSockets() DRAMSys::~DRAMSys() { - if(ecc) + if (ecc) delete ecc; delete arbiter; - for (auto dram : drams) - { + for (auto dram : drams) { delete dram; } - for (auto rec : tlmRecorders) - { + for (auto rec : tlmRecorders) { delete rec; } - for (auto tlmChecker : controllersTlmCheckers) - { + for (auto tlmChecker : controllersTlmCheckers) { delete tlmChecker; } - for (auto controller : controllers) - { + for (auto controller : controllers) { delete controller; } } diff --git a/DRAMSys/library/src/simulation/DRAMSys.h b/DRAMSys/library/src/simulation/DRAMSys.h index 63ea9052..0a3c2337 100644 --- a/DRAMSys/library/src/simulation/DRAMSys.h +++ b/DRAMSys/library/src/simulation/DRAMSys.h @@ -77,24 +77,24 @@ private: //TLM 2.0 Protocol Checkers std::vector*> - controllersTlmCheckers; + controllersTlmCheckers; // All transactions pass first through the ECC Controller ECCBaseClass *ecc; // All transactions pass through the same arbiter Arbiter *arbiter; // Each DRAM unit has a controller - std::vector controllers; + std::vector controllers; // TODO: Each DRAM has a reorder buffer (check this!) ReorderBuffer *reorder; // DRAM units - std::vector drams; + std::vector drams; // Transaction Recorders (one per channel). // They generate the output databases. - std::vector tlmRecorders; + std::vector tlmRecorders; void report(std::string message); void setupTlmRecorders(const string &traceName, diff --git a/DRAMSys/library/src/simulation/Dram.h b/DRAMSys/library/src/simulation/Dram.h index cafd7255..c1e0a9cf 100644 --- a/DRAMSys/library/src/simulation/Dram.h +++ b/DRAMSys/library/src/simulation/Dram.h @@ -63,8 +63,7 @@ using namespace std; using namespace tlm; using namespace Data; -struct Dram : sc_module -{ +struct Dram : sc_module { unsigned int bytesPerBurst = Configuration::getInstance().getBytesPerBurst(); // TLM Related: @@ -72,7 +71,8 @@ struct Dram : sc_module // Power Model related bool powerAnalysis = Configuration::getInstance().PowerAnalysis; - sc_time powerWindowSize = Configuration::getInstance().memSpec.clk*Configuration::getInstance().WindowSize; + sc_time powerWindowSize = Configuration::getInstance().memSpec.clk * + Configuration::getInstance().WindowSize; libDRAMPower *DRAMPower; // Bandwidth realted: @@ -92,66 +92,74 @@ struct Dram : sc_module SC_CTOR(Dram) : tSocket("socket") { - // Adjust number of bytes per burst dynamically to the selected ecc controller - bytesPerBurst = Configuration::getInstance().adjustNumBytesAfterECC(bytesPerBurst); + // Adjust number of bytes per burst dynamically to the selected ecc controller + bytesPerBurst = Configuration::getInstance().adjustNumBytesAfterECC( + bytesPerBurst); dramController = NULL; tlmRecorder = NULL; std::uint64_t memorySize = Configuration::getInstance().getSimMemSizeInBytes(); // allocate and model storage of one DRAM channel using memory map - memory = (unsigned char *)mmap(NULL, memorySize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_NORESERVE, -1, 0); + memory = (unsigned char *)mmap(NULL, memorySize, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANON | MAP_NORESERVE, -1, 0); tSocket.register_nb_transport_fw(this, &Dram::nb_transport_fw); - tSocket.register_transport_dbg(this,&Dram::transport_dbg); + tSocket.register_transport_dbg(this, &Dram::transport_dbg); - if(powerAnalysis == true) - { + if (powerAnalysis == true) { sc_time clk = Configuration::getInstance().memSpec.clk; MemArchitectureSpec memArchSpec; - memArchSpec.burstLength = Configuration::getInstance().memSpec.BurstLength; + memArchSpec.burstLength = + Configuration::getInstance().memSpec.BurstLength; memArchSpec.dataRate = Configuration::getInstance().memSpec.DataRate; - memArchSpec.nbrOfRows = Configuration::getInstance().memSpec.NumberOfRows; - memArchSpec.nbrOfBanks = Configuration::getInstance().memSpec.NumberOfBanks; - memArchSpec.nbrOfColumns = Configuration::getInstance().memSpec.NumberOfColumns; - memArchSpec.nbrOfRanks = Configuration::getInstance().memSpec.NumberOfRanks; + memArchSpec.nbrOfRows = + Configuration::getInstance().memSpec.NumberOfRows; + memArchSpec.nbrOfBanks = + Configuration::getInstance().memSpec.NumberOfBanks; + memArchSpec.nbrOfColumns = + Configuration::getInstance().memSpec.NumberOfColumns; + memArchSpec.nbrOfRanks = + Configuration::getInstance().memSpec.NumberOfRanks; memArchSpec.width = Configuration::getInstance().memSpec.bitWidth; - memArchSpec.nbrOfBankGroups = Configuration::getInstance().memSpec.NumberOfBankGroups; - memArchSpec.twoVoltageDomains = (Configuration::getInstance().memSpec.vDD2 == 0 ? false : true); + memArchSpec.nbrOfBankGroups = + Configuration::getInstance().memSpec.NumberOfBankGroups; + memArchSpec.twoVoltageDomains = (Configuration::getInstance().memSpec.vDD2 == 0 + ? false : true); memArchSpec.dll = Configuration::getInstance().memSpec.DLL; MemTimingSpec memTimingSpec; - memTimingSpec.AL = Configuration::getInstance().memSpec.tAL/clk; - memTimingSpec.CCD = Configuration::getInstance().memSpec.tCCD_S/clk; - memTimingSpec.CCD_L = Configuration::getInstance().memSpec.tCCD_L/clk; - memTimingSpec.CCD_S = Configuration::getInstance().memSpec.tCCD_S/clk; - memTimingSpec.CKE = Configuration::getInstance().memSpec.tCKE/clk; - memTimingSpec.CKESR = Configuration::getInstance().memSpec.tCKESR/clk; + memTimingSpec.AL = Configuration::getInstance().memSpec.tAL / clk; + memTimingSpec.CCD = Configuration::getInstance().memSpec.tCCD_S / clk; + memTimingSpec.CCD_L = Configuration::getInstance().memSpec.tCCD_L / clk; + memTimingSpec.CCD_S = Configuration::getInstance().memSpec.tCCD_S / clk; + memTimingSpec.CKE = Configuration::getInstance().memSpec.tCKE / clk; + memTimingSpec.CKESR = Configuration::getInstance().memSpec.tCKESR / clk; memTimingSpec.clkMhz = int(1 / (clk.value() / 1000000.0)); memTimingSpec.clkPeriod = clk.value() / 1000.0; - memTimingSpec.DQSCK = Configuration::getInstance().memSpec.tDQSCK/clk; - memTimingSpec.FAW = Configuration::getInstance().memSpec.tNAW/clk; - memTimingSpec.RAS = Configuration::getInstance().memSpec.tRAS/clk; - memTimingSpec.RC = Configuration::getInstance().memSpec.tRC/clk; - memTimingSpec.RCD = Configuration::getInstance().memSpec.tRCD/clk; - memTimingSpec.REFI = Configuration::getInstance().memSpec.tREFI/clk; - memTimingSpec.RFC = Configuration::getInstance().memSpec.tRFC/clk; - memTimingSpec.RL = Configuration::getInstance().memSpec.tRL/clk; - memTimingSpec.RP = Configuration::getInstance().memSpec.tRP/clk; - memTimingSpec.RRD = Configuration::getInstance().memSpec.tRRD_S/clk; - memTimingSpec.RRD_L = Configuration::getInstance().memSpec.tRRD_L/clk; - memTimingSpec.RRD_S = Configuration::getInstance().memSpec.tRRD_S/clk; - memTimingSpec.RTP = Configuration::getInstance().memSpec.tRTP/clk; - memTimingSpec.TAW = Configuration::getInstance().memSpec.tNAW/clk; - memTimingSpec.WL = Configuration::getInstance().memSpec.tWL/clk; - memTimingSpec.WR = Configuration::getInstance().memSpec.tWR/clk; - memTimingSpec.WTR = Configuration::getInstance().memSpec.tWTR_S/clk; - memTimingSpec.WTR_L = Configuration::getInstance().memSpec.tWTR_L/clk; - memTimingSpec.WTR_S = Configuration::getInstance().memSpec.tWTR_S/clk; - memTimingSpec.XP = Configuration::getInstance().memSpec.tXP/clk; - memTimingSpec.XPDLL = Configuration::getInstance().memSpec.tXPDLL/clk; - memTimingSpec.XS = Configuration::getInstance().memSpec.tXSR/clk; - memTimingSpec.XSDLL = Configuration::getInstance().memSpec.tXSRDLL/clk; + memTimingSpec.DQSCK = Configuration::getInstance().memSpec.tDQSCK / clk; + memTimingSpec.FAW = Configuration::getInstance().memSpec.tNAW / clk; + memTimingSpec.RAS = Configuration::getInstance().memSpec.tRAS / clk; + memTimingSpec.RC = Configuration::getInstance().memSpec.tRC / clk; + memTimingSpec.RCD = Configuration::getInstance().memSpec.tRCD / clk; + memTimingSpec.REFI = Configuration::getInstance().memSpec.tREFI / clk; + memTimingSpec.RFC = Configuration::getInstance().memSpec.tRFC / clk; + memTimingSpec.RL = Configuration::getInstance().memSpec.tRL / clk; + memTimingSpec.RP = Configuration::getInstance().memSpec.tRP / clk; + memTimingSpec.RRD = Configuration::getInstance().memSpec.tRRD_S / clk; + memTimingSpec.RRD_L = Configuration::getInstance().memSpec.tRRD_L / clk; + memTimingSpec.RRD_S = Configuration::getInstance().memSpec.tRRD_S / clk; + memTimingSpec.RTP = Configuration::getInstance().memSpec.tRTP / clk; + memTimingSpec.TAW = Configuration::getInstance().memSpec.tNAW / clk; + memTimingSpec.WL = Configuration::getInstance().memSpec.tWL / clk; + memTimingSpec.WR = Configuration::getInstance().memSpec.tWR / clk; + memTimingSpec.WTR = Configuration::getInstance().memSpec.tWTR_S / clk; + memTimingSpec.WTR_L = Configuration::getInstance().memSpec.tWTR_L / clk; + memTimingSpec.WTR_S = Configuration::getInstance().memSpec.tWTR_S / clk; + memTimingSpec.XP = Configuration::getInstance().memSpec.tXP / clk; + memTimingSpec.XPDLL = Configuration::getInstance().memSpec.tXPDLL / clk; + memTimingSpec.XS = Configuration::getInstance().memSpec.tXSR / clk; + memTimingSpec.XSDLL = Configuration::getInstance().memSpec.tXSRDLL / clk; MemPowerSpec memPowerSpec; memPowerSpec.idd0 = Configuration::getInstance().memSpec.iDD0; @@ -190,7 +198,7 @@ struct Dram : sc_module // Create a thread that is triggered every $powerWindowSize // to generate a Power over Time plot in the Trace analyzer: - if(Configuration::getInstance().EnableWindowing) + if (Configuration::getInstance().EnableWindowing) SC_THREAD(powerWindow); } @@ -200,9 +208,9 @@ struct Dram : sc_module lastAccess = SC_ZERO_TIME; // For each bank in a channel a error Model is created: - if(StoreMode == StorageMode::ErrorModel) - { - for (unsigned i = 0; i < Configuration::getInstance().memSpec.NumberOfBanks; i++) { + if (StoreMode == StorageMode::ErrorModel) { + for (unsigned i = 0; i < Configuration::getInstance().memSpec.NumberOfBanks; + i++) { errorModel *em; std::string errorModelStr = "errorModel_bank" + std::to_string(i); if (powerAnalysis == true) { @@ -221,68 +229,67 @@ struct Dram : sc_module ~Dram() { - if (powerAnalysis == true) - { + if (powerAnalysis == true) { // Obtain the residual energy which was not covered by // previous windows DRAMPower->calcEnergy(); tlmRecorder->recordPower(sc_time_stamp().to_seconds(), - DRAMPower->getPower().window_average_power - * Configuration::getInstance().NumberOfDevicesOnDIMM); + DRAMPower->getPower().window_average_power + * Configuration::getInstance().NumberOfDevicesOnDIMM); // Print the final total energy and the average power for // the simulation: cout << name() << string(" Total Energy: ") - << fixed <getEnergy().total_energy - * Configuration::getInstance().NumberOfDevicesOnDIMM + * Configuration::getInstance().NumberOfDevicesOnDIMM << string(" pJ") << endl; cout << name() << string(" Average Power: ") - << fixed <getPower().average_power - * Configuration::getInstance().NumberOfDevicesOnDIMM + * Configuration::getInstance().NumberOfDevicesOnDIMM << string(" mW") << endl; } // Bandwidth: sc_time activeTime = numberOfTransactionsServed - * Configuration::getInstance().memSpec.BurstLength - / Configuration::getInstance().memSpec.DataRate - * Configuration::getInstance().memSpec.clk; + * Configuration::getInstance().memSpec.BurstLength + / Configuration::getInstance().memSpec.DataRate + * Configuration::getInstance().memSpec.clk; sc_time idleTime = dramController->getIdleTime(); sc_time endTime = dramController->getEndTime(); sc_time startTime = dramController->getStartTime(); - double bandwidth = (activeTime/(endTime-startTime)*100); - double bandwidth_IDLE = ((activeTime)/(endTime-startTime-idleTime)*100); + double bandwidth = (activeTime / (endTime - startTime) * 100); + double bandwidth_IDLE = ((activeTime) / (endTime - startTime - idleTime) * 100); double maxBandwidth = ( - // clk in Mhz e.g. 800 [MHz]: - (1000000/Configuration::getInstance().memSpec.clk.to_double()) - // DataRate e.g. 2 - * Configuration::getInstance().memSpec.DataRate - // BusWidth e.g. 8 or 64 - * Configuration::getInstance().memSpec.bitWidth - // Number of devices on a DIMM e.g. 8 - * Configuration::getInstance().NumberOfDevicesOnDIMM ) / ( 1024 ); + // clk in Mhz e.g. 800 [MHz]: + (1000000 / Configuration::getInstance().memSpec.clk.to_double()) + // DataRate e.g. 2 + * Configuration::getInstance().memSpec.DataRate + // BusWidth e.g. 8 or 64 + * Configuration::getInstance().memSpec.bitWidth + // Number of devices on a DIMM e.g. 8 + * Configuration::getInstance().NumberOfDevicesOnDIMM ) / ( 1024 ); cout << name() << string(" Total Time: ") - << (endTime-startTime).to_string() + << (endTime - startTime).to_string() << endl; cout << name() << string(" AVG BW: ") - << std::fixed<calcWindowEnergy(clk_cycles); @@ -322,26 +330,30 @@ struct Dram : sc_module assert(!is_equal(DRAMPower->getEnergy().window_energy, 0.0)); // Store the time (in seconds) and the current average power (in mW) into the database - tlmRecorder->recordPower(sc_time_stamp().to_seconds(), DRAMPower->getPower().window_average_power * Configuration::getInstance().NumberOfDevicesOnDIMM); + tlmRecorder->recordPower(sc_time_stamp().to_seconds(), + DRAMPower->getPower().window_average_power * + Configuration::getInstance().NumberOfDevicesOnDIMM); // Here considering that DRAMPower provides the energy in pJ and the power in mW - printDebugMessage(string("\tWindow Energy: \t") + to_string(DRAMPower->getEnergy().window_energy * Configuration::getInstance().NumberOfDevicesOnDIMM) + string("\t[pJ]")); - printDebugMessage(string("\tWindow Average Power: \t") + to_string(DRAMPower->getPower().window_average_power * Configuration::getInstance().NumberOfDevicesOnDIMM) + string("\t[mW]")); + printDebugMessage(string("\tWindow Energy: \t") + to_string( + DRAMPower->getEnergy().window_energy * + Configuration::getInstance().NumberOfDevicesOnDIMM) + string("\t[pJ]")); + printDebugMessage(string("\tWindow Average Power: \t") + to_string( + DRAMPower->getPower().window_average_power * + Configuration::getInstance().NumberOfDevicesOnDIMM) + string("\t[mW]")); - } while(true); + } while (true); } - virtual tlm::tlm_sync_enum nb_transport_fw(tlm::tlm_generic_payload& payload, tlm::tlm_phase& phase, sc_time& delay) + virtual tlm::tlm_sync_enum nb_transport_fw(tlm::tlm_generic_payload &payload, + tlm::tlm_phase &phase, sc_time &delay) { // Recording time used by the traceAnalyzer sc_time recTime = sc_time_stamp() + delay; - if(numberOfTransactionsServed == 0) - { + if (numberOfTransactionsServed == 0) { firstAccess = sc_time_stamp(); - } - else - { + } else { lastAccess = sc_time_stamp(); } @@ -363,242 +375,231 @@ struct Dram : sc_module unsigned int row = DramExtension::getExtension(payload).getRow().ID(); unsigned int col = DramExtension::getExtension(payload).getColumn().ID(); - printDebugMessage("[fw] Recording " + phaseNameToString(phase) + " thread " + to_string(thr) + " channel " + to_string(ch) + " bank group " + to_string(bg) + " bank " + to_string(bank) + " row " + to_string(row) + " column " + to_string(col) + " at " + recTime.to_string()); + printDebugMessage("[fw] Recording " + phaseNameToString( + phase) + " thread " + to_string(thr) + " channel " + to_string( + ch) + " bank group " + to_string(bg) + " bank " + to_string( + bank) + " row " + to_string(row) + " column " + to_string( + col) + " at " + recTime.to_string()); tlmRecorder->recordPhase(payload, phase, recTime); // This is only needed for power simulation: unsigned long long cycle = 0; - if(powerAnalysis == true) - { - cycle = sc_time_stamp().value()/Configuration::getInstance().memSpec.clk.value(); + if (powerAnalysis == true) { + cycle = sc_time_stamp().value() / + Configuration::getInstance().memSpec.clk.value(); } - if (phase == BEGIN_PRE) - { - if(powerAnalysis == true){DRAMPower->doCommand(MemCommand::PRE, bank, cycle);} - sendToController(payload, END_PRE, delay + getExecutionTime(Command::Precharge, payload)); - } - else if (phase == BEGIN_PRE_ALL) - { - if(powerAnalysis == true){DRAMPower->doCommand(MemCommand::PREA, bank, cycle);} - sendToController(payload, END_PRE_ALL,delay + getExecutionTime(Command::PrechargeAll, payload)); - } - else if (phase == BEGIN_ACT) - { - if(powerAnalysis == true){DRAMPower->doCommand(MemCommand::ACT, bank, cycle);} - sendToController(payload, END_ACT, delay + getExecutionTime(Command::Activate, payload)); + if (phase == BEGIN_PRE) { + if (powerAnalysis == true) { + DRAMPower->doCommand(MemCommand::PRE, bank, cycle); + } + sendToController(payload, END_PRE, delay + getExecutionTime(Command::Precharge, + payload)); + } else if (phase == BEGIN_PRE_ALL) { + if (powerAnalysis == true) { + DRAMPower->doCommand(MemCommand::PREA, bank, cycle); + } + sendToController(payload, END_PRE_ALL, + delay + getExecutionTime(Command::PrechargeAll, payload)); + } else if (phase == BEGIN_ACT) { + if (powerAnalysis == true) { + DRAMPower->doCommand(MemCommand::ACT, bank, cycle); + } + sendToController(payload, END_ACT, delay + getExecutionTime(Command::Activate, + payload)); unsigned int row = DramExtension::getExtension(payload).getRow().ID(); - if (StoreMode == StorageMode::ErrorModel) - { + if (StoreMode == StorageMode::ErrorModel) { ememory[bank]->activate(row); } - } - else if (phase == BEGIN_WR) - { + } else if (phase == BEGIN_WR) { #if !defined (DRAMSYS_PCT) && !defined (DRAMSYS_GEM5) assert(payload.get_data_length() == bytesPerBurst); #endif - if(powerAnalysis == true){DRAMPower->doCommand(MemCommand::WR, bank, cycle);} + if (powerAnalysis == true) { + DRAMPower->doCommand(MemCommand::WR, bank, cycle); + } numberOfTransactionsServed++; //save data: - if (StoreMode == StorageMode::NoStorage) - { + if (StoreMode == StorageMode::NoStorage) { // Don't store data - } - else if (StoreMode == StorageMode::Store) // Use Storage - { + } else if (StoreMode == StorageMode::Store) { // Use Storage unsigned char *phyAddr = memory + payload.get_address(); memcpy(phyAddr, payload.get_data_ptr(), payload.get_data_length()); - } - else // == 2 Use Storage with Error Model - { + } else { // == 2 Use Storage with Error Model ememory[bank]->store(payload); } - sendToController(payload, END_WR, delay + getExecutionTime(Command::Write, payload)); - } - else if (phase == BEGIN_RD) - { + sendToController(payload, END_WR, delay + getExecutionTime(Command::Write, + payload)); + } else if (phase == BEGIN_RD) { #if !defined (DRAMSYS_PCT) && !defined (DRAMSYS_GEM5) assert(payload.get_data_length() == bytesPerBurst); #endif numberOfTransactionsServed++; - if(powerAnalysis == true){DRAMPower->doCommand(MemCommand::RD, bank, cycle);} + if (powerAnalysis == true) { + DRAMPower->doCommand(MemCommand::RD, bank, cycle); + } // Load data: - if (StoreMode == StorageMode::Store) //use StorageMode - { + if (StoreMode == StorageMode::Store) { //use StorageMode unsigned char *phyAddr = memory + payload.get_address(); memcpy(payload.get_data_ptr(), phyAddr, payload.get_data_length()); - } - else if(StoreMode == StorageMode::ErrorModel)// use StorageMode with errormodel - { + } else if (StoreMode == + StorageMode::ErrorModel) { // use StorageMode with errormodel ememory[bank]->load(payload); } - sendToController(payload, END_RD, delay + getExecutionTime(Command::Read, payload)); - } - else if (phase == BEGIN_WRA) - { + sendToController(payload, END_RD, delay + getExecutionTime(Command::Read, + payload)); + } else if (phase == BEGIN_WRA) { numberOfTransactionsServed++; - if(powerAnalysis == true){DRAMPower->doCommand(MemCommand::WRA, bank, cycle);} + if (powerAnalysis == true) { + DRAMPower->doCommand(MemCommand::WRA, bank, cycle); + } //save data: - if (StoreMode == StorageMode::NoStorage) - { + if (StoreMode == StorageMode::NoStorage) { // Don't store data - } - else if (StoreMode == StorageMode::Store) // Use Storage - { + } else if (StoreMode == StorageMode::Store) { // Use Storage unsigned char *phyAddr = memory + payload.get_address(); memcpy(phyAddr, payload.get_data_ptr(), payload.get_data_length()); - } - else // == 2 Use Storage with Error Model - { + } else { // == 2 Use Storage with Error Model ememory[bank]->store(payload); } - sendToController(payload, END_WRA, delay + getExecutionTime(Command::WriteA, payload)); - } - else if (phase == BEGIN_RDA) - { + sendToController(payload, END_WRA, delay + getExecutionTime(Command::WriteA, + payload)); + } else if (phase == BEGIN_RDA) { numberOfTransactionsServed++; - if(powerAnalysis == true){DRAMPower->doCommand(MemCommand::RDA, bank, cycle);} + if (powerAnalysis == true) { + DRAMPower->doCommand(MemCommand::RDA, bank, cycle); + } // Load data: - if (StoreMode == StorageMode::Store) //use StorageMode - { + if (StoreMode == StorageMode::Store) { //use StorageMode unsigned char *phyAddr = memory + payload.get_address(); memcpy(payload.get_data_ptr(), phyAddr, payload.get_data_length()); - } - else if(StoreMode == StorageMode::ErrorModel)// use StorageMode with errormodel - { + } else if (StoreMode == + StorageMode::ErrorModel) { // use StorageMode with errormodel ememory[bank]->load(payload); } - sendToController(payload, END_RDA, delay + getExecutionTime(Command::ReadA, payload)); - } - else if (phase == BEGIN_REFA) - { - if(powerAnalysis == true){DRAMPower->doCommand(MemCommand::REF, bank, cycle);} - sendToController(payload, END_REFA, delay + getExecutionTime(Command::AutoRefresh, payload)); + sendToController(payload, END_RDA, delay + getExecutionTime(Command::ReadA, + payload)); + } else if (phase == BEGIN_REFA) { + if (powerAnalysis == true) { + DRAMPower->doCommand(MemCommand::REF, bank, cycle); + } + sendToController(payload, END_REFA, + delay + getExecutionTime(Command::AutoRefresh, payload)); unsigned int row = DramExtension::getExtension(payload).getRow().ID(); - if (StoreMode == StorageMode::ErrorModel) - { + if (StoreMode == StorageMode::ErrorModel) { ememory[bank]->refresh(row); } } - else if (phase == BEGIN_REFB) - { - if(powerAnalysis == true){ SC_REPORT_FATAL("DRAM", "Power calculation for bankwise logic not supported");} - sendToController(payload, END_REFB, delay + getExecutionTime(Command::AutoRefresh, payload)); + else if (phase == BEGIN_REFB) { + if (powerAnalysis == true) { + SC_REPORT_FATAL("DRAM", "Power calculation for bankwise logic not supported"); + } + sendToController(payload, END_REFB, + delay + getExecutionTime(Command::AutoRefresh, payload)); } //Powerdown phases have to be started and ended by the controller, because they do not have a fixed length - else if (phase == BEGIN_PDNA) - { - if(powerAnalysis == true){DRAMPower->doCommand(MemCommand::PDN_S_ACT, bank, cycle);} - } - else if (phase == END_PDNA) - { - if(powerAnalysis == true){DRAMPower->doCommand(MemCommand::PUP_ACT, bank, cycle);} - } - else if (phase == BEGIN_PDNAB) - { - if(powerAnalysis == true){SC_REPORT_FATAL("DRAM", "Power calculation for bankwise logic not supported");} - } - else if (phase == END_PDNAB) - { - if(powerAnalysis == true){SC_REPORT_FATAL("DRAM", "Power calculation for bankwise logic not supported");} - } - else if (phase == BEGIN_PDNP) - { - if(powerAnalysis == true){DRAMPower->doCommand(MemCommand::PDN_S_PRE, bank, cycle);} - } - else if (phase == END_PDNP) - { - if(powerAnalysis == true){DRAMPower->doCommand(MemCommand::PUP_PRE, bank, cycle);} - } - else if (phase == BEGIN_PDNPB) - { - if(powerAnalysis == true){SC_REPORT_FATAL("DRAM", "Power calculation for bankwise logic not supported");} - } - else if (phase == END_PDNPB) - { - if(powerAnalysis == true){SC_REPORT_FATAL("DRAM", "Power calculation for bankwise logic not supported");} - } - else if (phase == BEGIN_SREF) - { - if(powerAnalysis == true){DRAMPower->doCommand(MemCommand::SREN, bank, cycle);} - } - else if (phase == END_SREF) - { - if(powerAnalysis == true){DRAMPower->doCommand(MemCommand::SREX, bank, cycle);} - } - else if (phase == BEGIN_SREFB) - { - if(powerAnalysis == true){SC_REPORT_FATAL("DRAM", "Power calculation for bankwise logic not supported");} - } - else if (phase == END_SREFB) - { - if(powerAnalysis == true){SC_REPORT_FATAL("DRAM", "Power calculation for bankwise logic not supported");} - } - else - { - if(powerAnalysis == true){SC_REPORT_FATAL("DRAM", "DRAM PEQ was called with unknown phase");} + else if (phase == BEGIN_PDNA) { + if (powerAnalysis == true) { + DRAMPower->doCommand(MemCommand::PDN_S_ACT, bank, cycle); + } + } else if (phase == END_PDNA) { + if (powerAnalysis == true) { + DRAMPower->doCommand(MemCommand::PUP_ACT, bank, cycle); + } + } else if (phase == BEGIN_PDNAB) { + if (powerAnalysis == true) { + SC_REPORT_FATAL("DRAM", "Power calculation for bankwise logic not supported"); + } + } else if (phase == END_PDNAB) { + if (powerAnalysis == true) { + SC_REPORT_FATAL("DRAM", "Power calculation for bankwise logic not supported"); + } + } else if (phase == BEGIN_PDNP) { + if (powerAnalysis == true) { + DRAMPower->doCommand(MemCommand::PDN_S_PRE, bank, cycle); + } + } else if (phase == END_PDNP) { + if (powerAnalysis == true) { + DRAMPower->doCommand(MemCommand::PUP_PRE, bank, cycle); + } + } else if (phase == BEGIN_PDNPB) { + if (powerAnalysis == true) { + SC_REPORT_FATAL("DRAM", "Power calculation for bankwise logic not supported"); + } + } else if (phase == END_PDNPB) { + if (powerAnalysis == true) { + SC_REPORT_FATAL("DRAM", "Power calculation for bankwise logic not supported"); + } + } else if (phase == BEGIN_SREF) { + if (powerAnalysis == true) { + DRAMPower->doCommand(MemCommand::SREN, bank, cycle); + } + } else if (phase == END_SREF) { + if (powerAnalysis == true) { + DRAMPower->doCommand(MemCommand::SREX, bank, cycle); + } + } else if (phase == BEGIN_SREFB) { + if (powerAnalysis == true) { + SC_REPORT_FATAL("DRAM", "Power calculation for bankwise logic not supported"); + } + } else if (phase == END_SREFB) { + if (powerAnalysis == true) { + SC_REPORT_FATAL("DRAM", "Power calculation for bankwise logic not supported"); + } + } else { + if (powerAnalysis == true) { + SC_REPORT_FATAL("DRAM", "DRAM PEQ was called with unknown phase"); + } } return tlm::TLM_ACCEPTED; } - virtual unsigned int transport_dbg(tlm::tlm_generic_payload& trans) + virtual unsigned int transport_dbg(tlm::tlm_generic_payload &trans) { printDebugMessage("transport_dgb"); // TODO: This part is not tested yet, neither with traceplayers neither with GEM5 coupling - if (StoreMode == StorageMode::NoStorage) - { - SC_REPORT_FATAL("DRAM", "Debug Transport is used in combination with NoStorage"); - } - else - { + if (StoreMode == StorageMode::NoStorage) { + SC_REPORT_FATAL("DRAM", + "Debug Transport is used in combination with NoStorage"); + } else { tlm::tlm_command cmd = trans.get_command(); //sc_dt::uint64 adr = trans.get_address(); // TODO: - offset; - unsigned char* ptr = trans.get_data_ptr(); + unsigned char *ptr = trans.get_data_ptr(); unsigned int len = trans.get_data_length(); //unsigned int bank = DramExtension::getExtension(trans).getBank().ID(); //cout << "cmd " << (cmd ? "write" : "read") << " adr " << hex << adr << " len " << len << endl; - if ( cmd == tlm::TLM_READ_COMMAND ) - { - if (StoreMode == StorageMode::Store) // Use Storage - { + if ( cmd == tlm::TLM_READ_COMMAND ) { + if (StoreMode == StorageMode::Store) { // Use Storage unsigned char *phyAddr = memory + trans.get_address(); memcpy(ptr, phyAddr, trans.get_data_length()); - } - else - { + } else { //ememory[bank]->load(trans); SC_REPORT_FATAL("DRAM", "Debug transport not supported with error model yet."); } - } - else if ( cmd == tlm::TLM_WRITE_COMMAND ) - { + } else if ( cmd == tlm::TLM_WRITE_COMMAND ) { - if (StoreMode == StorageMode::Store) // Use Storage - { - unsigned char *phyAddr = memory + trans.get_address(); - memcpy(phyAddr, ptr, trans.get_data_length()); - } - else - { - //ememory[bank]->store(trans); - SC_REPORT_FATAL("DRAM", "Debug transport not supported with error model yet."); - } + if (StoreMode == StorageMode::Store) { // Use Storage + unsigned char *phyAddr = memory + trans.get_address(); + memcpy(phyAddr, ptr, trans.get_data_length()); + } else { + //ememory[bank]->store(trans); + SC_REPORT_FATAL("DRAM", "Debug transport not supported with error model yet."); + } } return len; @@ -606,7 +607,8 @@ struct Dram : sc_module return 0; } - void sendToController(tlm_generic_payload& payload, const tlm_phase& phase, const sc_time& delay) + void sendToController(tlm_generic_payload &payload, const tlm_phase &phase, + const sc_time &delay) { tlm_phase TPhase = phase; sc_time TDelay = delay; diff --git a/DRAMSys/library/src/simulation/ExampleInitiator.h b/DRAMSys/library/src/simulation/ExampleInitiator.h index f51a6717..f8b60b9e 100644 --- a/DRAMSys/library/src/simulation/ExampleInitiator.h +++ b/DRAMSys/library/src/simulation/ExampleInitiator.h @@ -10,15 +10,14 @@ using namespace std; -struct ExampleInitiator: sc_module -{ +struct ExampleInitiator: sc_module { // TLM-2 socket, defaults to 32-bits wide, base protocol tlm_utils::simple_initiator_socket socket; SC_CTOR(ExampleInitiator) - : socket("socket") // Construct and name socket - , request_in_progress(0) - , m_peq(this, &ExampleInitiator::peq_cb) + : socket("socket") // Construct and name socket + , request_in_progress(0) + , m_peq(this, &ExampleInitiator::peq_cb) { socket.register_nb_transport_bw(this, &ExampleInitiator::nb_transport_bw); @@ -27,7 +26,7 @@ struct ExampleInitiator: sc_module void thread_process() { - tlm::tlm_generic_payload* trans; + tlm::tlm_generic_payload *trans; tlm::tlm_phase phase; sc_time delay; @@ -39,8 +38,7 @@ struct ExampleInitiator: sc_module data[i] = 0x55; // Generate 2 write transactions - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { int adr = i * 64; tlm::tlm_command cmd = tlm::TLM_WRITE_COMMAND; @@ -51,7 +49,7 @@ struct ExampleInitiator: sc_module trans->set_command( cmd ); trans->set_address( adr ); - trans->set_data_ptr( reinterpret_cast(&data[0]) ); + trans->set_data_ptr( reinterpret_cast(&data[0]) ); trans->set_data_length( 64 ); trans->set_streaming_width( 4 ); trans->set_byte_enable_ptr( 0 ); @@ -71,7 +69,7 @@ struct ExampleInitiator: sc_module << ", data=" << hex << data[0] << " at time " << sc_time_stamp() << " in " << name() << endl; - GenerationExtension* genExtension = new GenerationExtension(sc_time_stamp()); + GenerationExtension *genExtension = new GenerationExtension(sc_time_stamp()); trans->set_auto_extension(genExtension); @@ -80,13 +78,10 @@ struct ExampleInitiator: sc_module status = socket->nb_transport_fw( *trans, phase, delay ); // Check value returned from nb_transport_fw - if (status == tlm::TLM_UPDATED) - { + if (status == tlm::TLM_UPDATED) { // The timing annotation must be honored m_peq.notify( *trans, phase, delay ); - } - else if (status == tlm::TLM_COMPLETED) - { + } else if (status == tlm::TLM_COMPLETED) { // The completion of the transaction necessarily ends the BEGIN_REQ phase request_in_progress = 0; @@ -109,13 +104,11 @@ struct ExampleInitiator: sc_module void init_mem() { unsigned char buffer[64]; - for (int i = 0; i < 64; i++) - { + for (int i = 0; i < 64; i++) { buffer[i] = 0xff; } - for (int addr = 0; addr < 128; addr += 64) - { + for (int addr = 0; addr < 128; addr += 64) { tlm::tlm_generic_payload trans; trans.set_command( tlm::TLM_WRITE_COMMAND ); trans.set_address( addr ); @@ -128,8 +121,7 @@ struct ExampleInitiator: sc_module void dump_mem() { - for (int addr = 0; addr < 128; addr += 64) - { + for (int addr = 0; addr < 128; addr += 64) { unsigned char buffer[64]; tlm::tlm_generic_payload trans; trans.set_command( tlm::TLM_READ_COMMAND ); @@ -147,8 +139,8 @@ struct ExampleInitiator: sc_module // TLM-2 backward non-blocking transport method - virtual tlm::tlm_sync_enum nb_transport_bw( tlm::tlm_generic_payload& trans, - tlm::tlm_phase& phase, sc_time& delay ) + virtual tlm::tlm_sync_enum nb_transport_bw( tlm::tlm_generic_payload &trans, + tlm::tlm_phase &phase, sc_time &delay ) { m_peq.notify( trans, phase, delay ); return tlm::TLM_ACCEPTED; @@ -157,19 +149,17 @@ struct ExampleInitiator: sc_module // Payload event queue callback to handle transactions from target // Transaction could have arrived through return path or backward path - void peq_cb(tlm::tlm_generic_payload& trans, const tlm::tlm_phase& phase) + void peq_cb(tlm::tlm_generic_payload &trans, const tlm::tlm_phase &phase) { - if (phase == tlm::END_REQ || (&trans == request_in_progress && phase == tlm::BEGIN_RESP)) - { + if (phase == tlm::END_REQ || (&trans == request_in_progress + && phase == tlm::BEGIN_RESP)) { // The end of the BEGIN_REQ phase request_in_progress = 0; end_request_event.notify(); - } - else if (phase == tlm::BEGIN_REQ || phase == tlm::END_RESP) + } else if (phase == tlm::BEGIN_REQ || phase == tlm::END_RESP) SC_REPORT_FATAL("TLM-2", "Illegal transaction phase received by initiator"); - if (phase == tlm::BEGIN_RESP) - { + if (phase == tlm::BEGIN_RESP) { check_transaction( trans ); // Send final phase transition to target @@ -184,10 +174,9 @@ struct ExampleInitiator: sc_module } // Called on receiving BEGIN_RESP or TLM_COMPLETED - void check_transaction(tlm::tlm_generic_payload& trans) + void check_transaction(tlm::tlm_generic_payload &trans) { - if ( trans.is_response_error() ) - { + if ( trans.is_response_error() ) { char txt[100]; sprintf(txt, "Transaction returned with error, response status = %s", trans.get_response_string().c_str()); @@ -196,7 +185,7 @@ struct ExampleInitiator: sc_module tlm::tlm_command cmd = trans.get_command(); sc_dt::uint64 adr = trans.get_address(); - int* ptr = reinterpret_cast( trans.get_data_ptr() ); + int *ptr = reinterpret_cast( trans.get_data_ptr() ); cout << hex << adr << " check, cmd=" << (cmd ? "write" : "read") << ", data=" << hex << *ptr << " at time " << sc_time_stamp() @@ -208,7 +197,7 @@ struct ExampleInitiator: sc_module MemoryManager m_mm; unsigned char data[64]; - tlm::tlm_generic_payload* request_in_progress; + tlm::tlm_generic_payload *request_in_progress; sc_event end_request_event; tlm_utils::peq_with_cb_and_phase m_peq; }; diff --git a/DRAMSys/library/src/simulation/IArbiter.h b/DRAMSys/library/src/simulation/IArbiter.h index 1dc3c646..3c3460cc 100644 --- a/DRAMSys/library/src/simulation/IArbiter.h +++ b/DRAMSys/library/src/simulation/IArbiter.h @@ -31,7 +31,7 @@ * * Authors: * Felipe S. Prado - * Matthias Jung + * Matthias Jung */ #ifndef IARBITER_H_ @@ -52,9 +52,10 @@ using namespace tlm; struct IArbiter: public sc_module { public: tlm_utils::multi_passthrough_target_socket tSocket; - tlm_utils::multi_passthrough_initiator_socket iSocket; + tlm_utils::multi_passthrough_initiator_socket iSocket; - SC_CTOR(IArbiter) { + SC_CTOR(IArbiter) + { // One or more devices can accesss all the memory units through the arbiter. // Devices' initiator sockets are bound to arbiter's target sockets. // As soon the arbiter receives a request in any of its target sockets it should treat and forward it to the proper memory channel. @@ -63,60 +64,72 @@ public: // The arbiter communicates with one or more memory unity through one or more sockets (one or more memory channels). // Each of the arbiter's initiator sockets is bound to a memory controller's target socket. // Anytime an transaction comes from a memory unity to the arbiter the "bw" callback is called. - iSocket.register_nb_transport_bw(this, &IArbiter::nb_transport_bw); + iSocket.register_nb_transport_bw(this, &IArbiter::nb_transport_bw); tSocket.register_transport_dbg(this, &IArbiter::transport_dbg); } - virtual void setTlmRecorder(TlmRecorder* recorder) = 0; + virtual void setTlmRecorder(TlmRecorder *recorder) = 0; virtual bool isOutputBufferFull(unsigned int initiatorSocket) = 0; - virtual void incrementNumberOfOutputBufferTransactions(unsigned int initiatorSocket) = 0; + virtual void incrementNumberOfOutputBufferTransactions(unsigned int + initiatorSocket) = 0; protected: // Initiated by initiator side // This function is called when an arbiter's target socket receives a transaction from a device - virtual tlm_sync_enum nb_transport_fw(int id, tlm_generic_payload& payload, tlm_phase& phase, sc_time& fwDelay) = 0; + virtual tlm_sync_enum nb_transport_fw(int id, tlm_generic_payload &payload, + tlm_phase &phase, sc_time &fwDelay) = 0; // Initiated by dram side // This function is called when an arbiter's initiator socket receives a transaction from a memory controller - virtual tlm_sync_enum nb_transport_bw(int channelId, tlm_generic_payload &payload, tlm_phase &phase, sc_time &bwDelay) = 0; + virtual tlm_sync_enum nb_transport_bw(int channelId, + tlm_generic_payload &payload, tlm_phase &phase, sc_time &bwDelay) = 0; - virtual unsigned int transport_dbg(int /*id*/, tlm::tlm_generic_payload &trans) = 0; + virtual unsigned int transport_dbg(int /*id*/, + tlm::tlm_generic_payload &trans) = 0; void printDebugMessage(std::string message) { DebugManager::getInstance().printDebugMessage(this->name(), message); } - void appendDramExtension(int socketId, tlm_generic_payload& payload) + void appendDramExtension(int socketId, tlm_generic_payload &payload) { // Append Generation Extension - GenerationExtension* genExtension = new GenerationExtension(clkAlign(sc_time_stamp(),Configuration::getInstance().ControllerClk)); + GenerationExtension *genExtension = new GenerationExtension(clkAlign( + sc_time_stamp(), Configuration::getInstance().ControllerClk)); payload.set_auto_extension(genExtension); unsigned int burstlength = payload.get_streaming_width(); - DecodedAddress decodedAddress = xmlAddressDecoder::getInstance().decodeAddress(payload.get_address()); + DecodedAddress decodedAddress = xmlAddressDecoder::getInstance().decodeAddress( + payload.get_address()); // Check the valid range of decodedAddress if (addressIsValid(decodedAddress)) { - DramExtension* extension = new DramExtension(Thread(socketId+1), Channel(decodedAddress.channel), Bank(decodedAddress.bank), BankGroup(decodedAddress.bankgroup), Row(decodedAddress.row), Column(decodedAddress.column),burstlength); + DramExtension *extension = new DramExtension(Thread(socketId + 1), + Channel(decodedAddress.channel), Bank(decodedAddress.bank), + BankGroup(decodedAddress.bankgroup), Row(decodedAddress.row), + Column(decodedAddress.column), burstlength); payload.set_auto_extension(extension); } else { - SC_REPORT_FATAL("Arbiter", "Decoded Address are not inside the valid range"); + SC_REPORT_FATAL("Arbiter", "Decoded Address are not inside the valid range"); } } - bool addressIsValid(DecodedAddress& decodedAddress) + bool addressIsValid(DecodedAddress &decodedAddress) { - if (decodedAddress.channel >= xmlAddressDecoder::getInstance().amount["channel"]) { + if (decodedAddress.channel >= + xmlAddressDecoder::getInstance().amount["channel"]) { return false; } if (decodedAddress.bank >= xmlAddressDecoder::getInstance().amount["bank"]) { return false; } - if (decodedAddress.bankgroup > xmlAddressDecoder::getInstance().amount["bankgroup"]) { + if (decodedAddress.bankgroup > + xmlAddressDecoder::getInstance().amount["bankgroup"]) { return false; } - if (decodedAddress.column >= xmlAddressDecoder::getInstance().amount["column"]) { + if (decodedAddress.column >= + xmlAddressDecoder::getInstance().amount["column"]) { return false; } if (decodedAddress.row >= xmlAddressDecoder::getInstance().amount["row"]) { diff --git a/DRAMSys/library/src/simulation/MemoryManager.cpp b/DRAMSys/library/src/simulation/MemoryManager.cpp index 736cae5b..6f456272 100644 --- a/DRAMSys/library/src/simulation/MemoryManager.cpp +++ b/DRAMSys/library/src/simulation/MemoryManager.cpp @@ -47,37 +47,33 @@ MemoryManager::MemoryManager(): numberOfAllocations(0), numberOfFrees(0) MemoryManager::~MemoryManager() { - for(gp* payload: freePayloads) - { - delete payload; - numberOfFrees++; - } + for (gp *payload : freePayloads) { + delete payload; + numberOfFrees++; + } //Comment in if you are suspecting a memory leak in the manager //DebugManager::getInstance().printDebugMessage("MemoryManager","Number of allocated payloads: " + to_string(numberOfAllocations)); //DebugManager::getInstance().printDebugMessage("MemoryManager","Number of freed payloads: " + to_string(numberOfFrees)); } -gp* MemoryManager::allocate() +gp *MemoryManager::allocate() { - if(freePayloads.empty()) - { - numberOfAllocations++; - return new gp(this); - } - else - { - gp* result = freePayloads.back(); - freePayloads.pop_back(); - return result; - } + if (freePayloads.empty()) { + numberOfAllocations++; + return new gp(this); + } else { + gp *result = freePayloads.back(); + freePayloads.pop_back(); + return result; + } } -void MemoryManager::free(gp* payload) +void MemoryManager::free(gp *payload) { //unsigned char *dptr = payload->get_data_ptr(); //delete[] dptr; - payload->reset(); //clears all extensions - freePayloads.push_back(payload); + payload->reset(); //clears all extensions + freePayloads.push_back(payload); } diff --git a/DRAMSys/library/src/simulation/MemoryManager.h b/DRAMSys/library/src/simulation/MemoryManager.h index 6799263a..8b431ca5 100644 --- a/DRAMSys/library/src/simulation/MemoryManager.h +++ b/DRAMSys/library/src/simulation/MemoryManager.h @@ -44,15 +44,15 @@ typedef tlm::tlm_generic_payload gp; class MemoryManager : public tlm::tlm_mm_interface { public: - MemoryManager(); - virtual ~MemoryManager(); - virtual gp* allocate(); - virtual void free(gp* payload); + MemoryManager(); + virtual ~MemoryManager(); + virtual gp *allocate(); + virtual void free(gp *payload); private: - unsigned int numberOfAllocations; - unsigned int numberOfFrees; - std::vector freePayloads; + unsigned int numberOfAllocations; + unsigned int numberOfFrees; + std::vector freePayloads; }; #endif /* MEMORYMANAGER_H_ */ diff --git a/DRAMSys/library/src/simulation/ReorderBuffer.h b/DRAMSys/library/src/simulation/ReorderBuffer.h index bbc1bc14..5b10544c 100644 --- a/DRAMSys/library/src/simulation/ReorderBuffer.h +++ b/DRAMSys/library/src/simulation/ReorderBuffer.h @@ -39,20 +39,20 @@ #define REORDERBUFFER_H #include -#include +#include #include using namespace std; using namespace tlm; -struct ReorderBuffer: public sc_module -{ +struct ReorderBuffer: public sc_module { public: tlm_utils::simple_initiator_socket iSocket; tlm_utils::simple_target_socket tSocket; SC_CTOR(ReorderBuffer) : - payloadEventQueue(this, &ReorderBuffer::peqCallback), responseIsPendingInInitator(false) + payloadEventQueue(this, &ReorderBuffer::peqCallback), + responseIsPendingInInitator(false) { iSocket.register_nb_transport_bw(this, &ReorderBuffer::nb_transport_bw); tSocket.register_nb_transport_fw(this, &ReorderBuffer::nb_transport_fw); @@ -60,29 +60,27 @@ public: private: tlm_utils::peq_with_cb_and_phase payloadEventQueue; - deque pendingRequestsInOrder; - set receivedResponses; + deque pendingRequestsInOrder; + set receivedResponses; bool responseIsPendingInInitator; // Initiated by dram side - tlm_sync_enum nb_transport_bw(tlm_generic_payload& payload, tlm_phase& phase, sc_time& bwDelay) + tlm_sync_enum nb_transport_bw(tlm_generic_payload &payload, tlm_phase &phase, + sc_time &bwDelay) { payloadEventQueue.notify(payload, phase, bwDelay); return TLM_ACCEPTED; } // Initiated by initator side (players) - tlm_sync_enum nb_transport_fw(tlm_generic_payload& payload, tlm_phase& phase, - sc_time& fwDelay) + tlm_sync_enum nb_transport_fw(tlm_generic_payload &payload, tlm_phase &phase, + sc_time &fwDelay) { - if (phase == BEGIN_REQ) - { - payload.acquire(); - } - else if (phase == END_RESP) - { + if (phase == BEGIN_REQ) { + payload.acquire(); + } else if (phase == END_RESP) { payload.release(); } @@ -90,17 +88,15 @@ private: return TLM_ACCEPTED; } - void peqCallback(tlm_generic_payload& payload, const tlm_phase& phase) + void peqCallback(tlm_generic_payload &payload, const tlm_phase &phase) { //Phases initiated by initiator side - if (phase == BEGIN_REQ) - { - pendingRequestsInOrder.push_back(&payload); - sendToTarget(payload, phase, SC_ZERO_TIME ); + if (phase == BEGIN_REQ) { + pendingRequestsInOrder.push_back(&payload); + sendToTarget(payload, phase, SC_ZERO_TIME ); } - else if (phase == END_RESP) - { + else if (phase == END_RESP) { responseIsPendingInInitator = false; pendingRequestsInOrder.pop_front(); receivedResponses.erase(&payload); @@ -108,37 +104,37 @@ private: } //Phases initiated by dram side - else if (phase == END_REQ) - { + else if (phase == END_REQ) { sendToInitiator(payload, phase, SC_ZERO_TIME); - } - else if (phase == BEGIN_RESP) - { + } else if (phase == BEGIN_RESP) { sendToTarget(payload, END_RESP, SC_ZERO_TIME); receivedResponses.emplace(&payload); sendNextResponse(); } - else - { - SC_REPORT_FATAL(0, "Payload event queue in arbiter was triggered with unknown phase"); + else { + SC_REPORT_FATAL(0, + "Payload event queue in arbiter was triggered with unknown phase"); } } - void sendToTarget(tlm_generic_payload& payload, const tlm_phase& phase, const sc_time& delay) + void sendToTarget(tlm_generic_payload &payload, const tlm_phase &phase, + const sc_time &delay) { tlm_phase TPhase = phase; sc_time TDelay = delay; iSocket->nb_transport_fw(payload, TPhase, TDelay); } - void sendToInitiator(tlm_generic_payload& payload, const tlm_phase& phase, const sc_time& delay) + void sendToInitiator(tlm_generic_payload &payload, const tlm_phase &phase, + const sc_time &delay) { sc_assert(phase == END_REQ || - (phase == BEGIN_RESP && pendingRequestsInOrder.front() == &payload && receivedResponses.count(&payload))); + (phase == BEGIN_RESP && pendingRequestsInOrder.front() == &payload + && receivedResponses.count(&payload))); tlm_phase TPhase = phase; sc_time TDelay = delay; @@ -149,11 +145,11 @@ private: { //only send the next response when there response for the oldest pending request (requestsInOrder.front()) //has been received - if(!responseIsPendingInInitator && receivedResponses.count(pendingRequestsInOrder.front())) - { - tlm_generic_payload* payloadToSend = pendingRequestsInOrder.front(); + if (!responseIsPendingInInitator + && receivedResponses.count(pendingRequestsInOrder.front())) { + tlm_generic_payload *payloadToSend = pendingRequestsInOrder.front(); responseIsPendingInInitator = true; - sendToInitiator(*payloadToSend,BEGIN_RESP,SC_ZERO_TIME); + sendToInitiator(*payloadToSend, BEGIN_RESP, SC_ZERO_TIME); } // else if(!responseIsPendingInInitator && receivedResponses.size()>0 && !receivedResponses.count(pendingRequestsInOrder.front())>0) // { diff --git a/DRAMSys/library/src/simulation/Setup.cpp b/DRAMSys/library/src/simulation/Setup.cpp index 53d0eb8d..b2b8ca79 100644 --- a/DRAMSys/library/src/simulation/Setup.cpp +++ b/DRAMSys/library/src/simulation/Setup.cpp @@ -36,26 +36,26 @@ #include "Setup.h" Setup::Setup(std::string uri, - std::string & memspec, - std::string & mcconfig, - std::string & amconfig, - std::string & simconfig, - std::string & thermalconfig) + std::string &memspec, + std::string &mcconfig, + std::string &amconfig, + std::string &simconfig, + std::string &thermalconfig) { // Load Simulation: tinyxml2::XMLDocument simulationdoc; loadXML(uri, simulationdoc); - tinyxml2::XMLElement* simulation = - simulationdoc.FirstChildElement("simulation"); + tinyxml2::XMLElement *simulation = + simulationdoc.FirstChildElement("simulation"); std::string xmlNodeName(simulation->Name()); - if( xmlNodeName != "simulation") + if ( xmlNodeName != "simulation") reportFatal("SimulationManager", "Cannot load simulation: simulation node expected"); // Load all sub-configuration XML files: - tinyxml2::XMLElement* s; + tinyxml2::XMLElement *s; s = simulation->FirstChildElement("memspec"); memspec = s->Attribute("src"); diff --git a/DRAMSys/library/src/simulation/Setup.h b/DRAMSys/library/src/simulation/Setup.h index 88ca5c41..a8398686 100644 --- a/DRAMSys/library/src/simulation/Setup.h +++ b/DRAMSys/library/src/simulation/Setup.h @@ -48,11 +48,11 @@ class Setup { public: Setup(std::string uri, - std::string & memspec, - std::string & mcconfig, - std::string & amconfig, - std::string & simconfig, - std::string & thermalconfig); + std::string &memspec, + std::string &mcconfig, + std::string &amconfig, + std::string &simconfig, + std::string &thermalconfig); }; #endif // SETUP_H diff --git a/DRAMSys/library/src/simulation/SimpleArbiter.h b/DRAMSys/library/src/simulation/SimpleArbiter.h index f29cda24..ec1994ae 100644 --- a/DRAMSys/library/src/simulation/SimpleArbiter.h +++ b/DRAMSys/library/src/simulation/SimpleArbiter.h @@ -47,12 +47,13 @@ using namespace tlm; // Annotated References [X,Y] --> Please refer to TLM AT Cheat Sheet on README -struct SimpleArbiter: public IArbiter{ +struct SimpleArbiter: public IArbiter { public: - SimpleArbiter(sc_module_name name) : IArbiter(name) { + SimpleArbiter(sc_module_name name) : IArbiter(name) + { } - void setTlmRecorder(TlmRecorder* recorder) + void setTlmRecorder(TlmRecorder *recorder) { tlmRecorder = recorder; } @@ -62,40 +63,38 @@ public: return false; } - virtual void incrementNumberOfOutputBufferTransactions(unsigned int /*initiatorSocket*/) + virtual void incrementNumberOfOutputBufferTransactions(unsigned + int /*initiatorSocket*/) { } protected: - TlmRecorder* tlmRecorder; + TlmRecorder *tlmRecorder; // Initiated by initiator side // This function is called when an arbiter's target socket receives a transaction from a device - virtual tlm_sync_enum nb_transport_fw(int id, tlm_generic_payload& payload, tlm_phase& phase, sc_time& fwDelay) + virtual tlm_sync_enum nb_transport_fw(int id, tlm_generic_payload &payload, + tlm_phase &phase, sc_time &fwDelay) { - if (phase == BEGIN_REQ) - { + if (phase == BEGIN_REQ) { payload.acquire(); // adjust address offset, e.g. for gem5 simulation - payload.set_address(payload.get_address() - Configuration::getInstance().AddressOffset); + payload.set_address(payload.get_address() - + Configuration::getInstance().AddressOffset); // In the begin request phase the socket ID is appended to the payload. // It will extracted from the payload and used later. appendDramExtension(id, payload); - tlmRecorder->recordArbiterPhase(payload, phase, sc_time_stamp()+fwDelay); - tlmRecorder->recordArbiterPhase(payload, END_REQ,sc_time_stamp()+fwDelay); - tlmRecorder->recordPhase(payload, phase, sc_time_stamp()+fwDelay); + tlmRecorder->recordArbiterPhase(payload, phase, sc_time_stamp() + fwDelay); + tlmRecorder->recordArbiterPhase(payload, END_REQ, sc_time_stamp() + fwDelay); + tlmRecorder->recordPhase(payload, phase, sc_time_stamp() + fwDelay); // Forward Path [1.0] iSocket[getISocketIndex(payload)]->nb_transport_fw(payload, phase, fwDelay); - } - else if(phase == END_RESP) - { + } else if (phase == END_RESP) { payload.release(); - tlmRecorder->recordArbiterPhase(payload, phase, sc_time_stamp()+fwDelay); - } - else - { + tlmRecorder->recordArbiterPhase(payload, phase, sc_time_stamp() + fwDelay); + } else { SC_REPORT_FATAL("Arbiter", "Illegal phase received by initiator"); } @@ -106,17 +105,18 @@ protected: // Initiated by dram side // This function is called when an arbiter's initiator socket receives a transaction from a memory controller - virtual tlm_sync_enum nb_transport_bw(int /*channelId*/, tlm_generic_payload &payload, tlm_phase &phase, sc_time &bwDelay) + virtual tlm_sync_enum nb_transport_bw(int /*channelId*/, + tlm_generic_payload &payload, tlm_phase &phase, sc_time &bwDelay) { tlmRecorder->recordPhase(payload, phase, bwDelay + sc_time_stamp()); - tSocket[DramExtension::getThread(payload).ID()]->nb_transport_bw(payload, TPhase, bwDelay); + tSocket[DramExtension::getThread(payload).ID()]->nb_transport_bw(payload, + TPhase, bwDelay); - if(phase == BEGIN_RESP) - { + if (phase == BEGIN_RESP) { // Early Completion [3.1] tlmRecorder->recordPhase(payload, END_RESP, bwDelay + sc_time_stamp()); - tlmRecorder->recordArbiterPhase(payload, BEGIN_RESP, sc_time_stamp()+bwDelay); + tlmRecorder->recordArbiterPhase(payload, BEGIN_RESP, sc_time_stamp() + bwDelay); return TLM_COMPLETED; } // 4-Phase Handshake [1.3] @@ -126,12 +126,13 @@ protected: virtual unsigned int transport_dbg(int /*id*/, tlm::tlm_generic_payload &trans) { // adjust address offset: - trans.set_address(trans.get_address() - Configuration::getInstance().AddressOffset); + trans.set_address(trans.get_address() - + Configuration::getInstance().AddressOffset); return iSocket[getISocketIndex(trans)]->transport_dbg(trans); } - virtual unsigned int getISocketIndex(tlm_generic_payload& payload) + virtual unsigned int getISocketIndex(tlm_generic_payload &payload) { return DramExtension::getBank(payload).ID(); } diff --git a/DRAMSys/library/src/simulation/StlPlayer.cpp b/DRAMSys/library/src/simulation/StlPlayer.cpp index 5bf712ed..e38c3405 100644 --- a/DRAMSys/library/src/simulation/StlPlayer.cpp +++ b/DRAMSys/library/src/simulation/StlPlayer.cpp @@ -43,8 +43,8 @@ StlPlayer::StlPlayer(sc_module_name, string pathToTrace, sc_time playerClk, TracePlayerListener *listener) : - TracePlayer(listener), - file(pathToTrace) + TracePlayer(listener), + file(pathToTrace) { if (!file.is_open()) SC_REPORT_FATAL(0, (string("Could not open trace ") + pathToTrace).c_str()); @@ -67,14 +67,11 @@ void StlPlayer::nextPayload() line.clear(); } - if (!file) - { + if (!file) { // The file is empty. Nothing more to do. this->finish(); return; - } - else - { + } else { numberOfTransactions++; } @@ -100,38 +97,51 @@ void StlPlayer::nextPayload() // Get the timestamp for the transaction. iss >> time; if (time.empty()) - SC_REPORT_FATAL("StlPlayer", ("Malformed trace file. Timestamp could not be found (line " + to_string(lineCnt) + ").").c_str()); + SC_REPORT_FATAL("StlPlayer", + ("Malformed trace file. Timestamp could not be found (line " + to_string( + lineCnt) + ").").c_str()); sc_time sendingTime = std::stoull(time.c_str()) * playerClk; // Get the command. iss >> command; if (command.empty()) - SC_REPORT_FATAL("StlPlayer", ("Malformed trace file. Command could not be found (line " + to_string(lineCnt) + ").").c_str()); + SC_REPORT_FATAL("StlPlayer", + ("Malformed trace file. Command could not be found (line " + to_string( + lineCnt) + ").").c_str()); enum tlm_command cmd; if (command == "read") { cmd = TLM_READ_COMMAND; } else if (command == "write") { cmd = TLM_WRITE_COMMAND; } else { - SC_REPORT_FATAL("StlPlayer", (string("Corrupted tracefile, command ") + command + string(" unknown")).c_str()); + SC_REPORT_FATAL("StlPlayer", + (string("Corrupted tracefile, command ") + command + + string(" unknown")).c_str()); } // Get the address. iss >> address; if (address.empty()) - SC_REPORT_FATAL("StlPlayer", ("Malformed trace file. Address could not be found (line " + to_string(lineCnt) + ").").c_str()); + SC_REPORT_FATAL("StlPlayer", + ("Malformed trace file. Address could not be found (line " + to_string( + lineCnt) + ").").c_str()); unsigned long long addr = std::stoull(address.c_str(), 0, 16); // Get the data if necessary. - if (Configuration::getInstance().StoreMode != StorageMode::NoStorage && cmd != TLM_READ_COMMAND) { + if (Configuration::getInstance().StoreMode != StorageMode::NoStorage + && cmd != TLM_READ_COMMAND) { // The input trace file must provide the data to be stored into the memory. iss >> dataStr; if (dataStr.empty()) - SC_REPORT_FATAL("StlPlayer", ("Malformed trace file. Data information could not be found (line " + to_string(lineCnt) + ").").c_str()); + SC_REPORT_FATAL("StlPlayer", + ("Malformed trace file. Data information could not be found (line " + to_string( + lineCnt) + ").").c_str()); // Check if data length in the trace file is correct. We need two characters to represent 1 byte in hexadecimal. if (dataStr.length() != (dataLength * 2)) - SC_REPORT_FATAL("StlPlayer", ("Data in the trace file has an invalid length (line " + to_string(lineCnt) + ").").c_str()); + SC_REPORT_FATAL("StlPlayer", + ("Data in the trace file has an invalid length (line " + to_string( + lineCnt) + ").").c_str()); // Set data for (unsigned i = 0; i < dataLength; i++) @@ -152,6 +162,7 @@ void StlPlayer::nextPayload() if (sendingTime <= sc_time_stamp()) this->payloadEventQueue.notify(*payload, BEGIN_REQ, SC_ZERO_TIME); else - this->payloadEventQueue.notify(*payload, BEGIN_REQ, sendingTime - sc_time_stamp()); + this->payloadEventQueue.notify(*payload, BEGIN_REQ, + sendingTime - sc_time_stamp()); } diff --git a/DRAMSys/library/src/simulation/StlPlayer.h b/DRAMSys/library/src/simulation/StlPlayer.h index a3b12ec4..4400c58c 100644 --- a/DRAMSys/library/src/simulation/StlPlayer.h +++ b/DRAMSys/library/src/simulation/StlPlayer.h @@ -46,8 +46,7 @@ using namespace std; using namespace tlm; -struct StlPlayer: public TracePlayer -{ +struct StlPlayer: public TracePlayer { public: StlPlayer(sc_module_name /*name*/, string pathToTrace, diff --git a/DRAMSys/library/src/simulation/TemperatureController.cpp b/DRAMSys/library/src/simulation/TemperatureController.cpp index a0fda47f..2e183a77 100644 --- a/DRAMSys/library/src/simulation/TemperatureController.cpp +++ b/DRAMSys/library/src/simulation/TemperatureController.cpp @@ -52,7 +52,8 @@ double TemperatureController::temperatureConvert(double tKelvin) double TemperatureController::getTemperature(int deviceId, float currentPower) { - printDebugMessage("Temperature requested by device " + std::to_string(deviceId) + " current power is " + std::to_string(currentPower)); + printDebugMessage("Temperature requested by device " + std::to_string( + deviceId) + " current power is " + std::to_string(currentPower)); if (dynamicTempSimEnabled == true) { currentPowerValues.at(deviceId) = currentPower; @@ -75,16 +76,19 @@ void TemperatureController::updateTemperatures() #ifdef THERMALSIM thermalSimulation->sendPowerValues(¤tPowerValues); thermalSimulation->simulate(); - thermalSimulation->getTemperature(temperaturesBuffer, TDICE_OUTPUT_INSTANT_SLOT, TDICE_OUTPUT_TYPE_TFLPEL, TDICE_OUTPUT_QUANTITY_AVERAGE); + thermalSimulation->getTemperature(temperaturesBuffer, TDICE_OUTPUT_INSTANT_SLOT, + TDICE_OUTPUT_TYPE_TFLPEL, TDICE_OUTPUT_QUANTITY_AVERAGE); std::string mapfile; sc_time ts = sc_time_stamp(); if (genTempMap == true) { - mapfile = temperatureMapFile + "_" + std::to_string(ts.to_default_time_units()) + ".txt"; + mapfile = temperatureMapFile + "_" + std::to_string(ts.to_default_time_units()) + + ".txt"; thermalSimulation->getTemperatureMap(mapfile); } if (genPowerMap == true) { - mapfile = powerMapFile + "_" + std::to_string(ts.to_default_time_units()) + ".txt"; + mapfile = powerMapFile + "_" + std::to_string(ts.to_default_time_units()) + + ".txt"; thermalSimulation->getPowerMap(mapfile); } #endif @@ -96,7 +100,8 @@ void TemperatureController::updateTemperatures() void TemperatureController::checkPowerThreshold(int deviceId) { - if (std::abs(lastPowerValues.at(deviceId) - currentPowerValues.at(deviceId)) > powerThresholds.at(deviceId)) { + if (std::abs(lastPowerValues.at(deviceId) - currentPowerValues.at( + deviceId)) > powerThresholds.at(deviceId)) { decreaseSimPeriod = true; } lastPowerValues.at(deviceId) = currentPowerValues.at(deviceId); @@ -134,7 +139,8 @@ double TemperatureController::adjustThermalSimPeriod() period = period / periodAdjustFactor; cyclesSinceLastPeriodAdjust = 0; decreaseSimPeriod = false; - printDebugMessage("Thermal Simulation period reduced to " + std::to_string(period) + ". Target is " + std::to_string(targetPeriod)); + printDebugMessage("Thermal Simulation period reduced to " + std::to_string( + period) + ". Target is " + std::to_string(targetPeriod)); } else { if (period != targetPeriod) { cyclesSinceLastPeriodAdjust++; @@ -143,7 +149,8 @@ double TemperatureController::adjustThermalSimPeriod() period = period * (periodAdjustFactor / 2); if (period > targetPeriod) period = targetPeriod; - printDebugMessage("Thermal Simulation period increased to " + std::to_string(period) + ". Target is " + std::to_string(targetPeriod)); + printDebugMessage("Thermal Simulation period increased to " + std::to_string( + period) + ". Target is " + std::to_string(targetPeriod)); } } } @@ -159,7 +166,8 @@ void TemperatureController::temperatureThread() int i = 0; for (auto t : temperatureValues) { - printDebugMessage("Temperature[" + std::to_string(i++) + "] is " + std::to_string(t)); + printDebugMessage("Temperature[" + std::to_string(i++) + "] is " + + std::to_string(t)); } printDebugMessage("Thermal simulation period is " + std::to_string(p)); diff --git a/DRAMSys/library/src/simulation/TemperatureController.h b/DRAMSys/library/src/simulation/TemperatureController.h index c4d05f67..d26dc2d7 100644 --- a/DRAMSys/library/src/simulation/TemperatureController.h +++ b/DRAMSys/library/src/simulation/TemperatureController.h @@ -50,21 +50,21 @@ #include "IceWrapper.h" #endif -SC_MODULE(TemperatureController) { +SC_MODULE(TemperatureController) +{ public: - static inline TemperatureController &getInstance() - { + static inline TemperatureController &getInstance() { static TemperatureController temperaturectrl("TemperatureController"); return temperaturectrl; } - SC_CTOR(TemperatureController) - { + SC_CTOR(TemperatureController) { temperatureScale = Configuration::getInstance().temperatureSim.TemperatureScale; dynamicTempSimEnabled = Configuration::getInstance().ThermalSimulation; - staticTemperature = Configuration::getInstance().temperatureSim.StaticTemperatureDefaultValue; + staticTemperature = + Configuration::getInstance().temperatureSim.StaticTemperatureDefaultValue; if (dynamicTempSimEnabled == true) { #ifdef THERMALSIM @@ -72,19 +72,24 @@ public: std::string ip = Configuration::getInstance().temperatureSim.IceServerIp; unsigned int port = Configuration::getInstance().temperatureSim.IceServerPort; thermalSimulation = new IceWrapper(ip, port); - printDebugMessage("Dynamic temperature simulation. Server @ " + ip + ":" + std::to_string(port)); + printDebugMessage("Dynamic temperature simulation. Server @ " + ip + ":" + + std::to_string(port)); #else - SC_REPORT_FATAL(name(), "DRAMSys was build without support to dynamic temperature simulation. Check the README file for further details."); + SC_REPORT_FATAL(name(), + "DRAMSys was build without support to dynamic temperature simulation. Check the README file for further details."); #endif // Initial power dissipation values (got from config) - currentPowerValues = Configuration::getInstance().temperatureSim.powerInitialValues; + currentPowerValues = + Configuration::getInstance().temperatureSim.powerInitialValues; lastPowerValues = currentPowerValues; // Substantial changes in power will trigger adjustments in the simulaiton period. Get the thresholds from config. powerThresholds = Configuration::getInstance().temperatureSim.powerThresholds; decreaseSimPeriod = false; - periodAdjustFactor = Configuration::getInstance().temperatureSim.SimPeriodAdjustFactor; - nPowStableCyclesToIncreasePeriod = Configuration::getInstance().temperatureSim.NPowStableCyclesToIncreasePeriod; + periodAdjustFactor = + Configuration::getInstance().temperatureSim.SimPeriodAdjustFactor; + nPowStableCyclesToIncreasePeriod = + Configuration::getInstance().temperatureSim.NPowStableCyclesToIncreasePeriod; cyclesSinceLastPeriodAdjust = 0; // Get the target period for the thermal simulation from config. @@ -102,7 +107,8 @@ public: SC_THREAD(temperatureThread); } else { - printDebugMessage("Static temperature simulation. Temperature set to " + std::to_string(staticTemperature)); + printDebugMessage("Static temperature simulation. Temperature set to " + + std::to_string(staticTemperature)); } } diff --git a/DRAMSys/library/src/simulation/TraceGenerator.h b/DRAMSys/library/src/simulation/TraceGenerator.h index 13c2ed72..04d9cc49 100644 --- a/DRAMSys/library/src/simulation/TraceGenerator.h +++ b/DRAMSys/library/src/simulation/TraceGenerator.h @@ -44,13 +44,12 @@ using namespace std; using namespace tlm; -struct TraceGenerator: public TracePlayer -{ +struct TraceGenerator: public TracePlayer { public: TraceGenerator(sc_module_name /*name*/, unsigned int clkMhz, - TracePlayerListener* listener) : TracePlayer(listener), transCounter(0) + TracePlayerListener *listener) : TracePlayer(listener), transCounter(0) { - if(clkMhz == 0) + if (clkMhz == 0) clk = Configuration::getInstance().memSpec.clk; else clk = FrequencyToClk(clkMhz); @@ -60,14 +59,14 @@ public: virtual void nextPayload() override { - if(transCounter >= 1000) // TODO set limit! - { + if (transCounter >= 1000) { // TODO set limit! this->terminate(); } - gp* payload = this->allocatePayload(); + gp *payload = this->allocatePayload(); - unsigned char * dataElement = new unsigned char[16]; // TODO: column / burst breite + unsigned char *dataElement = new unsigned + char[16]; // TODO: column / burst breite payload->set_address(0x0); payload->set_response_status(TLM_INCOMPLETE_RESPONSE); diff --git a/DRAMSys/library/src/simulation/TracePlayer.cpp b/DRAMSys/library/src/simulation/TracePlayer.cpp index 7b59309b..9eeb56d1 100644 --- a/DRAMSys/library/src/simulation/TracePlayer.cpp +++ b/DRAMSys/library/src/simulation/TracePlayer.cpp @@ -38,13 +38,13 @@ #include "TracePlayer.h" -TracePlayer::TracePlayer(TracePlayerListener* listener) : - payloadEventQueue(this, &TracePlayer::peqCallback), - transactionsSent(0), - transactionsReceived(0), - numberOfTransactions(0), - listener(listener), - finished(false) +TracePlayer::TracePlayer(TracePlayerListener *listener) : + payloadEventQueue(this, &TracePlayer::peqCallback), + transactionsSent(0), + transactionsReceived(0), + numberOfTransactions(0), + listener(listener), + finished(false) { iSocket.register_nb_transport_bw(this, &TracePlayer::nb_transport_bw); } @@ -70,47 +70,40 @@ void TracePlayer::printDebugMessage(std::string message) DebugManager::getInstance().printDebugMessage(this->name(), message); } -tlm_sync_enum TracePlayer::nb_transport_bw(tlm_generic_payload &payload, tlm_phase &phase, sc_time &bwDelay) +tlm_sync_enum TracePlayer::nb_transport_bw(tlm_generic_payload &payload, + tlm_phase &phase, sc_time &bwDelay) { payloadEventQueue.notify(payload, phase, bwDelay); return TLM_ACCEPTED; } -void TracePlayer::peqCallback(tlm_generic_payload &payload, const tlm_phase &phase) +void TracePlayer::peqCallback(tlm_generic_payload &payload, + const tlm_phase &phase) { - if (phase == BEGIN_REQ) - { + if (phase == BEGIN_REQ) { payload.acquire(); sendToTarget(payload, phase, SC_ZERO_TIME); transactionsSent++; - DebugManager::getInstance().printDebugMessage(name(), "Performing request #" + std::to_string(transactionsSent)); - } - else if (phase == END_REQ) - { + DebugManager::getInstance().printDebugMessage(name(), + "Performing request #" + std::to_string(transactionsSent)); + } else if (phase == END_REQ) { nextPayload(); - } - else if (phase == BEGIN_RESP) - { + } else if (phase == BEGIN_RESP) { sendToTarget(payload, END_RESP, SC_ZERO_TIME); payload.release(); - if(Configuration::getInstance().SimulationProgressBar) + if (Configuration::getInstance().SimulationProgressBar) listener->transactionFinished(); transactionsReceived++; // If all answers were received: - if(finished == true && numberOfTransactions == transactionsReceived) - { + if (finished == true && numberOfTransactions == transactionsReceived) { this->terminate(); } - } - else if (phase == END_RESP) - { - } - else - { + } else if (phase == END_RESP) { + } else { SC_REPORT_FATAL(0, "TracePlayer PEQ was triggered with unknown phase"); } } @@ -127,7 +120,8 @@ unsigned int TracePlayer::getNumberOfLines(string pathToTrace) // new lines will be skipped unless we stop it from happening: newFile.unsetf(std::ios_base::skipws); // count the lines with an algorithm specialized for counting: - unsigned int lineCount = std::count(std::istream_iterator(newFile), std::istream_iterator(), ':'); + unsigned int lineCount = std::count(std::istream_iterator(newFile), + std::istream_iterator(), ':'); newFile.close(); return lineCount; diff --git a/DRAMSys/library/src/simulation/TracePlayer.h b/DRAMSys/library/src/simulation/TracePlayer.h index 6a022f5e..d03f5ead 100644 --- a/DRAMSys/library/src/simulation/TracePlayer.h +++ b/DRAMSys/library/src/simulation/TracePlayer.h @@ -56,8 +56,7 @@ using namespace std; using namespace tlm; -struct TracePlayer: public sc_module -{ +struct TracePlayer: public sc_module { public: tlm_utils::simple_initiator_socket iSocket; TracePlayer(TracePlayerListener *listener); @@ -65,7 +64,7 @@ public: unsigned int getNumberOfLines(string pathToTrace); protected: - gp* allocatePayload(); + gp *allocatePayload(); tlm_utils::peq_with_cb_and_phase payloadEventQueue; void finish(); void terminate(); @@ -74,9 +73,11 @@ protected: unsigned int numberOfTransactions; private: - tlm_sync_enum nb_transport_bw(tlm_generic_payload& payload, tlm_phase& phase, sc_time& bwDelay); - void peqCallback(tlm_generic_payload& payload, const tlm_phase& phase); - void sendToTarget(tlm_generic_payload &payload, const tlm_phase &phase, const sc_time &delay) + tlm_sync_enum nb_transport_bw(tlm_generic_payload &payload, tlm_phase &phase, + sc_time &bwDelay); + void peqCallback(tlm_generic_payload &payload, const tlm_phase &phase); + void sendToTarget(tlm_generic_payload &payload, const tlm_phase &phase, + const sc_time &delay) { tlm_phase TPhase = phase; sc_time TDelay = delay; @@ -85,7 +86,7 @@ private: MemoryManager memoryManager; unsigned int transactionsSent; unsigned int transactionsReceived; - TracePlayerListener* listener; + TracePlayerListener *listener; bool finished; }; diff --git a/DRAMSys/library/src/simulation/TracePlayerListener.h b/DRAMSys/library/src/simulation/TracePlayerListener.h index bec9f043..430c10a0 100644 --- a/DRAMSys/library/src/simulation/TracePlayerListener.h +++ b/DRAMSys/library/src/simulation/TracePlayerListener.h @@ -43,7 +43,7 @@ class TracePlayerListener public: virtual void tracePlayerTerminates() = 0; virtual void transactionFinished() = 0; - virtual ~TracePlayerListener(){}; + virtual ~TracePlayerListener() {}; }; #endif // TRACEPLAYERLISTENER_H diff --git a/DRAMSys/library/src/simulation/TraceSetup.cpp b/DRAMSys/library/src/simulation/TraceSetup.cpp index 951b6360..21152069 100644 --- a/DRAMSys/library/src/simulation/TraceSetup.cpp +++ b/DRAMSys/library/src/simulation/TraceSetup.cpp @@ -37,38 +37,34 @@ traceSetup::traceSetup(std::string uri, std::string pathToResources, - std::vector * devices) + std::vector *devices) { // Load Simulation: tinyxml2::XMLDocument simulationdoc; loadXML(uri, simulationdoc); - tinyxml2::XMLElement* simulation = - simulationdoc.FirstChildElement("simulation"); + tinyxml2::XMLElement *simulation = + simulationdoc.FirstChildElement("simulation"); std::string xmlNodeName(simulation->Name()); - if( xmlNodeName != "simulation") + if ( xmlNodeName != "simulation") reportFatal("traceSetup", "Cannot load simulation: simulation node expected"); // Load TracePlayers: tinyxml2::XMLElement *tracesetup = - simulation->FirstChildElement("tracesetup"); + simulation->FirstChildElement("tracesetup"); for (tinyxml2::XMLElement *device = - tracesetup->FirstChildElement("device"); - device != NULL; - device = device->NextSiblingElement("device")) - { + tracesetup->FirstChildElement("device"); + device != NULL; + device = device->NextSiblingElement("device")) { sc_time playerClk; unsigned int frequency = device->IntAttribute("clkMhz"); - if (frequency == 0) - { - reportFatal("traceSetup","No Frequency Defined"); - } - else - { + if (frequency == 0) { + reportFatal("traceSetup", "No Frequency Defined"); + } else { playerClk = FrequencyToClk(frequency); } @@ -79,15 +75,14 @@ traceSetup::traceSetup(std::string uri, // replace all '.' to '_' std::replace( moduleName.begin(), moduleName.end(), '.', '_'); - StlPlayer * player = new StlPlayer(moduleName.c_str(), - stlFile, - playerClk, - this); + StlPlayer *player = new StlPlayer(moduleName.c_str(), + stlFile, + playerClk, + this); devices->push_back(player); - if(Configuration::getInstance().SimulationProgressBar) - { + if (Configuration::getInstance().SimulationProgressBar) { totalTransactions += player->getNumberOfLines(stlFile); } } @@ -100,8 +95,7 @@ void traceSetup::tracePlayerTerminates() { finishedTracePlayers++; - if (finishedTracePlayers == NumberOfTracePlayers) - { + if (finishedTracePlayers == NumberOfTracePlayers) { sc_stop(); } } @@ -111,8 +105,7 @@ void traceSetup::transactionFinished() loadbar(totalTransactions - remainingTransactions, totalTransactions); - if (remainingTransactions == 0) - { + if (remainingTransactions == 0) { cout << endl; } } diff --git a/DRAMSys/library/src/simulation/TraceSetup.h b/DRAMSys/library/src/simulation/TraceSetup.h index a11b4abe..2287d052 100644 --- a/DRAMSys/library/src/simulation/TraceSetup.h +++ b/DRAMSys/library/src/simulation/TraceSetup.h @@ -49,11 +49,11 @@ class traceSetup : public TracePlayerListener public: traceSetup(std::string uri, std::string pathToResources, - std::vector * devices); + std::vector *devices); virtual void tracePlayerTerminates() override; virtual void transactionFinished() override; - virtual ~traceSetup(){}; + virtual ~traceSetup() {}; private: unsigned int NumberOfTracePlayers; diff --git a/DRAMSys/simulator/main.cpp b/DRAMSys/simulator/main.cpp index 43fea800..39fb82d7 100644 --- a/DRAMSys/simulator/main.cpp +++ b/DRAMSys/simulator/main.cpp @@ -63,19 +63,16 @@ int sc_main(int argc, char **argv) // Get path of resources: resources = pathOfFile(argv[0]) - + string("/../../DRAMSys/library/resources/"); + + string("/../../DRAMSys/library/resources/"); string SimulationXML; - if(argc > 1) - { + if (argc > 1) { SimulationXML = argv[1]; - } - else - { + } else { SimulationXML = resources + "simulations/ddr3-example.xml"; } - std::vector players; + std::vector players; // Instantiate DRAMSys: DRAMSys *dramSys = new DRAMSys("DRAMSys", SimulationXML, resources); @@ -84,8 +81,7 @@ int sc_main(int argc, char **argv) traceSetup *ts = new traceSetup(SimulationXML, resources, &players); // Bind STL Players with DRAMSys: - for(auto& p : players) - { + for (auto &p : players) { p->iSocket.bind(dramSys->tSocket); } @@ -93,8 +89,7 @@ int sc_main(int argc, char **argv) clock_t simStartTime = clock(); // Kickstart the players: - for (auto& p : players) - { + for (auto &p : players) { p->nextPayload(); } diff --git a/DRAMSys/traceAnalyzer/businessObjects/calculatedMetric.h b/DRAMSys/traceAnalyzer/businessObjects/calculatedMetric.h index 4fd639a3..d5ee6d13 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/calculatedMetric.h +++ b/DRAMSys/traceAnalyzer/businessObjects/calculatedMetric.h @@ -42,9 +42,15 @@ class CalculatedMetric { public: - CalculatedMetric(QString name, double value): name(name),value(value){} - QString getName(){return name;} - double getValue(){return value;} + CalculatedMetric(QString name, double value): name(name), value(value) {} + QString getName() + { + return name; + } + double getValue() + { + return value; + } private: QString name; diff --git a/DRAMSys/traceAnalyzer/businessObjects/comment.h b/DRAMSys/traceAnalyzer/businessObjects/comment.h index 07af3e98..c4b56d05 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/comment.h +++ b/DRAMSys/traceAnalyzer/businessObjects/comment.h @@ -45,9 +45,15 @@ class Comment traceTime time; QString text; public: - Comment(traceTime time,QString text):time(time),text(text){} - traceTime Time() const{return time;} - const QString& Text() const{return text;} + Comment(traceTime time, QString text): time(time), text(text) {} + traceTime Time() const + { + return time; + } + const QString &Text() const + { + return text; + } }; #endif // COMMENT_H diff --git a/DRAMSys/traceAnalyzer/businessObjects/generalinfo.h b/DRAMSys/traceAnalyzer/businessObjects/generalinfo.h index d7100469..883ad0a1 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/generalinfo.h +++ b/DRAMSys/traceAnalyzer/businessObjects/generalinfo.h @@ -40,8 +40,7 @@ #include "timespan.h" #include -struct GeneralInfo -{ +struct GeneralInfo { unsigned int numberOfTransactions; unsigned int numberOfPhases; Timespan span; @@ -53,12 +52,18 @@ struct GeneralInfo unsigned int controllerThread; public: - GeneralInfo(unsigned int numberOfTransactions,unsigned int numberOfPhases,Timespan span,unsigned int numberOfBanks,const QString& description, QString unitOfTime,unsigned int clkPeriod, unsigned int windowSize, unsigned int controllerThread) : - numberOfTransactions(numberOfTransactions) , numberOfPhases(numberOfPhases),span(span), numberOfBanks(numberOfBanks), description(description), unitOfTime(unitOfTime), clkPeriod(clkPeriod), windowSize(windowSize), controllerThread(controllerThread) + GeneralInfo(unsigned int numberOfTransactions, unsigned int numberOfPhases, + Timespan span, unsigned int numberOfBanks, const QString &description, + QString unitOfTime, unsigned int clkPeriod, unsigned int windowSize, + unsigned int controllerThread) : + numberOfTransactions(numberOfTransactions) , numberOfPhases(numberOfPhases), + span(span), numberOfBanks(numberOfBanks), description(description), + unitOfTime(unitOfTime), clkPeriod(clkPeriod), windowSize(windowSize), + controllerThread(controllerThread) { } - GeneralInfo(){} + GeneralInfo() {} }; #endif // GENERALINFO_H diff --git a/DRAMSys/traceAnalyzer/businessObjects/phases/phase.cpp b/DRAMSys/traceAnalyzer/businessObjects/phases/phase.cpp index 11874c50..b72bf9ed 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/phases/phase.cpp +++ b/DRAMSys/traceAnalyzer/businessObjects/phases/phase.cpp @@ -42,68 +42,67 @@ using namespace std; -void Phase::draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &canvasRect, bool highlight, const TraceDrawingProperties &drawingProperties) const +void Phase::draw(QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap, const QRectF &canvasRect, bool highlight, + const TraceDrawingProperties &drawingProperties) const { Q_UNUSED(canvasRect); QColor color = getColor(drawingProperties); - painter->setBrush(QBrush(getColor(drawingProperties),getBrushStyle())); + painter->setBrush(QBrush(getColor(drawingProperties), getBrushStyle())); - if(!drawingProperties.drawBorder) - { + if (!drawingProperties.drawBorder) { painter->setPen(color); - } - else - { + } else { painter->setPen(Qt::black); } - if(highlight) - { + if (highlight) { QPen pen(Qt::red); pen.setWidth(3); painter->setPen(pen); } - if(!isBankwise()) - { - for(unsigned int i=0; iBegin(), spanOnDataBus->End(),drawingProperties.yValDataBus, false,PhaseSymbol::Hexagon, painter,xMap,yMap); + if (spanOnDataBus) { + drawPhaseSymbol(spanOnDataBus->Begin(), spanOnDataBus->End(), + drawingProperties.yValDataBus, false, PhaseSymbol::Hexagon, painter, xMap, + yMap); } } -void Phase::drawPhaseSymbol(traceTime begin, traceTime end, double y,bool drawtext,PhaseSymbol symbol, QPainter* painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap) const +void Phase::drawPhaseSymbol(traceTime begin, traceTime end, double y, + bool drawtext, PhaseSymbol symbol, QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap) const { double yVal = yMap.transform(y); - double symbolHeight = yMap.transform(0)-yMap.transform(hexagonHeigth); + double symbolHeight = yMap.transform(0) - yMap.transform(hexagonHeigth); - if(symbol == PhaseSymbol::Hexagon) - { - QPoint hexFrom(xMap.transform(begin),yVal); - QPoint hexTo(xMap.transform(end),yVal); + if (symbol == PhaseSymbol::Hexagon) { + QPoint hexFrom(xMap.transform(begin), yVal); + QPoint hexTo(xMap.transform(end), yVal); drawHexagon(painter, hexFrom, hexTo, symbolHeight); - } - else - { - QPoint upperLeft(xMap.transform(begin),yVal-symbolHeight/2); - QPoint bottomRight(xMap.transform(end),yVal+symbolHeight/2); - painter->drawRect(QRect(upperLeft,bottomRight)); + } else { + QPoint upperLeft(xMap.transform(begin), yVal - symbolHeight / 2); + QPoint bottomRight(xMap.transform(end), yVal + symbolHeight / 2); + painter->drawRect(QRect(upperLeft, bottomRight)); } - if(drawtext) - drawText(painter,Name(), QPoint(xMap.transform(begin), yVal + symbolHeight/2), TextPositioning::bottomRight); + if (drawtext) + drawText(painter, Name(), QPoint(xMap.transform(begin), + yVal + symbolHeight / 2), TextPositioning::bottomRight); } QColor Phase::getColor(const TraceDrawingProperties &drawingProperties) const @@ -113,7 +112,8 @@ QColor Phase::getColor(const TraceDrawingProperties &drawingProperties) const return getPhaseColor(); break; case ColorGrouping::Thread: - return ColorGenerator::getColor(static_cast(transaction->Thread())); + return ColorGenerator::getColor(static_cast + (transaction->Thread())); break; case ColorGrouping::Transaction: default: @@ -132,16 +132,19 @@ Qt::BrushStyle Phase::getBrushStyle() const return Qt::SolidPattern; } -bool Phase::isSelected(traceTime time, double yVal, const TraceDrawingProperties& drawingproperties) const +bool Phase::isSelected(traceTime time, double yVal, + const TraceDrawingProperties &drawingproperties) const { - if (span.contains(time) && (!this->isBankwise() || fabs(yVal-getYVal(drawingproperties))<=hexagonHeigth)) + if (span.contains(time) && (!this->isBankwise() + || fabs(yVal - getYVal(drawingproperties)) <= hexagonHeigth)) return true; - if (spanOnDataBus && spanOnDataBus->contains(time) && fabs(yVal-drawingproperties.yValDataBus)<=hexagonHeigth) + if (spanOnDataBus && spanOnDataBus->contains(time) + && fabs(yVal - drawingproperties.yValDataBus) <= hexagonHeigth) return true; - for(Timespan span: spansOnCommandBus) - { - if (span.contains(time) && fabs(yVal-drawingproperties.yValCommandBus)<=hexagonHeigth) + for (Timespan span : spansOnCommandBus) { + if (span.contains(time) + && fabs(yVal - drawingproperties.yValCommandBus) <= hexagonHeigth) return true; } diff --git a/DRAMSys/traceAnalyzer/businessObjects/phases/phase.h b/DRAMSys/traceAnalyzer/businessObjects/phases/phase.h index ef8d187a..952e1f2c 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/phases/phase.h +++ b/DRAMSys/traceAnalyzer/businessObjects/phases/phase.h @@ -53,16 +53,31 @@ class Transaction; class Phase { public: - Phase(ID id,Timespan span,const std::shared_ptr& transaction, std::vector spansOnCommandBus, std::shared_ptr spanOnDataBus): - id(id),span(span),transaction(transaction), spansOnCommandBus(spansOnCommandBus), spanOnDataBus(spanOnDataBus), - hexagonHeigth(0.6), captionPosition(TextPositioning::bottomRight){} + Phase(ID id, Timespan span, const std::shared_ptr &transaction, + std::vector spansOnCommandBus, + std::shared_ptr spanOnDataBus): + id(id), span(span), transaction(transaction), + spansOnCommandBus(spansOnCommandBus), spanOnDataBus(spanOnDataBus), + hexagonHeigth(0.6), captionPosition(TextPositioning::bottomRight) {} - void draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &canvasRect, bool highlight,const TraceDrawingProperties& drawingProperties) const; - bool isSelected(traceTime time, double yVal, const TraceDrawingProperties& drawingproperties) const; - const Timespan& Span() const {return span;} - ID Id() const {return id;} + void draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, + const QRectF &canvasRect, bool highlight, + const TraceDrawingProperties &drawingProperties) const; + bool isSelected(traceTime time, double yVal, + const TraceDrawingProperties &drawingproperties) const; + const Timespan &Span() const + { + return span; + } + ID Id() const + { + return id; + } virtual QString Name() const = 0; - virtual bool isBankwise() const {return true;} + virtual bool isBankwise() const + { + return true; + } protected: ID id; @@ -73,13 +88,15 @@ protected: double hexagonHeigth; TextPositioning captionPosition; - enum PhaseSymbol {Hexagon,Rect}; + enum PhaseSymbol {Hexagon, Rect}; virtual PhaseSymbol getPhaseSymbol() const; virtual Qt::BrushStyle getBrushStyle() const; virtual QColor getColor(const TraceDrawingProperties &drawingProperties) const; virtual int getYVal(const TraceDrawingProperties &drawingProperties) const; virtual QColor getPhaseColor() const = 0; - virtual void drawPhaseSymbol(traceTime begin, traceTime end, double y,bool drawtext,PhaseSymbol symbol, QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap) const; + virtual void drawPhaseSymbol(traceTime begin, traceTime end, double y, + bool drawtext, PhaseSymbol symbol, QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap) const; }; @@ -88,9 +105,19 @@ class REQ : public Phase public: using Phase::Phase; protected: - virtual QColor getPhaseColor() const override {return ColorGenerator::getColor(1);} - virtual QString Name() const final {return "REQ";} - virtual int getYVal(const TraceDrawingProperties &drawingProperties) const override {return drawingProperties.yValRequest;} + virtual QColor getPhaseColor() const override + { + return ColorGenerator::getColor(1); + } + virtual QString Name() const final + { + return "REQ"; + } + virtual int getYVal(const TraceDrawingProperties &drawingProperties) const + override + { + return drawingProperties.yValRequest; + } }; @@ -99,9 +126,19 @@ class RESP : public Phase public: using Phase::Phase; protected: - virtual QColor getPhaseColor() const override {return ColorGenerator::getColor(1);} - virtual QString Name() const override {return "RESP";} - virtual int getYVal(const TraceDrawingProperties &drawingProperties) const override {return drawingProperties.yValResponse;} + virtual QColor getPhaseColor() const override + { + return ColorGenerator::getColor(1); + } + virtual QString Name() const override + { + return "RESP"; + } + virtual int getYVal(const TraceDrawingProperties &drawingProperties) const + override + { + return drawingProperties.yValResponse; + } }; @@ -110,8 +147,14 @@ class PRE : public Phase public: using Phase::Phase; protected: - virtual QColor getPhaseColor() const override {return ColorGenerator::getColor(1);} - virtual QString Name() const override {return "PRE";} + virtual QColor getPhaseColor() const override + { + return ColorGenerator::getColor(1); + } + virtual QString Name() const override + { + return "PRE"; + } }; @@ -120,8 +163,14 @@ class ACT : public Phase public: using Phase::Phase; protected: - virtual QColor getPhaseColor() const override {return ColorGenerator::getColor(3);} - virtual QString Name() const override {return "ACT";} + virtual QColor getPhaseColor() const override + { + return ColorGenerator::getColor(3); + } + virtual QString Name() const override + { + return "ACT"; + } }; class RD : public Phase @@ -129,8 +178,14 @@ class RD : public Phase public: using Phase::Phase; protected: - virtual QColor getPhaseColor() const override {return ColorGenerator::getColor(4);} - virtual QString Name() const override {return "RD";} + virtual QColor getPhaseColor() const override + { + return ColorGenerator::getColor(4); + } + virtual QString Name() const override + { + return "RD"; + } }; class RDA : public Phase @@ -138,8 +193,14 @@ class RDA : public Phase public: using Phase::Phase; protected: - virtual QColor getPhaseColor() const override {return ColorGenerator::getColor(5);} - virtual QString Name() const override {return "RDA";} + virtual QColor getPhaseColor() const override + { + return ColorGenerator::getColor(5); + } + virtual QString Name() const override + { + return "RDA"; + } }; class WR : public Phase @@ -147,8 +208,14 @@ class WR : public Phase public: using Phase::Phase; protected: - virtual QColor getPhaseColor() const override {return ColorGenerator::getColor(6);} - virtual QString Name() const override {return "WR";} + virtual QColor getPhaseColor() const override + { + return ColorGenerator::getColor(6); + } + virtual QString Name() const override + { + return "WR"; + } }; class WRA : public Phase @@ -156,8 +223,14 @@ class WRA : public Phase public: using Phase::Phase; protected: - virtual QColor getPhaseColor() const override {return ColorGenerator::getColor(7);} - virtual QString Name() const override {return "WRA";} + virtual QColor getPhaseColor() const override + { + return ColorGenerator::getColor(7); + } + virtual QString Name() const override + { + return "WRA"; + } }; class AUTO_REFRESH : public Phase @@ -165,13 +238,25 @@ class AUTO_REFRESH : public Phase public: using Phase::Phase; protected: - virtual QString Name() const override {return "REF";} - virtual std::vector getTimesOnCommandBus() const {return {span.Begin()};} - virtual QColor getColor(const TraceDrawingProperties &drawingProperties) const override {Q_UNUSED(drawingProperties) return getPhaseColor();} - virtual QColor getPhaseColor() const override {QColor phaseColor = QColor(Qt::darkCyan); - phaseColor.setAlpha(130); - return phaseColor; - } + virtual QString Name() const override + { + return "REF"; + } + virtual std::vector getTimesOnCommandBus() const + { + return {span.Begin()}; + } + virtual QColor getColor(const TraceDrawingProperties &drawingProperties) const + override + { + Q_UNUSED(drawingProperties) return getPhaseColor(); + } + virtual QColor getPhaseColor() const override + { + QColor phaseColor = QColor(Qt::darkCyan); + phaseColor.setAlpha(130); + return phaseColor; + } }; class REFA : public AUTO_REFRESH @@ -179,8 +264,14 @@ class REFA : public AUTO_REFRESH public: using AUTO_REFRESH::AUTO_REFRESH; protected: - virtual QString Name() const override {return "REFA";} - virtual bool isBankwise() const override {return false;} + virtual QString Name() const override + { + return "REFA"; + } + virtual bool isBankwise() const override + { + return false; + } }; class REFB : public AUTO_REFRESH @@ -188,7 +279,10 @@ class REFB : public AUTO_REFRESH public: using AUTO_REFRESH::AUTO_REFRESH; protected: - virtual QString Name() const override {return "REFB";} + virtual QString Name() const override + { + return "REFB"; + } }; @@ -197,11 +291,27 @@ class PRECHARGE_ALL : public Phase public: using Phase::Phase; protected: - virtual QString Name() const override {return "PREA";} - virtual std::vector getTimesOnCommandBus() const {return {span.Begin()};} - virtual QColor getColor(const TraceDrawingProperties &drawingProperties) const override {Q_UNUSED(drawingProperties) return getPhaseColor();} - virtual QColor getPhaseColor() const override {return ColorGenerator::getColor(10);} - virtual bool isBankwise() const override {return false;} + virtual QString Name() const override + { + return "PREA"; + } + virtual std::vector getTimesOnCommandBus() const + { + return {span.Begin()}; + } + virtual QColor getColor(const TraceDrawingProperties &drawingProperties) const + override + { + Q_UNUSED(drawingProperties) return getPhaseColor(); + } + virtual QColor getPhaseColor() const override + { + return ColorGenerator::getColor(10); + } + virtual bool isBankwise() const override + { + return false; + } }; class PDNAB : public Phase @@ -209,11 +319,27 @@ class PDNAB : public Phase public: using Phase::Phase; protected: - virtual QString Name() const override {return "PDNAB";} - virtual Qt::BrushStyle getBrushStyle() const override {return Qt::Dense6Pattern;} - virtual QColor getColor(const TraceDrawingProperties &drawingProperties) const override {Q_UNUSED(drawingProperties) return getPhaseColor();} - virtual QColor getPhaseColor() const override {return QColor(Qt::black);} - virtual Phase::PhaseSymbol getPhaseSymbol() const override {return PhaseSymbol::Rect;} + virtual QString Name() const override + { + return "PDNAB"; + } + virtual Qt::BrushStyle getBrushStyle() const override + { + return Qt::Dense6Pattern; + } + virtual QColor getColor(const TraceDrawingProperties &drawingProperties) const + override + { + Q_UNUSED(drawingProperties) return getPhaseColor(); + } + virtual QColor getPhaseColor() const override + { + return QColor(Qt::black); + } + virtual Phase::PhaseSymbol getPhaseSymbol() const override + { + return PhaseSymbol::Rect; + } }; class PDNA : public PDNAB @@ -221,8 +347,14 @@ class PDNA : public PDNAB public: using PDNAB::PDNAB; protected: - virtual QString Name() const override {return "PDNA";} - virtual bool isBankwise() const override {return false;} + virtual QString Name() const override + { + return "PDNA"; + } + virtual bool isBankwise() const override + { + return false; + } }; class PDNPB : public Phase @@ -230,11 +362,27 @@ class PDNPB : public Phase public: using Phase::Phase; protected: - virtual QString Name() const override {return "PDNPB";} - virtual Qt::BrushStyle getBrushStyle() const override{return Qt::Dense4Pattern;} - virtual QColor getColor(const TraceDrawingProperties &drawingProperties) const override {Q_UNUSED(drawingProperties) return getPhaseColor();} - virtual QColor getPhaseColor() const override {return QColor(Qt::black);} - virtual Phase::PhaseSymbol getPhaseSymbol() const override {return PhaseSymbol::Rect;} + virtual QString Name() const override + { + return "PDNPB"; + } + virtual Qt::BrushStyle getBrushStyle() const override + { + return Qt::Dense4Pattern; + } + virtual QColor getColor(const TraceDrawingProperties &drawingProperties) const + override + { + Q_UNUSED(drawingProperties) return getPhaseColor(); + } + virtual QColor getPhaseColor() const override + { + return QColor(Qt::black); + } + virtual Phase::PhaseSymbol getPhaseSymbol() const override + { + return PhaseSymbol::Rect; + } }; class PDNP : public PDNPB @@ -242,8 +390,14 @@ class PDNP : public PDNPB public: using PDNPB::PDNPB; protected: - virtual QString Name() const override {return "PDNP";} - virtual bool isBankwise() const override {return false;} + virtual QString Name() const override + { + return "PDNP"; + } + virtual bool isBankwise() const override + { + return false; + } }; class SREFB : public Phase @@ -251,11 +405,27 @@ class SREFB : public Phase public: using Phase::Phase; protected: - virtual QString Name() const override {return "SREFB";} - virtual Qt::BrushStyle getBrushStyle() const override {return Qt::Dense1Pattern;} - virtual QColor getColor(const TraceDrawingProperties &drawingProperties) const override {Q_UNUSED(drawingProperties) return getPhaseColor();} - virtual QColor getPhaseColor() const override {return QColor(Qt::black);} - virtual Phase::PhaseSymbol getPhaseSymbol() const override {return PhaseSymbol::Rect;} + virtual QString Name() const override + { + return "SREFB"; + } + virtual Qt::BrushStyle getBrushStyle() const override + { + return Qt::Dense1Pattern; + } + virtual QColor getColor(const TraceDrawingProperties &drawingProperties) const + override + { + Q_UNUSED(drawingProperties) return getPhaseColor(); + } + virtual QColor getPhaseColor() const override + { + return QColor(Qt::black); + } + virtual Phase::PhaseSymbol getPhaseSymbol() const override + { + return PhaseSymbol::Rect; + } }; class SREF : public SREFB @@ -263,8 +433,14 @@ class SREF : public SREFB public: using SREFB::SREFB; protected: - virtual QString Name() const override {return "SREF";} - virtual bool isBankwise() const override {return false;} + virtual QString Name() const override + { + return "SREF"; + } + virtual bool isBankwise() const override + { + return false; + } }; diff --git a/DRAMSys/traceAnalyzer/businessObjects/phases/phasefactory.cpp b/DRAMSys/traceAnalyzer/businessObjects/phases/phasefactory.cpp index 0c69ae31..1d3393a7 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/phases/phasefactory.cpp +++ b/DRAMSys/traceAnalyzer/businessObjects/phases/phasefactory.cpp @@ -44,46 +44,69 @@ using namespace std; -shared_ptr PhaseFactory::CreatePhase(ID id, const QString& dbPhaseName,const Timespan& span, const shared_ptr& trans, TraceDB& database) +shared_ptr PhaseFactory::CreatePhase(ID id, const QString &dbPhaseName, + const Timespan &span, const shared_ptr &trans, TraceDB &database) { traceTime clk = database.getGeneralInfo().clkPeriod; - if(dbPhaseName == "REQ") - return shared_ptr(new REQ(id, span,trans,{},std::shared_ptr())); - else if(dbPhaseName == "RESP") - return shared_ptr(new RESP(id, span,trans,{},std::shared_ptr())); + if (dbPhaseName == "REQ") + return shared_ptr(new REQ(id, span, trans, {}, + std::shared_ptr())); + else if (dbPhaseName == "RESP") + return shared_ptr(new RESP(id, span, trans, {}, + std::shared_ptr())); - else if(dbPhaseName == "PRE") - return shared_ptr(new PRE(id, span,trans,{Timespan(span.Begin(),span.Begin()+clk)},std::shared_ptr())); - else if(dbPhaseName == "ACT") - return shared_ptr(new ACT(id, span,trans,{Timespan(span.Begin(),span.Begin()+clk)},std::shared_ptr())); - else if(dbPhaseName == "PRE_ALL") - return shared_ptr(new PRECHARGE_ALL(id,span,trans,{Timespan(span.Begin(),span.Begin()+clk)},std::shared_ptr())); - else if(dbPhaseName == "REFA") - return shared_ptr(new REFA(id, span,trans,{Timespan(span.Begin(),span.Begin()+clk)},std::shared_ptr())); - else if(dbPhaseName == "REFB") - return shared_ptr(new REFB(id, span,trans,{Timespan(span.Begin(),span.Begin()+clk)},std::shared_ptr())); + else if (dbPhaseName == "PRE") + return shared_ptr(new PRE(id, span, trans, {Timespan(span.Begin(), span.Begin() + clk)}, + std::shared_ptr())); + else if (dbPhaseName == "ACT") + return shared_ptr(new ACT(id, span, trans, {Timespan(span.Begin(), span.Begin() + clk)}, + std::shared_ptr())); + else if (dbPhaseName == "PRE_ALL") + return shared_ptr(new PRECHARGE_ALL(id, span, trans, {Timespan(span.Begin(), span.Begin() + clk)}, + std::shared_ptr())); + else if (dbPhaseName == "REFA") + return shared_ptr(new REFA(id, span, trans, {Timespan(span.Begin(), span.Begin() + clk)}, + std::shared_ptr())); + else if (dbPhaseName == "REFB") + return shared_ptr(new REFB(id, span, trans, {Timespan(span.Begin(), span.Begin() + clk)}, + std::shared_ptr())); - else if(dbPhaseName == "RD") - return shared_ptr(new RD(id, span,trans,{Timespan(span.Begin(),span.Begin()+clk)},std::shared_ptr(new Timespan(trans->SpanOnDataStrobe())))); - else if(dbPhaseName == "RDA") - return shared_ptr(new RDA(id, span,trans,{Timespan(span.Begin(),span.Begin()+clk)},std::shared_ptr(new Timespan(trans->SpanOnDataStrobe())))); - else if(dbPhaseName == "WR") - return shared_ptr(new WR(id, span,trans,{Timespan(span.Begin(),span.Begin()+clk)},std::shared_ptr(new Timespan(trans->SpanOnDataStrobe())))); - else if(dbPhaseName == "WRA") - return shared_ptr(new WRA(id, span,trans,{Timespan(span.Begin(),span.Begin()+clk)},std::shared_ptr(new Timespan(trans->SpanOnDataStrobe())))); - else if(dbPhaseName == "PDNA") - return shared_ptr(new PDNA(id, span,trans, {Timespan(span.Begin(),span.Begin()+clk),Timespan(span.End()-clk,span.End())},std::shared_ptr())); - else if(dbPhaseName == "PDNAB") - return shared_ptr(new PDNAB(id, span,trans, {Timespan(span.Begin(),span.Begin()+clk),Timespan(span.End()-clk,span.End())},std::shared_ptr())); - else if(dbPhaseName == "PDNP") - return shared_ptr(new PDNP(id, span,trans, {Timespan(span.Begin(),span.Begin()+clk),Timespan(span.End()-clk,span.End())},std::shared_ptr())); - else if(dbPhaseName == "PDNPB") - return shared_ptr(new PDNPB(id, span,trans, {Timespan(span.Begin(),span.Begin()+clk),Timespan(span.End()-clk,span.End())},std::shared_ptr())); - else if(dbPhaseName == "SREF") - return shared_ptr(new SREF(id, span, trans,{Timespan(span.Begin(),span.Begin()+clk),Timespan(span.End()-clk,span.End())},std::shared_ptr())); - else if(dbPhaseName == "SREFB") - return shared_ptr(new SREFB(id, span, trans,{Timespan(span.Begin(),span.Begin()+clk),Timespan(span.End()-clk,span.End())},std::shared_ptr())); + else if (dbPhaseName == "RD") + return shared_ptr(new RD(id, span, trans, {Timespan(span.Begin(), span.Begin() + clk)}, + std::shared_ptr + (new Timespan(trans->SpanOnDataStrobe())))); + else if (dbPhaseName == "RDA") + return shared_ptr(new RDA(id, span, trans, {Timespan(span.Begin(), span.Begin() + clk)}, + std::shared_ptr + (new Timespan(trans->SpanOnDataStrobe())))); + else if (dbPhaseName == "WR") + return shared_ptr(new WR(id, span, trans, {Timespan(span.Begin(), span.Begin() + clk)}, + std::shared_ptr + (new Timespan(trans->SpanOnDataStrobe())))); + else if (dbPhaseName == "WRA") + return shared_ptr(new WRA(id, span, trans, {Timespan(span.Begin(), span.Begin() + clk)}, + std::shared_ptr + (new Timespan(trans->SpanOnDataStrobe())))); + else if (dbPhaseName == "PDNA") + return shared_ptr(new PDNA(id, span, trans, {Timespan(span.Begin(), span.Begin() + clk), Timespan(span.End() - clk, span.End())}, + std::shared_ptr())); + else if (dbPhaseName == "PDNAB") + return shared_ptr(new PDNAB(id, span, trans, {Timespan(span.Begin(), span.Begin() + clk), Timespan(span.End() - clk, span.End())}, + std::shared_ptr())); + else if (dbPhaseName == "PDNP") + return shared_ptr(new PDNP(id, span, trans, {Timespan(span.Begin(), span.Begin() + clk), Timespan(span.End() - clk, span.End())}, + std::shared_ptr())); + else if (dbPhaseName == "PDNPB") + return shared_ptr(new PDNPB(id, span, trans, {Timespan(span.Begin(), span.Begin() + clk), Timespan(span.End() - clk, span.End())}, + std::shared_ptr())); + else if (dbPhaseName == "SREF") + return shared_ptr(new SREF(id, span, trans, {Timespan(span.Begin(), span.Begin() + clk), Timespan(span.End() - clk, span.End())}, + std::shared_ptr())); + else if (dbPhaseName == "SREFB") + return shared_ptr(new SREFB(id, span, trans, {Timespan(span.Begin(), span.Begin() + clk), Timespan(span.End() - clk, span.End())}, + std::shared_ptr())); else - throw std::runtime_error("DB phasename " + dbPhaseName.toStdString() + " unkown to phasefactory"); + throw std::runtime_error("DB phasename " + dbPhaseName.toStdString() + + " unkown to phasefactory"); } diff --git a/DRAMSys/traceAnalyzer/businessObjects/phases/phasefactory.h b/DRAMSys/traceAnalyzer/businessObjects/phases/phasefactory.h index ad4bed75..c50a667c 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/phases/phasefactory.h +++ b/DRAMSys/traceAnalyzer/businessObjects/phases/phasefactory.h @@ -49,7 +49,9 @@ class PhaseFactory private: PhaseFactory(); public: - static std::shared_ptr CreatePhase(ID id, const QString& dbPhaseName,const Timespan& span,const std::shared_ptr& trans, TraceDB& database); + static std::shared_ptr CreatePhase(ID id, const QString &dbPhaseName, + const Timespan &span, const std::shared_ptr &trans, + TraceDB &database); }; #endif // PHASEFACTORY_H diff --git a/DRAMSys/traceAnalyzer/businessObjects/pythoncaller.cpp b/DRAMSys/traceAnalyzer/businessObjects/pythoncaller.cpp index 3a072eba..21d6326f 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/pythoncaller.cpp +++ b/DRAMSys/traceAnalyzer/businessObjects/pythoncaller.cpp @@ -53,12 +53,13 @@ PythonCaller::PythonCaller() : metricFunctionName("calculateMetrics"), getMetricFunctionName("getMetrics"), - pathToScripts(QApplication::applicationDirPath().toStdString() + "/../../DRAMSys/traceAnalyzer/scripts/"), + pathToScripts(QApplication::applicationDirPath().toStdString() + + "/../../DRAMSys/traceAnalyzer/scripts/"), plotsModuleName("plots"), plotsFunctionName("generatePlots") { Py_Initialize(); - PyObject *sysPath = PySys_GetObject((char*)"path"); + PyObject *sysPath = PySys_GetObject((char *)"path"); PyObject *path = PyUnicode_FromString(this->pathToScripts.c_str()); PyList_Insert(sysPath, 0, path); Py_DECREF(path); @@ -69,28 +70,30 @@ PythonCaller::PythonCaller() : qDebug() << "Script: " << pathToScripts.c_str(); pRunTestsFunction = loadFunctionFromModule(testModuleName, testFunctionName); - pCalculateMetricsFunction = loadFunctionFromModule(metricModuleName, metricFunctionName); + pCalculateMetricsFunction = loadFunctionFromModule(metricModuleName, + metricFunctionName); pGenPlotsFunction = loadFunctionFromModule(plotsModuleName, plotsFunctionName); - pGetMetricsFunction = loadFunctionFromModule(metricModuleName, getMetricFunctionName); + pGetMetricsFunction = loadFunctionFromModule(metricModuleName, + getMetricFunctionName); } //returns new reference to the function (see: http://edcjones.tripod.com/refcount.html for the difference between "new reference" and "borrowed reference") -PyObject* PythonCaller::loadFunctionFromModule(string moduleName,string functionName) +PyObject *PythonCaller::loadFunctionFromModule(string moduleName, + string functionName) { - PyObject* pModuleName = PyUnicode_FromString(moduleName.c_str()); - PyObject* pModule = PyImport_Import(pModuleName); + PyObject *pModuleName = PyUnicode_FromString(moduleName.c_str()); + PyObject *pModule = PyImport_Import(pModuleName); - if(!pModule) - { - throw runtime_error(string("Could not load module "+ moduleName)); + if (!pModule) { + throw runtime_error(string("Could not load module " + moduleName)); } - PyObject* pFunction = PyObject_GetAttrString(pModule, functionName.c_str()); + PyObject *pFunction = PyObject_GetAttrString(pModule, functionName.c_str()); - if(!pFunction || !PyCallable_Check(pFunction)) - { - throw runtime_error(string("Could not load test function " + functionName + "in module " + moduleName)); + if (!pFunction || !PyCallable_Check(pFunction)) { + throw runtime_error(string("Could not load test function " + functionName + + "in module " + moduleName)); } Py_DECREF(pModuleName); @@ -107,15 +110,16 @@ PythonCaller::~PythonCaller() Py_Finalize(); } -PyObject* PythonCaller::callMetricsFunction(PyObject* function, QString argument, vector list) +PyObject *PythonCaller::callMetricsFunction(PyObject *function, + QString argument, vector list) { assert(PyCallable_Check(function)); - PyObject* pArgs = PyTuple_New(2); - PyObject* pArgumentString = PyUnicode_FromString(argument.toStdString().c_str()); - PyObject* pArgumentList = PyList_New(list.size()); - for(size_t i = 0; i < list.size(); i++) - { + PyObject *pArgs = PyTuple_New(2); + PyObject *pArgumentString = PyUnicode_FromString( + argument.toStdString().c_str()); + PyObject *pArgumentList = PyList_New(list.size()); + for (size_t i = 0; i < list.size(); i++) { PyList_SetItem(pArgumentList, i, PyBool_FromLong(list[i])); } PyTuple_SetItem(pArgs, 0, pArgumentString); @@ -123,30 +127,31 @@ PyObject* PythonCaller::callMetricsFunction(PyObject* function, QString argument PyObject *pResult = PyObject_CallObject(function, pArgs); Py_DECREF(pArgs); - if(!pResult) - { + if (!pResult) { PyErr_Print(); - throw runtime_error(string("Error in calling " + testFunctionName + " in module " + testModuleName)); + throw runtime_error(string("Error in calling " + testFunctionName + + " in module " + testModuleName)); } return pResult; } //returns a new reference to result of function call -PyObject* PythonCaller::callFunctionWithStringArgument(PyObject* function, QString argument) +PyObject *PythonCaller::callFunctionWithStringArgument(PyObject *function, + QString argument) { assert(PyCallable_Check(function)); - PyObject* pArgs = PyTuple_New(1); - PyObject* pArgument = PyUnicode_FromString(argument.toStdString().c_str()); + PyObject *pArgs = PyTuple_New(1); + PyObject *pArgument = PyUnicode_FromString(argument.toStdString().c_str()); PyTuple_SetItem(pArgs, 0, pArgument); PyObject *pResult = PyObject_CallObject(function, pArgs); Py_DECREF(pArgument); - if(!pResult) - { + if (!pResult) { PyErr_Print(); - throw runtime_error(string("Error in calling " + testFunctionName + " in module " + testModuleName)); + throw runtime_error(string("Error in calling " + testFunctionName + + " in module " + testModuleName)); } return pResult; @@ -155,32 +160,33 @@ PyObject* PythonCaller::callFunctionWithStringArgument(PyObject* function, QStri TraceTestResults PythonCaller::runTestsOnTrace(QString pathToTrace) { TraceTestResults traceTestResult(QFileInfo(pathToTrace).baseName()); - PyObject *pResult = callFunctionWithStringArgument(pRunTestsFunction, pathToTrace); + PyObject *pResult = callFunctionWithStringArgument(pRunTestsFunction, + pathToTrace); - for(Py_ssize_t i= 0; i < PyList_Size(pResult); ++i) - { - PyObject* currentTestResult = PyList_GetItem(pResult,i); - QString testName(PyUnicode_AsUTF8(PyTuple_GetItem(currentTestResult,0))); - bool testPassed = (Py_True == PyTuple_GetItem(currentTestResult,1)); - QString message(PyUnicode_AsUTF8(PyTuple_GetItem(currentTestResult,2))); + for (Py_ssize_t i = 0; i < PyList_Size(pResult); ++i) { + PyObject *currentTestResult = PyList_GetItem(pResult, i); + QString testName(PyUnicode_AsUTF8(PyTuple_GetItem(currentTestResult, 0))); + bool testPassed = (Py_True == PyTuple_GetItem(currentTestResult, 1)); + QString message(PyUnicode_AsUTF8(PyTuple_GetItem(currentTestResult, 2))); - traceTestResult.addTestResult(TestResult(testName,testPassed,message)); + traceTestResult.addTestResult(TestResult(testName, testPassed, message)); } Py_DECREF(pResult); return traceTestResult; } -TraceCalculatedMetrics PythonCaller::calculateMetricsOnTrace(QString pathToTrace, vector list) +TraceCalculatedMetrics PythonCaller::calculateMetricsOnTrace( + QString pathToTrace, vector list) { TraceCalculatedMetrics result(QFileInfo(pathToTrace).baseName()); - PyObject *pResult = callMetricsFunction(pCalculateMetricsFunction, pathToTrace,list); + PyObject *pResult = callMetricsFunction(pCalculateMetricsFunction, pathToTrace, + list); - for(Py_ssize_t i= 0; i < PyList_Size(pResult); ++i) - { - PyObject* calculatedMetric = PyList_GetItem(pResult,i); - QString metricName(PyUnicode_AsUTF8(PyTuple_GetItem(calculatedMetric,0))); - double value = PyFloat_AsDouble(PyTuple_GetItem(calculatedMetric,1)); - result.addCalculatedMetric(CalculatedMetric(metricName,value)); + for (Py_ssize_t i = 0; i < PyList_Size(pResult); ++i) { + PyObject *calculatedMetric = PyList_GetItem(pResult, i); + QString metricName(PyUnicode_AsUTF8(PyTuple_GetItem(calculatedMetric, 0))); + double value = PyFloat_AsDouble(PyTuple_GetItem(calculatedMetric, 1)); + result.addCalculatedMetric(CalculatedMetric(metricName, value)); } Py_DECREF(pResult); @@ -190,11 +196,11 @@ TraceCalculatedMetrics PythonCaller::calculateMetricsOnTrace(QString pathToTrace vector PythonCaller::getMetrics(QString pathToTrace) { vector result; - PyObject *pResult = callFunctionWithStringArgument(pGetMetricsFunction, pathToTrace); + PyObject *pResult = callFunctionWithStringArgument(pGetMetricsFunction, + pathToTrace); - for(Py_ssize_t i= 0; i < PyList_Size(pResult); ++i) - { - PyObject* metric = PyList_GetItem(pResult,i); + for (Py_ssize_t i = 0; i < PyList_Size(pResult); ++i) { + PyObject *metric = PyList_GetItem(pResult, i); QString metricName(PyUnicode_AsUTF8(metric)); result.push_back(metricName.toStdString().c_str()); } @@ -207,7 +213,8 @@ QString PythonCaller::generatePlotsOnTrace(QString pathToTrace) { assert(PyCallable_Check(pGenPlotsFunction)); - PyObject* pResult = callFunctionWithStringArgument(pGenPlotsFunction, pathToTrace); + PyObject *pResult = callFunctionWithStringArgument(pGenPlotsFunction, + pathToTrace); QString outputFiles (PyUnicode_AsUTF8(pResult)); Py_DECREF(pResult); return outputFiles; diff --git a/DRAMSys/traceAnalyzer/businessObjects/pythoncaller.h b/DRAMSys/traceAnalyzer/businessObjects/pythoncaller.h index 9e58f13a..17ff8819 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/pythoncaller.h +++ b/DRAMSys/traceAnalyzer/businessObjects/pythoncaller.h @@ -51,20 +51,24 @@ public: PythonCaller(); ~PythonCaller(); TraceTestResults runTestsOnTrace(QString pathToTrace); - TraceCalculatedMetrics calculateMetricsOnTrace(QString pathToTrace, std::vector list); + TraceCalculatedMetrics calculateMetricsOnTrace(QString pathToTrace, + std::vector list); std::vector getMetrics(QString pathToTrace); QString generatePlotsOnTrace(QString pathToTrace); private: PyObject *pRunTestsFunction, *pCalculateMetricsFunction, *pGetMetricsFunction; PyObject *pGenPlotsFunction; - PyObject* loadFunctionFromModule(std::string moduleName, std::string functionName); - std::string testModuleName, testFunctionName, metricModuleName, metricFunctionName, getMetricFunctionName, pathToScripts; + PyObject *loadFunctionFromModule(std::string moduleName, + std::string functionName); + std::string testModuleName, testFunctionName, metricModuleName, + metricFunctionName, getMetricFunctionName, pathToScripts; std::string plotsModuleName; std::string plotsFunctionName; PyObject *callFunctionWithStringArgument(PyObject *function, QString argument); - PyObject *callMetricsFunction(PyObject* function, QString argument, std::vector list); + PyObject *callMetricsFunction(PyObject *function, QString argument, + std::vector list); }; #endif // PYTHONCALLER_H diff --git a/DRAMSys/traceAnalyzer/businessObjects/testresult.h b/DRAMSys/traceAnalyzer/businessObjects/testresult.h index f243e96f..8e3ea76e 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/testresult.h +++ b/DRAMSys/traceAnalyzer/businessObjects/testresult.h @@ -42,12 +42,21 @@ class TestResult { public: - TestResult(const QString& testName, bool passed, QString& message) : - testName(testName),passed(passed),message(message){} + TestResult(const QString &testName, bool passed, QString &message) : + testName(testName), passed(passed), message(message) {} - QString getTestName() const{return testName;} - QString getMessage() const{return message;} - bool hasPassed() const{return passed;} + QString getTestName() const + { + return testName; + } + QString getMessage() const + { + return message; + } + bool hasPassed() const + { + return passed; + } private: QString testName; diff --git a/DRAMSys/traceAnalyzer/businessObjects/timespan.cpp b/DRAMSys/traceAnalyzer/businessObjects/timespan.cpp index 276af548..f58cd24a 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/timespan.cpp +++ b/DRAMSys/traceAnalyzer/businessObjects/timespan.cpp @@ -39,7 +39,7 @@ bool Timespan::contains(traceTime time) const { - return (begin<=time && time<=end); + return (begin <= time && time <= end); } void Timespan::shift(traceTime offset) diff --git a/DRAMSys/traceAnalyzer/businessObjects/timespan.h b/DRAMSys/traceAnalyzer/businessObjects/timespan.h index dcc32839..f9da3514 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/timespan.h +++ b/DRAMSys/traceAnalyzer/businessObjects/timespan.h @@ -47,13 +47,31 @@ class Timespan traceTime end; public: - Timespan(traceTime begin = 0, traceTime end = 0) : begin(begin), end(end){} - traceTime timeCovered() const{return std::abs(End()-Begin());} - traceTime Begin() const{return begin;} - void setBegin(traceTime time){begin = time;} - traceTime End() const{return end;} - traceTime Middle() const{return (begin + end) / 2;} - void setEnd(traceTime time){end = time;} + Timespan(traceTime begin = 0, traceTime end = 0) : begin(begin), end(end) {} + traceTime timeCovered() const + { + return std::abs(End() - Begin()); + } + traceTime Begin() const + { + return begin; + } + void setBegin(traceTime time) + { + begin = time; + } + traceTime End() const + { + return end; + } + traceTime Middle() const + { + return (begin + end) / 2; + } + void setEnd(traceTime time) + { + end = time; + } bool contains(traceTime time) const; void shift(traceTime offset); }; diff --git a/DRAMSys/traceAnalyzer/businessObjects/tracecalculatedmetrics.h b/DRAMSys/traceAnalyzer/businessObjects/tracecalculatedmetrics.h index 8d3d0932..8de71297 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/tracecalculatedmetrics.h +++ b/DRAMSys/traceAnalyzer/businessObjects/tracecalculatedmetrics.h @@ -44,30 +44,37 @@ class TraceCalculatedMetrics { public: - TraceCalculatedMetrics(const QString& traceName): traceName(traceName){} + TraceCalculatedMetrics(const QString &traceName): traceName(traceName) {} - void addCalculatedMetric(const CalculatedMetric& result) {calculatedMetrics.push_back(result);} - QString getTraceName() const {return traceName;} - const std::vector& getCalculatedMetrics() const{return calculatedMetrics;} + void addCalculatedMetric(const CalculatedMetric &result) + { + calculatedMetrics.push_back(result); + } + QString getTraceName() const + { + return traceName; + } + const std::vector &getCalculatedMetrics() const + { + return calculatedMetrics; + } QString toCSVHeader() { QString result = ""; result.append("Trace"); - for(CalculatedMetric calculatedMetric : calculatedMetrics) - { + for (CalculatedMetric calculatedMetric : calculatedMetrics) { result.append(","); result.append(calculatedMetric.getName()); } return result; - } + } QString toCSVLine() { QString result = ""; result.append(traceName); - for(CalculatedMetric calculatedMetric : calculatedMetrics) - { + for (CalculatedMetric calculatedMetric : calculatedMetrics) { result.append(","); result.append(QString::number(calculatedMetric.getValue())); } diff --git a/DRAMSys/traceAnalyzer/businessObjects/tracetestresults.cpp b/DRAMSys/traceAnalyzer/businessObjects/tracetestresults.cpp index 467b9a94..448ffce8 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/tracetestresults.cpp +++ b/DRAMSys/traceAnalyzer/businessObjects/tracetestresults.cpp @@ -40,9 +40,8 @@ bool TraceTestResults::hasPassedAllTests() const { - for(const TestResult& testResult: testResults) - { - if(!testResult.hasPassed()) + for (const TestResult &testResult : testResults) { + if (!testResult.hasPassed()) return false; } return true; diff --git a/DRAMSys/traceAnalyzer/businessObjects/tracetestresults.h b/DRAMSys/traceAnalyzer/businessObjects/tracetestresults.h index 09320281..3ed6d96f 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/tracetestresults.h +++ b/DRAMSys/traceAnalyzer/businessObjects/tracetestresults.h @@ -44,13 +44,22 @@ class TraceTestResults { public: - TraceTestResults(const QString& traceName): traceName(traceName){} + TraceTestResults(const QString &traceName): traceName(traceName) {} - void addTestResult(const TestResult& result) {testResults.push_back(result);} + void addTestResult(const TestResult &result) + { + testResults.push_back(result); + } - QString getTraceName() const {return traceName;} + QString getTraceName() const + { + return traceName; + } bool hasPassedAllTests() const; - const std::vector& getTestResults() const{return testResults;} + const std::vector &getTestResults() const + { + return testResults; + } private: QString traceName; std::vector testResults; diff --git a/DRAMSys/traceAnalyzer/businessObjects/tracetime.h b/DRAMSys/traceAnalyzer/businessObjects/tracetime.h index a580fdfa..a50bd098 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/tracetime.h +++ b/DRAMSys/traceAnalyzer/businessObjects/tracetime.h @@ -45,19 +45,20 @@ typedef long long traceTime; inline QString prettyFormatTime(traceTime time) { - return QString::number(time/1000) + QString(" ns"); + return QString::number(time / 1000) + QString(" ns"); } inline QString formatInClks(traceTime time, unsigned int clkPeriod) { - long long numberOfClockCovered = time/clkPeriod; - QString suffix = (numberOfClockCovered != 1) ? QString(" clks") : QString(" clk"); + long long numberOfClockCovered = time / clkPeriod; + QString suffix = (numberOfClockCovered != 1) ? QString(" clks") : + QString(" clk"); return QString::number(numberOfClockCovered) + suffix; } inline traceTime alignToClk(traceTime time, unsigned int clkPeriod) { - return round(1.0*time/clkPeriod)*clkPeriod; + return round(1.0 * time / clkPeriod) * clkPeriod; } diff --git a/DRAMSys/traceAnalyzer/businessObjects/transaction.cpp b/DRAMSys/traceAnalyzer/businessObjects/transaction.cpp index 0578cbb2..8d1d72ab 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/transaction.cpp +++ b/DRAMSys/traceAnalyzer/businessObjects/transaction.cpp @@ -38,27 +38,32 @@ #include "transaction.h" using namespace std; -Transaction::Transaction(ID id,unsigned int address,unsigned int burstlength,int thread, unsigned int channel, unsigned int bank,unsigned int bankgroup, unsigned int row, unsigned int column, Timespan span, Timespan spanOnDataStrobe) - :address(address), burstlength(burstlength), thread(thread), channel(channel), bank(bank),bankgroup(bankgroup), row(row), column(column),span(span),spanOnDataStrobe(spanOnDataStrobe),id(id){} +Transaction::Transaction(ID id, unsigned int address, unsigned int burstlength, + int thread, unsigned int channel, unsigned int bank, unsigned int bankgroup, + unsigned int row, unsigned int column, Timespan span, Timespan spanOnDataStrobe) + : address(address), burstlength(burstlength), thread(thread), channel(channel), + bank(bank), bankgroup(bankgroup), row(row), column(column), span(span), + spanOnDataStrobe(spanOnDataStrobe), id(id) {} void Transaction::addPhase(shared_ptr phase) { phases.push_back(phase); } -void Transaction::draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &canvasRect, bool highlight, const TraceDrawingProperties &drawingProperties) const +void Transaction::draw(QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap, const QRectF &canvasRect, bool highlight, + const TraceDrawingProperties &drawingProperties) const { - for(shared_ptr phase: phases) - phase->draw(painter,xMap,yMap,canvasRect,highlight,drawingProperties); + for (shared_ptr phase : phases) + phase->draw(painter, xMap, yMap, canvasRect, highlight, drawingProperties); } -bool Transaction::isSelected(traceTime time, double yVal, const TraceDrawingProperties& drawingproperties) const +bool Transaction::isSelected(traceTime time, double yVal, + const TraceDrawingProperties &drawingproperties) const { - if(span.contains(time)) - { - for(shared_ptr phase: phases) - { - if(phase->isSelected(time,yVal,drawingproperties)) + if (span.contains(time)) { + for (shared_ptr phase : phases) { + if (phase->isSelected(time, yVal, drawingproperties)) return true; } } diff --git a/DRAMSys/traceAnalyzer/businessObjects/transaction.h b/DRAMSys/traceAnalyzer/businessObjects/transaction.h index 7faa11fc..2bfbe1a9 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/transaction.h +++ b/DRAMSys/traceAnalyzer/businessObjects/transaction.h @@ -48,32 +48,75 @@ typedef unsigned int ID; class Transaction { private: - unsigned int address,burstlength,thread,channel,bank,bankgroup,row,column; + unsigned int address, burstlength, thread, channel, bank, bankgroup, row, + column; Timespan span; Timespan spanOnDataStrobe; ID id; std::vector> phases; public: - Transaction(ID id,unsigned int address,unsigned int burstlength,int thread, unsigned int channel, unsigned int bank,unsigned int bankgroup, unsigned int row, unsigned int column, Timespan span, Timespan spanOnDataStrobe); + Transaction(ID id, unsigned int address, unsigned int burstlength, int thread, + unsigned int channel, unsigned int bank, unsigned int bankgroup, + unsigned int row, unsigned int column, Timespan span, + Timespan spanOnDataStrobe); - void draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &canvasRect, bool highlight,const TraceDrawingProperties& drawingProperties) const; + void draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, + const QRectF &canvasRect, bool highlight, + const TraceDrawingProperties &drawingProperties) const; void addPhase(std::shared_ptr phase); - bool isSelected(traceTime time,double yVal, const TraceDrawingProperties& drawingproperties) const; + bool isSelected(traceTime time, double yVal, + const TraceDrawingProperties &drawingproperties) const; - unsigned int Address() const{return address;} - unsigned int Burstlength() const{return burstlength;} - int Thread() {return thread;} - unsigned int Channel() const {return channel;} - unsigned int Bank() const{return bank;} - unsigned int BankGroup() const{return bankgroup;} - unsigned int Row() const{return row;} - unsigned int Column() const{return column;} - ID Id() const {return id;} - const Timespan& Span() const{return span;} - const Timespan& SpanOnDataStrobe() {return spanOnDataStrobe;} - const std::vector>& Phases() const{return phases;} + unsigned int Address() const + { + return address; + } + unsigned int Burstlength() const + { + return burstlength; + } + int Thread() + { + return thread; + } + unsigned int Channel() const + { + return channel; + } + unsigned int Bank() const + { + return bank; + } + unsigned int BankGroup() const + { + return bankgroup; + } + unsigned int Row() const + { + return row; + } + unsigned int Column() const + { + return column; + } + ID Id() const + { + return id; + } + const Timespan &Span() const + { + return span; + } + const Timespan &SpanOnDataStrobe() + { + return spanOnDataStrobe; + } + const std::vector> &Phases() const + { + return phases; + } }; #endif // TRANSACTION_H diff --git a/DRAMSys/traceAnalyzer/data/QueryTexts.h b/DRAMSys/traceAnalyzer/data/QueryTexts.h index 03c96dac..aeccca6d 100644 --- a/DRAMSys/traceAnalyzer/data/QueryTexts.h +++ b/DRAMSys/traceAnalyzer/data/QueryTexts.h @@ -39,17 +39,18 @@ #define QUERYTEXTS_H #include -struct TransactionQueryTexts -{ +struct TransactionQueryTexts { QString queryHead; - QString selectTransactionsByTimespan,selectTransactionById; + QString selectTransactionsByTimespan, selectTransactionById; TransactionQueryTexts() { - queryHead = "SELECT Transactions.ID AS TransactionID, Ranges.begin, Ranges.end,DataStrobeBegin,DataStrobeEnd, Address,Burstlength, TThread, TChannel, TBank,TBankgroup, TRow, TColumn,Phases.ID AS PhaseID, PhaseName, PhaseBegin, PhaseEnd " - " FROM Transactions INNER JOIN Phases ON Phases.Transact = Transactions.ID INNER JOIN Ranges ON Transactions.Range = Ranges.ID "; + queryHead = + "SELECT Transactions.ID AS TransactionID, Ranges.begin, Ranges.end,DataStrobeBegin,DataStrobeEnd, Address,Burstlength, TThread, TChannel, TBank,TBankgroup, TRow, TColumn,Phases.ID AS PhaseID, PhaseName, PhaseBegin, PhaseEnd " + " FROM Transactions INNER JOIN Phases ON Phases.Transact = Transactions.ID INNER JOIN Ranges ON Transactions.Range = Ranges.ID "; - selectTransactionsByTimespan = queryHead + " WHERE Ranges.end >= :begin AND Ranges.begin <= :end"; + selectTransactionsByTimespan = queryHead + + " WHERE Ranges.end >= :begin AND Ranges.begin <= :end"; selectTransactionById = queryHead + " WHERE Transactions.ID = :id"; } diff --git a/DRAMSys/traceAnalyzer/data/tracedb.cpp b/DRAMSys/traceAnalyzer/data/tracedb.cpp index 00706d5f..b1b19a65 100644 --- a/DRAMSys/traceAnalyzer/data/tracedb.cpp +++ b/DRAMSys/traceAnalyzer/data/tracedb.cpp @@ -66,7 +66,7 @@ TraceDB::TraceDB(QString path, bool openExisting) database = QSqlDatabase::addDatabase("QSQLITE", path); database.setDatabaseName(path); database.open(); - if(!openExisting) + if (!openExisting) dropAndCreateTables(); prepareQueries(); generalInfo = getGeneralInfoFromDB(); @@ -93,10 +93,9 @@ void TraceDB::updateComments(vector comments) executeQuery(query); query.prepare("insert into Comments values(:time,:text)"); - for(const Comment &comment:comments) - { - query.bindValue(":time",comment.Time()); - query.bindValue(":text",comment.Text()); + for (const Comment &comment : comments) { + query.bindValue(":time", comment.Time()); + query.bindValue(":text", comment.Text()); executeQuery(query); } } @@ -105,7 +104,7 @@ void TraceDB::updateFileDescription(const QString &description) { QSqlQuery query(database); query.prepare("UPDATE GeneralInfo SET Description=:description"); - query.bindValue(":description",description); + query.bindValue(":description", description); executeQuery(query); } @@ -116,7 +115,8 @@ void TraceDB::refreshData() //QueryText must select the fields //TransactionID, Ranges.begin, Ranges.end, Address, TThread, TChannel, TBank, TRow, TColumn, Phases.ID AS PhaseID, PhaseName, PhaseBegin, PhaseEnd -vector> TraceDB::getTransactionsWithCustomQuery(QString queryText) +vector> TraceDB::getTransactionsWithCustomQuery( + QString queryText) { QSqlQuery query(database); query.prepare(queryText); @@ -124,10 +124,11 @@ vector> TraceDB::getTransactionsWithCustomQuery(QString return parseTransactionsFromQuery(query); } -vector> TraceDB::getTransactionsInTimespan(const Timespan &span) +vector> TraceDB::getTransactionsInTimespan( + const Timespan &span) { - selectTransactionsByTimespan.bindValue(":begin",span.Begin()); - selectTransactionsByTimespan.bindValue(":end",span.End()); + selectTransactionsByTimespan.bindValue(":begin", span.Begin()); + selectTransactionsByTimespan.bindValue(":end", span.End()); executeQuery(selectTransactionsByTimespan); return parseTransactionsFromQuery(selectTransactionsByTimespan); } @@ -139,17 +140,19 @@ shared_ptr TraceDB::getTransactionByID(ID id) selectTransactionById.bindValue(":id", id); executeQuery(selectTransactionById); auto result = parseTransactionsFromQuery(selectTransactionById); - if(!result.empty()) + if (!result.empty()) return result[0]; else -throw sqlException(("Transaction with ID " + QString::number(id) + " not in DB").toStdString(),this->pathToDB.toStdString()); + throw sqlException(("Transaction with ID " + QString::number( + id) + " not in DB").toStdString(), this->pathToDB.toStdString()); } shared_ptr TraceDB::getNextActivate(ID currentTransactionId) { QSqlQuery query(database); - QString queryText = queryTexts.queryHead + "WHERE TransactionID > :currentID AND PhaseName = 'ACT' LIMIT 1"; + QString queryText = queryTexts.queryHead + + "WHERE TransactionID > :currentID AND PhaseName = 'ACT' LIMIT 1"; query.prepare(queryText); query.bindValue(":currentID", currentTransactionId); @@ -160,7 +163,8 @@ shared_ptr TraceDB::getNextActivate(ID currentTransactionId) shared_ptr TraceDB::getNextPrecharge(ID currentTransactionId) { QSqlQuery query(database); - QString queryText = queryTexts.queryHead + "WHERE TransactionID > :currentID AND PhaseName IN ('PRE','PRE_ALL') LIMIT 1"; + QString queryText = queryTexts.queryHead + + "WHERE TransactionID > :currentID AND PhaseName IN ('PRE','PRE_ALL') LIMIT 1"; query.prepare(queryText); query.bindValue(":currentID", currentTransactionId); @@ -171,7 +175,8 @@ shared_ptr TraceDB::getNextPrecharge(ID currentTransactionId) shared_ptr TraceDB::getNextRefresh(ID currentTransactionId) { QSqlQuery query(database); - QString queryText = queryTexts.queryHead + "WHERE TransactionID > :currentID AND PhaseName = 'AUTO_REFRESH' LIMIT 1"; + QString queryText = queryTexts.queryHead + + "WHERE TransactionID > :currentID AND PhaseName = 'AUTO_REFRESH' LIMIT 1"; query.prepare(queryText); query.bindValue(":currentID", currentTransactionId); @@ -183,16 +188,14 @@ ID TraceDB::getTransactionIDFromPhaseID(ID phaseID) { QSqlQuery query(database); query.prepare("SELECT Transact FROM Phases WHERE ID=:id"); - query.bindValue(":id",phaseID); + query.bindValue(":id", phaseID); executeQuery(query); - if(query.next()) - { - return query.value(0).toInt(); - } - else - { - throw sqlException("Phase with ID "+ to_string(phaseID) + " not in db", this->pathToDB.toStdString()); + if (query.next()) { + return query.value(0).toInt(); + } else { + throw sqlException("Phase with ID " + to_string(phaseID) + " not in db", + this->pathToDB.toStdString()); } } @@ -202,8 +205,7 @@ GeneralInfo TraceDB::getGeneralInfoFromDB() query.prepare("SELECT NumberOfTransactions,TraceEnd,NumberOfBanks,Clk,UnitOfTime,Traces,Memspec,MCconfig, WindowSize, ControllerThread FROM GeneralInfo"); executeQuery(query); - if(query.next()) - { + if (query.next()) { unsigned int numberOfTransactions = query.value(0).toInt(); traceTime traceEnd = query.value(1).toLongLong(); unsigned int numberOfBanks = query.value(2).toInt(); @@ -220,16 +222,19 @@ GeneralInfo TraceDB::getGeneralInfoFromDB() QString description = (traces + "\n"); description += mcconfig + "\n"; description += memspec + "\n"; - description += "Number of Transactions: " + QString::number(numberOfTransactions) + "\n"; - description += "Clock period: " + QString::number(clkPeriod) + " " + unitOfTime + "\n"; + description += "Number of Transactions: " + QString::number( + numberOfTransactions) + "\n"; + description += "Clock period: " + QString::number(clkPeriod) + " " + unitOfTime + + "\n"; description += "Length of trace: " + prettyFormatTime(traceEnd) + "\n"; description += "Window size:" + QString::number(windowSize) + "\n"; - return GeneralInfo(numberOfTransactions, numberOfPhases, Timespan(0,traceEnd),numberOfBanks,description,unitOfTime,clkPeriod, windowSize, controllerThread); - } - else - { - throw sqlException("Tracefile corrupted. No general info table", this->pathToDB.toStdString()); + return GeneralInfo(numberOfTransactions, numberOfPhases, Timespan(0, traceEnd), + numberOfBanks, description, unitOfTime, clkPeriod, windowSize, + controllerThread); + } else { + throw sqlException("Tracefile corrupted. No general info table", + this->pathToDB.toStdString()); } } @@ -254,18 +259,19 @@ vector TraceDB::getComments() vector TraceDB::getDebugMessagesInTimespan(const Timespan &span) { - selectDebugMessagesByTimespan.bindValue(":begin",span.Begin()); - selectDebugMessagesByTimespan.bindValue(":end",span.End()); + selectDebugMessagesByTimespan.bindValue(":begin", span.Begin()); + selectDebugMessagesByTimespan.bindValue(":end", span.End()); executeQuery(selectDebugMessagesByTimespan); return parseCommentsFromQuery(selectDebugMessagesByTimespan); } -vector TraceDB::getDebugMessagesInTimespan(const Timespan &span, unsigned int limit = 50) +vector TraceDB::getDebugMessagesInTimespan(const Timespan &span, + unsigned int limit = 50) { - selectDebugMessagesByTimespanWithLimit.bindValue(":begin",span.Begin()); - selectDebugMessagesByTimespanWithLimit.bindValue(":end",span.End()); - selectDebugMessagesByTimespanWithLimit.bindValue(":limit",limit); + selectDebugMessagesByTimespanWithLimit.bindValue(":begin", span.Begin()); + selectDebugMessagesByTimespanWithLimit.bindValue(":end", span.End()); + selectDebugMessagesByTimespanWithLimit.bindValue(":limit", limit); executeQuery(selectDebugMessagesByTimespanWithLimit); return parseCommentsFromQuery(selectDebugMessagesByTimespanWithLimit); } @@ -280,13 +286,14 @@ vector TraceDB::getDebugMessagesInTimespan(const Timespan &span, unsign shared_ptr TraceDB::parseTransactionFromQuery(QSqlQuery &query) { auto result = parseTransactionsFromQuery(query); - if(!result.empty()) + if (!result.empty()) return result[0]; else return shared_ptr(); } -vector> TraceDB::parseTransactionsFromQuery(QSqlQuery &query) +vector> TraceDB::parseTransactionsFromQuery( + QSqlQuery &query) { vector> result; @@ -294,60 +301,61 @@ vector> TraceDB::parseTransactionsFromQuery(QSqlQuery &q ID currentID = 0; int i = -1; - while(query.next()){ + while (query.next()) { ID id = query.value(0).toInt(); - if(currentID != id || firstIteration) - { + if (currentID != id || firstIteration) { ++i; firstIteration = false; currentID = id; - Timespan span(query.value(1).toLongLong(),query.value(2).toLongLong()); - Timespan spanOnStrobe(query.value(3).toLongLong(),query.value(4).toLongLong()); + Timespan span(query.value(1).toLongLong(), query.value(2).toLongLong()); + Timespan spanOnStrobe(query.value(3).toLongLong(), query.value(4).toLongLong()); unsigned int address = query.value(5).toInt(); unsigned int burstlength = query.value(6).toInt(); - unsigned int thread= query.value(7).toInt(); + unsigned int thread = query.value(7).toInt(); unsigned int channel = query.value(8).toInt(); unsigned int bank = query.value(9).toInt(); unsigned int bankgroup = query.value(10).toInt(); unsigned int row = query.value(11).toInt(); unsigned int column = query.value(12).toInt(); - result.push_back(shared_ptr(new Transaction(id,address,burstlength,thread,channel,bank,bankgroup,row,column,span,spanOnStrobe))); + result.push_back(shared_ptr(new Transaction(id, address, + burstlength, thread, channel, bank, bankgroup, row, column, span, + spanOnStrobe))); } unsigned int phaseID = query.value(13).toInt(); QString phaseName = query.value(14).toString(); - Timespan span(query.value(15).toLongLong(),query.value(16).toLongLong()); - result.at(result.size()-1)->addPhase(PhaseFactory::CreatePhase(phaseID,phaseName,span,result.at(result.size()-1),*this)); + Timespan span(query.value(15).toLongLong(), query.value(16).toLongLong()); + result.at(result.size() - 1)->addPhase(PhaseFactory::CreatePhase(phaseID, + phaseName, span, result.at(result.size() - 1), *this)); } return result; } vector TraceDB::parseCommentsFromQuery(QSqlQuery &query) { - vector result; - while(query.next()) - { - result.push_back(Comment(query.value(0).toLongLong(),query.value(1).toString())); - } - return result; + vector result; + while (query.next()) { + result.push_back(Comment(query.value(0).toLongLong(), + query.value(1).toString())); + } + return result; } void TraceDB::executeQuery(QSqlQuery query) { //query.exec returns bool indicating if the query was sucessfull - if(query.exec()) - { + if (query.exec()) { #ifdef printqueries cout << queryToString(query).toStdString() << endl; #endif } - else - { - throw sqlException( ("Query:\n " + queryToString(query) + "\n failed. Error: \n"+ + else { + throw sqlException( ("Query:\n " + queryToString(query) + "\n failed. Error: \n" + + query.lastError().text()).toStdString(), this->pathToDB.toStdString()); } } @@ -356,10 +364,9 @@ QString TraceDB::queryToString(QSqlQuery query) { QString str = query.lastQuery(); QMapIterator it(query.boundValues()); - while (it.hasNext()) - { + while (it.hasNext()) { it.next(); - str.replace(it.key(),it.value().toString()); + str.replace(it.key(), it.value().toString()); } return str; } @@ -375,20 +382,18 @@ void TraceDB::executeScriptFile(QString fileName) QSqlQuery query(database); QFile scriptFile(fileName); - if (scriptFile.open(QIODevice::ReadOnly)) - { + if (scriptFile.open(QIODevice::ReadOnly)) { // The SQLite driver executes only a single (the first) query in the QSqlQuery // if the script contains more queries, it needs to be splitted. QStringList scriptQueries = QTextStream(&scriptFile).readAll().split(';'); - for (QString &queryTxt : scriptQueries) - { + for (QString &queryTxt : scriptQueries) { if (queryTxt.trimmed().isEmpty()) { continue; } - if (!query.exec(queryTxt)) - { - throw sqlException("Querry failed:" + query.lastError().text().toStdString(), this->pathToDB.toStdString()); + if (!query.exec(queryTxt)) { + throw sqlException("Querry failed:" + query.lastError().text().toStdString(), + this->pathToDB.toStdString()); } query.finish(); } diff --git a/DRAMSys/traceAnalyzer/data/tracedb.h b/DRAMSys/traceAnalyzer/data/tracedb.h index ad19ffbe..b4baf8bb 100644 --- a/DRAMSys/traceAnalyzer/data/tracedb.h +++ b/DRAMSys/traceAnalyzer/data/tracedb.h @@ -62,16 +62,24 @@ class TraceDB : public QObject public: TraceDB(QString path, bool openExisting); - const QString& getPathToDB(){return pathToDB;} + const QString &getPathToDB() + { + return pathToDB; + } void updateComments(std::vector comments); void updateFileDescription(const QString &description); void refreshData(); - const GeneralInfo& getGeneralInfo() {return generalInfo;} + const GeneralInfo &getGeneralInfo() + { + return generalInfo; + } - std::vector> getTransactionsWithCustomQuery(QString queryText); - std::vector> getTransactionsInTimespan(const Timespan &span); + std::vector> getTransactionsWithCustomQuery( + QString queryText); + std::vector> getTransactionsInTimespan( + const Timespan &span); std::shared_ptr getNextPrecharge(ID currentTransactionId); std::shared_ptr getNextActivate(ID currentTransactionId); std::shared_ptr getNextRefresh(ID currentTransactionId); @@ -82,7 +90,8 @@ public: std::vector getComments(); std::vector getDebugMessagesInTimespan(const Timespan &span); - std::vector getDebugMessagesInTimespan(const Timespan &span, unsigned int limit); + std::vector getDebugMessagesInTimespan(const Timespan &span, + unsigned int limit); private: QString pathToDB; @@ -101,7 +110,8 @@ private: void executeQuery(QSqlQuery query); QString queryToString(QSqlQuery query); std::shared_ptr parseTransactionFromQuery(QSqlQuery &query); - std::vector> parseTransactionsFromQuery(QSqlQuery &query); + std::vector> parseTransactionsFromQuery( + QSqlQuery &query); std::vector parseCommentsFromQuery(QSqlQuery &query); void executeScriptFile(QString fileName); @@ -120,9 +130,10 @@ private: public: sqlException(std::string message, std::string filename) { - this->message = std::string("Error in file ") + filename + std::string(" ") + message; + this->message = std::string("Error in file ") + filename + std::string(" ") + + message; } - const char* what() const noexcept + const char *what() const noexcept { return message.c_str(); } diff --git a/DRAMSys/traceAnalyzer/evaluationtool.cpp b/DRAMSys/traceAnalyzer/evaluationtool.cpp index 004e30af..e4ef6f15 100644 --- a/DRAMSys/traceAnalyzer/evaluationtool.cpp +++ b/DRAMSys/traceAnalyzer/evaluationtool.cpp @@ -60,9 +60,11 @@ EvaluationTool::EvaluationTool(QWidget *parent) : ui->setupUi(this); traceFilesModel = new QStandardItemModel(this); ui->listView->setModel(traceFilesModel); - QObject::connect(ui->traceTestTreeWidget,SIGNAL(setMessage(QString)),this,SLOT(setTestMessage(QString))); + QObject::connect(ui->traceTestTreeWidget, SIGNAL(setMessage(QString)), this, + SLOT(setTestMessage(QString))); selectMetrics = new SelectMetrics(this); - QObject::connect(selectMetrics, SIGNAL(getSelectedMetrics()), this, SLOT(getSelectedMetrics())); + QObject::connect(selectMetrics, SIGNAL(getSelectedMetrics()), this, + SLOT(getSelectedMetrics())); } EvaluationTool::~EvaluationTool() @@ -95,17 +97,16 @@ void EvaluationTool::showAndEvaluateMetrics(QList paths) show(); ui->toolBox->setCurrentIndex(1); selectMetrics->setMetrics(getMetrics()); - cout<<"done"< EvaluationTool::getMetrics() { vector metrics; - for(int row = 0; row < traceFilesModel->rowCount(); ++row) - { - TraceFileItem* item = static_cast(traceFilesModel->item(row)); + for (int row = 0; row < traceFilesModel->rowCount(); ++row) { + TraceFileItem *item = static_cast(traceFilesModel->item(row)); vector result = pythonCaller.getMetrics(item->getPath()); - if(result.size() > metrics.size()) + if (result.size() > metrics.size()) metrics = result; } return metrics; @@ -123,9 +124,11 @@ void EvaluationTool::cleanUpUI() void EvaluationTool::fillFileList(QList paths) { - qSort(paths.begin(), paths.end(), [] (const QString &path1, const QString &path2) {return QFileInfo(path1).baseName() < QFileInfo(path2).baseName();}); - for(const QString& path: paths) - { + qSort(paths.begin(), paths.end(), [] (const QString & path1, + const QString & path2) { + return QFileInfo(path1).baseName() < QFileInfo(path2).baseName(); + }); + for (const QString &path : paths) { traceFilesModel->appendRow(new TraceFileItem(path)); } } @@ -140,23 +143,23 @@ void EvaluationTool::runTests() ui->traceTestTreeWidget->clear(); ui->testLight->setGray(); - if(traceFilesModel->rowCount() == 0) + if (traceFilesModel->rowCount() == 0) return; bool allTestsPassed = true; - for(int row = 0; row < traceFilesModel->rowCount(); ++row) - { - TraceFileItem* item = static_cast(traceFilesModel->item(row)); - TraceTestResults traceTestResult = pythonCaller.runTestsOnTrace(item->getPath()); - if(!traceTestResult.hasPassedAllTests()) + for (int row = 0; row < traceFilesModel->rowCount(); ++row) { + TraceFileItem *item = static_cast(traceFilesModel->item(row)); + TraceTestResults traceTestResult = pythonCaller.runTestsOnTrace( + item->getPath()); + if (!traceTestResult.hasPassedAllTests()) allTestsPassed = false; ui->traceTestTreeWidget->addTraceTestResult(traceTestResult); } ui->traceTestTreeWidget->expandAll(); - if(allTestsPassed) + if (allTestsPassed) ui->testLight->setGreen(); else ui->testLight->setRed(); @@ -164,16 +167,15 @@ void EvaluationTool::runTests() void EvaluationTool::on_btn_calculateMetrics_clicked() { - selectMetrics->raise(); - selectMetrics->activateWindow(); - selectMetrics->show(); + selectMetrics->raise(); + selectMetrics->activateWindow(); + selectMetrics->show(); } void EvaluationTool::getSelectedMetrics() { vector selectedMetrics; - for(QCheckBox* metric : selectMetrics->metrics) - { + for (QCheckBox *metric : selectMetrics->metrics) { selectedMetrics.push_back(metric->isChecked()); } calculateMetrics(selectedMetrics); @@ -181,15 +183,15 @@ void EvaluationTool::getSelectedMetrics() void EvaluationTool::calculateMetrics(vector selectedMetrics) { - ui->traceMetricTreeWidget->clear(); - for(int row = 0; row < traceFilesModel->rowCount(); ++row) - { - TraceFileItem* item = static_cast(traceFilesModel->item(row)); - TraceCalculatedMetrics result = pythonCaller.calculateMetricsOnTrace(item->getPath(), selectedMetrics); - calculatedMetrics.push_back(result); - ui->traceMetricTreeWidget->addTraceMetricResults(result); - } - ui->traceMetricTreeWidget->expandAll(); + ui->traceMetricTreeWidget->clear(); + for (int row = 0; row < traceFilesModel->rowCount(); ++row) { + TraceFileItem *item = static_cast(traceFilesModel->item(row)); + TraceCalculatedMetrics result = pythonCaller.calculateMetricsOnTrace( + item->getPath(), selectedMetrics); + calculatedMetrics.push_back(result); + ui->traceMetricTreeWidget->addTraceMetricResults(result); + } + ui->traceMetricTreeWidget->expandAll(); } void EvaluationTool::setTestMessage(QString message) @@ -208,17 +210,15 @@ EvaluationTool::TraceFileItem::TraceFileItem(const QString &path) void EvaluationTool::on_btn_exportCSV_clicked() { - if(calculatedMetrics.size() > 0) - { - QString filename = QFileDialog::getSaveFileName(this, "Export to CSV", "", "Comma separated Values(*.csv)"); - if(filename != "") - { + if (calculatedMetrics.size() > 0) { + QString filename = QFileDialog::getSaveFileName(this, "Export to CSV", "", + "Comma separated Values(*.csv)"); + if (filename != "") { QFile file(filename); file.open(QIODevice::WriteOnly | QIODevice::Text); QTextStream out(&file); out << calculatedMetrics[0].toCSVHeader() << "\n"; - for(TraceCalculatedMetrics& metrics : calculatedMetrics) - { + for (TraceCalculatedMetrics &metrics : calculatedMetrics) { out << metrics.toCSVLine() << "\n"; } file.close(); @@ -235,12 +235,14 @@ void EvaluationTool::genPlots() { ui->traceMetricTreeWidget->clear(); - if(traceFilesModel->rowCount() == 0) + if (traceFilesModel->rowCount() == 0) return; for (int row = 0; row < traceFilesModel->rowCount(); ++row) { - TraceFileItem *item = static_cast(traceFilesModel->item(row)); - ui->traceMetricTreeWidget->addTracePlotResults(QFileInfo(item->getPath()).baseName(), pythonCaller.generatePlotsOnTrace(item->getPath())); + TraceFileItem *item = static_cast(traceFilesModel->item(row)); + ui->traceMetricTreeWidget->addTracePlotResults(QFileInfo( + item->getPath()).baseName(), + pythonCaller.generatePlotsOnTrace(item->getPath())); } ui->traceMetricTreeWidget->expandAll(); } diff --git a/DRAMSys/traceAnalyzer/evaluationtool.h b/DRAMSys/traceAnalyzer/evaluationtool.h index 496d438a..32977f5b 100644 --- a/DRAMSys/traceAnalyzer/evaluationtool.h +++ b/DRAMSys/traceAnalyzer/evaluationtool.h @@ -95,8 +95,11 @@ private: class TraceFileItem : public QStandardItem { public: - TraceFileItem(const QString& path); - QString getPath(){return path;} + TraceFileItem(const QString &path); + QString getPath() + { + return path; + } private: QString path; diff --git a/DRAMSys/traceAnalyzer/gototimedialog.cpp b/DRAMSys/traceAnalyzer/gototimedialog.cpp index c0dbb22c..aefe224f 100644 --- a/DRAMSys/traceAnalyzer/gototimedialog.cpp +++ b/DRAMSys/traceAnalyzer/gototimedialog.cpp @@ -39,7 +39,7 @@ #include "ui_gototimedialog.h" #include -GoToTimeDialog::GoToTimeDialog(double* goToSecond,QWidget *parent) : +GoToTimeDialog::GoToTimeDialog(double *goToSecond, QWidget *parent) : QDialog(parent), goToSecond(goToSecond), ui(new Ui::GoToTimeDialog) @@ -56,11 +56,11 @@ void GoToTimeDialog::on_pushButton_clicked() { QLocale c(QLocale::C); bool validNumber; - *goToSecond = c.toDouble(ui->timeEdit->text(),&validNumber); - if(validNumber) + *goToSecond = c.toDouble(ui->timeEdit->text(), &validNumber); + if (validNumber) accept(); - else - { - QMessageBox::warning(this,"Invalid number","Please enter a valid floating point number"); + else { + QMessageBox::warning(this, "Invalid number", + "Please enter a valid floating point number"); } } diff --git a/DRAMSys/traceAnalyzer/gototimedialog.h b/DRAMSys/traceAnalyzer/gototimedialog.h index 68465d1b..9e1b1b62 100644 --- a/DRAMSys/traceAnalyzer/gototimedialog.h +++ b/DRAMSys/traceAnalyzer/gototimedialog.h @@ -42,7 +42,7 @@ namespace Ui { - class GoToTimeDialog; +class GoToTimeDialog; } class GoToTimeDialog : public QDialog @@ -50,12 +50,12 @@ class GoToTimeDialog : public QDialog Q_OBJECT public: - explicit GoToTimeDialog(double* goToSecond, QWidget *parent = 0); + explicit GoToTimeDialog(double *goToSecond, QWidget *parent = 0); ~GoToTimeDialog(); private: - double* goToSecond; + double *goToSecond; private Q_SLOTS: void on_pushButton_clicked(); diff --git a/DRAMSys/traceAnalyzer/main.cpp b/DRAMSys/traceAnalyzer/main.cpp index fb5e07f8..39ccc91a 100644 --- a/DRAMSys/traceAnalyzer/main.cpp +++ b/DRAMSys/traceAnalyzer/main.cpp @@ -50,33 +50,28 @@ int main(int argc, char *argv[]) cout << argv[0] << std::endl; QApplication a(argc, argv); - if(argc > 1) - { + if (argc > 1) { QSet arguments; - for(int i = 1;i paths = arguments; - arguments.clear(); - for(QString path : paths) - { + QSet paths = arguments; + arguments.clear(); + for (QString path : paths) { QDir directory(path); QStringList files = directory.entryList(nameFilter); - for(QString& file : files) - { + for (QString &file : files) { arguments.insert(path.append("/") + file); } } @@ -85,9 +80,7 @@ int main(int argc, char *argv[]) TraceAnalyzer analyzer(arguments, startupOption); analyzer.show(); return a.exec(); - } - else - { + } else { TraceAnalyzer analyzer; analyzer.show(); return a.exec(); diff --git a/DRAMSys/traceAnalyzer/mainwindow.cpp b/DRAMSys/traceAnalyzer/mainwindow.cpp index eedac58e..7155466f 100644 --- a/DRAMSys/traceAnalyzer/mainwindow.cpp +++ b/DRAMSys/traceAnalyzer/mainwindow.cpp @@ -46,25 +46,31 @@ MainWindow::MainWindow(QWidget *parent) : ui(new Ui::MainWindow) { ui->setupUi(this); - // xmlDeserializer des("config.xml"); - // des.xmlToTraceDB("tpr.xml") + // xmlDeserializer des("config.xml"); + // des.xmlToTraceDB("tpr.xml") db = new TraceDB("tpr.tdb", true); traceNavigator = new TraceNavigator(db->getGeneralInfo(), this); ui->tracePlot->init(traceNavigator, db); ui->pornoTraceScroller->init(traceNavigator, db, ui->tracePlot); - phases = db->getPhasesInTimespan(traceNavigator->GeneralTraceInfo().TraceSpan()); - transactions = db->getTransactionsInTimespan(traceNavigator->GeneralTraceInfo().TraceSpan()); + phases = db->getPhasesInTimespan( + traceNavigator->GeneralTraceInfo().TraceSpan()); + transactions = db->getTransactionsInTimespan( + traceNavigator->GeneralTraceInfo().TraceSpan()); - ui->qwtPlot->setAxisScale(QwtPlot::xBottom,traceNavigator->GeneralTraceInfo().TraceSpan().Begin(),traceNavigator->GeneralTraceInfo().TraceSpan().End()); + ui->qwtPlot->setAxisScale(QwtPlot::xBottom, + traceNavigator->GeneralTraceInfo().TraceSpan().Begin(), + traceNavigator->GeneralTraceInfo().TraceSpan().End()); unsigned int banksize = traceNavigator -> GeneralTraceInfo().NumberOfBanks(); - ui->qwtPlot->setAxisScale(QwtPlot::yLeft,0.0,banksize + 3, 1.0); + ui->qwtPlot->setAxisScale(QwtPlot::yLeft, 0.0, banksize + 3, 1.0); - PhaseCollectionDrawingProperties* drawingProperties = new PhaseCollectionDrawingProperties(banksize,this); + PhaseCollectionDrawingProperties *drawingProperties = new + PhaseCollectionDrawingProperties(banksize, this); drawingProperties->setDrawText(false); drawingProperties->setDrawBorder(false); drawingProperties->setDrawPowerDownStates(false); - phaseCollectionPlotItem *phaseCollectionPlot = new phaseCollectionPlotItem(phases,transactions,drawingProperties); + phaseCollectionPlotItem *phaseCollectionPlot = new phaseCollectionPlotItem( + phases, transactions, drawingProperties); phaseCollectionPlot->attach(ui->qwtPlot); traceNavigator->navigateToTime(0); diff --git a/DRAMSys/traceAnalyzer/mainwindow.h b/DRAMSys/traceAnalyzer/mainwindow.h index 6c96ac79..4b07fe0c 100644 --- a/DRAMSys/traceAnalyzer/mainwindow.h +++ b/DRAMSys/traceAnalyzer/mainwindow.h @@ -46,7 +46,7 @@ class TraceDB; namespace Ui { - class MainWindow; +class MainWindow; } class MainWindow : public QMainWindow @@ -64,8 +64,8 @@ private: Ui::MainWindow *ui; TraceNavigator *traceNavigator; TraceDB *db; - QHash phases; - QHash transactions; + QHash phases; + QHash transactions; }; diff --git a/DRAMSys/traceAnalyzer/markerplotitem.cpp b/DRAMSys/traceAnalyzer/markerplotitem.cpp index 085e7bf0..3b08c865 100644 --- a/DRAMSys/traceAnalyzer/markerplotitem.cpp +++ b/DRAMSys/traceAnalyzer/markerplotitem.cpp @@ -41,10 +41,11 @@ int MarkerPlotItem::rtti() const { - return QwtPlotItem::Rtti_PlotUserItem; + return QwtPlotItem::Rtti_PlotUserItem; } -void MarkerPlotItem::draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &canvasRect) const +void MarkerPlotItem::draw(QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap, const QRectF &canvasRect) const { - drawVerticalLine(painter,xMap.transform(time),canvasRect,color,width); + drawVerticalLine(painter, xMap.transform(time), canvasRect, color, width); } diff --git a/DRAMSys/traceAnalyzer/markerplotitem.h b/DRAMSys/traceAnalyzer/markerplotitem.h index 5952b2f6..68a802b2 100644 --- a/DRAMSys/traceAnalyzer/markerplotitem.h +++ b/DRAMSys/traceAnalyzer/markerplotitem.h @@ -48,9 +48,11 @@ private: QColor color; public: - MarkerPlotItem(traceTime time, int width = 4, QColor color = QColor(Qt::black)):time(time), width(width), color(color){} + MarkerPlotItem(traceTime time, int width = 4, + QColor color = QColor(Qt::black)): time(time), width(width), color(color) {} virtual int rtti() const; - virtual void draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &canvasRect) const; + virtual void draw(QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap, const QRectF &canvasRect) const; }; diff --git a/DRAMSys/traceAnalyzer/presentation/commenttreewidget.cpp b/DRAMSys/traceAnalyzer/presentation/commenttreewidget.cpp index 1fe30e94..744468a6 100644 --- a/DRAMSys/traceAnalyzer/presentation/commenttreewidget.cpp +++ b/DRAMSys/traceAnalyzer/presentation/commenttreewidget.cpp @@ -47,11 +47,14 @@ void CommentTreeWidget::init(TraceNavigator *navigator) this->navigator = navigator; setColumnCount(2); setHeaderLabels(QStringList({"Time", "Comment"})); - QObject::connect(navigator,SIGNAL(commentsChanged()),this, SLOT(commentsChanged())); - QObject::connect(this,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),this,SLOT(itemDoubleClicked(QTreeWidgetItem*,int))); - QObject::connect(this,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(ContextMenuRequested(QPoint))); + QObject::connect(navigator, SIGNAL(commentsChanged()), this, + SLOT(commentsChanged())); + QObject::connect(this, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)), this, + SLOT(itemDoubleClicked(QTreeWidgetItem *, int))); + QObject::connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, + SLOT(ContextMenuRequested(QPoint))); setContextMenuPolicy(Qt::CustomContextMenu); - deleteComment = new QAction("Delete comment",this); + deleteComment = new QAction("Delete comment", this); printComments(); } @@ -63,10 +66,9 @@ void CommentTreeWidget::commentsChanged() void CommentTreeWidget::printComments() { - for(const auto &pair: navigator->getComments()) - { + for (const auto &pair : navigator->getComments()) { const Comment &comment = pair.second; - QTreeWidgetItem* item = new CommentTreeItem(this,comment); + QTreeWidgetItem *item = new CommentTreeItem(this, comment); addTopLevelItem(item); } resizeColumnToContents(0); @@ -74,7 +76,7 @@ void CommentTreeWidget::printComments() void CommentTreeWidget::itemDoubleClicked(QTreeWidgetItem *item, int /*column*/) { - CommentTreeItem* commentItem = static_cast(item); + CommentTreeItem *commentItem = static_cast(item); navigator->navigateToTime(commentItem->Time()); } @@ -82,21 +84,20 @@ void CommentTreeWidget::ContextMenuRequested(QPoint point) { QMenu contextMenu; contextMenu.addActions({deleteComment}); - QAction* selectedItem = contextMenu.exec(mapToGlobal(point)); + QAction *selectedItem = contextMenu.exec(mapToGlobal(point)); - if(selectedItem) - { - for(QTreeWidgetItem *item: selectedItems()) - { - CommentTreeItem *commentItem = static_cast(item); + if (selectedItem) { + for (QTreeWidgetItem *item : selectedItems()) { + CommentTreeItem *commentItem = static_cast(item); navigator->removeCommentAtTime(commentItem->Time()); } } } -CommentTreeWidget::CommentTreeItem::CommentTreeItem(QTreeWidget *parent, const Comment &comment):QTreeWidgetItem(parent),comment(comment) +CommentTreeWidget::CommentTreeItem::CommentTreeItem(QTreeWidget *parent, + const Comment &comment): QTreeWidgetItem(parent), comment(comment) { - this->setText(0,prettyFormatTime(comment.Time())); - this->setText(1,comment.Text()); + this->setText(0, prettyFormatTime(comment.Time())); + this->setText(1, comment.Text()); } diff --git a/DRAMSys/traceAnalyzer/presentation/commenttreewidget.h b/DRAMSys/traceAnalyzer/presentation/commenttreewidget.h index 0314ef17..4b1f67b2 100644 --- a/DRAMSys/traceAnalyzer/presentation/commenttreewidget.h +++ b/DRAMSys/traceAnalyzer/presentation/commenttreewidget.h @@ -48,27 +48,31 @@ class CommentTreeWidget : public QTreeWidget Q_OBJECT public: - CommentTreeWidget(QWidget *parent = 0) : QTreeWidget(parent),isInitialized(false){} - void init(TraceNavigator* navigator); + CommentTreeWidget(QWidget *parent = 0) : QTreeWidget(parent), + isInitialized(false) {} + void init(TraceNavigator *navigator); public Q_SLOTS: void commentsChanged(); - void itemDoubleClicked(QTreeWidgetItem * item, int column); + void itemDoubleClicked(QTreeWidgetItem *item, int column); void ContextMenuRequested(QPoint point); private: bool isInitialized; TraceNavigator *navigator; void printComments(); - QAction* deleteComment; + QAction *deleteComment; class CommentTreeItem : public QTreeWidgetItem { private: Comment comment; public: - CommentTreeItem(QTreeWidget * parent, const Comment &comment); - traceTime Time() {return comment.Time();} + CommentTreeItem(QTreeWidget *parent, const Comment &comment); + traceTime Time() + { + return comment.Time(); + } }; }; diff --git a/DRAMSys/traceAnalyzer/presentation/debugmessagetreewidget.cpp b/DRAMSys/traceAnalyzer/presentation/debugmessagetreewidget.cpp index 919543c0..f9dc6666 100644 --- a/DRAMSys/traceAnalyzer/presentation/debugmessagetreewidget.cpp +++ b/DRAMSys/traceAnalyzer/presentation/debugmessagetreewidget.cpp @@ -41,13 +41,16 @@ using namespace std; -void DebugMessageTreeWidget::init(TraceNavigator *navigator, TracePlot *traceplot) +void DebugMessageTreeWidget::init(TraceNavigator *navigator, + TracePlot *traceplot) { Q_ASSERT(isInitialized == false); isInitialized = true; arrangeUiSettings(); - connect(navigator,SIGNAL(currentTraceTimeChanged()),this,SLOT(currentTraceTimeChanged())); - connect(navigator,SIGNAL(selectedTransactionsChanged()),this,SLOT(selectedTransactionChanged())); + connect(navigator, SIGNAL(currentTraceTimeChanged()), this, + SLOT(currentTraceTimeChanged())); + connect(navigator, SIGNAL(selectedTransactionsChanged()), this, + SLOT(selectedTransactionChanged())); this->traceplot = traceplot; this->navigator = navigator; currentTraceTimeChanged(); @@ -64,40 +67,35 @@ void DebugMessageTreeWidget::arrangeUiSettings() void DebugMessageTreeWidget::selectedTransactionChanged() { - if(navigator->hasSelectedTransactions()) - { + if (navigator->hasSelectedTransactions()) { Timespan span = navigator->getSpanCoveredBySelectedTransaction(); showDebugMessages(navigator->TraceFile().getDebugMessagesInTimespan(span)); - } - else - { - showDebugMessages(navigator->TraceFile().getDebugMessagesInTimespan(traceplot->GetCurrentTimespan())); + } else { + showDebugMessages(navigator->TraceFile().getDebugMessagesInTimespan( + traceplot->GetCurrentTimespan())); } } void DebugMessageTreeWidget::currentTraceTimeChanged() { - if(!navigator->hasSelectedTransactions()) - showDebugMessages(navigator->TraceFile().getDebugMessagesInTimespan(traceplot->GetCurrentTimespan())); + if (!navigator->hasSelectedTransactions()) + showDebugMessages(navigator->TraceFile().getDebugMessagesInTimespan( + traceplot->GetCurrentTimespan())); } -void DebugMessageTreeWidget::showDebugMessages(const vector& comments) +void DebugMessageTreeWidget::showDebugMessages(const vector &comments) { clear(); - if(comments.empty()) + if (comments.empty()) return; traceTime currentTime = -1; - for(Comment comment: comments) - { - if(currentTime != comment.Time()) - { + for (Comment comment : comments) { + if (currentTime != comment.Time()) { addTopLevelItem(new QTreeWidgetItem({prettyFormatTime(comment.Time()), formatDebugMessage(comment.Text())})); currentTime = comment.Time(); - } - else - { + } else { addTopLevelItem(new QTreeWidgetItem({"", formatDebugMessage(comment.Text())})); } } @@ -109,17 +107,16 @@ void DebugMessageTreeWidget::showDebugMessages(const vector& comments) QString DebugMessageTreeWidget::formatDebugMessage(const QString &message) { QString formattedMessage = message; - formattedMessage.replace(hexAdressMatcher,""); - formattedMessage.replace(timeAnnotationMatcher,""); - formattedMessage.replace("\t"," "); + formattedMessage.replace(hexAdressMatcher, ""); + formattedMessage.replace(timeAnnotationMatcher, ""); + formattedMessage.replace("\t", " "); return formattedMessage; } void DebugMessageTreeWidget::mousePressEvent(QMouseEvent *event) { - QTreeWidgetItem* itemUnderCursor = itemAt(event->pos()); - if(itemUnderCursor != NULL) - { + QTreeWidgetItem *itemUnderCursor = itemAt(event->pos()); + if (itemUnderCursor != NULL) { QToolTip::showText(this->mapToGlobal(event->pos()), itemUnderCursor->text(1)); } } diff --git a/DRAMSys/traceAnalyzer/presentation/debugmessagetreewidget.h b/DRAMSys/traceAnalyzer/presentation/debugmessagetreewidget.h index 6b06b958..c884aa8d 100644 --- a/DRAMSys/traceAnalyzer/presentation/debugmessagetreewidget.h +++ b/DRAMSys/traceAnalyzer/presentation/debugmessagetreewidget.h @@ -51,10 +51,12 @@ class DebugMessageTreeWidget : public QTreeWidget Q_OBJECT public: - DebugMessageTreeWidget(QWidget *parent = 0) : QTreeWidget(parent),isInitialized(false), timeAnnotationMatcher(QString("@[0-9]+ n?s")), hexAdressMatcher(QString("0x[0-9,a-f]+")) {} - void init(TraceNavigator* navigator, TracePlot* traceplot); + DebugMessageTreeWidget(QWidget *parent = 0) : QTreeWidget(parent), + isInitialized(false), timeAnnotationMatcher(QString("@[0-9]+ n?s")), + hexAdressMatcher(QString("0x[0-9,a-f]+")) {} + void init(TraceNavigator *navigator, TracePlot *traceplot); - void showDebugMessages(const std::vector& comments); + void showDebugMessages(const std::vector &comments); void arrangeUiSettings(); public Q_SLOTS: @@ -63,11 +65,11 @@ public Q_SLOTS: private: bool isInitialized; - TracePlot* traceplot; - TraceNavigator* navigator; + TracePlot *traceplot; + TraceNavigator *navigator; QRegularExpression timeAnnotationMatcher; QRegularExpression hexAdressMatcher; - QString formatDebugMessage(const QString& message); + QString formatDebugMessage(const QString &message); void mousePressEvent(QMouseEvent *event); }; diff --git a/DRAMSys/traceAnalyzer/presentation/pornotracescroller.cpp b/DRAMSys/traceAnalyzer/presentation/pornotracescroller.cpp index 78f6c367..45b46ec9 100644 --- a/DRAMSys/traceAnalyzer/presentation/pornotracescroller.cpp +++ b/DRAMSys/traceAnalyzer/presentation/pornotracescroller.cpp @@ -43,9 +43,10 @@ #include "util/engineeringScaleDraw.h" PornoTraceScroller::PornoTraceScroller(QWidget *parent): - QwtPlot(parent),isInitialized(false),drawingProperties(false, false, ColorGrouping::Transaction) + QwtPlot(parent), isInitialized(false), drawingProperties(false, false, + ColorGrouping::Transaction) { - setAxisScaleDraw(xBottom,new EngineeringScaleDraw); + setAxisScaleDraw(xBottom, new EngineeringScaleDraw); canvas()->setCursor(Qt::ArrowCursor); canvasClip = new QwtPlotZoneItem(); canvasClip->setZ(2); @@ -66,16 +67,19 @@ void PornoTraceScroller::init(TraceNavigator *navigator, TracePlot *tracePlot) getAndDrawComments(); this->tracePlot = tracePlot; - QObject::connect(tracePlot,SIGNAL(tracePlotZoomChanged()),this,SLOT(tracePlotZoomChanged())); + QObject::connect(tracePlot, SIGNAL(tracePlotZoomChanged()), this, + SLOT(tracePlotZoomChanged())); tracePlotZoomChanged(); - QObject::connect(tracePlot,SIGNAL(colorGroupingChanged(ColorGrouping)),this,SLOT(colorGroupingChanged(ColorGrouping))); + QObject::connect(tracePlot, SIGNAL(colorGroupingChanged(ColorGrouping)), this, + SLOT(colorGroupingChanged(ColorGrouping))); } void PornoTraceScroller::setUpTracePlotItem() { - TracePlotItem *tracePlotItem = new TracePlotItem(transactions,*navigator, drawingProperties); + TracePlotItem *tracePlotItem = new TracePlotItem(transactions, *navigator, + drawingProperties); tracePlotItem->setZ(1); tracePlotItem->attach(this); } @@ -100,22 +104,29 @@ void PornoTraceScroller::setUpAxis() void PornoTraceScroller::connectNavigatorQ_SIGNALS() { - QObject::connect(navigator,SIGNAL(currentTraceTimeChanged()), this, SLOT(currentTraceTimeChanged())); - QObject::connect(navigator,SIGNAL(commentsChanged()),this,SLOT(commentsChanged())); - QObject::connect(navigator,SIGNAL(selectedTransactionsChanged()),this,SLOT(selectedTransactionsChanged())); + QObject::connect(navigator, SIGNAL(currentTraceTimeChanged()), this, + SLOT(currentTraceTimeChanged())); + QObject::connect(navigator, SIGNAL(commentsChanged()), this, + SLOT(commentsChanged())); + QObject::connect(navigator, SIGNAL(selectedTransactionsChanged()), this, + SLOT(selectedTransactionsChanged())); } Timespan PornoTraceScroller::GetCurrentTimespan() { - traceTime deltaOnTracePlot = navigator->GeneralTraceInfo().span.End() - tracePlot->ZoomLevel(); - traceTime deltaOnPornoTraceScroller = navigator->GeneralTraceInfo().span.End() - zoomLevel; + traceTime deltaOnTracePlot = navigator->GeneralTraceInfo().span.End() - + tracePlot->ZoomLevel(); + traceTime deltaOnPornoTraceScroller = navigator->GeneralTraceInfo().span.End() - + zoomLevel; - traceTime newBegin = static_cast (tracePlot->GetCurrentTimespan().Begin() * (1.0*deltaOnPornoTraceScroller)/deltaOnTracePlot); + traceTime newBegin = static_cast + (tracePlot->GetCurrentTimespan().Begin() * (1.0 * deltaOnPornoTraceScroller) / + deltaOnTracePlot); Timespan span(newBegin, newBegin + zoomLevel); - if(span.Begin() < 0) + if (span.Begin() < 0) span.shift(-span.Begin()); - else if(span.End() > navigator->GeneralTraceInfo().span.End()) + else if (span.End() > navigator->GeneralTraceInfo().span.End()) span.shift(navigator->GeneralTraceInfo().span.End() - span.End()); return span; } @@ -123,13 +134,12 @@ Timespan PornoTraceScroller::GetCurrentTimespan() void PornoTraceScroller::getAndDrawComments() { - for(const auto &pair: navigator->getComments()) - { + for (const auto &pair : navigator->getComments()) { const Comment &comment = pair.second; QwtPlotMarker *maker = new QwtPlotMarker(); maker->setXValue(static_cast(comment.Time())); maker->setLineStyle(QwtPlotMarker::LineStyle::VLine); - maker->setLinePen(QColor(Qt::blue),2); + maker->setLinePen(QColor(Qt::blue), 2); maker->attach(this); } } @@ -157,7 +167,7 @@ void PornoTraceScroller::currentTraceTimeChanged() canvasClip->setInterval(spanOnTracePlot.Begin(), spanOnTracePlot.End()); Timespan span = GetCurrentTimespan(); transactions = navigator->TraceFile().getTransactionsInTimespan(span); - setAxisScale(xBottom,span.Begin(),span.End()); + setAxisScale(xBottom, span.Begin(), span.End()); replot(); } @@ -170,98 +180,84 @@ void PornoTraceScroller::commentsChanged() void PornoTraceScroller::tracePlotZoomChanged() { - zoomLevel = tracePlot->ZoomLevel()*tracePlotEnlargementFactor; - if(zoomLevel > navigator->GeneralTraceInfo().span.timeCovered()) + zoomLevel = tracePlot->ZoomLevel() * tracePlotEnlargementFactor; + if (zoomLevel > navigator->GeneralTraceInfo().span.timeCovered()) zoomLevel = navigator->GeneralTraceInfo().span.timeCovered(); } bool PornoTraceScroller::eventFilter( QObject *object, QEvent *event ) { - if(object == canvas()) - { + if (object == canvas()) { static bool clipDragged = false; static bool leftMousePressed = false; static int mouseDownX = 0; static traceTime mouseDownTracePlotTime = 0; - switch(event->type()) - { - case QEvent::Wheel : - { + switch (event->type()) { + case QEvent::Wheel : { QWheelEvent *wheelEvent = static_cast(event); traceTime offset; int speed = 4; - (wheelEvent->delta() > 0) ? offset = -zoomLevel * speed : offset = zoomLevel * speed; + (wheelEvent->delta() > 0) ? offset = -zoomLevel * speed : offset = zoomLevel * + speed; navigator->navigateToTime(navigator->CurrentTraceTime() + offset); return true; } - case QEvent::MouseButtonDblClick: - { + case QEvent::MouseButtonDblClick: { QMouseEvent *mouseEvent = static_cast(event); traceTime time = invTransform(xBottom, mouseEvent->x()); navigator->navigateToTime(time); return true; } - case QEvent::MouseButtonPress: - { + case QEvent::MouseButtonPress: { QMouseEvent *mouseEvent = static_cast(event); - if(mouseEvent->button() == Qt::LeftButton) - { + if (mouseEvent->button() == Qt::LeftButton) { canvas()->setCursor(Qt::ClosedHandCursor); leftMousePressed = true; mouseDownTracePlotTime = tracePlot->GetCurrentTimespan().Middle(); mouseDownX = mouseEvent->x(); - if(tracePlot->GetCurrentTimespan().contains(invTransform(xBottom, mouseEvent->x()))) + if (tracePlot->GetCurrentTimespan().contains(invTransform(xBottom, + mouseEvent->x()))) clipDragged = true; else clipDragged = false; return true; - } - else if(mouseEvent->button() == Qt::RightButton) - { - navigator->navigateToTime(static_cast(invTransform(xBottom, mouseEvent->x()))); + } else if (mouseEvent->button() == Qt::RightButton) { + navigator->navigateToTime(static_cast(invTransform(xBottom, + mouseEvent->x()))); return true; } } - case QEvent::MouseButtonRelease: - { + case QEvent::MouseButtonRelease: { QMouseEvent *mouseEvent = static_cast(event); - if(mouseEvent->button() == Qt::LeftButton) - { + if (mouseEvent->button() == Qt::LeftButton) { clipDragged = false; leftMousePressed = false; canvas()->setCursor(Qt::ArrowCursor); return true; } } - case QEvent::MouseMove: - { + case QEvent::MouseMove: { QMouseEvent *mouseEvent = static_cast(event); - if(leftMousePressed) - { - if(clipDragged) - { - double clipWidth = transform(xBottom, tracePlot->ZoomLevel()) - transform(xBottom, 0); + if (leftMousePressed) { + if (clipDragged) { + double clipWidth = transform(xBottom, + tracePlot->ZoomLevel()) - transform(xBottom, 0); - if(mouseEvent->x() < clipWidth/2) - { + if (mouseEvent->x() < clipWidth / 2) { navigator->navigateToTime(0); - } - else if(mouseEvent->x() > canvas()->width() - clipWidth/2) - { + } else if (mouseEvent->x() > canvas()->width() - clipWidth / 2) { navigator->navigateToTime(navigator->GeneralTraceInfo().span.End()); - } - else - { - traceTime time = static_cast((mouseEvent->x() - clipWidth/2) / - (canvas()->width() - clipWidth) * (navigator->GeneralTraceInfo().span.End() - tracePlot->ZoomLevel())); + } else { + traceTime time = static_cast((mouseEvent->x() - clipWidth / 2) / + (canvas()->width() - clipWidth) * (navigator->GeneralTraceInfo().span.End() - + tracePlot->ZoomLevel())); navigator->navigateToTime(time); } - } - else - { - traceTime deltaTime = invTransform(xBottom, mouseDownX) - invTransform(xBottom, mouseEvent->x()); + } else { + traceTime deltaTime = invTransform(xBottom, mouseDownX) - invTransform(xBottom, + mouseEvent->x()); navigator->navigateToTime(mouseDownTracePlotTime + deltaTime); } return true; diff --git a/DRAMSys/traceAnalyzer/presentation/pornotracescroller.h b/DRAMSys/traceAnalyzer/presentation/pornotracescroller.h index 18437337..98f5a97b 100644 --- a/DRAMSys/traceAnalyzer/presentation/pornotracescroller.h +++ b/DRAMSys/traceAnalyzer/presentation/pornotracescroller.h @@ -47,12 +47,12 @@ class PornoTraceScroller : public QwtPlot { -Q_OBJECT + Q_OBJECT private: std::vector> transactions; bool isInitialized; - TraceNavigator* navigator; - TracePlot* tracePlot; + TraceNavigator *navigator; + TracePlot *tracePlot; constexpr static int tracePlotEnlargementFactor = 4; void setUpTracePlotItem(); void setUpDrawingProperties(); @@ -68,7 +68,7 @@ private: public: PornoTraceScroller(QWidget *parent = NULL); - void init(TraceNavigator* navigator, TracePlot* tracePlot); + void init(TraceNavigator *navigator, TracePlot *tracePlot); Timespan GetCurrentTimespan(); public Q_SLOTS: diff --git a/DRAMSys/traceAnalyzer/presentation/selectedtransactiontreewidget.cpp b/DRAMSys/traceAnalyzer/presentation/selectedtransactiontreewidget.cpp index 77333f07..28d16ac7 100644 --- a/DRAMSys/traceAnalyzer/presentation/selectedtransactiontreewidget.cpp +++ b/DRAMSys/traceAnalyzer/presentation/selectedtransactiontreewidget.cpp @@ -42,8 +42,7 @@ void SelectedTransactionTreeWidget::selectedTransactionsChanged() { this->clear(); - for(const auto& transaction : navigator->SelectedTransactions()) - { + for (const auto &transaction : navigator->SelectedTransactions()) { AppendTransaction(transaction); } expandAll(); @@ -53,5 +52,6 @@ void SelectedTransactionTreeWidget::selectedTransactionsChanged() void SelectedTransactionTreeWidget::init(TraceNavigator *navigator) { TransactionTreeWidget::init(navigator); - QObject::connect(navigator, SIGNAL(selectedTransactionsChanged()), this, SLOT(selectedTransactionsChanged())); + QObject::connect(navigator, SIGNAL(selectedTransactionsChanged()), this, + SLOT(selectedTransactionsChanged())); } diff --git a/DRAMSys/traceAnalyzer/presentation/selectedtransactiontreewidget.h b/DRAMSys/traceAnalyzer/presentation/selectedtransactiontreewidget.h index 7b485a4e..cfa4f229 100644 --- a/DRAMSys/traceAnalyzer/presentation/selectedtransactiontreewidget.h +++ b/DRAMSys/traceAnalyzer/presentation/selectedtransactiontreewidget.h @@ -45,8 +45,9 @@ class SelectedTransactionTreeWidget : public TransactionTreeWidget bool isInitialized; public: - SelectedTransactionTreeWidget(QWidget *parent = 0) : TransactionTreeWidget(parent), isInitialized(false){} - virtual void init(TraceNavigator* navigator); + SelectedTransactionTreeWidget(QWidget *parent = 0) : TransactionTreeWidget( + parent), isInitialized(false) {} + virtual void init(TraceNavigator *navigator); public Q_SLOTS: void selectedTransactionsChanged(); diff --git a/DRAMSys/traceAnalyzer/presentation/tracePlotMouseLabel.cpp b/DRAMSys/traceAnalyzer/presentation/tracePlotMouseLabel.cpp index 2d501ead..7210de34 100644 --- a/DRAMSys/traceAnalyzer/presentation/tracePlotMouseLabel.cpp +++ b/DRAMSys/traceAnalyzer/presentation/tracePlotMouseLabel.cpp @@ -45,18 +45,16 @@ void TracePlotMouseLabel::setMode(MouseLabelMode mode) QwtText TracePlotMouseLabel::trackerText(const QPoint &point) const { - if(mode == MouseLabelMode::AbsoluteTime) - { - traceTime mouseTime = static_cast(traceplot->invTransform(traceplot->xBottom, point.x())); - return QwtText(prettyFormatTime(alignToClk(mouseTime,clkPeriod)) + "(" + formatInClks(mouseTime,clkPeriod) + ")"); - } - else if(mode == MouseLabelMode::Timedifference) - { + if (mode == MouseLabelMode::AbsoluteTime) { + traceTime mouseTime = static_cast(traceplot->invTransform( + traceplot->xBottom, point.x())); + return QwtText(prettyFormatTime(alignToClk(mouseTime, + clkPeriod)) + "(" + formatInClks(mouseTime, clkPeriod) + ")"); + } else if (mode == MouseLabelMode::Timedifference) { traceTime mouseTime = timeDifferenceSpan.timeCovered(); - return QwtText(prettyFormatTime(alignToClk(mouseTime,clkPeriod)) + "(" + formatInClks(mouseTime,clkPeriod) + ")"); - } - else - { + return QwtText(prettyFormatTime(alignToClk(mouseTime, + clkPeriod)) + "(" + formatInClks(mouseTime, clkPeriod) + ")"); + } else { Q_ASSERT(false); } return QwtText(QString("")); diff --git a/DRAMSys/traceAnalyzer/presentation/tracePlotMouseLabel.h b/DRAMSys/traceAnalyzer/presentation/tracePlotMouseLabel.h index 3164279c..20d73354 100644 --- a/DRAMSys/traceAnalyzer/presentation/tracePlotMouseLabel.h +++ b/DRAMSys/traceAnalyzer/presentation/tracePlotMouseLabel.h @@ -41,15 +41,17 @@ #include #include "traceplot.h" -enum class MouseLabelMode{AbsoluteTime, Timedifference}; +enum class MouseLabelMode {AbsoluteTime, Timedifference}; class TracePlotMouseLabel : public QwtPlotPicker { public: - TracePlotMouseLabel(TracePlot* traceplot, unsigned int clkPeriod, Timespan& timeDifferenceSpan): - QwtPlotPicker(QwtPlot::xBottom, QwtPlot::yLeft,QwtPlotPicker::VLineRubberBand, + TracePlotMouseLabel(TracePlot *traceplot, unsigned int clkPeriod, + Timespan &timeDifferenceSpan): + QwtPlotPicker(QwtPlot::xBottom, QwtPlot::yLeft, QwtPlotPicker::VLineRubberBand, QwtPicker::AlwaysOn, traceplot->canvas()), - mode(MouseLabelMode::AbsoluteTime),traceplot(traceplot),clkPeriod(clkPeriod), timeDifferenceSpan(timeDifferenceSpan){} + mode(MouseLabelMode::AbsoluteTime), traceplot(traceplot), clkPeriod(clkPeriod), + timeDifferenceSpan(timeDifferenceSpan) {} void setMode(MouseLabelMode mode); protected: @@ -57,9 +59,9 @@ protected: private: MouseLabelMode mode; - TracePlot* traceplot; + TracePlot *traceplot; unsigned int clkPeriod; - Timespan& timeDifferenceSpan; + Timespan &timeDifferenceSpan; }; #endif // TRACEPLOTPICKER_H diff --git a/DRAMSys/traceAnalyzer/presentation/tracedrawing.cpp b/DRAMSys/traceAnalyzer/presentation/tracedrawing.cpp index c69ce69f..eeb19a91 100644 --- a/DRAMSys/traceAnalyzer/presentation/tracedrawing.cpp +++ b/DRAMSys/traceAnalyzer/presentation/tracedrawing.cpp @@ -49,9 +49,9 @@ void drawVerticalLine(QPainter *painter, int xPos, const QRectF &canvasRect) - QPoint P1(xPos,static_cast(canvasRect.top())); - QPoint P2(xPos,static_cast(canvasRect.bottom())); - painter->drawLine(QLine(P1,P2)); + QPoint P1(xPos, static_cast(canvasRect.top())); + QPoint P2(xPos, static_cast(canvasRect.bottom())); + painter->drawLine(QLine(P1, P2)); } void drawDoubleArrow(QPainter *painter, int xFrom, int xTo, int y) @@ -66,55 +66,55 @@ void drawDoubleArrow(QPainter *painter, int xFrom, int xTo, int y) // P2 P4 */ - QPoint from(xFrom,y); - QPoint to(xTo,y); - QPoint P1(xFrom+10,y-5); - QPoint P2(xFrom+10,y+5); - QPoint P3(xTo-10,y-5); - QPoint P4(xTo-10,y+5); + QPoint from(xFrom, y); + QPoint to(xTo, y); + QPoint P1(xFrom + 10, y - 5); + QPoint P2(xFrom + 10, y + 5); + QPoint P3(xTo - 10, y - 5); + QPoint P4(xTo - 10, y + 5); - painter->drawLine(from,to); - painter->drawLine(P1,from); - painter->drawLine(P2,from); - painter->drawLine(P3,to); - painter->drawLine(P4,to); + painter->drawLine(from, to); + painter->drawLine(P1, from); + painter->drawLine(P2, from); + painter->drawLine(P3, to); + painter->drawLine(P4, to); } -void drawDoubleArrow(QPainter *painter, int xFrom, int xTo, int y, const QString &text, const QColor &textColor) +void drawDoubleArrow(QPainter *painter, int xFrom, int xTo, int y, + const QString &text, const QColor &textColor) { drawDoubleArrow(painter, xFrom, xTo, y); - drawText(painter, text, QPoint((xTo + xFrom) / 2, y), TextPositioning::topCenter, textColor); + drawText(painter, text, QPoint((xTo + xFrom) / 2, y), + TextPositioning::topCenter, textColor); } -void drawHexagon(QPainter *painter, const QPoint& from, const QPoint& to, double height) +void drawHexagon(QPainter *painter, const QPoint &from, const QPoint &to, + double height) { - // {text} - // P1------------------------P2 - // From / \ To - // \ / - // P4-------------------------P3 +// {text} +// P1------------------------P2 +// From / \ To +// \ / +// P4-------------------------P3 int offset = 10; - if( (to.x() - from.x()) <= 20) - { + if ( (to.x() - from.x()) <= 20) { offset = 5; } - if( (to.x() - from.x()) <= 10) - { + if ( (to.x() - from.x()) <= 10) { offset = 2; } - if( (to.x() - from.x()) <= 4) - { + if ( (to.x() - from.x()) <= 4) { offset = 0; } - QPointF P1(from.x()+offset , from.y()-height/2); - QPointF P2(to.x() -offset , to.y() -height/2); - QPointF P3(to.x() -offset , to.y() +height/2); - QPointF P4(from.x()+offset , from.y()+height/2); + QPointF P1(from.x() + offset , from.y() - height / 2); + QPointF P2(to.x() - offset , to.y() - height / 2); + QPointF P3(to.x() - offset , to.y() + height / 2); + QPointF P4(from.x() + offset , from.y() + height / 2); QPolygonF polygon; polygon << from @@ -127,7 +127,8 @@ void drawHexagon(QPainter *painter, const QPoint& from, const QPoint& to, double painter->drawPolygon(polygon); } -void drawText(QPainter *painter, const QString &text, const QPoint &position, const TextPositioning &positioning, const QColor &textColor) +void drawText(QPainter *painter, const QString &text, const QPoint &position, + const TextPositioning &positioning, const QColor &textColor) { //*--------------* //| | | @@ -142,8 +143,7 @@ void drawText(QPainter *painter, const QString &text, const QPoint &position, co QRect rect(position - offset, position + offset); int flags; - switch(positioning) - { + switch (positioning) { case TextPositioning::topRight: flags = Qt::AlignRight | Qt::AlignTop; break; @@ -162,7 +162,8 @@ void drawText(QPainter *painter, const QString &text, const QPoint &position, co case TextPositioning::centerCenter: flags = Qt::AlignHCenter | Qt::AlignCenter; break; - case TextPositioning::topLeft:default: + case TextPositioning::topLeft: + default: flags = Qt::AlignLeft | Qt::AlignTop; break; } diff --git a/DRAMSys/traceAnalyzer/presentation/tracedrawing.h b/DRAMSys/traceAnalyzer/presentation/tracedrawing.h index 4337c0cb..0deef07e 100644 --- a/DRAMSys/traceAnalyzer/presentation/tracedrawing.h +++ b/DRAMSys/traceAnalyzer/presentation/tracedrawing.h @@ -43,12 +43,16 @@ #include #include -enum class TextPositioning{topRight, topLeft, bottomRight, bottomLeft, topCenter, bottomCenter, centerCenter}; +enum class TextPositioning {topRight, topLeft, bottomRight, bottomLeft, topCenter, bottomCenter, centerCenter}; void drawVerticalLine(QPainter *painter, int xPos, const QRectF &canvasRect); void drawDoubleArrow(QPainter *painter, int xFrom, int xTo, int y); -void drawDoubleArrow(QPainter *painter, int xFrom, int xTo, int y, const QString &text, const QColor &textColor = QColor(Qt::black)); -void drawHexagon(QPainter *painter, const QPoint& from, const QPoint& to, double height); -void drawText(QPainter *painter, const QString &text, const QPoint &position, const TextPositioning &positioning, const QColor &textColor = QColor(Qt::black)); +void drawDoubleArrow(QPainter *painter, int xFrom, int xTo, int y, + const QString &text, const QColor &textColor = QColor(Qt::black)); +void drawHexagon(QPainter *painter, const QPoint &from, const QPoint &to, + double height); +void drawText(QPainter *painter, const QString &text, const QPoint &position, + const TextPositioning &positioning, + const QColor &textColor = QColor(Qt::black)); #endif // TRACEDRAWING_H diff --git a/DRAMSys/traceAnalyzer/presentation/tracedrawingproperties.h b/DRAMSys/traceAnalyzer/presentation/tracedrawingproperties.h index 73e5cd8c..21351fc3 100644 --- a/DRAMSys/traceAnalyzer/presentation/tracedrawingproperties.h +++ b/DRAMSys/traceAnalyzer/presentation/tracedrawingproperties.h @@ -45,8 +45,7 @@ enum class ColorGrouping {PhaseType, Transaction, Thread}; -struct TraceDrawingProperties -{ +struct TraceDrawingProperties { bool drawText; bool drawBorder; ColorGrouping colorGrouping; @@ -56,16 +55,23 @@ struct TraceDrawingProperties int yValDataBus; unsigned int numberOfBanks; - TraceDrawingProperties() : drawText(true), drawBorder(true), colorGrouping(ColorGrouping::Transaction){} - TraceDrawingProperties(bool drawText, bool drawBorder, ColorGrouping colorGrouping) : drawText(drawText), drawBorder(drawBorder), colorGrouping(colorGrouping){} - TraceDrawingProperties(bool drawText, bool drawBorder, ColorGrouping colorGrouping, int yValResponse,int yValRequest, int yValCommandBus,int yValDataBus, unsigned int numberOfBanks) : - drawText(drawText), drawBorder(drawBorder), colorGrouping(colorGrouping), yValResponse(yValResponse), yValRequest(yValRequest), yValCommandBus(yValCommandBus),yValDataBus(yValDataBus),numberOfBanks(numberOfBanks){} + TraceDrawingProperties() : drawText(true), drawBorder(true), + colorGrouping(ColorGrouping::Transaction) {} + TraceDrawingProperties(bool drawText, bool drawBorder, + ColorGrouping colorGrouping) : drawText(drawText), drawBorder(drawBorder), + colorGrouping(colorGrouping) {} + TraceDrawingProperties(bool drawText, bool drawBorder, + ColorGrouping colorGrouping, int yValResponse, int yValRequest, + int yValCommandBus, int yValDataBus, unsigned int numberOfBanks) : + drawText(drawText), drawBorder(drawBorder), colorGrouping(colorGrouping), + yValResponse(yValResponse), yValRequest(yValRequest), + yValCommandBus(yValCommandBus), yValDataBus(yValDataBus), + numberOfBanks(numberOfBanks) {} - QHash getLabels() const + QHash getLabels() const { - QHash result; - for(unsigned int i=0; i result; + for (unsigned int i = 0; i < numberOfBanks; i++) { result[i] = QString("Bank ") + QString::number(i); } diff --git a/DRAMSys/traceAnalyzer/presentation/tracemetrictreewidget.cpp b/DRAMSys/traceAnalyzer/presentation/tracemetrictreewidget.cpp index d7960d14..90cfa26f 100644 --- a/DRAMSys/traceAnalyzer/presentation/tracemetrictreewidget.cpp +++ b/DRAMSys/traceAnalyzer/presentation/tracemetrictreewidget.cpp @@ -38,34 +38,33 @@ #include "tracemetrictreewidget.h" -TraceMetricTreeWidget::TraceMetricTreeWidget(QWidget *parent) : QTreeWidget(parent) +TraceMetricTreeWidget::TraceMetricTreeWidget(QWidget *parent) : QTreeWidget( + parent) { setHeaderHidden(true); } -void TraceMetricTreeWidget::addTraceMetricResults(const TraceCalculatedMetrics& result) +void TraceMetricTreeWidget::addTraceMetricResults(const TraceCalculatedMetrics + &result) { - QTreeWidgetItem* top = new QTreeWidgetItem({result.getTraceName()}); + QTreeWidgetItem *top = new QTreeWidgetItem({result.getTraceName()}); addTopLevelItem(top); - if(result.getCalculatedMetrics().empty()) - { - new QTreeWidgetItem(top,{QString("Number of threads: 1")}); - } - else - { - for(CalculatedMetric calculatedMetric : result.getCalculatedMetrics()) - { - new QTreeWidgetItem(top,{calculatedMetric.getName() + QString(": ") + QString::number(calculatedMetric.getValue())}); + if (result.getCalculatedMetrics().empty()) { + new QTreeWidgetItem(top, {QString("Number of threads: 1")}); + } else { + for (CalculatedMetric calculatedMetric : result.getCalculatedMetrics()) { + new QTreeWidgetItem(top, {calculatedMetric.getName() + QString(": ") + QString::number(calculatedMetric.getValue())}); } } } -void TraceMetricTreeWidget::addTracePlotResults(QString traceName, QString outputFiles) +void TraceMetricTreeWidget::addTracePlotResults(QString traceName, + QString outputFiles) { - QTreeWidgetItem* top = new QTreeWidgetItem({traceName}); + QTreeWidgetItem *top = new QTreeWidgetItem({traceName}); addTopLevelItem(top); - new QTreeWidgetItem(top,{outputFiles}); + new QTreeWidgetItem(top, {outputFiles}); } diff --git a/DRAMSys/traceAnalyzer/presentation/tracemetrictreewidget.h b/DRAMSys/traceAnalyzer/presentation/tracemetrictreewidget.h index 859c5ef9..4eace2fc 100644 --- a/DRAMSys/traceAnalyzer/presentation/tracemetrictreewidget.h +++ b/DRAMSys/traceAnalyzer/presentation/tracemetrictreewidget.h @@ -46,9 +46,9 @@ class TraceMetricTreeWidget : public QTreeWidget { Q_OBJECT public: - TraceMetricTreeWidget(QWidget *parent = 0); - void addTraceMetricResults(const TraceCalculatedMetrics& result); - void addTracePlotResults(QString traceName, QString outputFiles); + TraceMetricTreeWidget(QWidget *parent = 0); + void addTraceMetricResults(const TraceCalculatedMetrics &result); + void addTracePlotResults(QString traceName, QString outputFiles); }; diff --git a/DRAMSys/traceAnalyzer/presentation/tracenavigator.cpp b/DRAMSys/traceAnalyzer/presentation/tracenavigator.cpp index 5f8d57c7..4d2a15b2 100644 --- a/DRAMSys/traceAnalyzer/presentation/tracenavigator.cpp +++ b/DRAMSys/traceAnalyzer/presentation/tracenavigator.cpp @@ -40,8 +40,8 @@ using namespace std; -TraceNavigator::TraceNavigator(QString path, QObject * parent) - : QObject(parent),traceFile(path,true), changesToCommitExist(false) +TraceNavigator::TraceNavigator(QString path, QObject *parent) + : QObject(parent), traceFile(path, true), changesToCommitExist(false) { getCommentsFromDB(); } @@ -57,12 +57,11 @@ TraceNavigator::~TraceNavigator() void TraceNavigator::navigateToTime(traceTime time) { - if(time < 0) + if (time < 0) time = 0; - else if(time>traceFile.getGeneralInfo().span.End()) + else if (time > traceFile.getGeneralInfo().span.End()) time = traceFile.getGeneralInfo().span.End(); - else - { + else { currentTraceTime = time; Q_EMIT currentTraceTimeChanged(); } @@ -87,8 +86,7 @@ void TraceNavigator::insertComment(const Comment &comment) void TraceNavigator::removeCommentAtTime(traceTime time) { auto found = comments.find(time); - if(found != comments.end()) - { + if (found != comments.end()) { comments.erase(found); changesToCommitExist = true; Q_EMIT commentsChanged(); @@ -104,8 +102,7 @@ void TraceNavigator::removeCommentAtTime(traceTime time) void TraceNavigator::commitChangesToDB() { vector commentsToInsert; - for(const auto& pair: comments) - { + for (const auto &pair : comments) { commentsToInsert.push_back(pair.second); } @@ -115,9 +112,8 @@ void TraceNavigator::commitChangesToDB() void TraceNavigator::getCommentsFromDB() { - for(const Comment& comment: traceFile.getComments()) - { - comments.emplace(comment.Time(),comment); + for (const Comment &comment : traceFile.getComments()) { + comments.emplace(comment.Time(), comment); } } @@ -133,26 +129,27 @@ void TraceNavigator::refreshData() * */ -void TraceNavigator::addSelectedTransactions(const vector>& transactions) +void TraceNavigator::addSelectedTransactions(const + vector> &transactions) { - for(const auto transaction : transactions) - { + for (const auto transaction : transactions) { selectedTransactions.push_back(transaction); } Q_EMIT selectedTransactionsChanged(); } -void TraceNavigator::addSelectedTransaction(const shared_ptr &transaction) +void TraceNavigator::addSelectedTransaction(const shared_ptr + &transaction) { - selectedTransactions.push_back(transaction); - Q_EMIT selectedTransactionsChanged(); + selectedTransactions.push_back(transaction); + Q_EMIT selectedTransactionsChanged(); } void TraceNavigator::addSelectedTransaction(ID id) { - shared_ptr transaction = TraceFile().getTransactionByID(id); - selectedTransactions.push_back(transaction); - Q_EMIT selectedTransactionsChanged(); + shared_ptr transaction = TraceFile().getTransactionByID(id); + selectedTransactions.push_back(transaction); + Q_EMIT selectedTransactionsChanged(); } void TraceNavigator::selectTransaction(ID id) @@ -162,14 +159,17 @@ void TraceNavigator::selectTransaction(ID id) navigateToTransaction(id); } -void TraceNavigator::selectTransaction(const shared_ptr &transaction) +void TraceNavigator::selectTransaction(const shared_ptr + &transaction) { selectTransaction(transaction->Id()); } void TraceNavigator::selectNextTransaction() { - if(selectedTransactions.empty() || selectedTransactions.front()->Id() == traceFile.getGeneralInfo().numberOfTransactions) + if (selectedTransactions.empty() + || selectedTransactions.front()->Id() == + traceFile.getGeneralInfo().numberOfTransactions) selectFirstTransaction(); else selectTransaction(selectedTransactions.front()->Id() + 1); @@ -177,7 +177,7 @@ void TraceNavigator::selectNextTransaction() void TraceNavigator::selectPreviousTransaction() { - if(selectedTransactions.empty() || selectedTransactions.front()->Id() == 1) + if (selectedTransactions.empty() || selectedTransactions.front()->Id() == 1) selectLastTransaction(); else selectTransaction(selectedTransactions.front()->Id() - 1); @@ -198,52 +198,54 @@ void TraceNavigator::selectNextRefresh() { shared_ptr nextRefresh; - if(!SelectedTransactions().empty()) + if (!SelectedTransactions().empty()) nextRefresh = traceFile.getNextRefresh(SelectedTransactions().front()->Id()); else nextRefresh = traceFile.getNextRefresh(0); - if(nextRefresh) - selectTransaction(nextRefresh); + if (nextRefresh) + selectTransaction(nextRefresh); } void TraceNavigator::selectNextActivate() { shared_ptr nextActivate; - if(!SelectedTransactions().empty()) + if (!SelectedTransactions().empty()) nextActivate = traceFile.getNextActivate(SelectedTransactions().front()->Id()); else nextActivate = traceFile.getNextActivate(0); - if(nextActivate) - selectTransaction(nextActivate); + if (nextActivate) + selectTransaction(nextActivate); } void TraceNavigator::selectNextPrecharge() { shared_ptr nextPrecharge; - if(!SelectedTransactions().empty()) - nextPrecharge = traceFile.getNextPrecharge(SelectedTransactions().front()->Id()); + if (!SelectedTransactions().empty()) + nextPrecharge = traceFile.getNextPrecharge( + SelectedTransactions().front()->Id()); else nextPrecharge = traceFile.getNextPrecharge(0); - if(nextPrecharge) - selectTransaction(nextPrecharge); + if (nextPrecharge) + selectTransaction(nextPrecharge); } -bool TraceNavigator::transactionIsSelected(const shared_ptr &transaction) const +bool TraceNavigator::transactionIsSelected(const shared_ptr + &transaction) const { return transactionIsSelected(transaction->Id()); } bool TraceNavigator::transactionIsSelected(ID id) const { - for (const auto& transaction : selectedTransactions) { - if(transaction->Id() == id) + for (const auto &transaction : selectedTransactions) { + if (transaction->Id() == id) return true; } return false; @@ -251,8 +253,7 @@ bool TraceNavigator::transactionIsSelected(ID id) const void TraceNavigator::clearSelectedTransactions() { - if(hasSelectedTransactions()) - { + if (hasSelectedTransactions()) { selectedTransactions.clear(); Q_EMIT selectedTransactionsChanged(); } @@ -265,16 +266,16 @@ bool TraceNavigator::hasSelectedTransactions() Timespan TraceNavigator::getSpanCoveredBySelectedTransaction() { - if(!hasSelectedTransactions()) - return Timespan(0,0); + if (!hasSelectedTransactions()) + return Timespan(0, 0); traceTime begin = SelectedTransactions().at(0)->Span().Begin(); traceTime end = SelectedTransactions().at(0)->Span().End(); - for (const auto& transaction : selectedTransactions) { - if(transaction->Span().End() > end) + for (const auto &transaction : selectedTransactions) { + if (transaction->Span().End() > end) end = transaction->Span().End(); } - return Timespan(begin,end); + return Timespan(begin, end); } diff --git a/DRAMSys/traceAnalyzer/presentation/tracenavigator.h b/DRAMSys/traceAnalyzer/presentation/tracenavigator.h index 4839202f..a31591d7 100644 --- a/DRAMSys/traceAnalyzer/presentation/tracenavigator.h +++ b/DRAMSys/traceAnalyzer/presentation/tracenavigator.h @@ -56,12 +56,21 @@ class TraceNavigator : public QObject using CommentMap = std::map; public: - TraceNavigator(QString path, QObject * parent = 0); + TraceNavigator(QString path, QObject *parent = 0); ~TraceNavigator(); - traceTime CurrentTraceTime() const{return currentTraceTime;} - TraceDB& TraceFile(){return traceFile;} - const GeneralInfo& GeneralTraceInfo() {return traceFile.getGeneralInfo();} + traceTime CurrentTraceTime() const + { + return currentTraceTime; + } + TraceDB &TraceFile() + { + return traceFile; + } + const GeneralInfo &GeneralTraceInfo() + { + return traceFile.getGeneralInfo(); + } void navigateToTime(traceTime time); void navigateToTransaction(ID id); @@ -79,8 +88,12 @@ public: void selectNextActivate(); void selectNextPrecharge(); - void addSelectedTransactions(const std::vector>& transactions); - const std::vector>& SelectedTransactions(){return selectedTransactions;} + void addSelectedTransactions(const std::vector> + &transactions); + const std::vector> &SelectedTransactions() + { + return selectedTransactions; + } void addSelectedTransaction(const std::shared_ptr &Transaction); void addSelectedTransaction(ID id); void clearSelectedTransactions(); @@ -88,10 +101,14 @@ public: Timespan getSpanCoveredBySelectedTransaction(); bool transactionIsSelected(ID id) const; - bool transactionIsSelected(const std::shared_ptr &Transaction) const; + bool transactionIsSelected(const std::shared_ptr &Transaction) + const; - void insertComment(const Comment& comment); - const CommentMap& getComments(){return comments;} + void insertComment(const Comment &comment); + const CommentMap &getComments() + { + return comments; + } void removeCommentAtTime(traceTime time); void commitChangesToDB(); diff --git a/DRAMSys/traceAnalyzer/presentation/traceplot.cpp b/DRAMSys/traceAnalyzer/presentation/traceplot.cpp index b1110541..f2020e7c 100644 --- a/DRAMSys/traceAnalyzer/presentation/traceplot.cpp +++ b/DRAMSys/traceAnalyzer/presentation/traceplot.cpp @@ -61,7 +61,7 @@ using namespace std; TracePlot::TracePlot(QWidget *parent): - QwtPlot(parent),isInitialized(false) + QwtPlot(parent), isInitialized(false) { canvas()->setCursor(Qt::ArrowCursor); setUpActions(); @@ -69,56 +69,67 @@ TracePlot::TracePlot(QWidget *parent): void TracePlot::setUpActions() { - insertComment = new QAction("Insert comment",this); - QObject::connect(insertComment, SIGNAL(triggered()), this, SLOT(on_insertComment())); + insertComment = new QAction("Insert comment", this); + QObject::connect(insertComment, SIGNAL(triggered()), this, + SLOT(on_insertComment())); - goToTime = new QAction("Go to time",this); + goToTime = new QAction("Go to time", this); QObject::connect(goToTime, SIGNAL(triggered()), this, SLOT(on_goToTime())); goToTransaction = new QAction("Go to transaction", this); - QObject::connect(goToTransaction, SIGNAL(triggered()), this, SLOT(on_goToTransaction())); + QObject::connect(goToTransaction, SIGNAL(triggered()), this, + SLOT(on_goToTransaction())); - deselectAll = new QAction("Deselect all",this); - QObject::connect(deselectAll, SIGNAL(triggered()), this, SLOT(on_deselectAll())); + deselectAll = new QAction("Deselect all", this); + QObject::connect(deselectAll, SIGNAL(triggered()), this, + SLOT(on_deselectAll())); goToPhase = new QAction("Go to phase", this); QObject::connect(goToPhase, SIGNAL(triggered()), this, SLOT(on_goToPhase())); - showQueryEditor = new QAction("Execute query",this); + showQueryEditor = new QAction("Execute query", this); showQueryEditor->setShortcut(QKeySequence("ctrl+e")); addAction(showQueryEditor); - QObject::connect(showQueryEditor,SIGNAL(triggered()),this,SLOT(on_executeQuery())); + QObject::connect(showQueryEditor, SIGNAL(triggered()), this, + SLOT(on_executeQuery())); - selectNextRefresh = new QAction("Select next refresh",this); + selectNextRefresh = new QAction("Select next refresh", this); selectNextRefresh->setShortcut(QKeySequence("alt+r")); addAction(selectNextRefresh); - QObject::connect(selectNextRefresh, SIGNAL(triggered()), this, SLOT(on_selectNextRefresh())); + QObject::connect(selectNextRefresh, SIGNAL(triggered()), this, + SLOT(on_selectNextRefresh())); - selectNextActivate = new QAction("Select next activate",this); + selectNextActivate = new QAction("Select next activate", this); selectNextActivate->setShortcut(QKeySequence("alt+a")); addAction(selectNextActivate); - QObject::connect(selectNextActivate, SIGNAL(triggered()), this, SLOT(on_selectNextActivate())); + QObject::connect(selectNextActivate, SIGNAL(triggered()), this, + SLOT(on_selectNextActivate())); - selectNextPrecharge = new QAction("Select next precharge",this); + selectNextPrecharge = new QAction("Select next precharge", this); selectNextPrecharge->setShortcut(QKeySequence("alt+p")); addAction(selectNextPrecharge); - QObject::connect(selectNextPrecharge, SIGNAL(triggered()), this, SLOT(on_selectNextPrecharge())); + QObject::connect(selectNextPrecharge, SIGNAL(triggered()), this, + SLOT(on_selectNextPrecharge())); - setColorGroupingPhase = new QAction("Group by Phase",this); + setColorGroupingPhase = new QAction("Group by Phase", this); addAction(setColorGroupingPhase); - QObject::connect(setColorGroupingPhase, SIGNAL(triggered()), this, SLOT(on_colorGroupingPhase())); + QObject::connect(setColorGroupingPhase, SIGNAL(triggered()), this, + SLOT(on_colorGroupingPhase())); - setColorGroupingTransaction = new QAction("Group by Transaction",this); + setColorGroupingTransaction = new QAction("Group by Transaction", this); addAction(setColorGroupingTransaction); - QObject::connect(setColorGroupingTransaction, SIGNAL(triggered()), this, SLOT(on_colorGroupingTransaction())); + QObject::connect(setColorGroupingTransaction, SIGNAL(triggered()), this, + SLOT(on_colorGroupingTransaction())); - setColorGroupingThread = new QAction("Group by Thread",this); + setColorGroupingThread = new QAction("Group by Thread", this); addAction(setColorGroupingThread); - QObject::connect(setColorGroupingThread, SIGNAL(triggered()), this, SLOT(on_colorGroupingThread())); + QObject::connect(setColorGroupingThread, SIGNAL(triggered()), this, + SLOT(on_colorGroupingThread())); exportToPdf = new QAction("Export to SVG", this); addAction(exportToPdf); - QObject::connect(exportToPdf, SIGNAL(triggered()), this, SLOT(on_exportToPDF())); + QObject::connect(exportToPdf, SIGNAL(triggered()), this, + SLOT(on_exportToPDF())); setUpContextMenu(); } @@ -128,22 +139,22 @@ void TracePlot::setUpContextMenu() contextMenu = new QMenu(this); contextMenu->addActions({deselectAll}); - QMenu* colorGroupingSubMenu = new QMenu("Group by",contextMenu); + QMenu *colorGroupingSubMenu = new QMenu("Group by", contextMenu); colorGroupingSubMenu->addActions({setColorGroupingTransaction, setColorGroupingPhase, setColorGroupingThread}); contextMenu->addMenu(colorGroupingSubMenu); - QMenu* goToSubMenu = new QMenu("Go to",contextMenu); - goToSubMenu->addActions({goToPhase,goToTransaction,goToTime}); + QMenu *goToSubMenu = new QMenu("Go to", contextMenu); + goToSubMenu->addActions({goToPhase, goToTransaction, goToTime}); contextMenu->addMenu(goToSubMenu); - QMenu* selectSubMenu = new QMenu("Select",contextMenu); - selectSubMenu->addActions({selectNextRefresh, selectNextActivate,selectNextPrecharge}); + QMenu *selectSubMenu = new QMenu("Select", contextMenu); + selectSubMenu->addActions({selectNextRefresh, selectNextActivate, selectNextPrecharge}); contextMenu->addMenu(selectSubMenu); - contextMenu->addActions({showQueryEditor, insertComment,exportToPdf}); + contextMenu->addActions({showQueryEditor, insertComment, exportToPdf}); } -void TracePlot::init(TraceNavigator* navigator) +void TracePlot::init(TraceNavigator *navigator) { Q_ASSERT(isInitialized == false); isInitialized = true; @@ -156,7 +167,8 @@ void TracePlot::init(TraceNavigator* navigator) setUpTracePlotItem(); setUpZoom(); setUpQueryEditor(); - mouseLabel = new TracePlotMouseLabel(this,navigator->GeneralTraceInfo().clkPeriod,this->mouseDownData.zoomSpan); + mouseLabel = new TracePlotMouseLabel(this, + navigator->GeneralTraceInfo().clkPeriod, this->mouseDownData.zoomSpan); getAndDrawComments(); setZoomLevel(1000); replot(); @@ -165,9 +177,12 @@ void TracePlot::init(TraceNavigator* navigator) void TracePlot::connectNavigatorQ_SIGNALS() { - QObject::connect(navigator,SIGNAL(currentTraceTimeChanged()),this,SLOT(currentTraceTimeChanged())); - QObject::connect(navigator,SIGNAL(selectedTransactionsChanged()),this,SLOT(selectedTransactionsChanged())); - QObject::connect(navigator,SIGNAL(commentsChanged()),this,SLOT(commentsChanged())); + QObject::connect(navigator, SIGNAL(currentTraceTimeChanged()), this, + SLOT(currentTraceTimeChanged())); + QObject::connect(navigator, SIGNAL(selectedTransactionsChanged()), this, + SLOT(selectedTransactionsChanged())); + QObject::connect(navigator, SIGNAL(commentsChanged()), this, + SLOT(commentsChanged())); } void TracePlot::setUpDrawingProperties() @@ -185,13 +200,14 @@ void TracePlot::setUpQueryEditor() { queryEditor = new QueryEditor(this); queryEditor->setWindowFlags(Qt::Window); - queryEditor->setWindowTitle("Query " + QFileInfo(navigator->TraceFile().getPathToDB()).baseName()); + queryEditor->setWindowTitle("Query " + QFileInfo( + navigator->TraceFile().getPathToDB()).baseName()); queryEditor->init(navigator); } void TracePlot::setUpTracePlotItem() { - tracePlotItem = new TracePlotItem(transactions,*navigator,drawingProperties); + tracePlotItem = new TracePlotItem(transactions, *navigator, drawingProperties); tracePlotItem->setZ(1); tracePlotItem->attach(this); } @@ -199,7 +215,7 @@ void TracePlot::setUpTracePlotItem() void TracePlot::setUpGrid() { unsigned int clk = navigator->GeneralTraceInfo().clkPeriod; - QwtPlotGrid *grid = new ClkGrid(clk, GridVisiblityClks*clk); + QwtPlotGrid *grid = new ClkGrid(clk, GridVisiblityClks * clk); grid->setZ(0); grid->attach(this); } @@ -208,7 +224,8 @@ void TracePlot::setUpZoom() { minZoomLevel = minZoomClks * navigator->GeneralTraceInfo().clkPeriod; maxZoomLevel = maxZoomClks * navigator->GeneralTraceInfo().clkPeriod; - textVisibilityZoomLevel = textVisibilityClks * navigator->GeneralTraceInfo().clkPeriod; + textVisibilityZoomLevel = textVisibilityClks * + navigator->GeneralTraceInfo().clkPeriod; zoomZone = new QwtPlotZoneItem(); zoomZone->setZ(2); zoomZone->attach(this); @@ -220,7 +237,8 @@ void TracePlot::setUpAxis() int numberOfBanks = navigator -> GeneralTraceInfo().numberOfBanks; setAxisScale(yLeft, -5, numberOfBanks + 2, 1.0); - setAxisScaleDraw(yLeft,new CustomLabelScaleDraw(drawingProperties.getLabels())); + setAxisScaleDraw(yLeft, new CustomLabelScaleDraw( + drawingProperties.getLabels())); setAxisTitle(xBottom, "Time in ns"); setAxisScaleDraw(xBottom, new EngineeringScaleDraw); @@ -228,18 +246,18 @@ void TracePlot::setUpAxis() Timespan TracePlot::GetCurrentTimespan() { - Timespan span(navigator->CurrentTraceTime() - zoomLevel / 2, navigator->CurrentTraceTime() + zoomLevel / 2); - if(span.Begin() < 0) + Timespan span(navigator->CurrentTraceTime() - zoomLevel / 2, + navigator->CurrentTraceTime() + zoomLevel / 2); + if (span.Begin() < 0) span.shift(-span.Begin()); - else if(span.End() > navigator->GeneralTraceInfo().span.End()) + else if (span.End() > navigator->GeneralTraceInfo().span.End()) span.shift(navigator->GeneralTraceInfo().span.End() - span.End()); return span; } void TracePlot::getAndDrawComments() { - for(const auto &pair: navigator->getComments()) - { + for (const auto &pair : navigator->getComments()) { const Comment &comment = pair.second; QwtPlotMarker *maker = new QwtPlotMarker(); maker->setLabel(comment.Text()); @@ -247,7 +265,7 @@ void TracePlot::getAndDrawComments() maker->setLabelAlignment(Qt::AlignLeft | Qt::AlignBottom); maker->setXValue(static_cast(comment.Time())); maker->setLineStyle(QwtPlotMarker::LineStyle::VLine); - maker->setLinePen(QColor(Qt::blue),2); + maker->setLinePen(QColor(Qt::blue), 2); maker->attach(this); } } @@ -257,7 +275,8 @@ void TracePlot::enterZoomMode() mouseDownData.mouseIsDownForZooming = true; mouseLabel->setMode(MouseLabelMode::Timedifference); zoomZone->setVisible(true); - zoomZone->setInterval(mouseDownData.zoomSpan.Begin(),mouseDownData.zoomSpan.End()); + zoomZone->setInterval(mouseDownData.zoomSpan.Begin(), + mouseDownData.zoomSpan.End()); } void TracePlot::exitZoomMode() @@ -269,7 +288,8 @@ void TracePlot::exitZoomMode() void TracePlot::zoomIn(traceTime zoomCenter) { setZoomLevel(zoomLevel * zoomFactor); - traceTime time = zoomCenter + (GetCurrentTimespan().Middle() - zoomCenter) * zoomFactor; + traceTime time = zoomCenter + (GetCurrentTimespan().Middle() - zoomCenter) * + zoomFactor; Q_EMIT tracePlotZoomChanged(); navigator->navigateToTime(time); } @@ -278,23 +298,24 @@ void TracePlot::zoomOut(traceTime zoomCenter) { setZoomLevel(zoomLevel / zoomFactor); Q_EMIT tracePlotZoomChanged(); - navigator->navigateToTime(static_cast(zoomCenter + (GetCurrentTimespan().Middle() - zoomCenter) / zoomFactor)); + navigator->navigateToTime(static_cast(zoomCenter + + (GetCurrentTimespan().Middle() - zoomCenter) / zoomFactor)); } void TracePlot::setZoomLevel(traceTime newZoomLevel) { zoomLevel = newZoomLevel; - if(zoomLevel < minZoomLevel) + if (zoomLevel < minZoomLevel) zoomLevel = minZoomLevel; - if(zoomLevel > navigator->GeneralTraceInfo().span.timeCovered()) + if (zoomLevel > navigator->GeneralTraceInfo().span.timeCovered()) zoomLevel = navigator->GeneralTraceInfo().span.timeCovered(); - if(zoomLevel > maxZoomLevel) + if (zoomLevel > maxZoomLevel) zoomLevel = maxZoomLevel; - if(zoomLevel < textVisibilityZoomLevel) + if (zoomLevel < textVisibilityZoomLevel) drawingProperties.drawText = true; - if(zoomLevel > textVisibilityZoomLevel) + if (zoomLevel > textVisibilityZoomLevel) drawingProperties.drawText = false; } @@ -306,8 +327,9 @@ void TracePlot::setZoomLevel(traceTime newZoomLevel) void TracePlot::currentTraceTimeChanged() { - transactions = navigator->TraceFile().getTransactionsInTimespan(GetCurrentTimespan()); - setAxisScale(xBottom,GetCurrentTimespan().Begin(),GetCurrentTimespan().End()); + transactions = navigator->TraceFile().getTransactionsInTimespan( + GetCurrentTimespan()); + setAxisScale(xBottom, GetCurrentTimespan().Begin(), GetCurrentTimespan().End()); replot(); } @@ -368,9 +390,10 @@ void TracePlot::on_goToTransaction() { bool ok; int maxID = navigator->GeneralTraceInfo().numberOfTransactions; - int transactionID = QInputDialog::getInt(this,"Go to transaction","Enter transaction ID (1 - " + QString::number(maxID) + ")",0,1,maxID,1,&ok); - if(ok) - { + int transactionID = QInputDialog::getInt(this, "Go to transaction", + "Enter transaction ID (1 - " + QString::number(maxID) + ")", 0, 1, maxID, 1, + &ok); + if (ok) { navigator->clearSelectedTransactions(); navigator->selectTransaction(transactionID); } @@ -380,12 +403,13 @@ void TracePlot::on_goToPhase() { bool ok; int maxID = navigator->GeneralTraceInfo().numberOfPhases; - int phaseID = QInputDialog::getInt(this,"Go to phase","Enter phase ID (1 - " + QString::number(maxID) + ")",0,1,maxID,1,&ok); + int phaseID = QInputDialog::getInt(this, "Go to phase", + "Enter phase ID (1 - " + QString::number(maxID) + ")", 0, 1, maxID, 1, &ok); - if(ok) - { + if (ok) { navigator->clearSelectedTransactions(); - navigator->selectTransaction(navigator->TraceFile().getTransactionIDFromPhaseID(phaseID)); + navigator->selectTransaction(navigator->TraceFile().getTransactionIDFromPhaseID( + phaseID)); } } @@ -398,21 +422,21 @@ void TracePlot::on_insertComment() { traceTime time = invTransform(xBottom, contextMenuMouseDown.x()); bool ok; - QString text = QInputDialog::getText(this,QString("Insert comment"),QString("Insert comment at ") + prettyFormatTime(time),QLineEdit::Normal,QString(),&ok); - if(ok) - { - navigator->insertComment(Comment(time,text)); + QString text = QInputDialog::getText(this, QString("Insert comment"), + QString("Insert comment at ") + prettyFormatTime(time), QLineEdit::Normal, + QString(), &ok); + if (ok) { + navigator->insertComment(Comment(time, text)); } } void TracePlot::on_goToTime() { double goToTime; - GoToTimeDialog dialog(&goToTime,this); + GoToTimeDialog dialog(&goToTime, this); int dialogCode = dialog.exec(); - if(dialogCode == QDialog::Accepted) - { - traceTime time = static_cast(goToTime)*1000; + if (dialogCode == QDialog::Accepted) { + traceTime time = static_cast(goToTime) * 1000; navigator->navigateToTime(time); } } @@ -420,12 +444,13 @@ void TracePlot::on_goToTime() void TracePlot::on_exportToPDF() { QwtPlotRenderer renderer; - QString filename = QFileDialog::getSaveFileName(this, "Export to SVG", "", "Portable Document Format(*.svg)"); - if(filename != "") - { + QString filename = QFileDialog::getSaveFileName(this, "Export to SVG", "", + "Portable Document Format(*.svg)"); + if (filename != "") { QBrush saved = this->canvasBackground(); this->setCanvasBackground(QBrush(Qt::white)); - renderer.renderDocument(this, filename,"svg", QSizeF(this->widthMM(),this->heightMM())); + renderer.renderDocument(this, filename, "svg", QSizeF(this->widthMM(), + this->heightMM())); this->setCanvasBackground(QBrush(saved)); } } @@ -438,20 +463,17 @@ void TracePlot::on_exportToPDF() void TracePlot::keyPressEvent(QKeyEvent *keyPressedEvent) { int key = keyPressedEvent->key(); - if(Qt::Key_Control == key) + if (Qt::Key_Control == key) keyPressData.ctrlPressed = true; - else if(Qt::Key_Shift == key) + else if (Qt::Key_Shift == key) keyPressData.shiftPressed = true; - else if(Qt::Key_Right == key) + else if (Qt::Key_Right == key) navigator->selectNextTransaction(); - else if(Qt::Key_Left == key) + else if (Qt::Key_Left == key) navigator->selectPreviousTransaction(); - else if(Qt::Key_Minus == key) - { + else if (Qt::Key_Minus == key) { zoomOut(GetCurrentTimespan().Middle()); - } - else if(Qt::Key_Plus == key) - { + } else if (Qt::Key_Plus == key) { zoomIn(GetCurrentTimespan().Middle()); } } @@ -460,10 +482,9 @@ void TracePlot::keyReleaseEvent(QKeyEvent *keyReleasedEvent) { int key = keyReleasedEvent->key(); - if(Qt::Key_Control == key) + if (Qt::Key_Control == key) keyPressData.ctrlPressed = false; - else if(Qt::Key_Shift == key) - { + else if (Qt::Key_Shift == key) { keyPressData.shiftPressed = false; exitZoomMode(); replot(); @@ -473,33 +494,28 @@ void TracePlot::keyReleaseEvent(QKeyEvent *keyReleasedEvent) bool TracePlot::eventFilter(QObject *object, QEvent *event) { - if(object == canvas()) - { - switch(event->type()) - { - case QEvent::Wheel : - { + if (object == canvas()) { + switch (event->type()) { + case QEvent::Wheel : { QWheelEvent *wheelEvent = static_cast(event); - traceTime zoomCenter = static_cast(this->invTransform(xBottom, wheelEvent->x())); + traceTime zoomCenter = static_cast(this->invTransform(xBottom, + wheelEvent->x())); (wheelEvent->delta() > 0) ? zoomIn(zoomCenter) : zoomOut(zoomCenter); return true; } - case QEvent::MouseButtonPress: - { + case QEvent::MouseButtonPress: { QMouseEvent *mouseEvent = static_cast(event); - if(mouseEvent->button() == Qt::LeftButton) - { - if(keyPressData.shiftPressed) - { - mouseDownData.zoomSpan.setBegin(alignToClk(invTransform(xBottom, mouseEvent->x()),navigator->GeneralTraceInfo().clkPeriod)); - mouseDownData.zoomSpan.setEnd(alignToClk(invTransform(xBottom, mouseEvent->x()),navigator->GeneralTraceInfo().clkPeriod)); + if (mouseEvent->button() == Qt::LeftButton) { + if (keyPressData.shiftPressed) { + mouseDownData.zoomSpan.setBegin(alignToClk(invTransform(xBottom, + mouseEvent->x()), navigator->GeneralTraceInfo().clkPeriod)); + mouseDownData.zoomSpan.setEnd(alignToClk(invTransform(xBottom, mouseEvent->x()), + navigator->GeneralTraceInfo().clkPeriod)); enterZoomMode(); - } - else - { + } else { mouseDownData.mouseDownX = mouseEvent->x(); mouseDownData.mouseDownTime = GetCurrentTimespan().Middle(); mouseDownData.mouseIsDownForDragging = true; @@ -507,28 +523,22 @@ bool TracePlot::eventFilter(QObject *object, QEvent *event) SelectTransaction(mouseEvent->x(), mouseEvent->y()); } return true; - } - else if(mouseEvent->button() == Qt::RightButton) - { - openContextMenu(this->canvas()->mapToGlobal(mouseEvent->pos()),mouseEvent->pos()); + } else if (mouseEvent->button() == Qt::RightButton) { + openContextMenu(this->canvas()->mapToGlobal(mouseEvent->pos()), + mouseEvent->pos()); return true; } break; } - case QEvent::MouseButtonRelease: - { + case QEvent::MouseButtonRelease: { QMouseEvent *mouseEvent = static_cast(event); - if(mouseEvent->button() == Qt::LeftButton) - { - if(mouseDownData.mouseIsDownForDragging) - { + if (mouseEvent->button() == Qt::LeftButton) { + if (mouseDownData.mouseIsDownForDragging) { mouseDownData.mouseIsDownForDragging = false; canvas()->setCursor(Qt::ArrowCursor); return true; - } - else if(mouseDownData.mouseIsDownForZooming) - { + } else if (mouseDownData.mouseIsDownForZooming) { exitZoomMode(); traceTime newCenter = mouseDownData.zoomSpan.Middle(); setZoomLevel(mouseDownData.zoomSpan.timeCovered()); @@ -539,23 +549,23 @@ bool TracePlot::eventFilter(QObject *object, QEvent *event) } break; } - case QEvent::MouseMove: - { + case QEvent::MouseMove: { QMouseEvent *mouseEvent = static_cast(event); - if(mouseDownData.mouseIsDownForDragging) - { - traceTime deltaTime = invTransform(xBottom, mouseDownData.mouseDownX) - invTransform(xBottom, mouseEvent->x()); + if (mouseDownData.mouseIsDownForDragging) { + traceTime deltaTime = invTransform(xBottom, + mouseDownData.mouseDownX) - invTransform(xBottom, mouseEvent->x()); navigator->navigateToTime(mouseDownData.mouseDownTime + deltaTime); return true; - } - else if(mouseDownData.mouseIsDownForZooming) - { - mouseDownData.zoomSpan.setEnd(alignToClk(invTransform(xBottom, mouseEvent->x()),navigator->GeneralTraceInfo().clkPeriod)); - if(mouseDownData.zoomSpan.Begin() < mouseDownData.zoomSpan.End()) - zoomZone->setInterval(mouseDownData.zoomSpan.Begin(),mouseDownData.zoomSpan.End()); + } else if (mouseDownData.mouseIsDownForZooming) { + mouseDownData.zoomSpan.setEnd(alignToClk(invTransform(xBottom, mouseEvent->x()), + navigator->GeneralTraceInfo().clkPeriod)); + if (mouseDownData.zoomSpan.Begin() < mouseDownData.zoomSpan.End()) + zoomZone->setInterval(mouseDownData.zoomSpan.Begin(), + mouseDownData.zoomSpan.End()); else - zoomZone->setInterval(mouseDownData.zoomSpan.End(),mouseDownData.zoomSpan.Begin()); + zoomZone->setInterval(mouseDownData.zoomSpan.End(), + mouseDownData.zoomSpan.Begin()); replot(); } @@ -573,16 +583,16 @@ void TracePlot::SelectTransaction(int x, int y) { double yVal = invTransform(yLeft, y); traceTime time = invTransform(xBottom, x); - vector> selectedTransactions = tracePlotItem->getSelectedTransactions(time,yVal); - if(selectedTransactions.size() > 0) - { - if(!keyPressData.ctrlPressed) + vector> selectedTransactions = + tracePlotItem->getSelectedTransactions(time, yVal); + if (selectedTransactions.size() > 0) { + if (!keyPressData.ctrlPressed) navigator->clearSelectedTransactions(); navigator->addSelectedTransactions(selectedTransactions); } } -void TracePlot::openContextMenu(const QPoint& pos,const QPoint& mouseDown) +void TracePlot::openContextMenu(const QPoint &pos, const QPoint &mouseDown) { contextMenuMouseDown = mouseDown; contextMenu->exec(pos); diff --git a/DRAMSys/traceAnalyzer/presentation/traceplot.h b/DRAMSys/traceAnalyzer/presentation/traceplot.h index 97ce83e7..322102b2 100644 --- a/DRAMSys/traceAnalyzer/presentation/traceplot.h +++ b/DRAMSys/traceAnalyzer/presentation/traceplot.h @@ -66,9 +66,12 @@ class TracePlot : public QwtPlot public: TracePlot(QWidget *parent = NULL); - void init(TraceNavigator* navigator); + void init(TraceNavigator *navigator); Timespan GetCurrentTimespan(); - traceTime ZoomLevel() const{return zoomLevel;} + traceTime ZoomLevel() const + { + return zoomLevel; + } void setUpActions(); @@ -100,13 +103,13 @@ private Q_SLOTS: private: bool isInitialized; - TraceNavigator* navigator; + TraceNavigator *navigator; TraceDrawingProperties drawingProperties; TracePlotItem *tracePlotItem; QwtPlotZoneItem *zoomZone; std::vector> transactions; QueryEditor *queryEditor; - QMenu* contextMenu; + QMenu *contextMenu; void setUpTracePlotItem(); void setUpDrawingProperties(); @@ -127,7 +130,7 @@ private: constexpr static int maxZoomClks = 2000; constexpr static int GridVisiblityClks = 100; constexpr static int textVisibilityClks = 200; - traceTime minZoomLevel,maxZoomLevel, textVisibilityZoomLevel; + traceTime minZoomLevel, maxZoomLevel, textVisibilityZoomLevel; constexpr static double zoomFactor = 0.8; void zoomIn(traceTime zoomCenter); @@ -142,42 +145,41 @@ private: */ bool eventFilter( QObject *object, QEvent *event ); - QAction* goToTime; - QAction* goToTransaction; - QAction* goToPhase; - QAction* showQueryEditor; - QAction* insertComment; - QAction* deselectAll; - QAction* selectNextRefresh; - QAction* selectNextActivate; - QAction* selectNextPrecharge; - QAction* setColorGroupingPhase; - QAction* setColorGroupingTransaction; - QAction* setColorGroupingThread; - QAction* exportToPdf; + QAction *goToTime; + QAction *goToTransaction; + QAction *goToPhase; + QAction *showQueryEditor; + QAction *insertComment; + QAction *deselectAll; + QAction *selectNextRefresh; + QAction *selectNextActivate; + QAction *selectNextPrecharge; + QAction *setColorGroupingPhase; + QAction *setColorGroupingTransaction; + QAction *setColorGroupingThread; + QAction *exportToPdf; - TracePlotMouseLabel* mouseLabel; + TracePlotMouseLabel *mouseLabel; - void openContextMenu(const QPoint& pos,const QPoint& mouseDown); + void openContextMenu(const QPoint &pos, const QPoint &mouseDown); QPoint contextMenuMouseDown; void SelectTransaction(int x, int y); void keyPressEvent(QKeyEvent *keyPressedEvent); void keyReleaseEvent(QKeyEvent *keyReleasedEvent); - struct KeyPressData - { + struct KeyPressData { bool ctrlPressed, shiftPressed; - KeyPressData():ctrlPressed(false),shiftPressed(false){} + KeyPressData(): ctrlPressed(false), shiftPressed(false) {} }; - struct MouseDownData - { + struct MouseDownData { traceTime mouseDownTime; Timespan zoomSpan; int mouseDownX; bool mouseIsDownForDragging; bool mouseIsDownForZooming; - MouseDownData(): mouseDownTime(0),mouseDownX(0),mouseIsDownForDragging(false),mouseIsDownForZooming(false){} + MouseDownData(): mouseDownTime(0), mouseDownX(0), mouseIsDownForDragging(false), + mouseIsDownForZooming(false) {} }; MouseDownData mouseDownData; diff --git a/DRAMSys/traceAnalyzer/presentation/traceplotitem.cpp b/DRAMSys/traceAnalyzer/presentation/traceplotitem.cpp index f9269dcb..b3bbdf14 100644 --- a/DRAMSys/traceAnalyzer/presentation/traceplotitem.cpp +++ b/DRAMSys/traceAnalyzer/presentation/traceplotitem.cpp @@ -50,22 +50,23 @@ int TracePlotItem::rtti() const return QwtPlotItem::Rtti_PlotUserItem; } -void TracePlotItem::draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &canvasRect) const +void TracePlotItem::draw(QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap, const QRectF &canvasRect) const { - for(const auto &transaction : transactions) - { + for (const auto &transaction : transactions) { bool highlight = navigator.transactionIsSelected(transaction); - transaction->draw(painter,xMap,yMap,canvasRect,highlight,drawingProperties); + transaction->draw(painter, xMap, yMap, canvasRect, highlight, + drawingProperties); } } -vector> TracePlotItem::getSelectedTransactions(traceTime time, double yVal) +vector> TracePlotItem::getSelectedTransactions( + traceTime time, double yVal) { vector> result; - for(const auto &transaction : transactions) - { - if(transaction->isSelected(time,yVal,drawingProperties)) + for (const auto &transaction : transactions) { + if (transaction->isSelected(time, yVal, drawingProperties)) result.push_back(transaction); } diff --git a/DRAMSys/traceAnalyzer/presentation/traceplotitem.h b/DRAMSys/traceAnalyzer/presentation/traceplotitem.h index 7a081371..f8e8afe0 100644 --- a/DRAMSys/traceAnalyzer/presentation/traceplotitem.h +++ b/DRAMSys/traceAnalyzer/presentation/traceplotitem.h @@ -52,16 +52,21 @@ class TracePlotItem : public QwtPlotItem { private: const std::vector> &transactions; - const TraceNavigator& navigator; + const TraceNavigator &navigator; const TraceDrawingProperties &drawingProperties; public: - TracePlotItem(const std::vector> &transactions,const TraceNavigator& navigator, const TraceDrawingProperties &drawingProperties): - transactions(transactions),navigator(navigator),drawingProperties(drawingProperties){} + TracePlotItem(const std::vector> &transactions, + const TraceNavigator &navigator, + const TraceDrawingProperties &drawingProperties): + transactions(transactions), navigator(navigator), + drawingProperties(drawingProperties) {} virtual int rtti() const; - virtual void draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &canvasRect) const; - std::vector> getSelectedTransactions(traceTime time,double yVal); + virtual void draw(QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap, const QRectF &canvasRect) const; + std::vector> getSelectedTransactions( + traceTime time, double yVal); }; diff --git a/DRAMSys/traceAnalyzer/presentation/tracetesttreewidget.cpp b/DRAMSys/traceAnalyzer/presentation/tracetesttreewidget.cpp index 26c67a65..49749398 100644 --- a/DRAMSys/traceAnalyzer/presentation/tracetesttreewidget.cpp +++ b/DRAMSys/traceAnalyzer/presentation/tracetesttreewidget.cpp @@ -39,44 +39,46 @@ TraceTestTreeWidget::TraceTestTreeWidget(QWidget *parent) : QTreeWidget(parent) { - QObject::connect(this,SIGNAL(itemSelectionChanged()),this,SLOT(itemSelectionChanged())); + QObject::connect(this, SIGNAL(itemSelectionChanged()), this, + SLOT(itemSelectionChanged())); setHeaderHidden(true); } -void TraceTestTreeWidget::addTraceTestResult(const TraceTestResults &traceTestResult) +void TraceTestTreeWidget::addTraceTestResult(const TraceTestResults + &traceTestResult) { - QTreeWidgetItem* top = new QTreeWidgetItem({traceTestResult.getTraceName()}); + QTreeWidgetItem *top = new QTreeWidgetItem({traceTestResult.getTraceName()}); addTopLevelItem(top); - if(traceTestResult.hasPassedAllTests()) - top->setTextColor(0,Qt::green); + if (traceTestResult.hasPassedAllTests()) + top->setTextColor(0, Qt::green); else - top->setTextColor(0,Qt::red); + top->setTextColor(0, Qt::red); - for(const TestResult& testResult: traceTestResult.getTestResults()) - { + for (const TestResult &testResult : traceTestResult.getTestResults()) { new TestResultTreeItem(top, testResult); } } void TraceTestTreeWidget::itemSelectionChanged() { - if(!selectedItems().isEmpty() && selectedItems().at(0)->type() == TestResultTreeItem::testResultTreeItemType) - { - TestResultTreeItem* testResultItem = static_cast(selectedItems().at(0)); + if (!selectedItems().isEmpty() + && selectedItems().at(0)->type() == + TestResultTreeItem::testResultTreeItemType) { + TestResultTreeItem *testResultItem = static_cast + (selectedItems().at(0)); Q_EMIT setMessage(testResultItem->getMessage()); - } - else - { + } else { setMessage(QString("")); } } -TraceTestTreeWidget::TestResultTreeItem::TestResultTreeItem(QTreeWidgetItem *parent, const TestResult& testResult) - :QTreeWidgetItem(parent,testResultTreeItemType) +TraceTestTreeWidget::TestResultTreeItem::TestResultTreeItem( + QTreeWidgetItem *parent, const TestResult &testResult) + : QTreeWidgetItem(parent, testResultTreeItemType) { setText(0, testResult.getTestName()); - if(!testResult.hasPassed()) - setTextColor(0,Qt::red); + if (!testResult.hasPassed()) + setTextColor(0, Qt::red); message = testResult.getMessage(); } diff --git a/DRAMSys/traceAnalyzer/presentation/tracetesttreewidget.h b/DRAMSys/traceAnalyzer/presentation/tracetesttreewidget.h index 3e84d174..db67fa59 100644 --- a/DRAMSys/traceAnalyzer/presentation/tracetesttreewidget.h +++ b/DRAMSys/traceAnalyzer/presentation/tracetesttreewidget.h @@ -45,7 +45,7 @@ class TraceTestTreeWidget: public QTreeWidget Q_OBJECT public: TraceTestTreeWidget(QWidget *parent = 0); - void addTraceTestResult(const TraceTestResults& traceTestResult); + void addTraceTestResult(const TraceTestResults &traceTestResult); Q_SIGNALS: void setMessage(QString message); @@ -54,9 +54,12 @@ private: class TestResultTreeItem : public QTreeWidgetItem { public: - TestResultTreeItem(QTreeWidgetItem *parent, const TestResult& testResult); + TestResultTreeItem(QTreeWidgetItem *parent, const TestResult &testResult); static constexpr int testResultTreeItemType = 1002; - QString getMessage(){return message;} + QString getMessage() + { + return message; + } private: QString message; }; diff --git a/DRAMSys/traceAnalyzer/presentation/transactiontreewidget.cpp b/DRAMSys/traceAnalyzer/presentation/transactiontreewidget.cpp index 7f552e8f..849da090 100644 --- a/DRAMSys/traceAnalyzer/presentation/transactiontreewidget.cpp +++ b/DRAMSys/traceAnalyzer/presentation/transactiontreewidget.cpp @@ -43,11 +43,13 @@ using namespace std; -TransactionTreeWidget::TransactionTreeWidget(QWidget *parent) : QTreeWidget(parent), isInitialized(false) +TransactionTreeWidget::TransactionTreeWidget(QWidget *parent) : QTreeWidget( + parent), isInitialized(false) { - QObject::connect(this,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(ContextMenuRequested(QPoint))); + QObject::connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, + SLOT(ContextMenuRequested(QPoint))); setContextMenuPolicy(Qt::CustomContextMenu); - goToTransaction = new QAction("Move to",this); + goToTransaction = new QAction("Move to", this); } void TransactionTreeWidget::init(TraceNavigator *navigator) @@ -60,29 +62,35 @@ void TransactionTreeWidget::init(TraceNavigator *navigator) setHeaderLabels(QStringList({"Transaction", "Value", "Value"})); } -void TransactionTreeWidget::AppendTransaction(const shared_ptr &transaction) +void TransactionTreeWidget::AppendTransaction(const shared_ptr + &transaction) { - QTreeWidgetItem *node = new TransactionTreeItem(this,transaction, navigator->GeneralTraceInfo().controllerThread); + QTreeWidgetItem *node = new TransactionTreeItem(this, transaction, + navigator->GeneralTraceInfo().controllerThread); addTopLevelItem(node); } void TransactionTreeWidget::ContextMenuRequested(QPoint point) { - if(selectedItems().count() > 0 && selectedItems().at(0)->type() == TransactionTreeWidget::TransactionTreeItem::transactionTreeItemType) - { + if (selectedItems().count() > 0 + && selectedItems().at(0)->type() == + TransactionTreeWidget::TransactionTreeItem::transactionTreeItemType) { QMenu contextMenu; contextMenu.addActions({goToTransaction}); - QAction* selectedContextMenuItems = contextMenu.exec(mapToGlobal(point)); + QAction *selectedContextMenuItems = contextMenu.exec(mapToGlobal(point)); - if(selectedContextMenuItems) - { - TransactionTreeItem *item = static_cast(selectedItems().at(0)); + if (selectedContextMenuItems) { + TransactionTreeItem *item = static_cast + (selectedItems().at(0)); navigator->selectTransaction(item->Id()); } } } -TransactionTreeWidget::TransactionTreeItem::TransactionTreeItem(QTreeWidget *parent, const shared_ptr &transaction, unsigned int controllerThread) : QTreeWidgetItem(parent,transactionTreeItemType) +TransactionTreeWidget::TransactionTreeItem::TransactionTreeItem( + QTreeWidget *parent, const shared_ptr &transaction, + unsigned int controllerThread) : QTreeWidgetItem(parent, + transactionTreeItemType) { this->setText(0, QString::number(transaction->Id())); this->id = transaction->Id(); @@ -97,33 +105,34 @@ TransactionTreeWidget::TransactionTreeItem::TransactionTreeItem(QTreeWidget *par this->addChild(new QTreeWidgetItem( {"Bankgroup", QString::number(transaction->BankGroup())} )); this->addChild(new QTreeWidgetItem( {"Row", QString::number(transaction->Row())} )); this->addChild(new QTreeWidgetItem( {"Column", QString::number(transaction->Column())} )); - this->addChild(new QTreeWidgetItem( {"Address", QString("0x") + QString::number(transaction->Address(),16)} )); + this->addChild(new QTreeWidgetItem( {"Address", QString("0x") + QString::number(transaction->Address(), 16)} )); - if(!transaction->Thread() != controllerThread) - { + if (!transaction->Thread() != controllerThread) { this->addChild(new QTreeWidgetItem( {"Burstlength", QString::number(transaction->Burstlength())})); this->addChild(new QTreeWidgetItem( {"Thread", QString::number(transaction->Thread())})); } QTreeWidgetItem *phasesNode = new QTreeWidgetItem(this); - phasesNode->setText(0,"Phases"); + phasesNode->setText(0, "Phases"); phasesNode->addChild(new QTreeWidgetItem( {"", "Begin", "End"} )); - for(std::shared_ptr phase : transaction->Phases()) - { + for (std::shared_ptr phase : transaction->Phases()) { AppendPhase(phasesNode, *phase); } } -void TransactionTreeWidget::TransactionTreeItem::AppendPhase(QTreeWidgetItem *parent, const Phase &phase) +void TransactionTreeWidget::TransactionTreeItem::AppendPhase( + QTreeWidgetItem *parent, const Phase &phase) { QTreeWidgetItem *node = new QTreeWidgetItem(parent); - node->setText(0, phase.Name() + QString(" [") + QString::number(phase.Id()) + QString("]")); + node->setText(0, phase.Name() + QString(" [") + QString::number( + phase.Id()) + QString("]")); AppendTimespan(node, phase.Span()); } -void TransactionTreeWidget::TransactionTreeItem::AppendTimespan(QTreeWidgetItem *parent, const Timespan ×pan) +void TransactionTreeWidget::TransactionTreeItem::AppendTimespan( + QTreeWidgetItem *parent, const Timespan ×pan) { parent->setText(1, prettyFormatTime(timespan.Begin())); parent->setText(2, prettyFormatTime(timespan.End())); diff --git a/DRAMSys/traceAnalyzer/presentation/transactiontreewidget.h b/DRAMSys/traceAnalyzer/presentation/transactiontreewidget.h index e2c7ed06..5084865d 100644 --- a/DRAMSys/traceAnalyzer/presentation/transactiontreewidget.h +++ b/DRAMSys/traceAnalyzer/presentation/transactiontreewidget.h @@ -64,14 +64,18 @@ private: bool isInitialized; void AppendTimespan(QTreeWidgetItem *parent, const Timespan ×pan); void AppendPhase(QTreeWidgetItem *parent, const Phase &phase); - QAction* goToTransaction; + QAction *goToTransaction; class TransactionTreeItem : public QTreeWidgetItem { public: static constexpr int transactionTreeItemType = 1001; - TransactionTreeItem(QTreeWidget *parent, const std::shared_ptr &trans, unsigned int controllerThread); - ID Id(){return id;} + TransactionTreeItem(QTreeWidget *parent, + const std::shared_ptr &trans, unsigned int controllerThread); + ID Id() + { + return id; + } private: ID id; void AppendTimespan(QTreeWidgetItem *parent, const Timespan ×pan); diff --git a/DRAMSys/traceAnalyzer/presentation/util/clkgrid.cpp b/DRAMSys/traceAnalyzer/presentation/util/clkgrid.cpp index 07481e86..0e87ee7b 100644 --- a/DRAMSys/traceAnalyzer/presentation/util/clkgrid.cpp +++ b/DRAMSys/traceAnalyzer/presentation/util/clkgrid.cpp @@ -42,25 +42,24 @@ using namespace std; void ClkGrid::updateScaleDiv(const QwtScaleDiv &xMap, const QwtScaleDiv &yMap) { - QwtScaleDiv scaleDiv; - scaleDiv.setInterval( xMap.interval() ); + QwtScaleDiv scaleDiv; + scaleDiv.setInterval( xMap.interval() ); - double min = xMap.interval().minValue(); - double max = xMap.interval().maxValue(); + double min = xMap.interval().minValue(); + double max = xMap.interval().maxValue(); - if ( min > max ) - qSwap( min, max ); + if ( min > max ) + qSwap( min, max ); - if((max - min) < maxVisibility) - { - min = static_cast( min / clkPeriod ) * clkPeriod; - QList ticks; - for ( double tick = min; tick <= max; tick += clkPeriod ) - ticks += tick; + if ((max - min) < maxVisibility) { + min = static_cast( min / clkPeriod ) * clkPeriod; + QList ticks; + for ( double tick = min; tick <= max; tick += clkPeriod ) + ticks += tick; - scaleDiv.setTicks( QwtScaleDiv::MajorTick, ticks ); + scaleDiv.setTicks( QwtScaleDiv::MajorTick, ticks ); - } + } - QwtPlotGrid::updateScaleDiv( scaleDiv, yMap ); - } + QwtPlotGrid::updateScaleDiv( scaleDiv, yMap ); +} diff --git a/DRAMSys/traceAnalyzer/presentation/util/clkgrid.h b/DRAMSys/traceAnalyzer/presentation/util/clkgrid.h index 19aa33f9..8be46310 100644 --- a/DRAMSys/traceAnalyzer/presentation/util/clkgrid.h +++ b/DRAMSys/traceAnalyzer/presentation/util/clkgrid.h @@ -45,7 +45,8 @@ class ClkGrid : public QwtPlotGrid { public: virtual void updateScaleDiv(const QwtScaleDiv &xMap, const QwtScaleDiv &yMap); - ClkGrid(unsigned int clkPeriod, traceTime maxVisibility) : clkPeriod(clkPeriod), maxVisibility(maxVisibility){} + ClkGrid(unsigned int clkPeriod, traceTime maxVisibility) : clkPeriod(clkPeriod), + maxVisibility(maxVisibility) {} private: unsigned int clkPeriod; diff --git a/DRAMSys/traceAnalyzer/presentation/util/colorgenerator.cpp b/DRAMSys/traceAnalyzer/presentation/util/colorgenerator.cpp index a06a5a7b..b9869f29 100644 --- a/DRAMSys/traceAnalyzer/presentation/util/colorgenerator.cpp +++ b/DRAMSys/traceAnalyzer/presentation/util/colorgenerator.cpp @@ -39,21 +39,57 @@ #include ColorGenerator::ColorGenerator() { - r[0] = 0xFF; r[1] = 0x00; r[2] = 0x00; r[3] = 0xFF; - g[0] = 0x00; g[1] = 0xFF; g[2] = 0x00; g[3] = 0xFF; - b[0] = 0x00; b[1] = 0x00; b[2] = 0xFF; b[3] = 0x00; + r[0] = 0xFF; + r[1] = 0x00; + r[2] = 0x00; + r[3] = 0xFF; + g[0] = 0x00; + g[1] = 0xFF; + g[2] = 0x00; + g[3] = 0xFF; + b[0] = 0x00; + b[1] = 0x00; + b[2] = 0xFF; + b[3] = 0x00; - r[4] = 0xFF; r[5] = 0x00; r[6] = 0xFF; r[7] = 0x6B; - g[4] = 0x00; g[5] = 0xFF; g[6] = 0xA5; g[7] = 0x8E; - b[4] = 0xFF; b[5] = 0xFF; b[6] = 0x00; b[7] = 0x23; + r[4] = 0xFF; + r[5] = 0x00; + r[6] = 0xFF; + r[7] = 0x6B; + g[4] = 0x00; + g[5] = 0xFF; + g[6] = 0xA5; + g[7] = 0x8E; + b[4] = 0xFF; + b[5] = 0xFF; + b[6] = 0x00; + b[7] = 0x23; - r[8] = 0x8A; r[9] = 0xFF; r[10] = 0x7C; r[11] = 0x00; - g[8] = 0x2B; g[9] = 0xD7; g[10] = 0xFC; g[11] = 0x00; - b[8] = 0xE2; b[9] = 0x00; b[10] = 0x00; b[11] = 0x80; + r[8] = 0x8A; + r[9] = 0xFF; + r[10] = 0x7C; + r[11] = 0x00; + g[8] = 0x2B; + g[9] = 0xD7; + g[10] = 0xFC; + g[11] = 0x00; + b[8] = 0xE2; + b[9] = 0x00; + b[10] = 0x00; + b[11] = 0x80; - r[12] = 0x80; r[13] = 0x00; r[14] = 0xEE; r[15] = 0xFF; - g[12] = 0x00; g[13] = 0x80; g[14] = 0x82; g[15] = 0x45; - b[12] = 0x00; b[13] = 0x00; b[14] = 0xEE; b[15] = 0x00; + r[12] = 0x80; + r[13] = 0x00; + r[14] = 0xEE; + r[15] = 0xFF; + g[12] = 0x00; + g[13] = 0x80; + g[14] = 0x82; + g[15] = 0x45; + b[12] = 0x00; + b[13] = 0x00; + b[14] = 0xEE; + b[15] = 0x00; } @@ -61,7 +97,7 @@ QColor ColorGenerator::getColor(unsigned int i) { static ColorGenerator gen; i = i % 16; - QColor result(gen.r[i],gen.g[i],gen.b[i]); + QColor result(gen.r[i], gen.g[i], gen.b[i]); result.setAlpha(130); return result; } diff --git a/DRAMSys/traceAnalyzer/presentation/util/customlabelscaledraw.h b/DRAMSys/traceAnalyzer/presentation/util/customlabelscaledraw.h index 99bbdfdb..31b48ce0 100644 --- a/DRAMSys/traceAnalyzer/presentation/util/customlabelscaledraw.h +++ b/DRAMSys/traceAnalyzer/presentation/util/customlabelscaledraw.h @@ -44,14 +44,14 @@ class CustomLabelScaleDraw : public QwtScaleDraw { private: - QHash labels; + QHash labels; public: - CustomLabelScaleDraw(QHash labels): labels(labels){} - virtual QwtText label(double v) const - { - return QwtText(labels[static_cast(v)]); - } + CustomLabelScaleDraw(QHash labels): labels(labels) {} + virtual QwtText label(double v) const + { + return QwtText(labels[static_cast(v)]); + } }; #endif // CUSTOMLABELSCALEDRAW_H diff --git a/DRAMSys/traceAnalyzer/presentation/util/engineeringScaleDraw.h b/DRAMSys/traceAnalyzer/presentation/util/engineeringScaleDraw.h index 31416ffd..52ac8349 100644 --- a/DRAMSys/traceAnalyzer/presentation/util/engineeringScaleDraw.h +++ b/DRAMSys/traceAnalyzer/presentation/util/engineeringScaleDraw.h @@ -43,10 +43,10 @@ class EngineeringScaleDraw : public QwtScaleDraw { - public: - virtual QwtText label(double number) const - { - return QwtText(QString::number(number/1000,'g',9)); - } +public: + virtual QwtText label(double number) const + { + return QwtText(QString::number(number / 1000, 'g', 9)); + } }; #endif // ENGINEERINGSCALEDRAW_H diff --git a/DRAMSys/traceAnalyzer/presentation/util/testlight.cpp b/DRAMSys/traceAnalyzer/presentation/util/testlight.cpp index b77652c0..130cba96 100644 --- a/DRAMSys/traceAnalyzer/presentation/util/testlight.cpp +++ b/DRAMSys/traceAnalyzer/presentation/util/testlight.cpp @@ -45,8 +45,8 @@ TestLight::TestLight(QWidget *parent) : QWidget(parent) void TestLight::setGray() { - lightColor = QColor(Qt::gray); - update(); + lightColor = QColor(Qt::gray); + update(); } void TestLight::setGreen() @@ -61,10 +61,10 @@ void TestLight::setRed() update(); } -void TestLight::paintEvent(QPaintEvent* /*paintEvent*/) +void TestLight::paintEvent(QPaintEvent * /*paintEvent*/) { QPainter painter(this); - painter.fillRect(this->rect(),lightColor); + painter.fillRect(this->rect(), lightColor); painter.drawRect(this->rect()); } diff --git a/DRAMSys/traceAnalyzer/queryeditor.cpp b/DRAMSys/traceAnalyzer/queryeditor.cpp index 149210fa..e9b92b82 100644 --- a/DRAMSys/traceAnalyzer/queryeditor.cpp +++ b/DRAMSys/traceAnalyzer/queryeditor.cpp @@ -61,17 +61,15 @@ void QueryEditor::init(TraceNavigator *navigator) void QueryEditor::on_executeQuery_clicked() { - try - { - std::vector> result = navigator->TraceFile().getTransactionsWithCustomQuery(queryTexts.queryHead + " " + ui->queryEdit->toPlainText()); + try { + std::vector> result = + navigator->TraceFile().getTransactionsWithCustomQuery(queryTexts.queryHead + " " + + ui->queryEdit->toPlainText()); ui->transactiontreeWidget->clear(); - for(const auto & trans : result) - { + for (const auto &trans : result) { ui->transactiontreeWidget->AppendTransaction(trans); } - } - catch(sqlException ex) - { - QMessageBox::warning(this,"Query failed",ex.what()); + } catch (sqlException ex) { + QMessageBox::warning(this, "Query failed", ex.what()); } } diff --git a/DRAMSys/traceAnalyzer/queryeditor.h b/DRAMSys/traceAnalyzer/queryeditor.h index be957111..41f6ac3e 100644 --- a/DRAMSys/traceAnalyzer/queryeditor.h +++ b/DRAMSys/traceAnalyzer/queryeditor.h @@ -60,7 +60,7 @@ private Q_SLOTS: private: Ui::QueryEditor *ui; - TraceNavigator* navigator; + TraceNavigator *navigator; TransactionQueryTexts queryTexts; }; diff --git a/DRAMSys/traceAnalyzer/schedulerwrapper.h b/DRAMSys/traceAnalyzer/schedulerwrapper.h index 3f0046c0..eb59f013 100644 --- a/DRAMSys/traceAnalyzer/schedulerwrapper.h +++ b/DRAMSys/traceAnalyzer/schedulerwrapper.h @@ -44,8 +44,7 @@ #include #include -struct SchedulerWrapper : public sc_module -{ +struct SchedulerWrapper : public sc_module { tlm_utils::simple_initiator_socket iSocket; tlm_utils::simple_target_socket tSocket; @@ -56,12 +55,17 @@ struct SchedulerWrapper : public sc_module private: tlm_utils::peq_with_cb_and_phase payloadEventQueue; - tlm::tlm_sync_enum nb_transport_bw(tlm::tlm_generic_payload& payload,tlm::tlm_phase& phase,sc_time& bwDelay); - tlm::tlm_sync_enum nb_transport_fw(tlm::tlm_generic_payload& payload,tlm::tlm_phase& phase,sc_time& fwDelay); + tlm::tlm_sync_enum nb_transport_bw(tlm::tlm_generic_payload &payload, + tlm::tlm_phase &phase, sc_time &bwDelay); + tlm::tlm_sync_enum nb_transport_fw(tlm::tlm_generic_payload &payload, + tlm::tlm_phase &phase, sc_time &fwDelay); - void peqCallback(tlm::tlm_generic_payload& payload,const tlm::tlm_phase& phase); - void sendToTarget(tlm::tlm_generic_payload& payload,const tlm::tlm_phase& phase,const sc_time& delay); - void sendToInitiator(tlm::tlm_generic_payload& payload,const tlm::tlm_phase& phase,const sc_time& delay); + void peqCallback(tlm::tlm_generic_payload &payload, + const tlm::tlm_phase &phase); + void sendToTarget(tlm::tlm_generic_payload &payload, + const tlm::tlm_phase &phase, const sc_time &delay); + void sendToInitiator(tlm::tlm_generic_payload &payload, + const tlm::tlm_phase &phase, const sc_time &delay); }; diff --git a/DRAMSys/traceAnalyzer/selectmetrics.cpp b/DRAMSys/traceAnalyzer/selectmetrics.cpp index 9767caa3..4edd988a 100644 --- a/DRAMSys/traceAnalyzer/selectmetrics.cpp +++ b/DRAMSys/traceAnalyzer/selectmetrics.cpp @@ -53,59 +53,50 @@ SelectMetrics::SelectMetrics(QWidget *parent) : } void SelectMetrics::on_okButton_clicked() -{ - if(isThereAnyMetricSelected()) - { +{ + if (isThereAnyMetricSelected()) { close(); Q_EMIT getSelectedMetrics(); - } - else - { - QMessageBox::warning(this,"Warning","Please select at least one metric"); + } else { + QMessageBox::warning(this, "Warning", "Please select at least one metric"); } } void SelectMetrics::on_clearAllButton_clicked() { - for(QCheckBox* checkBox : metrics) - { - checkBox->setChecked(false); - } + for (QCheckBox *checkBox : metrics) { + checkBox->setChecked(false); + } } void SelectMetrics::on_selectAllButton_clicked() { - for(QCheckBox* checkBox : metrics) - { + for (QCheckBox *checkBox : metrics) { checkBox->setChecked(true); } } bool SelectMetrics::isThereAnyMetricSelected() { - for(QCheckBox* checkBox : metrics) - { - if(checkBox->isChecked()) - return true; + for (QCheckBox *checkBox : metrics) { + if (checkBox->isChecked()) + return true; } return false; } void SelectMetrics::setMetrics(std::vector metrics) { - if(this->metrics.size() != metrics.size()) - { - for(QCheckBox* checkBox : this->metrics) - { + if (this->metrics.size() != metrics.size()) { + for (QCheckBox *checkBox : this->metrics) { layout->removeWidget(checkBox); } this->metrics.clear(); - for(std::string metric : metrics) - { - QCheckBox * checkBox = new QCheckBox(); + for (std::string metric : metrics) { + QCheckBox *checkBox = new QCheckBox(); checkBox->setObjectName (QString::fromStdString(metric)); checkBox->setCheckable (true); checkBox->setChecked (true); diff --git a/DRAMSys/traceAnalyzer/selectmetrics.h b/DRAMSys/traceAnalyzer/selectmetrics.h index 63b82259..182d6f34 100644 --- a/DRAMSys/traceAnalyzer/selectmetrics.h +++ b/DRAMSys/traceAnalyzer/selectmetrics.h @@ -55,7 +55,7 @@ public: explicit SelectMetrics(QWidget *parent = 0); ~SelectMetrics(); - std::vector metrics; + std::vector metrics; void setMetrics(std::vector metrics); @@ -71,7 +71,7 @@ private Q_SLOTS: private: Ui::SelectMetrics *ui; - QVBoxLayout* layout; + QVBoxLayout *layout; bool isThereAnyMetricSelected(); }; diff --git a/DRAMSys/traceAnalyzer/traceanalyzer.cpp b/DRAMSys/traceAnalyzer/traceanalyzer.cpp index 55ecbd86..1b7cb66a 100644 --- a/DRAMSys/traceAnalyzer/traceanalyzer.cpp +++ b/DRAMSys/traceAnalyzer/traceanalyzer.cpp @@ -71,17 +71,17 @@ TraceAnalyzer::TraceAnalyzer(QWidget *parent) : ui->actionMetrics->setEnabled(false); } -TraceAnalyzer::TraceAnalyzer(QSet paths, StartupOption option, QWidget *parent): +TraceAnalyzer::TraceAnalyzer(QSet paths, StartupOption option, + QWidget *parent): QMainWindow(parent), ui(new Ui::TraceAnalyzer) { setUpGui(); - for(const QString& path : paths) + for (const QString &path : paths) openTracefile(path); - if(option == StartupOption::runTests) - { + if (option == StartupOption::runTests) { ui->actionTest->trigger(); } } @@ -97,25 +97,24 @@ void TraceAnalyzer::on_actionOpen_triggered() tr("Open Tracefile"), "../simulator/", tr("Tracefile (*.tdb)")); - if(paths.isEmpty()) - { + if (paths.isEmpty()) { return; } - for(const QString &path: paths) - { + for (const QString &path : paths) { openTracefile(path); } } void TraceAnalyzer::openTracefile(const QString &path) { - if(openedTraceFiles.contains(path)) + if (openedTraceFiles.contains(path)) return; - TraceFileTab* tab = new TraceFileTab(this, path); - connect(tab, SIGNAL(statusChanged(QString, bool)), this, SLOT(statusChanged(QString, bool))); - ui->traceFileTabs->addTab(tab,QFileInfo(path).baseName()); + TraceFileTab *tab = new TraceFileTab(this, path); + connect(tab, SIGNAL(statusChanged(QString, bool)), this, + SLOT(statusChanged(QString, bool))); + ui->traceFileTabs->addTab(tab, QFileInfo(path).baseName()); openedTraceFiles.insert(path); // Enable actions @@ -130,7 +129,8 @@ void TraceAnalyzer::openTracefile(const QString &path) void TraceAnalyzer::on_traceFileTabs_tabCloseRequested(int index) { - TraceFileTab* traceFileTab = static_cast(ui->traceFileTabs->widget(index)); + TraceFileTab *traceFileTab = static_cast + (ui->traceFileTabs->widget(index)); openedTraceFiles.remove(traceFileTab->getPathToTraceFile()); ui->traceFileTabs->removeTab(index); delete traceFileTab; @@ -138,7 +138,7 @@ void TraceAnalyzer::on_traceFileTabs_tabCloseRequested(int index) void TraceAnalyzer::on_actionClose_all_triggered() { - while(ui->traceFileTabs->count()) + while (ui->traceFileTabs->count()) on_traceFileTabs_tabCloseRequested(0); // All files closed. Disable actions except for "Open". @@ -158,8 +158,9 @@ void TraceAnalyzer::on_actionReload_all_triggered() // Remove all tabs int tabIndex = 0; while (ui->traceFileTabs->count() != 0) { - traceFileTab = static_cast(ui->traceFileTabs->widget(0)); - std::cout << "Closing tab #" << tabIndex << " \"" << traceFileTab->getPathToTraceFile().toStdString() << "\"" << std::endl; + traceFileTab = static_cast(ui->traceFileTabs->widget(0)); + std::cout << "Closing tab #" << tabIndex << " \"" << + traceFileTab->getPathToTraceFile().toStdString() << "\"" << std::endl; ui->traceFileTabs->removeTab(0); delete traceFileTab; @@ -173,10 +174,12 @@ void TraceAnalyzer::on_actionReload_all_triggered() // Recreate all tabs tabIndex = 0; for (auto path : list) { - std::cout << "Reopening tab# " << tabIndex << " \"" << path.toStdString() << "\"" << std::endl; + std::cout << "Reopening tab# " << tabIndex << " \"" << path.toStdString() << + "\"" << std::endl; traceFileTab = new TraceFileTab(this, path); - connect(traceFileTab, SIGNAL(statusChanged(QString, bool)), this, SLOT(statusChanged(QString, bool))); + connect(traceFileTab, SIGNAL(statusChanged(QString, bool)), this, + SLOT(statusChanged(QString, bool))); ui->traceFileTabs->addTab(traceFileTab, QFileInfo(path).baseName()); tabIndex++; @@ -190,7 +193,8 @@ void TraceAnalyzer::on_actionSaveChangesToDB_triggered() for (int index = 0; index < ui->traceFileTabs->count(); index++) { // Changes in the database files will trigger the file watchers from // the TraceFileTab class. They generate signals connected to TraceAnalyzer::statusChanged(). - TraceFileTab *traceFileTab = static_cast(ui->traceFileTabs->widget(index)); + TraceFileTab *traceFileTab = static_cast + (ui->traceFileTabs->widget(index)); traceFileTab->commitChangesToDB(); } } diff --git a/DRAMSys/traceAnalyzer/traceanalyzer.h b/DRAMSys/traceAnalyzer/traceanalyzer.h index f1c04887..b9a36059 100644 --- a/DRAMSys/traceAnalyzer/traceanalyzer.h +++ b/DRAMSys/traceAnalyzer/traceanalyzer.h @@ -49,8 +49,8 @@ namespace Ui { class TraceAnalyzer; } -enum class StartupOption{showPlots,runTests}; -enum class OpenOptions{files,folders}; +enum class StartupOption {showPlots, runTests}; +enum class OpenOptions {files, folders}; class TraceAnalyzer : public QMainWindow { @@ -58,7 +58,8 @@ class TraceAnalyzer : public QMainWindow public: explicit TraceAnalyzer(QWidget *parent = 0); - explicit TraceAnalyzer(QSet paths, StartupOption option, QWidget *parent = 0); + explicit TraceAnalyzer(QSet paths, StartupOption option, + QWidget *parent = 0); ~TraceAnalyzer(); EvaluationTool evaluationTool; diff --git a/DRAMSys/traceAnalyzer/tracefiletab.cpp b/DRAMSys/traceAnalyzer/tracefiletab.cpp index e2132d84..bf0ff6ef 100644 --- a/DRAMSys/traceAnalyzer/tracefiletab.cpp +++ b/DRAMSys/traceAnalyzer/tracefiletab.cpp @@ -42,17 +42,19 @@ #include "qmessagebox.h" #include -TraceFileTab::TraceFileTab(QWidget *parent,const QString& path) : +TraceFileTab::TraceFileTab(QWidget *parent, const QString &path) : QWidget(parent), ui(new Ui::TraceFileTab), savingChangesToDB(false) { ui->setupUi(this); this->path = path; - std::cout << "Opening new tab for \"" << path.toStdString() << "\"" << std::endl; + std::cout << "Opening new tab for \"" << path.toStdString() << "\"" << + std::endl; initNavigatorAndItsDependentWidgets(path); setUpFileWatcher(path); - ui->fileDescriptionEdit->setPlainText(navigator->GeneralTraceInfo().description); + ui->fileDescriptionEdit->setPlainText( + navigator->GeneralTraceInfo().description); tracefileChanged(); } @@ -69,12 +71,13 @@ void TraceFileTab::commitChangesToDB() void TraceFileTab::initNavigatorAndItsDependentWidgets(QString path) { - navigator = new TraceNavigator(path,this); + navigator = new TraceNavigator(path, this); ui->traceplot->init(navigator); ui->pornoTraceScroller->init(navigator, ui->traceplot); - connect(this,SIGNAL(colorGroupingChanged(ColorGrouping)),ui->pornoTraceScroller,SLOT(colorGroupingChanged(ColorGrouping))); + connect(this, SIGNAL(colorGroupingChanged(ColorGrouping)), + ui->pornoTraceScroller, SLOT(colorGroupingChanged(ColorGrouping))); ui->selectedTransactionTree->init(navigator); //ui->debugMessages->init(navigator,ui->traceplot); @@ -84,8 +87,9 @@ void TraceFileTab::initNavigatorAndItsDependentWidgets(QString path) void TraceFileTab::setUpFileWatcher(QString path) { - fileWatcher = new QFileSystemWatcher(QStringList(path),this); - QObject::connect(fileWatcher,SIGNAL(fileChanged(QString)),this,SLOT(tracefileChanged())); + fileWatcher = new QFileSystemWatcher(QStringList(path), this); + QObject::connect(fileWatcher, SIGNAL(fileChanged(QString)), this, + SLOT(tracefileChanged())); } void TraceFileTab::tracefileChanged() @@ -100,7 +104,8 @@ void TraceFileTab::tracefileChanged() // was overwritten when running a new test). // The "Save changes to DB" menu must be disabled to avoid saving // changes to a corrupted or inconsistent file. - Q_EMIT statusChanged(QString("At least one database has changed on disk "), false); + Q_EMIT statusChanged(QString("At least one database has changed on disk "), + false); } navigator->refreshData(); } diff --git a/DRAMSys/traceAnalyzer/tracefiletab.h b/DRAMSys/traceAnalyzer/tracefiletab.h index 5acaa96a..3bef247c 100644 --- a/DRAMSys/traceAnalyzer/tracefiletab.h +++ b/DRAMSys/traceAnalyzer/tracefiletab.h @@ -54,12 +54,15 @@ class TraceFileTab : public QWidget Q_OBJECT public: - explicit TraceFileTab(QWidget *parent,const QString& path); + explicit TraceFileTab(QWidget *parent, const QString &path); ~TraceFileTab(); void setUpFileWatcher(QString filename); void initNavigatorAndItsDependentWidgets(QString path); - QString getPathToTraceFile(){return path;} + QString getPathToTraceFile() + { + return path; + } void commitChangesToDB(void); private: @@ -71,7 +74,7 @@ private: bool savingChangesToDB; public Q_SLOTS: - void tracefileChanged(); + void tracefileChanged(); Q_SIGNALS: void statusChanged(QString message, bool saveChangesEnable = false); From 7aa8983051b988f0806fa43d647b7c4ff096fabc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Tue, 29 May 2018 19:09:30 +0200 Subject: [PATCH 29/38] PEP8 --- DRAMSys/library/resources/scripts/trace_gen.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/DRAMSys/library/resources/scripts/trace_gen.py b/DRAMSys/library/resources/scripts/trace_gen.py index cbbff5a2..2efb4012 100755 --- a/DRAMSys/library/resources/scripts/trace_gen.py +++ b/DRAMSys/library/resources/scripts/trace_gen.py @@ -131,7 +131,7 @@ for ch in range(0, num_ch): for row in range(0, num_rows): address = set_bits(row_mask, row_shift, address, row) for col in range(0, num_col, burst_len): - address = set_bits(col_mask, col_shift, address, col) - print('# clock cycle: {0:d} | {1} | address: 0x{2:010X} | channel: {3} | bank group: {4} | bank: {5} | row: {6} | column: {7}'.format(clock_cycle, transaction, address, ch, bg, b, row, col)) - print('{0:d}:\t{1}\t0x{2:010X}'.format(clock_cycle, transaction, address)) - clock_cycle = clock_cycle + clock_increment + address = set_bits(col_mask, col_shift, address, col) + print('# clock cycle: {0:d} | {1} | address: 0x{2:010X} | channel: {3} | bank group: {4} | bank: {5} | row: {6} | column: {7}'.format(clock_cycle, transaction, address, ch, bg, b, row, col)) + print('{0:d}:\t{1}\t0x{2:010X}'.format(clock_cycle, transaction, address)) + clock_cycle = clock_cycle + clock_increment From bf6558a231a92c70faec6611b011588b7a145f1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Tue, 29 May 2018 19:17:19 +0200 Subject: [PATCH 30/38] doc updated --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/README.md b/README.md index d2ab4e5e..7d1c1b94 100644 --- a/README.md +++ b/README.md @@ -791,6 +791,15 @@ sim_files=" " ``` +**Traces to be used in each of the simulation setups have to be explicitly added to the traces list**. + +```bash +traces=" +ddr3_example.stl +mediabench-unepic_32.stl +" +``` + The script runs one instance of DRAMSys for each of the files in the list. **The multiple instances run in parallel**. For more information check the documentation in [DRAMSylva folder](DRAMSys/library/resources/scripts/DRAMSylva). From 9945db4f4bd8ab035ad8c4863646181d9143cfee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Wed, 30 May 2018 10:12:40 +0200 Subject: [PATCH 31/38] doc updated --- README.md | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 7d1c1b94..b42de057 100644 --- a/README.md +++ b/README.md @@ -118,15 +118,15 @@ $ cd ~/qwt-6.1 $ sudo make install ``` -For further information refer to [this](http://qwt.sourceforge.net/) +Further information about Qwt can be found [here](http://qwt.sourceforge.net/). To grant flexibility to the user the paths where to find some essential libraries and headers can be specified with environment variables. Make sure you have the environment variables below in your ~/.bashrc file. -Note that some of the variables are automatically generated by the scripts. If +**Note that some of the variables are automatically generated by the scripts. If you install the libraries in custom paths in your system you have to adapt the -environment variables accordingly. +environment variables accordingly**. ```bash # SystemC home and target architecture @@ -146,7 +146,14 @@ export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${SYSTEMC_HOME}/lib-$SYSTEMC_TARGET_AR ### Coding Style -Please read the [coding-style document](coding-style.md) before start coding. +Please read the [coding-style document](coding-style.md) before starting to +code. + +A script is provided to apply the coding style. +```bash +$ cd util +$ ./make_pretty.sh +``` ### Buiding with QTCreator Execute the *QTCreator*. @@ -791,7 +798,10 @@ sim_files=" " ``` -**Traces to be used in each of the simulation setups have to be explicitly added to the traces list**. +**Traces have to be explicitly added to the traces list**. A new simulation +is defined by a combination of two elements, one from the simulation files +list and the other from the traces list. Thus the number of simulations +executed is the number of simulation files multiplied by the number of traces. ```bash traces=" @@ -841,8 +851,7 @@ Bank (B): 8 [30:32] (BA0 - BA2) -> 3 bit B B B | R R R R R R R R R R R R R R R R R | C C C C C C C C C C | Y Y Y ``` -The parameters for the DDR3-SDRAM DIMM with address mapping presented above -are presented below. +The parameters for the address mapping just described are presented below. ``` # Channel information. From 136da88b748d0844694358a5e513d17af3ff19d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Mon, 4 Jun 2018 16:38:21 +0200 Subject: [PATCH 32/38] Fix bug introduced in pr#191 --- DRAMSys/traceAnalyzer/presentation/transactiontreewidget.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DRAMSys/traceAnalyzer/presentation/transactiontreewidget.cpp b/DRAMSys/traceAnalyzer/presentation/transactiontreewidget.cpp index 849da090..49211af4 100644 --- a/DRAMSys/traceAnalyzer/presentation/transactiontreewidget.cpp +++ b/DRAMSys/traceAnalyzer/presentation/transactiontreewidget.cpp @@ -107,7 +107,7 @@ TransactionTreeWidget::TransactionTreeItem::TransactionTreeItem( this->addChild(new QTreeWidgetItem( {"Column", QString::number(transaction->Column())} )); this->addChild(new QTreeWidgetItem( {"Address", QString("0x") + QString::number(transaction->Address(), 16)} )); - if (!transaction->Thread() != controllerThread) { + if (transaction->Thread() != controllerThread) { this->addChild(new QTreeWidgetItem( {"Burstlength", QString::number(transaction->Burstlength())})); this->addChild(new QTreeWidgetItem( {"Thread", QString::number(transaction->Thread())})); } From 457dce57b24ae5ca72fe90173339c7f7a8630d1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Mon, 4 Jun 2018 16:44:36 +0200 Subject: [PATCH 33/38] Some warnings eliminated. 9 warnings to go, all from external code (e.g., systemc lib). --- .../src/controller/scheduler/Fr_Fcfs_read_priority.cpp | 1 + DRAMSys/library/src/simulation/TracePlayer.cpp | 2 +- DRAMSys/traceAnalyzer/businessObjects/transaction.cpp | 5 +++-- DRAMSys/traceAnalyzer/businessObjects/transaction.h | 8 ++++---- 4 files changed, 9 insertions(+), 7 deletions(-) diff --git a/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_read_priority.cpp b/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_read_priority.cpp index 66b1f260..57c2f60f 100644 --- a/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_read_priority.cpp +++ b/DRAMSys/library/src/controller/scheduler/Fr_Fcfs_read_priority.cpp @@ -108,6 +108,7 @@ std::pair FR_FCFS_RP::getNextRequest(Bank bank) } reportFatal("FR_FCFS_RP", "Never should go here ..."); + return pair(Command::NOP, NULL); } // There is a hazard if a read is found which will be scheduled before a write diff --git a/DRAMSys/library/src/simulation/TracePlayer.cpp b/DRAMSys/library/src/simulation/TracePlayer.cpp index 9eeb56d1..581098a3 100644 --- a/DRAMSys/library/src/simulation/TracePlayer.cpp +++ b/DRAMSys/library/src/simulation/TracePlayer.cpp @@ -40,9 +40,9 @@ TracePlayer::TracePlayer(TracePlayerListener *listener) : payloadEventQueue(this, &TracePlayer::peqCallback), + numberOfTransactions(0), transactionsSent(0), transactionsReceived(0), - numberOfTransactions(0), listener(listener), finished(false) { diff --git a/DRAMSys/traceAnalyzer/businessObjects/transaction.cpp b/DRAMSys/traceAnalyzer/businessObjects/transaction.cpp index 8d1d72ab..9bdec5f5 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/transaction.cpp +++ b/DRAMSys/traceAnalyzer/businessObjects/transaction.cpp @@ -39,8 +39,9 @@ using namespace std; Transaction::Transaction(ID id, unsigned int address, unsigned int burstlength, - int thread, unsigned int channel, unsigned int bank, unsigned int bankgroup, - unsigned int row, unsigned int column, Timespan span, Timespan spanOnDataStrobe) + unsigned int thread, unsigned int channel, unsigned int bank, + unsigned int bankgroup, unsigned int row, unsigned int column, Timespan span, + Timespan spanOnDataStrobe) : address(address), burstlength(burstlength), thread(thread), channel(channel), bank(bank), bankgroup(bankgroup), row(row), column(column), span(span), spanOnDataStrobe(spanOnDataStrobe), id(id) {} diff --git a/DRAMSys/traceAnalyzer/businessObjects/transaction.h b/DRAMSys/traceAnalyzer/businessObjects/transaction.h index 2bfbe1a9..767c4f48 100644 --- a/DRAMSys/traceAnalyzer/businessObjects/transaction.h +++ b/DRAMSys/traceAnalyzer/businessObjects/transaction.h @@ -56,9 +56,9 @@ private: std::vector> phases; public: - Transaction(ID id, unsigned int address, unsigned int burstlength, int thread, - unsigned int channel, unsigned int bank, unsigned int bankgroup, - unsigned int row, unsigned int column, Timespan span, + Transaction(ID id, unsigned int address, unsigned int burstlength, + unsigned int thread, unsigned int channel, unsigned int bank, + unsigned int bankgroup, unsigned int row, unsigned int column, Timespan span, Timespan spanOnDataStrobe); void draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, @@ -77,7 +77,7 @@ public: { return burstlength; } - int Thread() + unsigned int Thread() { return thread; } From 8a787ad14fc990de16fb753aa0aaf2c160e390a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Mon, 4 Jun 2018 16:54:14 +0200 Subject: [PATCH 34/38] Simulation ID (optional) If a simulation file is passed as argument to DRAMSys the simulation ID is prepended to the simulation name if found. E.g.: ... --- DRAMSys/library/src/simulation/DRAMSys.cpp | 23 ++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/DRAMSys/library/src/simulation/DRAMSys.cpp b/DRAMSys/library/src/simulation/DRAMSys.cpp index 25c93ad6..3d9829db 100644 --- a/DRAMSys/library/src/simulation/DRAMSys.cpp +++ b/DRAMSys/library/src/simulation/DRAMSys.cpp @@ -122,9 +122,28 @@ DRAMSys::DRAMSys(sc_module_name __attribute__((unused)) name, + "configs/thermalsim/" + thermalconfig); + // If a simulation file is passed as argument to DRAMSys the simulation ID + // is prepended to the simulation name if found. + std::string simName; + simName = Configuration::getInstance().SimulationName; + tinyxml2::XMLDocument simulationdoc; + loadXML(simulationToRun, simulationdoc); + tinyxml2::XMLElement *simulation = simulationdoc.FirstChildElement("simulation"); + if (simulation != NULL) { + tinyxml2::XMLElement *simid = simulation->FirstChildElement("simulationid"); + if (simid != NULL) { + auto r = simid->Attribute("id"); + if (r != NULL) { + std::string sid; + sid = r; + simName = sid + '_' + Configuration::getInstance().SimulationName; + } + } + } + cout << "Simulation name set to: " << simName << endl; + // Instantiate all internal DRAMSys modules: - instantiateModules(Configuration::getInstance().SimulationName, - pathToResources); + instantiateModules(simName, pathToResources); // Connect all internal DRAMSys modules: bindSockets(); From 8d6b6054198415e68ef2e6ea5b3197f344d8400c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Mon, 4 Jun 2018 17:03:34 +0200 Subject: [PATCH 35/38] Doc updated --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index b42de057..ed2b86e2 100644 --- a/README.md +++ b/README.md @@ -329,6 +329,8 @@ The XML code below shows a typic configuration: ``` xml + + From b59dd058ca25b97f18d4ce31b1999ab2adbde894 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89der=20F=2E=20Zulian?= Date: Mon, 4 Jun 2018 18:38:12 +0200 Subject: [PATCH 36/38] Trace list made optional in DRAMSylva --- README.md | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index ed2b86e2..f1d61991 100644 --- a/README.md +++ b/README.md @@ -800,10 +800,20 @@ sim_files=" " ``` -**Traces have to be explicitly added to the traces list**. A new simulation -is defined by a combination of two elements, one from the simulation files -list and the other from the traces list. Thus the number of simulations -executed is the number of simulation files multiplied by the number of traces. +Set the variable **use_trace_list** to **yes** in order to use all traces +from the trace list for all simulation files. Each pair generates a new +simulation. Otherwise it runs a simulation per simulation file. The trace +specified inside the simulation file is used. + +``` bash +use_trace_list="yes" +``` + +When you choose **yes** then **traces have to be explicitly added to the traces +list**. A new simulation is defined by a combination of two elements, one from +the simulation files list and the other from the traces list. Thus the number +of simulations executed is the number of simulation files multiplied by the +number of traces. ```bash traces=" @@ -812,7 +822,8 @@ mediabench-unepic_32.stl " ``` -The script runs one instance of DRAMSys for each of the files in the list. **The multiple instances run in parallel**. +The script runs one instance of DRAMSys for each of the files in the list. +**The multiple instances run in parallel**. For more information check the documentation in [DRAMSylva folder](DRAMSys/library/resources/scripts/DRAMSylva). From e75dbcd0984c3bb9ca51f895dcf94d7ba7b5e430 Mon Sep 17 00:00:00 2001 From: Matthias Jung Date: Fri, 8 Jun 2018 14:28:42 +0200 Subject: [PATCH 37/38] Add README.md to DRAMSys.pro --- DRAMSys/DRAMSys.pro | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DRAMSys/DRAMSys.pro b/DRAMSys/DRAMSys.pro index 8b03c967..3653e3bf 100644 --- a/DRAMSys/DRAMSys.pro +++ b/DRAMSys/DRAMSys.pro @@ -39,3 +39,5 @@ simulator.depends = library # Additional Files: # tests folder (DRAMSys/tests) include(tests/tests.pri) + +DISTFILES += ../README.md From 412630122cf2b56ab439288e19527971fd35851c Mon Sep 17 00:00:00 2001 From: Matthias Jung Date: Fri, 8 Jun 2018 14:30:53 +0200 Subject: [PATCH 38/38] Added Information about Windows Compiling --- README.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f1d61991..3402229f 100644 --- a/README.md +++ b/README.md @@ -217,7 +217,7 @@ $ export QT_QPA_PLATFORMTHEME=qgnomeplatform $ ./traceAnalyzer ``` -### Building on OSX +### Building on MacOS (Formerly OSX) - Install XCode - Install SystemC manually in /opt: @@ -319,6 +319,21 @@ $ make -j Now you can try to run DRAMSys and traceAnalyzer App inside folder simulator and traceAnalyzer, respectively +### Building on Windows 10 + +DRAMSys can also run on Windows 10 with the *Windows Subsystem for Linux* (WSL) feature. You can install a linux distribution like Debian over the windows app store. +We refer to the following example [website](https://docs.microsoft.com/en-us/windows/wsl/install-win10). + +Then DRAMSys can be installed as described above for Linux. However it might be advisable to install Qt, SystemC and qwt by hand. Qt should be downloaded from the Qt website. +The install systemc.sh script can be used to install SystemC and for QWT the version 6.1.3 should be used. + +Also the build configuration for SystemC should be configured as static with pthreads in the ```simulator.pro``` file: + +```qmake + #LIBS += -L$${systemc_home}/lib-$${systemc_target_arch} -lsystemc + LIBS += -L$${systemc_home}/lib-$${systemc_target_arch} -Wl,-Bstatic -lsystemc -Wl,-Bdynamic -pthread +``` + ### DRAMSys Configuration The **DRAMSys** executable supports one argument which is a XML file that