text
stringlengths 41
20k
|
---|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_lstm_input_trainer_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
adder adder("ADDER");
sc_signal<int> Ain;
sc_signal<int> Bin;
sc_signal<bool> clock;
sc_signal<int> out;
adder(clock, Ain, Bin, out);
Ain = 1;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
Ain = 2;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_lstm_input_trainer_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
adder adder("ADDER");
sc_signal<int> Ain;
sc_signal<int> Bin;
sc_signal<bool> clock;
sc_signal<int> out;
adder(clock, Ain, Bin, out);
Ain = 1;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
Ain = 2;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_lstm_output_trainer_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
adder adder("ADDER");
sc_signal<int> Ain;
sc_signal<int> Bin;
sc_signal<bool> clock;
sc_signal<int> out;
adder(clock, Ain, Bin, out);
Ain = 1;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
Ain = 2;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_lstm_output_trainer_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
adder adder("ADDER");
sc_signal<int> Ain;
sc_signal<int> Bin;
sc_signal<bool> clock;
sc_signal<int> out;
adder(clock, Ain, Bin, out);
Ain = 1;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
Ain = 2;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_lstm_output_trainer_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
adder adder("ADDER");
sc_signal<int> Ain;
sc_signal<int> Bin;
sc_signal<bool> clock;
sc_signal<int> out;
adder(clock, Ain, Bin, out);
Ain = 1;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
Ain = 2;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
return 0;
}
|
//This the top level structural host module
//PS, dont forget to link systemc, stdc++, and m
#include <systemc.h>
#include "fir.h"
#include "tb.h"
SC_MODULE( SYSTEM )
{
//module declarations
//Done by doing module_name Pointer_to_instance i.e. name *iname;
tb *tb0;
fir *fir0;
//signal declarations
sc_signal<bool> rst_sig;
sc_signal< sc_int<16> > inp_sig;
sc_signal< sc_int<16> > outp_sig;
sc_clock clk_sig;
sc_signal<bool> inp_sig_vld;
sc_signal<bool> inp_sig_rdy;
sc_signal<bool> outp_sig_vld;
sc_signal<bool> outp_sig_rdy;
//module instance signal connections
//There are three arguements
//The first is a character pointer string and can be anything you want
//The second is the number of units long the clock signal is
//The third arguement is a sc_time_unit
//SC_US is microsecond units
//SC_NS is nanoseconds units
//SC_PS is picoseconds units
//This is a copy constructor the the clock class will generate a repetitive clock signal
SC_CTOR( SYSTEM )
: clk_sig ("clk_sig_name", 10, SC_NS)
{
//Since these are SC_MODULES we need to pass the a charcter pointer string
tb0 = new tb("tb0");
fir0 = new fir("fir0");
//Since these are pointers (new allocates memory and returns a pointer to the first
// location in that memory) we can use the arrow style derefferencing operator to
// specify a particular port and then bind it to a signal with parenthesis
tb0->clk( clk_sig );
tb0->rst( rst_sig );
tb0->inp( inp_sig );
tb0->outp( outp_sig );
fir0->clk( clk_sig );
fir0->rst( rst_sig );
fir0->inp( inp_sig );
fir0->outp( outp_sig );
tb0->inp_sig_vld( inp_sig_vld );
tb0->inp_sig_rdy( inp_sig_rdy );
tb0->outp_sig_vld( outp_sig_vld );
tb0->outp_sig_rdy( outp_sig_rdy );
fir0->inp_sig_vld( inp_sig_vld );
fir0->inp_sig_rdy( inp_sig_rdy );
fir0->outp_sig_vld( outp_sig_vld );
fir0->outp_sig_rdy( outp_sig_rdy );
}
//Destructor
~SYSTEM()
{
//free the memory up from the functions that are no longer needed
delete tb0;
delete fir0;
}
};
//Module declaration just like we did in main for fir and tb but we just assign at
//instantiation time NULL, could have done this above as well
SYSTEM *top = NULL;
//Make it int in case the compiler requires it
int sc_main( int argc, char *argv[])
{
top = new SYSTEM( "top" );
sc_start();
return 0;
}
/*
This is what you need to ad to your make file to auto check results
GOLD_DIR = ./golden
GOLD_FILE = $(GOLD_DIR)/ref_output.dat
cmp_result:
@echo "*******************************************************"
@if diff -w $(GOLD_FILE) ./output.dat; then \
echo "SIMULAITON PASSED"; \
else \
echo "SIMULATION FAILED"; \
fi
@echo "*******************************************************"
*/
/*
* sc_time represents anything in systemc that can be measured in time units
*
*/
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_lstm_output_trainer_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
adder adder("ADDER");
sc_signal<int> Ain;
sc_signal<int> Bin;
sc_signal<bool> clock;
sc_signal<int> out;
adder(clock, Ain, Bin, out);
Ain = 1;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
Ain = 2;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "systemc.h"
#define SIZE_I_IN 4
#define SIZE_J_IN 4
#define SIZE_K_IN 4
SC_MODULE(tensor_matrix_convolution) {
sc_in_clk clock;
sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN];
sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN];
sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN];
SC_CTOR(tensor_matrix_convolution) {
SC_METHOD(convolution);
sensitive << clock.pos();
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
sensitive << data_a_in[i][j][k];
}
sensitive << data_b_in[i][j];
}
}
}
void convolution() {
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
int temporal = 0;
for (int m = 0; m < i; m++) {
for (int n = 0; n < j; n++) {
for (int p = 0; p < k; p++) {
temporal += data_a_in[m][n][p].read() * data_b_in[i - m][j - n].read();
}
}
}
data_out[i][j] = temporal;
}
}
}
}
};
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "systemc.h"
#define SIZE_I_IN 4
#define SIZE_J_IN 4
#define SIZE_K_IN 4
SC_MODULE(tensor_matrix_convolution) {
sc_in_clk clock;
sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN];
sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN];
sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN];
SC_CTOR(tensor_matrix_convolution) {
SC_METHOD(convolution);
sensitive << clock.pos();
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
sensitive << data_a_in[i][j][k];
}
sensitive << data_b_in[i][j];
}
}
}
void convolution() {
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
int temporal = 0;
for (int m = 0; m < i; m++) {
for (int n = 0; n < j; n++) {
for (int p = 0; p < k; p++) {
temporal += data_a_in[m][n][p].read() * data_b_in[i - m][j - n].read();
}
}
}
data_out[i][j] = temporal;
}
}
}
}
};
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "systemc.h"
#define SIZE_I_IN 4
#define SIZE_J_IN 4
#define SIZE_K_IN 4
SC_MODULE(tensor_matrix_convolution) {
sc_in_clk clock;
sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN];
sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN];
sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN];
SC_CTOR(tensor_matrix_convolution) {
SC_METHOD(convolution);
sensitive << clock.pos();
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
sensitive << data_a_in[i][j][k];
}
sensitive << data_b_in[i][j];
}
}
}
void convolution() {
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
int temporal = 0;
for (int m = 0; m < i; m++) {
for (int n = 0; n < j; n++) {
for (int p = 0; p < k; p++) {
temporal += data_a_in[m][n][p].read() * data_b_in[i - m][j - n].read();
}
}
}
data_out[i][j] = temporal;
}
}
}
}
};
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "systemc.h"
#define SIZE_I_IN 4
#define SIZE_J_IN 4
#define SIZE_K_IN 4
SC_MODULE(tensor_matrix_convolution) {
sc_in_clk clock;
sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN];
sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN];
sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN];
SC_CTOR(tensor_matrix_convolution) {
SC_METHOD(convolution);
sensitive << clock.pos();
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
sensitive << data_a_in[i][j][k];
}
sensitive << data_b_in[i][j];
}
}
}
void convolution() {
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
int temporal = 0;
for (int m = 0; m < i; m++) {
for (int n = 0; n < j; n++) {
for (int p = 0; p < k; p++) {
temporal += data_a_in[m][n][p].read() * data_b_in[i - m][j - n].read();
}
}
}
data_out[i][j] = temporal;
}
}
}
}
};
|
/*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
/*****************************************************************************
display.cpp --
Original Author: Rocco Jonack, Synopsys, Inc.
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation: Teodor Vasilache and Dragos Dospinescu,
AMIQ Consulting s.r.l. ([email protected])
Date: 2018-Feb-20
Description of Modification: Included the FC4SC library in order to collect
functional coverage data and generate a coverage database.
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
#include <systemc.h>
#include "display.h"
#include "fc4sc.hpp"
void display::entry(){
// Reading Data when valid if high
tmp1 = result.read();
cout << "Display : " << tmp1 << " "
/* << " at time " << sc_time_stamp() << endl; */
<< " at time " << sc_time_stamp().to_double() << endl;
i++;
// sample the data
this->out_cg.sample(result, output_data_ready);
if(i == 24) {
cout << "Simulation of " << i << " items finished"
/* << " at time " << sc_time_stamp() << endl; */
<< " at time " << sc_time_stamp().to_double() << endl;
// generate the coverage database from the collected data
fc4sc::global::coverage_save("coverage_results.xml");
sc_stop();
};
}
// EOF
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_scalar_deviation_function_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
adder adder("ADDER");
sc_signal<int> Ain;
sc_signal<int> Bin;
sc_signal<bool> clock;
sc_signal<int> out;
adder(clock, Ain, Bin, out);
Ain = 1;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
Ain = 2;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_scalar_deviation_function_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
adder adder("ADDER");
sc_signal<int> Ain;
sc_signal<int> Bin;
sc_signal<bool> clock;
sc_signal<int> out;
adder(clock, Ain, Bin, out);
Ain = 1;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
Ain = 2;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_scalar_deviation_function_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
adder adder("ADDER");
sc_signal<int> Ain;
sc_signal<int> Bin;
sc_signal<bool> clock;
sc_signal<int> out;
adder(clock, Ain, Bin, out);
Ain = 1;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
Ain = 2;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_scalar_deviation_function_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
adder adder("ADDER");
sc_signal<int> Ain;
sc_signal<int> Bin;
sc_signal<bool> clock;
sc_signal<int> out;
adder(clock, Ain, Bin, out);
Ain = 1;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
Ain = 2;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
return 0;
}
|
#include <systemc.h>
#include "Producer.h"
#include "Consumer.h"
int sc_main(int argc, char* argv[])
{
// generating the sc_signal
sc_signal<int> data_sig;
// generating the modules
Producer prod1("Producer1");
Consumer cons1("Consumer1");
// connecting modules via signals
prod1.data(data_sig);
cons1.data(data_sig);
// Run the simulation till sc_stop is encountered
sc_start();
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_vector_multiplication_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
adder adder("ADDER");
sc_signal<int> Ain;
sc_signal<int> Bin;
sc_signal<bool> clock;
sc_signal<int> out;
adder(clock, Ain, Bin, out);
Ain = 1;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
Ain = 2;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_vector_multiplication_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
adder adder("ADDER");
sc_signal<int> Ain;
sc_signal<int> Bin;
sc_signal<bool> clock;
sc_signal<int> out;
adder(clock, Ain, Bin, out);
Ain = 1;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
Ain = 2;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_vector_multiplication_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
adder adder("ADDER");
sc_signal<int> Ain;
sc_signal<int> Bin;
sc_signal<bool> clock;
sc_signal<int> out;
adder(clock, Ain, Bin, out);
Ain = 1;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
Ain = 2;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_vector_multiplication_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
adder adder("ADDER");
sc_signal<int> Ain;
sc_signal<int> Bin;
sc_signal<bool> clock;
sc_signal<int> out;
adder(clock, Ain, Bin, out);
Ain = 1;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
Ain = 2;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_lstm_input_d_trainer_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
adder adder("ADDER");
sc_signal<int> Ain;
sc_signal<int> Bin;
sc_signal<bool> clock;
sc_signal<int> out;
adder(clock, Ain, Bin, out);
Ain = 1;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
Ain = 2;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_lstm_input_d_trainer_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
adder adder("ADDER");
sc_signal<int> Ain;
sc_signal<int> Bin;
sc_signal<bool> clock;
sc_signal<int> out;
adder(clock, Ain, Bin, out);
Ain = 1;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
Ain = 2;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_lstm_input_d_trainer_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
adder adder("ADDER");
sc_signal<int> Ain;
sc_signal<int> Bin;
sc_signal<bool> clock;
sc_signal<int> out;
adder(clock, Ain, Bin, out);
Ain = 1;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
Ain = 2;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_lstm_input_d_trainer_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
adder adder("ADDER");
sc_signal<int> Ain;
sc_signal<int> Bin;
sc_signal<bool> clock;
sc_signal<int> out;
adder(clock, Ain, Bin, out);
Ain = 1;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
Ain = 2;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_vector_adder_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
vector_adder vector_adder("VECTOR_ADDER");
sc_signal<bool> clock;
sc_signal<sc_int<64>> data_a_in[SIZE_I_IN];
sc_signal<sc_int<64>> data_b_in[SIZE_I_IN];
sc_signal<sc_int<64>> data_out[SIZE_I_IN];
vector_adder.clock(clock);
for (int i = 0; i < SIZE_I_IN; i++) {
vector_adder.data_a_in[i](data_a_in[i]);
vector_adder.data_b_in[i](data_b_in[i]);
vector_adder.data_out[i](data_out[i]);
}
for (int i = 0; i < SIZE_I_IN; i++) {
data_a_in[i] = i;
data_b_in[i] = i + 1;
}
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
for (int i = 0; i < SIZE_I_IN; i++) {
cout << "@" << sc_time_stamp() << ": data_out[" << i << "] = " << data_out[i].read() << endl;
}
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_vector_adder_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
vector_adder vector_adder("VECTOR_ADDER");
sc_signal<bool> clock;
sc_signal<sc_int<64>> data_a_in[SIZE_I_IN];
sc_signal<sc_int<64>> data_b_in[SIZE_I_IN];
sc_signal<sc_int<64>> data_out[SIZE_I_IN];
vector_adder.clock(clock);
for (int i = 0; i < SIZE_I_IN; i++) {
vector_adder.data_a_in[i](data_a_in[i]);
vector_adder.data_b_in[i](data_b_in[i]);
vector_adder.data_out[i](data_out[i]);
}
for (int i = 0; i < SIZE_I_IN; i++) {
data_a_in[i] = i;
data_b_in[i] = i + 1;
}
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
for (int i = 0; i < SIZE_I_IN; i++) {
cout << "@" << sc_time_stamp() << ": data_out[" << i << "] = " << data_out[i].read() << endl;
}
return 0;
}
|
#include <systemc.h>
SC_MODULE (hello_world) {
SC_CTOR (hello_world) {
}
void say_hello() {
cout << "Hello World SystemC-2.3.1.\n";
}
};
int sc_main(int argc, char* argv[]) {
hello_world hello("HELLO");
hello.say_hello();
return(0);
} |
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_vector_adder_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
vector_adder vector_adder("VECTOR_ADDER");
sc_signal<bool> clock;
sc_signal<sc_int<64>> data_a_in[SIZE_I_IN];
sc_signal<sc_int<64>> data_b_in[SIZE_I_IN];
sc_signal<sc_int<64>> data_out[SIZE_I_IN];
vector_adder.clock(clock);
for (int i = 0; i < SIZE_I_IN; i++) {
vector_adder.data_a_in[i](data_a_in[i]);
vector_adder.data_b_in[i](data_b_in[i]);
vector_adder.data_out[i](data_out[i]);
}
for (int i = 0; i < SIZE_I_IN; i++) {
data_a_in[i] = i;
data_b_in[i] = i + 1;
}
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
for (int i = 0; i < SIZE_I_IN; i++) {
cout << "@" << sc_time_stamp() << ": data_out[" << i << "] = " << data_out[i].read() << endl;
}
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_vector_adder_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
vector_adder vector_adder("VECTOR_ADDER");
sc_signal<bool> clock;
sc_signal<sc_int<64>> data_a_in[SIZE_I_IN];
sc_signal<sc_int<64>> data_b_in[SIZE_I_IN];
sc_signal<sc_int<64>> data_out[SIZE_I_IN];
vector_adder.clock(clock);
for (int i = 0; i < SIZE_I_IN; i++) {
vector_adder.data_a_in[i](data_a_in[i]);
vector_adder.data_b_in[i](data_b_in[i]);
vector_adder.data_out[i](data_out[i]);
}
for (int i = 0; i < SIZE_I_IN; i++) {
data_a_in[i] = i;
data_b_in[i] = i + 1;
}
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
for (int i = 0; i < SIZE_I_IN; i++) {
cout << "@" << sc_time_stamp() << ": data_out[" << i << "] = " << data_out[i].read() << endl;
}
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_tensor_product_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
tensor_product tensor_product("TENSOR_PRODUCT");
sc_signal<bool> clock;
sc_signal<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN];
sc_signal<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN];
sc_signal<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN];
tensor_product.clock(clock);
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
tensor_product.data_a_in[i][j][k](data_a_in[i][j][k]);
tensor_product.data_b_in[i][j][k](data_b_in[i][j][k]);
tensor_product.data_out[i][j][k](data_out[i][j][k]);
}
}
}
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
data_a_in[i][j][k] = i + j + k;
data_b_in[i][j][k] = i - j - k;
}
}
}
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
cout << "@" << sc_time_stamp() << ": data_out[" << i << ", " << j << ", " << k << "] = " << data_out[i][j][k].read() << endl;
}
}
}
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_tensor_product_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
tensor_product tensor_product("TENSOR_PRODUCT");
sc_signal<bool> clock;
sc_signal<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN];
sc_signal<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN];
sc_signal<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN];
tensor_product.clock(clock);
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
tensor_product.data_a_in[i][j][k](data_a_in[i][j][k]);
tensor_product.data_b_in[i][j][k](data_b_in[i][j][k]);
tensor_product.data_out[i][j][k](data_out[i][j][k]);
}
}
}
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
data_a_in[i][j][k] = i + j + k;
data_b_in[i][j][k] = i - j - k;
}
}
}
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
cout << "@" << sc_time_stamp() << ": data_out[" << i << ", " << j << ", " << k << "] = " << data_out[i][j][k].read() << endl;
}
}
}
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_tensor_product_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
tensor_product tensor_product("TENSOR_PRODUCT");
sc_signal<bool> clock;
sc_signal<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN];
sc_signal<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN];
sc_signal<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN];
tensor_product.clock(clock);
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
tensor_product.data_a_in[i][j][k](data_a_in[i][j][k]);
tensor_product.data_b_in[i][j][k](data_b_in[i][j][k]);
tensor_product.data_out[i][j][k](data_out[i][j][k]);
}
}
}
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
data_a_in[i][j][k] = i + j + k;
data_b_in[i][j][k] = i - j - k;
}
}
}
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
cout << "@" << sc_time_stamp() << ": data_out[" << i << ", " << j << ", " << k << "] = " << data_out[i][j][k].read() << endl;
}
}
}
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_tensor_product_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
tensor_product tensor_product("TENSOR_PRODUCT");
sc_signal<bool> clock;
sc_signal<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN];
sc_signal<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN];
sc_signal<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN];
tensor_product.clock(clock);
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
tensor_product.data_a_in[i][j][k](data_a_in[i][j][k]);
tensor_product.data_b_in[i][j][k](data_b_in[i][j][k]);
tensor_product.data_out[i][j][k](data_out[i][j][k]);
}
}
}
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
data_a_in[i][j][k] = i + j + k;
data_b_in[i][j][k] = i - j - k;
}
}
}
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
cout << "@" << sc_time_stamp() << ": data_out[" << i << ", " << j << ", " << k << "] = " << data_out[i][j][k].read() << endl;
}
}
}
return 0;
}
|
/*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
/*****************************************************************************
stage1.cpp -- This is the implementation file for the stage1 module.
Original Author: Amit Rao, Synopsys, Inc.
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
#include "systemc.h"
#include "stage1.h"
//Definition of addsub method
void stage1::addsub()
{
double a;
double b;
a = in1.read();
b = in2.read();
sum.write(a+b);
diff.write(a-b);
} // end of addsub method
|
//
//------------------------------------------------------------//
// Copyright 2009-2012 Mentor Graphics Corporation //
// All Rights Reserved Worldwid //
// //
// Licensed under the Apache License, Version 2.0 (the //
// "License"); you may not use this file except in //
// compliance with the License. You may obtain a copy of //
// the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in //
// writing, software distributed under the License is //
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR //
// CONDITIONS OF ANY KIND, either express or implied. See //
// the License for the specific language governing //
// permissions and limitations under the License. //
//------------------------------------------------------------//
//-----------------------------------------------------------------------------
// Title- UVMC-based SC to SC Connections (not implemented yet)
//
// This example demonstrates connecting two SC components using UVMC.
//
// (see UVMC_Connections_SC2SC.png)
//
// In this example, we instantiate a <producer> and <consumer>
// sc_module. Then two ~uvmc_connect~ calls are made, one for each side of
// the connection. Because we use the same lookup string, "sc2sc", in each
// of these calls, UVMC will establish the connection during binding resolution
// at elaboration time.
//
// The connection must be valid, i.e. the port/export/interface types and
// transaction type must be compatible, else an elaboration-time error will
// result.
//
//-----------------------------------------------------------------------------
// (- inline source)
#include <systemc.h>
using namespace sc_core;
#include "consumer.h"
#include "producer.h"
#include "packet.h"
int sc_main(int argc, char* argv[])
{
producer prod("prod");
consumer cons("cons");
uvmc_connect(prod.out, "sc2sc");
uvmc_connect(cons.in, "sc2sc");
sc_start(-1);
return 0;
}
|
/*******************************************************************************
* gn_mixed.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design
*******************************************************************************
* Description:
* This is a derivative of the sc_signal_resolved class from SystemC
* which was extended to support a third, analog level, data state. It should
* be noted that this is not a real AMS style signal, for that we need
* SystemC-AMS. This is just a shortcut to make it possible to express
* a signal which can be either analog or 4-state without having to
* use a AMS style simulator.
*******************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This was based off the work licensed as:
*
* Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
* more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Accellera licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Original Author: Martin Janssen, Synopsys, Inc., 2001-05-21
*******************************************************************************
*/
#include <systemc.h>
#include "gn_mixed.h"
/* The table for resolving GN_LOGIC.
* Some notes:
* -weak always looses from strong,
* -there is no weak undefined as we do not know if a weak undefined would
* loose.
* -Analog only wins from Z as a short between analog requires us to know
* the currents.
* -Conflicts with Undefined always produce an Undefined.
*/
gn_mixed::gn_logic_t
gn_logic_resolution_tbl[7][7] =
/* 0 */ /* 1 */ /* W0 */ /* W1 */ /* Z */ /* A */ /* X */
/* 0 */{{GN_LOGIC_0,GN_LOGIC_X,GN_LOGIC_0 ,GN_LOGIC_0 ,GN_LOGIC_0 ,GN_LOGIC_X,GN_LOGIC_X},
/* 1 */ {GN_LOGIC_X,GN_LOGIC_1,GN_LOGIC_1 ,GN_LOGIC_1 ,GN_LOGIC_1 ,GN_LOGIC_X,GN_LOGIC_X},
/*W0 */ {GN_LOGIC_0,GN_LOGIC_1,GN_LOGIC_W0,GN_LOGIC_X ,GN_LOGIC_W0,GN_LOGIC_X,GN_LOGIC_X},
/*W1 */ {GN_LOGIC_0,GN_LOGIC_1,GN_LOGIC_X ,GN_LOGIC_W1,GN_LOGIC_W1,GN_LOGIC_X,GN_LOGIC_X},
/* Z */ {GN_LOGIC_0,GN_LOGIC_1,GN_LOGIC_W0,GN_LOGIC_W1,GN_LOGIC_Z ,GN_LOGIC_A,GN_LOGIC_X},
/* A */ {GN_LOGIC_X,GN_LOGIC_X,GN_LOGIC_X ,GN_LOGIC_X ,GN_LOGIC_A ,GN_LOGIC_X,GN_LOGIC_X},
/* X */ {GN_LOGIC_X,GN_LOGIC_X,GN_LOGIC_X ,GN_LOGIC_X ,GN_LOGIC_X ,GN_LOGIC_X,GN_LOGIC_X}};
/* These are globals that set the analog levels to be used for the different
* digital levels. There is no resolution or feedback calculated in them.
* It is just a convention to make it more easily vieable in a digital
* waveform viewer. vdd_lvl is the level for logic 1, vss_lvl is for logic 0
* and undef_lvl is for Z or X.
*/
float gn_mixed::vdd_lvl = 3.3f;
float gn_mixed::vss_lvl = 0.0f;
float gn_mixed::undef_lvl = 1.5f;
sc_logic gn_to_sc_logic(gn_mixed::gn_logic_t g) {
switch(g) {
case GN_LOGIC_0:
case GN_LOGIC_W0: return SC_LOGIC_0;
case GN_LOGIC_1:
case GN_LOGIC_W1: return SC_LOGIC_1;
case GN_LOGIC_Z: return SC_LOGIC_Z;
default: return SC_LOGIC_X;
}
}
float gn_mixed::guess_lvl(sc_logic &l) {
if (l == SC_LOGIC_0) return vss_lvl;
else if (l == SC_LOGIC_1) return vdd_lvl;
else return undef_lvl;
}
gn_mixed::gn_param_t gn_mixed::guess_param(gn_logic_t g) {
switch(g) {
case GN_LOGIC_W0: return GN_TYPE_WEAK;
case GN_LOGIC_W1: return GN_TYPE_WEAK;
case GN_LOGIC_A: return GN_TYPE_ANALOG;
case GN_LOGIC_Z: return GN_TYPE_Z;
default: return GN_TYPE_STRONG;
}
}
gn_mixed::gn_logic_t char_to_gn(const char c_) {
switch(c_) {
case '0': return GN_LOGIC_0;
case '1': return GN_LOGIC_1;
case 'l': return GN_LOGIC_W0;
case 'h': return GN_LOGIC_W1;
case 'Z': return GN_LOGIC_Z;
case 'A': return GN_LOGIC_A;
default: return GN_LOGIC_X;
}
}
gn_mixed::gn_mixed() {
logic = SC_LOGIC_X;
lvl = undef_lvl;
param = GN_TYPE_STRONG;
}
gn_mixed::gn_mixed(const gn_mixed &n) {
logic = n.logic;
lvl = n.lvl;
param = n.param;
}
gn_mixed::gn_mixed(const gn_logic_t n_) {
logic = gn_to_sc_logic(n_);
lvl = guess_lvl(logic);
param = guess_param(n_);
}
gn_mixed::gn_mixed(const sc_logic &n) {
logic = n;
lvl = guess_lvl(logic);
param = (n == SC_LOGIC_Z)?GN_TYPE_Z:GN_TYPE_STRONG;
}
gn_mixed::gn_mixed(const float &n) {
logic = SC_LOGIC_X;
lvl = n;
param = GN_TYPE_ANALOG;
}
gn_mixed::gn_mixed(const char c_) {
gn_logic_t g = char_to_gn(c_);
logic = gn_to_sc_logic(g);
lvl = guess_lvl(logic);
param = guess_param(g);
}
gn_mixed::gn_mixed(const bool b_) {
logic = sc_logic(b_);
lvl = guess_lvl(logic);
param = GN_TYPE_STRONG;
}
gn_mixed &gn_mixed::operator=(const gn_mixed &n) {
logic = n.logic;
lvl = n.lvl;
param = n.param;
return *this;
}
gn_mixed &gn_mixed::operator=(const gn_logic_t n_) {
logic = gn_to_sc_logic(n_);
lvl = guess_lvl(logic);
param = guess_param(n_);
return *this;
}
gn_mixed &gn_mixed::operator=(const sc_logic &n) {
logic = n;
lvl = guess_lvl(logic);
param = (n == SC_LOGIC_Z)?GN_TYPE_Z:GN_TYPE_STRONG;
return *this;
}
gn_mixed &gn_mixed::operator=(const float &n) {
logic = LOGIC_A;
lvl = n;
param = GN_TYPE_ANALOG;
return *this;
}
gn_mixed &gn_mixed::operator=(const char c_) {
gn_logic_t g = char_to_gn(c_);
logic = gn_to_sc_logic(g);
lvl = guess_lvl(logic);
param = guess_param(g);
return *this;
}
gn_mixed &gn_mixed::operator=(const bool b_) {
logic = sc_logic(b_);
lvl = guess_lvl(logic);
param = GN_TYPE_STRONG;
return *this;
}
/* When comparing GN_MIXED, we compare all fields. When comparing GN_MIXED to
* SC_LOGIC we have to treat the weak and strong signals as the same. We also
* have to treat analog signals as simply undefined.
*/
bool operator==(const gn_mixed &a, const gn_mixed &b) {
if (a.logic != b.logic) return false;
if (a.param != b.param) return false;
if (a.param != gn_mixed::GN_TYPE_ANALOG) return true;
return (a.lvl > b.lvl - 0.01 && a.lvl < b.lvl + 0.01);
}
bool operator==(const gn_mixed &a, const sc_logic &b) {
return a.logic == b;
}
char gn_mixed::to_char() const {
if (param == GN_TYPE_ANALOG) return 'A';
else if (logic == SC_LOGIC_X) return 'X';
else if (logic == SC_LOGIC_Z) return 'Z';
else if (logic == SC_LOGIC_0) return (param == GN_TYPE_WEAK)?'l':'0';
else if (logic == SC_LOGIC_1) return (param == GN_TYPE_WEAK)?'h':'1';
else return GN_LOGIC_X;
}
gn_mixed::gn_logic_t gn_mixed::value() {
if (param == GN_TYPE_ANALOG) return GN_LOGIC_A;
else if (logic == SC_LOGIC_X) return GN_LOGIC_X;
else if (logic == SC_LOGIC_Z) return GN_LOGIC_Z;
else if (logic == SC_LOGIC_0)
return (param == GN_TYPE_WEAK)?GN_LOGIC_W0:GN_LOGIC_0;
else if (logic == SC_LOGIC_1)
return (param == GN_TYPE_WEAK)?GN_LOGIC_W1:GN_LOGIC_1;
else return GN_LOGIC_X;
}
static void gn_mixed_resolve(gn_mixed& result_,
const std::vector<gn_mixed>& values_ )
{
int sz = values_.size();
sc_assert( sz != 0 );
if( sz == 1 ) {
result_ = values_[0];
return;
}
gn_mixed current;
gn_mixed res = values_[0];
int i;
/* We now scan the list of driven values so we can resolve it. If we find
* a X it all goes X, so we can stop looking.
*/
for(i = sz - 1; i>0 && res.logic != SC_LOGIC_X; --i) {
/* If the resolved is high-Z, we resolve to the next one. */
if (res.value() == GN_LOGIC_Z) {
res = values_[i];
continue;
}
/* In other cases we use the resolution table. */
current = values_[i];
/* This case is simple. */
if (current.value() == GN_LOGIC_Z) continue;
/* We let the resolution table handle the rest. */
res = gn_logic_resolution_tbl[res.value()][current.value()];
}
result_ = res;
}
void gn_signal_mix::write(const value_type& value_) {
sc_process_b* cur_proc = sc_get_current_process_b();
bool value_changed = false;
bool found = false;
for( int i = m_proc_vec.size() - 1; i >= 0; -- i ) {
if( cur_proc == m_proc_vec[i] ) {
if( value_ != m_val_vec[i] ) {
m_val_vec[i] = value_;
value_changed = true;
}
found = true;
break;
}
}
if( ! found ) {
m_proc_vec.push_back( cur_proc );
m_val_vec.push_back( value_ );
value_changed = true;
}
if( value_changed ) {
request_update();
}
}
void gn_signal_mix::write( const gn_mixed::gn_logic_t value_ )
{ write(gn_mixed(value_));}
void gn_signal_mix::write( const sc_logic& value_ ) { write(gn_mixed(value_)); }
void gn_signal_mix::write( const float& value_ ) { write(gn_mixed(value_)); }
void gn_signal_mix::write( const char value_ ) { write(gn_mixed(value_)); }
void gn_signal_mix::write( const bool value_ ) { write(gn_mixed(value_)); }
sc_logic gn_signal_mix::read_logic( ) {
return read().logic;
}
float gn_signal_mix::read_lvl( ) {
return read().lvl;
}
void gn_signal_mix::update()
{
gn_mixed_resolve( m_new_val, m_val_vec );
base_type::update();
}
void gn_tie_mix::update()
{
base_type::update();
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "systemc.h"
#define SIZE_I_IN 4
#define SIZE_J_IN 4
SC_MODULE(matrix_multiplier) {
sc_in_clk clock;
sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN];
sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN];
sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN];
SC_CTOR(matrix_multiplier) {
SC_METHOD(multiplier);
sensitive << clock.pos();
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
sensitive << data_a_in[i][j];
sensitive << data_b_in[i][j];
}
}
}
void multiplier() {
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
data_out[i][j].write(data_a_in[i][j].read() * data_b_in[i][j].read());
}
}
}
};
|
/*******************************************************************************
* gpio_mfmix.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design
*******************************************************************************
* Description:
* Implements a SystemC model of a generic multi-function GPIO with
* analog function.
*******************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************
*/
#include <systemc.h>
#include "gpio_mfmix.h"
#include "info.h"
/*********************
* Function: set_function()
* inputs: new function
* outputs: none
* returns: none
* globals: none
*
* Sets the function, can be GPIO or ANALOG.
*/
void gpio_mfmix::set_function(gpio_function_t newfunction) {
/* We ignore unchanged function requests. */
if (newfunction == function) return;
/* We also ignore illegal function requests. */
if (newfunction == GPIOMF_ANALOG && !anaok) {
PRINTF_WARN("GPIOMFMIX", "%s cannot be set to ANALOG", name())
return;
}
/* To select a function there must be at least the fin or the fout
* available. The fen is optional. Ideal would be to require all three
* but there are some peripherals that need only one of these pins,
* so to make life easier, we require at least a fin or a fout.
*/
if (newfunction >= GPIOMF_FUNCTION &&
(newfunction-1 >= fin.size() && newfunction-1 >= fout.size())) {
PRINTF_WARN("GPIOMF", "%s cannot be set to FUNC%d", name(),
newfunction)
return;
}
/* When we change to the GPIO function, we set the driver high and set
* the function accordingly.
*/
if (newfunction == GPIOMF_GPIO) {
PRINTF_INFO("GPIOMFMIX", "%s set to GPIO mode", name())
function = newfunction;
driveok = true;
/* set_val() handles the driver. */
gpio_base::set_val(pinval);
}
/* Analog drives the pin to nothing. */
else if (newfunction == GPIOMF_ANALOG) {
/* This set_mode is an elegance thing, it might not be necessary. */
set_mode(GPIOMODE_NONE);
PRINTF_INFO("GPIOMFMIX", "%s set to ANALOG", name())
function = GPIOMF_ANALOG;
driveok = false;
}
/* And with the multi function we let the drive_func handle the settings. */
else {
PRINTF_INFO("GPIOMFMIX", "%s set to FUNC%d", name(), newfunction)
function = newfunction;
}
/* And we set any notifications we need. */
updatefunc.notify();
updatereturn.notify();
}
/*********************
* Function: get_function()
* inputs: none
* outputs: none
* returns: current function
* globals: none
*
* Returns the current function.
*/
gpio_function_t gpio_mfmix::get_function() {
return function;
}
/*********************
* Thread: drive_return()
* inputs: none
* outputs: none
* returns: none
* globals: none
*
* Drives the return path from the pin onto the alternate functions.
*/
void gpio_mfmix::drive_return() {
gn_mixed pinsamp;
bool retval;
int func;
/* We begin driving all returns to low. */
for (func = 0; func < fout.size(); func = func + 1) fout[func]->write(false);
/* Now we go into the loop waiting for a return or a change in function. */
for(;;) {
/*
printf("<<%s>>: U:%d pin:%d:%c @%s\n",
name(), updatereturn.triggered(), pin.event(), pin.read().to_char(),
sc_time_stamp().to_string().c_str());
*/
pinsamp = pin.read();
if (pinsamp.logic.to_char() == 'X') printf(">%s : %s : %d/%d %c-\n", name(), sc_time_stamp().to_string().c_str(),
pin.default_event().triggered(), updatereturn.triggered(), pinsamp.to_char());
/* If the sampling value is Z or X and we have a function set, we
* then issue a warning. We also do not warn at time 0s or we get some
* dummy initialization warnings.
*/
if (sc_time_stamp() != sc_time(0, SC_NS) &&
(pinsamp == GN_LOGIC_A || pinsamp == GN_LOGIC_X
|| pinsamp == GN_LOGIC_Z) &&
function != GPIOMF_ANALOG && function != GPIOMF_GPIO) {
retval = false;
PRINTF_WARN("GPIOMFMIX", "can't return '%c' onto FUNC%d",
pinsamp.to_char(), function)
}
else if (pinsamp == GN_LOGIC_1) retval = true;
else retval = false;
for (func = 0; func < fout.size(); func = func + 1)
if (function == GPIOMF_ANALOG) fout[func]->write(false);
else if (function == GPIOMF_GPIO) fout[func]->write(false);
else if (func != function-1) fout[func]->write(false);
else fout[func]->write(retval);
wait();
}
}
/*********************
* Thread: drive_func()
* inputs: none
* outputs: none
* returns: none
* globals: none
*
* Drives the value from an alternate function onto the pins. This does not
* actually drive the value, it just places it in the correct variables so that
* the drive() thread handles it.
*/
void gpio_mfmix::drive_func() {
for(;;) {
/* We only use this thread if we have an alternate function selected. */
if (function != GPIOMF_GPIO && function != GPIOMF_ANALOG &&
function-1 < fin.size()) {
/* We check if the fen is ok. If this function has no fen we default
* it to enabled.
*/
if (function-1 < fen.size() || fen[function-1]->read() == true)
driveok = true;
else driveok = false;
/* Note that we do not set the pin val, just call set_val to handle
* the pin drive.
*/
gpio_base::set_val(fin[function-1]->read());
}
/* We now wait for a change. If the function is no selected or if we
* have an illegal function selected, we have to wait for a change
* in the function selection.
*/
if (function == GPIOMF_ANALOG || function == GPIOMF_GPIO ||
function-1 >= fin.size())
wait(updatefunc);
/* If we have a valid function selected, we wait for either the
* function or the fen to change. We also have to wait for a
* function change.
*/
else if (fen.size() >= function-1)
wait(updatefunc | fin[function-1]->value_changed_event());
else wait(updatefunc | fin[function-1]->value_changed_event()
| fen[function-1]->value_changed_event());
}
}
|
/*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
/*****************************************************************************
exec.cpp -- Integer Execution Unit.
Original Author: Martin Wang, Synopsys, Inc.
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
#include "systemc.h"
#include "exec.h"
#include "directive.h"
void exec::entry(){
int opcode_tmp = 0;
int add1_tmp = 0;
signed int dina_tmp = 0;
signed int dinb_tmp = 0;
sc_dt::int64 dout_tmp = 0;
unsigned int dest_tmp = 0;
//
// main loop
//
//
// initialization of output
wait(3);
while(1) {
if (in_valid.read() == true) {
dina_tmp = dina.read();
dinb_tmp = dinb.read();
opcode_tmp = opcode.read();
dest_tmp = dest.read();
// output MUX
switch (opcode_tmp) {
case 0: // Stall
dout_tmp = dout_tmp;
wait();
break;
case 1: // add with carry
dout_tmp = dina_tmp + dinb_tmp + add1_tmp;
wait();
break;
case 2: // sub with carry
dout_tmp = dina_tmp - dinb_tmp - add1_tmp;
wait();
break;
case 3: // add without carry
dout_tmp = dina_tmp + dinb_tmp;
wait();
break;
case 4: // sub without carry
dout_tmp = dina_tmp - dinb_tmp;
wait();
break;
case 5: // multiply assume 2 clock cycle multiplication
dout_tmp = dina_tmp * dinb_tmp;
wait(); // so that BC has something to do
wait();
break;
case 6: // divide assume 2 clock cycle multiplication
if (dinb_tmp == 0) {
printf("Division Exception - Divide by zero \n");
} else {
dout_tmp = dina_tmp / dinb_tmp;
}
wait(); // so that BC has something to do
wait();
break;
case 7: // bitwise NAND
dout_tmp = ~(dina_tmp & dinb_tmp);
wait();
break;
case 8: // bitwise AND
dout_tmp = dina_tmp & dinb_tmp;
wait();
break;
case 9: // bitwise OR
dout_tmp = dina_tmp | dinb_tmp;
wait();
break;
case 10: // bitwise XOR
dout_tmp = dina_tmp ^ dinb_tmp;
wait();
break;
case 11: // bitwise complement
dout_tmp = ~ dina_tmp;
wait();
break;
case 12: // left shift
dout_tmp = dina_tmp << dinb_tmp;
wait();
break;
case 13: // right shift
dout_tmp = dina_tmp >> dinb_tmp;
wait();
break;
case 14: // modulo
dout_tmp = dina_tmp % dinb_tmp;
wait();
break;
default:
printf("ALU: Bad Opcode %d.\n",opcode_tmp);
break;
}
dout.write(static_cast<signed int>(dout_tmp));
out_valid.write(true);
destout.write(dest_tmp);
if (dout_tmp == 0) {
Z.write(true);
} else {
Z.write(false);
}
sc_dt::int64 abs_dout = dout_tmp >= 0 ? dout_tmp : -dout_tmp;
const sc_dt::int64 carry_mask = sc_dt::int64(1) << 32;
if (abs_dout & carry_mask) {
C.write(true);
} else {
C.write(false);
}
if (abs_dout > carry_mask) {
V.write(true);
} else {
V.write(false);
}
printf("\t\t\t\t\t\t\t-------------------------------\n");
cout << "\t\t\t\t\t\t\tALU :" << " op= " << opcode_tmp
<< " A= " << dina_tmp << " B= " << dinb_tmp << endl;
cout << "\t\t\t\t\t\t\tALU :" << " R= " << dout_tmp << "-> R" << dest_tmp;
cout << " at CSIM " << sc_time_stamp() << endl;
printf("\t\t\t\t\t\t\t-------------------------------\n");
wait();
out_valid.write(false);
wait();
} else {
wait();
}
}
}
|
/*
Problem 2 Design
*/
#include<systemc.h>
SC_MODULE(counters) {
sc_in<sc_uint<8> > in1 , in2 , in3;
sc_in<bool> dec1 , dec2 , clock , load1 , load2;
sc_out<sc_uint<8> > count1 , count2;
sc_out<bool> ended;
sc_signal<bool> isOverflow1 , isOverflow2;
void handleCount1();
void handleCount2();
void updateEnded();
SC_CTOR(counters) {
isOverflow1.write(false);
isOverflow2.write(false);
SC_METHOD(handleCount1);
sensitive<<clock.pos();
SC_METHOD(handleCount2);
sensitive<<clock.pos();
SC_METHOD(updateEnded);
sensitive<<clock.pos();
}
};
void counters::handleCount1() {
if(load1.read() == true) {
cout<<"@ "<<sc_time_stamp()<<"----------Start registerCount1---------"<<endl;
count1.write(in1.read());
cout<<"@ "<<sc_time_stamp()<<"----------End registerCount1---------"<<endl;
} else if(dec1.read() == true) {
cout<<"@ "<<sc_time_stamp()<<"----------Start decCount1---------"<<endl;
if(count1.read() == 0) {
isOverflow1.write(true);
return;
}
isOverflow1.write(false);
count1.write(count1.read() - 1);
cout<<"@ "<<sc_time_stamp()<<"----------End decCount1---------"<<endl;
}
}
void counters::handleCount2() {
if(load2.read() == true) {
cout<<"@ "<<sc_time_stamp()<<"----------Start registerCount2---------"<<endl;
count2.write(in2.read());
cout<<"@ "<<sc_time_stamp()<<"----------End registerCount2---------"<<endl;
} else if(dec2.read() == true) {
cout<<"@ "<<sc_time_stamp()<<"----------Start decCount2---------"<<endl;
if(count2.read() <= in3.read()) {
isOverflow2.write(true);
return;
}
isOverflow2.write(false);
count2.write(count2.read() - in3.read());
cout<<"@ "<<sc_time_stamp()<<"----------End decCount2---------"<<endl;
}
}
void counters::updateEnded() {
cout<<"@ "<<sc_time_stamp()<<"----------Start updateEnded---------"<<endl;
if(count1.read() == count2.read() || isOverflow1.read() || isOverflow2.read()) {
ended.write(true);
} else {
ended.write(false);
}
cout<<"@ "<<sc_time_stamp()<<"----------End updateEnded---------"<<endl;
} |
/*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
/*****************************************************************************
main.cpp -- Example program for specialized signal support.
Original Author: Andy Goodrich, Forte Design Systems, 11 April 2005
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
#include "systemc.h"
#include "scx_signal_int.h"
#include "scx_signal_signed.h"
#include "scx_signal_uint.h"
#include "scx_signal_unsigned.h"
#define DISPLAY(exp,base) cout << #exp << " = " << base << exp << endl;
#define TEST(exp1,exp2,base) \
if ( exp1 != exp2 ) \
{ \
cout << #exp1 << "(" << base << exp1 << ") != " \
<< #exp2 << "(" << base << exp2 << ")" << endl; \
}
SC_MODULE(DUT)
{
SC_CTOR(DUT)
{
SC_THREAD(exec)
sensitive << m_clk.pos();
// CONNECT PORTS TO THEIR BACKING SIGNALS:
m_in_bigint4(m_back_in_bigint4);
m_inout_bigint4(m_back_inout_bigint4);
m_in_biguint4(m_back_in_biguint4);
m_inout_biguint4(m_back_inout_biguint4);
m_in_int4(m_back_in_int4);
m_inout_int4(m_back_inout_int4);
m_in_uint4(m_back_in_uint4);
m_inout_uint4(m_back_inout_uint4);
}
void exec()
{
// TEST RIGHT HAND CONCATENATION:
m_back_in_bigint4 = 1;
m_back_inout_bigint4 = 2;
m_back_in_biguint4 = 3;
m_back_inout_biguint4 = 4;
m_back_in_int4 = 5;
m_back_inout_int4 = 6;
m_back_in_uint4 = 7;
m_back_inout_uint4 = 8;
wait();
DISPLAY((
m_in_bigint4,
m_inout_bigint4,
m_in_biguint4,
m_inout_biguint4,
m_in_int4,
m_inout_int4,
m_in_uint4,
m_inout_uint4
),hex);
m_signal_bigint8 = ( m_in_bigint4,m_inout_uint4);
m_signal_biguint8 = ( m_inout_bigint4,m_in_uint4);
m_signal_int8 = ( m_in_biguint4,m_inout_int4);
m_signal_uint8 = ( m_inout_biguint4,m_in_int4);
wait();
DISPLAY(m_signal_bigint8,hex);
DISPLAY(m_signal_biguint8,hex);
DISPLAY(m_signal_int8,hex);
DISPLAY(m_signal_uint8,hex);
// TEST LEFT HAND CONCATENATION:
(m_inout_uint4,m_signal_biguint8) = 0x123;
wait();
(m_signal_bigint8,m_inout_bigint4) = (m_inout_uint4,m_signal_biguint8);
(m_signal_biguint8,m_inout_biguint4) = 0x456;
(m_inout_int4,m_signal_int8) = 0x978;
(m_inout_uint4,m_signal_uint8) = 0xcab;
wait();
DISPLAY(m_signal_bigint8,hex);
DISPLAY(m_inout_bigint4,hex);
DISPLAY(m_signal_biguint8,hex);
DISPLAY(m_inout_biguint4,hex);
DISPLAY(m_signal_int8,hex);
DISPLAY(m_inout_int4,hex);
DISPLAY(m_signal_uint8,hex);
DISPLAY(m_inout_uint4,hex);
// TEST MATH OPERATIONS:
//
// Note there is not need to call .read() methods!
m_nb_signal_bigint8 = -1;
m_nb_signal_biguint8 = 255;
m_nb_signal_int8 = -2;
m_nb_signal_uint8 = 128;
m_signal_bigint8 = -1;
m_signal_biguint8 = 255;
m_signal_int8 = -2;
m_signal_uint8 = 128;
wait();
TEST(m_signal_bigint8*m_signal_biguint8,
m_nb_signal_bigint8*m_nb_signal_biguint8,dec);
TEST(m_signal_bigint8*m_signal_uint8,
m_nb_signal_bigint8*m_nb_signal_uint8,dec);
TEST(m_signal_int8*m_signal_biguint8,
m_nb_signal_int8*m_nb_signal_biguint8,dec);
TEST(m_signal_int8*m_signal_uint8,
m_nb_signal_int8*m_nb_signal_uint8,dec);
TEST(m_signal_bigint8+m_signal_biguint8,
m_nb_signal_bigint8+m_nb_signal_biguint8,dec);
TEST(m_signal_bigint8+m_signal_uint8,
m_nb_signal_bigint8+m_nb_signal_uint8,dec);
TEST(m_signal_int8+m_signal_biguint8,
m_nb_signal_int8+m_nb_signal_biguint8,dec);
TEST(m_signal_int8+m_signal_uint8,
m_nb_signal_int8+m_nb_signal_uint8,dec);
TEST(m_signal_bigint8-m_signal_biguint8,
m_nb_signal_bigint8-m_nb_signal_biguint8,dec);
TEST(m_signal_bigint8-m_signal_uint8,
m_nb_signal_bigint8-m_nb_signal_uint8,dec);
TEST(m_signal_int8-m_signal_biguint8,
m_nb_signal_int8-m_nb_signal_biguint8,dec);
TEST(m_signal_int8-m_signal_uint8,
m_nb_signal_int8-m_nb_signal_uint8,dec);
TEST(m_signal_int8+m_signal_uint8*m_signal_bigint8-m_signal_biguint8,
m_nb_signal_int8+m_nb_signal_uint8*m_nb_signal_bigint8-m_nb_signal_biguint8,dec);
m_nb_in_bigint4 = -1;
m_nb_in_biguint4 = 15;
m_nb_in_int4 = -2;
m_nb_in_uint4 = 8;
m_back_in_bigint4 = -1;
m_back_in_biguint4 = 15;
m_back_in_int4 = -2;
m_back_in_uint4 = 8;
wait();
TEST(m_in_bigint4*m_in_biguint4,
m_nb_in_bigint4*m_nb_in_biguint4,dec);
TEST(m_in_bigint4*m_in_uint4,
m_nb_in_bigint4*m_nb_in_uint4,dec);
TEST(m_in_int4*m_in_biguint4,
m_nb_in_int4*m_nb_in_biguint4,dec);
TEST(m_in_int4*m_in_uint4,
m_nb_in_int4*m_nb_in_uint4,dec);
TEST(m_in_bigint4+m_in_biguint4,
m_nb_in_bigint4+m_nb_in_biguint4,dec);
TEST(m_in_bigint4+m_in_uint4,
m_nb_in_bigint4+m_nb_in_uint4,dec);
TEST(m_in_int4+m_in_biguint4,
m_nb_in_int4+m_nb_in_biguint4,dec);
TEST(m_in_int4+m_in_uint4,
m_nb_in_int4+m_nb_in_uint4,dec);
TEST(m_in_bigint4-m_in_biguint4,
m_nb_in_bigint4-m_nb_in_biguint4,dec);
TEST(m_in_bigint4-m_in_uint4,
m_nb_in_bigint4-m_nb_in_uint4,dec);
TEST(m_in_int4-m_in_biguint4,
m_nb_in_int4-m_nb_in_biguint4,dec);
TEST(m_in_int4-m_in_uint4,
m_nb_in_int4-m_nb_in_uint4,dec);
TEST(m_in_int4+m_in_uint4*m_in_bigint4-m_in_biguint4,
m_nb_in_int4+m_nb_in_uint4*m_nb_in_bigint4-m_nb_in_biguint4,dec);
sc_stop();
}
sc_in<bool> m_clk;
sc_signal<sc_bigint<4> > m_back_in_bigint4;
sc_signal<sc_bigint<4> > m_back_inout_bigint4;
sc_signal<sc_biguint<4> > m_back_in_biguint4;
sc_signal<sc_biguint<4> > m_back_inout_biguint4;
sc_signal<sc_int<4> > m_back_in_int4;
sc_signal<sc_int<4> > m_back_inout_int4;
sc_signal<sc_uint<4> > m_back_in_uint4;
sc_signal<sc_uint<4> > m_back_inout_uint4;
sc_in<sc_bigint<4> > m_in_bigint4;
sc_inout<sc_bigint<4> > m_inout_bigint4;
sc_signal<sc_bigint<8> > m_signal_bigint8;
sc_in<sc_biguint<4> > m_in_biguint4;
sc_inout<sc_biguint<4> > m_inout_biguint4;
sc_signal<sc_biguint<8> > m_signal_biguint8;
sc_in<sc_int<4> > m_in_int4;
sc_inout<sc_int<4> > m_inout_int4;
sc_signal<sc_int<8> > m_signal_int8;
sc_in<sc_uint<4> > m_in_uint4;
sc_inout<sc_uint<4> > m_inout_uint4;
sc_signal<sc_uint<8> > m_signal_uint8;
sc_bigint<4> m_nb_in_bigint4;
sc_bigint<4> m_nb_inout_bigint4;
sc_bigint<8> m_nb_signal_bigint8;
sc_biguint<4> m_nb_in_biguint4;
sc_biguint<4> m_nb_inout_biguint4;
sc_biguint<8> m_nb_signal_biguint8;
sc_int<4> m_nb_in_int4;
sc_int<4> m_nb_inout_int4;
sc_int<8> m_nb_signal_int8;
sc_uint<4> m_nb_in_uint4;
sc_uint<4> m_nb_inout_uint4;
sc_uint<8> m_nb_signal_uint8;
};
int sc_main( int , char* [] )
{
sc_clock clock;
DUT dut("dut");
dut.m_clk(clock);
sc_start();
return 0;
}
|
#ifndef RGB2GRAY_TLM_CPP
#define RGB2GRAY_TLM_CPP
#include <systemc.h>
using namespace sc_core;
using namespace sc_dt;
using namespace std;
#include <tlm.h>
#include <tlm_utils/simple_initiator_socket.h>
#include <tlm_utils/simple_target_socket.h>
#include <tlm_utils/peq_with_cb_and_phase.h>
#include "rgb2gray_tlm.hpp"
#include "common_func.hpp"
void rgb2gray_tlm::do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address){
unsigned char pixel_value;
pixel_value = this->obtain_gray_value();
dbgimgtarmodprint(use_prints, "%0u", pixel_value);
memcpy(data, &pixel_value, sizeof(char));
}
void rgb2gray_tlm::do_when_write_transaction(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address){
unsigned char rgb_values[3];
int j = 0;
for (unsigned char *i = data; (i - data) < 3; i++)
{
rgb_values[j] = *i;
dbgimgtarmodprint(use_prints, "VAL: %0ld -> %0u", i - data, *i);
j++;
}
this->set_rgb_pixel(rgb_values[0], rgb_values[1], rgb_values[2]);
}
#endif // RGB2GRAY_TLM_CPP
|
//This the top level structural host module
//PS, dont forget to link systemc, stdc++, and m
#include <systemc.h>
#include "fir.h"
#include "tb.h"
SC_MODULE( SYSTEM )
{
//module declarations
//Done by doing module_name Pointer_to_instance i.e. name *iname;
tb *tb0;
fir *fir0;
//signal declarations
sc_signal<bool> rst_sig;
sc_signal< sc_int<16> > inp_sig;
sc_signal< sc_int<16> > outp_sig;
sc_clock clk_sig;
sc_signal<bool> inp_sig_vld;
sc_signal<bool> inp_sig_rdy;
sc_signal<bool> outp_sig_vld;
sc_signal<bool> outp_sig_rdy;
//module instance signal connections
//There are three arguements
//The first is a character pointer string and can be anything you want
//The second is the number of units long the clock signal is
//The third arguement is a sc_time_unit
//SC_US is microsecond units
//SC_NS is nanoseconds units
//SC_PS is picoseconds units
//This is a copy constructor the the clock class will generate a repetitive clock signal
SC_CTOR( SYSTEM )
: clk_sig ("clk_sig_name", 10, SC_NS)
{
//Since these are SC_MODULES we need to pass the a charcter pointer string
tb0 = new tb("tb0");
fir0 = new fir("fir0");
//Since these are pointers (new allocates memory and returns a pointer to the first
// location in that memory) we can use the arrow style derefferencing operator to
// specify a particular port and then bind it to a signal with parenthesis
tb0->clk( clk_sig );
tb0->rst( rst_sig );
tb0->inp( inp_sig );
tb0->outp( outp_sig );
fir0->clk( clk_sig );
fir0->rst( rst_sig );
fir0->inp( inp_sig );
fir0->outp( outp_sig );
tb0->inp_sig_vld( inp_sig_vld );
tb0->inp_sig_rdy( inp_sig_rdy );
tb0->outp_sig_vld( outp_sig_vld );
tb0->outp_sig_rdy( outp_sig_rdy );
fir0->inp_sig_vld( inp_sig_vld );
fir0->inp_sig_rdy( inp_sig_rdy );
fir0->outp_sig_vld( outp_sig_vld );
fir0->outp_sig_rdy( outp_sig_rdy );
}
//Destructor
~SYSTEM()
{
//free the memory up from the functions that are no longer needed
delete tb0;
delete fir0;
}
};
//Module declaration just like we did in main for fir and tb but we just assign at
//instantiation time NULL, could have done this above as well
SYSTEM *top = NULL;
//Make it int in case the compiler requires it
int sc_main( int argc, char *argv[])
{
top = new SYSTEM( "top" );
sc_start();
return 0;
}
/*
This is what you need to ad to your make file to auto check results
GOLD_DIR = ./golden
GOLD_FILE = $(GOLD_DIR)/ref_output.dat
cmp_result:
@echo "*******************************************************"
@if diff -w $(GOLD_FILE) ./output.dat; then \
echo "SIMULAITON PASSED"; \
else \
echo "SIMULATION FAILED"; \
fi
@echo "*******************************************************"
*/
/*
* sc_time represents anything in systemc that can be measured in time units
*
*/
|
/*
Problem 3 Testbench
*/
#include<systemc.h>
#include<comm.cpp>
SC_MODULE(communicationInterfaceTB) {
sc_signal<sc_uint<12> > inData;
sc_signal<bool> clock , reset , clear;
sc_signal<sc_uint<4> > payloadOut;
sc_signal<sc_uint<8> > countOut , errorOut;
void clockSignal();
void clearSignal();
void resetSignal();
void inDataSignal();
communicationInterface* cI;
SC_CTOR(communicationInterfaceTB) {
cI = new communicationInterface ("CI");
cI->clock(clock);
cI->inData(inData);
cI->reset(reset);
cI->clear(clear);
cI->payloadOut(payloadOut);
cI->countOut(countOut);
cI->errorOut(errorOut);
SC_THREAD(clockSignal);
SC_THREAD(clearSignal);
SC_THREAD(resetSignal);
SC_THREAD(inDataSignal);
}
};
void communicationInterfaceTB::clockSignal() {
while (true){
wait(20 , SC_NS);
clock = false;
wait(20 , SC_NS);
clock = true;
}
}
void communicationInterfaceTB::clearSignal() {
while (true){
wait(10 , SC_NS);
clear = false;
wait(100 , SC_NS);
clear = true;
wait(10 , SC_NS);
clear = false;
wait(100 , SC_NS);
}
}
void communicationInterfaceTB::resetSignal() {
while (true) {
wait(10 , SC_NS);
reset = true;
wait(70 , SC_NS);
reset = false;
wait(10 , SC_NS);
reset = true;
wait(1000 , SC_NS);
}
}
void communicationInterfaceTB::inDataSignal() {
while (true) {
wait(10 , SC_NS);
inData = 497;
wait(30 , SC_NS);
inData = 224;
wait(50 , SC_NS);
inData = 369;
wait(30 , SC_NS);
inData = 224;
wait(30 , SC_NS);
}
}
int sc_main(int argc , char* argv[]) {
cout<<"@ "<<sc_time_stamp()<<"----------Start---------"<<endl;
communicationInterfaceTB* cITB = new communicationInterfaceTB ("CITB");
cout<<"@ "<<sc_time_stamp()<<"----------Testbench Instance Created---------"<<endl;
sc_trace_file* VCDFile;
VCDFile = sc_create_vcd_trace_file("communication-interface");
cout<<"@ "<<sc_time_stamp()<<"----------VCD File Created---------"<<endl;
sc_trace(VCDFile, cITB->clock, "Clock");
sc_trace(VCDFile, cITB->inData, "inData");
sc_trace(VCDFile, cITB->reset, "reset");
sc_trace(VCDFile, cITB->clear, "clear");
sc_trace(VCDFile, cITB->payloadOut, "payloadOut");
sc_trace(VCDFile, cITB->countOut, "countOut");
sc_trace(VCDFile, cITB->errorOut, "errorOut");
cout<<"@ "<<sc_time_stamp()<<"----------Start Simulation---------"<<endl;
sc_start(4000, SC_NS);
cout<<"@ "<<sc_time_stamp()<<"----------End Simulation---------"<<endl;
return 0;
}
|
/******************************************************************************
* *
* Copyright (C) 2022 MachineWare GmbH *
* All Rights Reserved *
* *
* This is work is licensed under the terms described in the LICENSE file *
* found in the root directory of this source tree. *
* *
******************************************************************************/
#include "vcml/core/systemc.h"
#include "vcml/core/thctl.h"
#include "vcml/core/module.h"
#include "vcml/debugging/suspender.h"
namespace vcml {
namespace debugging {
struct suspend_manager {
atomic<bool> is_quitting;
atomic<bool> is_suspended;
mutable mutex suspender_lock;
vector<suspender*> suspenders;
void request_pause(suspender* s);
void request_resume(suspender* s);
bool is_suspending(const suspender* s) const;
size_t count() const;
suspender* current() const;
void quit();
void notify_suspend(sc_object* obj = nullptr);
void notify_resume(sc_object* obj = nullptr);
void handle_requests();
suspend_manager();
static suspend_manager& instance();
};
suspend_manager& g_manager = suspend_manager::instance();
void suspend_manager::request_pause(suspender* s) {
if (is_quitting)
return;
if (!sim_running())
VCML_ERROR("cannot suspend, simulation not running");
lock_guard<mutex> guard(suspender_lock);
if (suspenders.empty())
on_next_update([&]() -> void { handle_requests(); });
stl_add_unique(suspenders, s);
}
void suspend_manager::request_resume(suspender* s) {
lock_guard<mutex> guard(suspender_lock);
stl_remove(suspenders, s);
if (suspenders.empty())
thctl_notify();
}
bool suspend_manager::is_suspending(const suspender* s) const {
lock_guard<mutex> guard(suspender_lock);
return stl_contains(suspenders, s);
}
size_t suspend_manager::count() const {
lock_guard<mutex> guard(suspender_lock);
size_t n = 0;
for (auto s : suspenders)
if (s->check_suspension_point())
n++;
return n;
}
suspender* suspend_manager::current() const {
lock_guard<mutex> guard(suspender_lock);
if (suspenders.empty())
return nullptr;
return suspenders.front();
}
void suspend_manager::quit() {
lock_guard<mutex> guard(suspender_lock);
if (!is_quitting)
on_next_update(request_stop);
is_quitting = true;
suspenders.clear();
thctl_notify();
}
void suspend_manager::notify_suspend(sc_object* obj) {
const auto& children = obj ? obj->get_child_objects()
: sc_core::sc_get_top_level_objects();
for (auto child : children)
notify_suspend(child);
if (obj == nullptr)
return;
module* mod = dynamic_cast<module*>(obj);
if (mod != nullptr)
mod->session_suspend();
}
void suspend_manager::notify_resume(sc_object* obj) {
const auto& children = obj ? obj->get_child_objects()
: sc_core::sc_get_top_level_objects();
for (auto child : children)
notify_resume(child);
if (obj == nullptr)
return;
module* mod = dynamic_cast<module*>(obj);
if (mod != nullptr)
mod->session_resume();
}
void suspend_manager::handle_requests() {
if (is_quitting || count() == 0)
return;
is_suspended = true;
notify_suspend();
while (count() > 0)
thctl_suspend();
notify_resume();
is_suspended = false;
}
suspend_manager::suspend_manager():
is_quitting(false), is_suspended(false), suspender_lock(), suspenders() {
}
suspend_manager& suspend_manager::instance() {
static suspend_manager singleton;
return singleton;
}
suspender::suspender(const string& name):
m_pcount(), m_name(name), m_owner(hierarchy_top()) {
if (m_owner != nullptr)
m_name = mkstr("%s%c", m_owner->name(), SC_HIERARCHY_CHAR) + name;
}
suspender::~suspender() {
if (is_suspending())
resume();
}
bool suspender::check_suspension_point() {
return true;
}
bool suspender::is_suspending() const {
return suspend_manager::instance().is_suspending(this);
}
void suspender::suspend(bool wait) {
suspend_manager& manager = suspend_manager::instance();
if (m_pcount++ == 0)
manager.request_pause(this);
if (wait && !thctl_is_sysc_thread())
thctl_block();
}
void suspender::resume() {
if (--m_pcount == 0)
suspend_manager::instance().request_resume(this);
VCML_ERROR_ON(m_pcount < 0, "unmatched resume");
}
suspender* suspender::current() {
return suspend_manager::instance().current();
}
void suspender::quit() {
suspend_manager::instance().quit();
}
bool suspender::simulation_suspended() {
return suspend_manager::instance().is_suspended;
}
void suspender::handle_requests() {
suspend_manager::instance().handle_requests();
}
} // namespace debugging
} // namespace vcml
|
#include "PluginFactory.h"
#include "PrintITL/PrintITL.h"
#include "PrintAML/PrintAML.h"
#include "PrintSkeleton/PrintSkeleton.h"
#include "PrintDot/PrintDotSimple.h"
#include "PrintDot/PrintDotFull.h"
#include "PrintDot/PrintDotStates.h"
#include "PrintSystemC/PrintSystemC.h"
#include "PrintSVA/PrintSVA.h"
#include "PrintXML/PrintXML.h"
PluginFactory *PluginFactory::create(std::string type) {
if (type == "PrintITL") return new PrintITL();
if (type == "PrintAML") return new PrintAML();
if (type == "PrintSkeleton") return new PrintSkeleton();
if (type == "PrintDotSimple") return new PrintDotSimple();
if (type == "PrintDotFull") return new PrintDotFull();
if (type == "PrintDotStates") return new PrintDotStates();
if (type == "PrintSystemC") return new PrintSystemC();
if (type == "PrintSVA") return new PrintSVA();
if (type == "PrintXML") return new PrintXML();
return nullptr;
} |
#include<systemc.h>
#include<string>
#include<vector>
#include<map>
#include<fstream>
#include<nana/gui.hpp>
#include<nana/gui/widgets/button.hpp>
#include<nana/gui/widgets/menubar.hpp>
#include<nana/gui/widgets/group.hpp>
#include<nana/gui/widgets/textbox.hpp>
#include<nana/gui/filebox.hpp>
#include "top.hpp"
#include "gui.hpp"
using std::string;
using std::vector;
using std::map;
using std::fstream;
int sc_main(int argc, char *argv[])
{
using namespace nana;
vector<string> instruction_queue;
string bench_name = "";
int nadd,nmul,nls, n_bits, bpb_size, cpu_freq;
nadd = 3;
nmul = nls = 2;
n_bits = 2;
bpb_size = 4;
cpu_freq = 500; // definido em Mhz - 500Mhz default
std::vector<int> sizes;
bool spec = false;
int mode = 0;
bool fila = false;
ifstream inFile;
form fm(API::make_center(1024,700));
place plc(fm);
place upper(fm);
place lower(fm);
listbox table(fm);
listbox reg(fm);
listbox instruct(fm);
listbox rob(fm);
menubar mnbar(fm);
button start(fm);
button run_all(fm);
button clock_control(fm);
button exit(fm);
group clock_group(fm);
label clock_count(clock_group);
fm.caption("TFSim");
clock_group.caption("Ciclo");
clock_group.div("count");
grid memory(fm,rectangle(),10,50);
// Tempo de latencia de uma instrucao
// Novas instrucoes devem ser inseridas manualmente aqui
map<string,int> instruct_time{{"DADD",4},{"DADDI",4},{"DSUB",6},
{"DSUBI",6},{"DMUL",10},{"DDIV",16},{"MEM",2},
{"SLT",1},{"SGT", 1}};
// Responsavel pelos modos de execução
top top1("top");
start.caption("Start");
clock_control.caption("Next cycle");
run_all.caption("Run all");
exit.caption("Exit");
plc["rst"] << table;
plc["btns"] << start << clock_control << run_all << exit;
plc["memor"] << memory;
plc["regs"] << reg;
plc["rob"] << rob;
plc["instr"] << instruct;
plc["clk_c"] << clock_group;
clock_group["count"] << clock_count;
clock_group.collocate();
spec = false;
//set_spec eh so visual
set_spec(plc,spec);
plc.collocate();
mnbar.push_back("Opções");
menu &op = mnbar.at(0);
//menu::item_proxy spec_ip =
op.append("Especulação");
auto spec_sub = op.create_sub_menu(0);
// Modo com 1 preditor para todos os branchs
spec_sub->append("1 Preditor", [&](menu::item_proxy &ip)
{
if(ip.checked()){
spec = true;
mode = 1;
spec_sub->checked(1, false);
}
else{
spec = false;
mode = 0;
}
set_spec(plc,spec);
});
// Modo com o bpb
spec_sub->append("Branch Prediction Buffer", [&](menu::item_proxy &ip)
{
if(ip.checked()){
spec = true;
mode = 2;
spec_sub->checked(0, false);
}
else{
spec = false;
mode = 0;
}
set_spec(plc, spec);
});
spec_sub->check_style(0,menu::checks::highlight);
spec_sub->check_style(1,menu::checks::highlight);
op.append("Modificar valores...");
// novo submenu para escolha do tamanho do bpb e do preditor
auto sub = op.create_sub_menu(1);
sub->append("Tamanho do BPB e Preditor", [&](menu::item_proxy &ip)
{
inputbox ibox(fm, "", "Definir tamanhos");
inputbox::integer size("BPB", bpb_size, 2, 10, 2);
inputbox::integer bits("N_BITS", n_bits, 1, 3, 1);
if(ibox.show_modal(size, bits)){
bpb_size = size.value();
n_bits = bits.value();
}
});
sub->append("Número de Estações de Reserva",[&](menu::item_proxy ip)
{
inputbox ibox(fm,"","Quantidade de Estações de Reserva");
inputbox::integer add("ADD/SUB",nadd,1,10,1);
inputbox::integer mul("MUL/DIV",nmul,1,10,1);
inputbox::integer sl("LOAD/STORE",nls,1,10,1);
if(ibox.show_modal(add,mul,sl))
{
nadd = add.value();
nmul = mul.value();
nls = sl.value();
}
});
// Menu de ajuste dos tempos de latencia na interface
// Novas instrucoes devem ser adcionadas manualmente aqui
sub->append("Tempos de latência", [&](menu::item_proxy &ip)
{
inputbox ibox(fm,"","Tempos de latência para instruções");
inputbox::text dadd_t("DADD",std::to_string(instruct_time["DADD"]));
inputbox::text daddi_t("DADDI",std::to_string(instruct_time["DADDI"]));
inputbox::text dsub_t("DSUB",std::to_string(instruct_time["DSUB"]));
inputbox::text dsubi_t("DSUBI",std::to_string(instruct_time["DSUBI"]));
inputbox::text dmul_t("DMUL",std::to_string(instruct_time["DMUL"]));
inputbox::text ddiv_t("DDIV",std::to_string(instruct_time["DDIV"]));
inputbox::text mem_t("Load/Store",std::to_string(instruct_time["MEM"]));
if(ibox.show_modal(dadd_t,daddi_t,dsub_t,dsubi_t,dmul_t,ddiv_t,mem_t))
{
instruct_time["DADD"] = std::stoi(dadd_t.value());
instruct_time["DADDI"] = std::stoi(daddi_t.value());
instruct_time["DSUB"] = std::stoi(dsub_t.value());
instruct_time["DSUBI"] = std::stoi(dsubi_t.value());
instruct_time["DMUL"] = std::stoi(dmul_t.value());
instruct_time["DDIV"] = std::stoi(ddiv_t.value());
instruct_time["MEM"] = std::stoi(mem_t.value());
}
});
sub->append("Frequência CPU", [&](menu::item_proxy &ip)
{
inputbox ibox(fm,"Em Mhz","Definir frequência da CPU");
inputbox::text freq("Frequência", std::to_string(cpu_freq));
if(ibox.show_modal(freq)){
cpu_freq = std::stoi(freq.value());
}
});
sub->append("Fila de instruções", [&](menu::item_proxy &ip)
{
filebox fb(0,true);
inputbox ibox(fm,"Localização do arquivo com a lista de instruções:");
inputbox::path caminho("",fb);
if(ibox.show_modal(caminho))
{
auto path = caminho.value();
inFile.open(path);
if(!add_instructions(inFile,instruction_queue,instruct))
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
fila = true;
}
});
sub->append("Valores de registradores inteiros",[&](menu::item_proxy &ip)
{
filebox fb(0,true);
inputbox ibox(fm,"Localização do arquivo de valores de registradores inteiros:");
inputbox::path caminho("",fb);
if(ibox.show_modal(caminho))
{
auto path = caminho.value();
inFile.open(path);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
auto reg_gui = reg.at(0);
int value,i = 0;
while(inFile >> value && i < 32)
{
reg_gui.at(i).text(1,std::to_string(value));
i++;
}
for(; i < 32 ; i++)
reg_gui.at(i).text(1,"0");
inFile.close();
}
}
});
sub->append("Valores de registradores PF",[&](menu::item_proxy &ip)
{
filebox fb(0,true);
inputbox ibox(fm,"Localização do arquivo de valores de registradores PF:");
inputbox::path caminho("",fb);
if(ibox.show_modal(caminho))
{
auto path = caminho.value();
inFile.open(path);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
auto reg_gui = reg.at(0);
int i = 0;
float value;
while(inFile >> value && i < 32)
{
reg_gui.at(i).text(4,std::to_string(value));
i++;
}
for(; i < 32 ; i++)
reg_gui.at(i).text(4,"0");
inFile.close();
}
}
});
sub->append("Valores de memória",[&](menu::item_proxy &ip)
{
filebox fb(0,true);
inputbox ibox(fm,"Localização do arquivo de valores de memória:");
inputbox::path caminho("",fb);
if(ibox.show_modal(caminho))
{
auto path = caminho.value();
inFile.open(path);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
int i = 0;
int value;
while(inFile >> value && i < 500)
{
memory.Set(i,std::to_string(value));
i++;
}
for(; i < 500 ; i++)
{
memory.Set(i,"0");
}
inFile.close();
}
}
});
op.append("Verificar conteúdo...");
auto new_sub = op.create_sub_menu(2);
new_sub->append("Valores de registradores",[&](menu::item_proxy &ip) {
filebox fb(0,true);
inputbox ibox(fm,"Localização do arquivo de valores de registradores:");
inputbox::path caminho("",fb);
if(ibox.show_modal(caminho))
{
auto path = caminho.value();
inFile.open(path);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
string str;
int reg_pos,i;
bool is_float, ok;
ok = true;
while(inFile >> str)
{
if(str[0] == '$')
{
if(str[1] == 'f')
{
i = 2;
is_float = true;
}
else
{
i = 1;
is_float = false;
}
reg_pos = std::stoi(str.substr(i,str.size()-i));
auto reg_gui = reg.at(0);
string value;
inFile >> value;
if(!is_float)
{
if(reg_gui.at(reg_pos).text(1) != value)
{
ok = false;
break;
}
}
else
{
if(std::stof(reg_gui.at(reg_pos).text(4)) != std::stof(value))
{
ok = false;
break;
}
}
}
}
inFile.close();
msgbox msg("Verificação de registradores");
if(ok)
{
msg << "Registradores especificados apresentam valores idênticos!";
msg.icon(msgbox::icon_information);
}
else
{
msg << "Registradores especificados apresentam valores distintos!";
msg.icon(msgbox::icon_error);
}
msg.show();
}
}
});
new_sub->append("Valores de memória",[&](menu::item_proxy &ip) {
filebox fb(0,true);
inputbox ibox(fm,"Localização do arquivo de valores de memória:");
inputbox::path caminho("",fb);
if(ibox.show_modal(caminho))
{
auto path = caminho.value();
inFile.open(path);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
string value;
bool ok;
ok = true;
for(int i = 0 ; i < 500 ; i++)
{
inFile >> value;
if(std::stoi(memory.Get(i)) != (int)std::stol(value,nullptr,16))
{
ok = false;
break;
}
}
inFile.close();
msgbox msg("Verificação de memória");
if(ok)
{
msg << "Endereços de memória especificados apresentam valores idênticos!";
msg.icon(msgbox::icon_information);
}
else
{
msg << "Endereços de memória especificados apresentam valores distintos!";
msg.icon(msgbox::icon_error);
}
msg.show();
}
}
});
op.append("Benchmarks");
auto bench_sub = op.create_sub_menu(3);
bench_sub->append("Fibonacci",[&](menu::item_proxy &ip){
string path = "in/benchmarks/fibonacci/fibonacci.txt";
bench_name = "fibonacci";
inFile.open(path);
if(!add_instructions(inFile,instruction_queue,instruct))
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
fila = true;
});
bench_sub->append("Stall por Divisão",[&](menu::item_proxy &ip){
string path = "in/benchmarks/division_stall.txt";
inFile.open(path);
if(!add_instructions(inFile,instruction_queue,instruct))
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
fila = true;
});
bench_sub->append("Stress de Memória (Stores)",[&](menu::item_proxy &ip){
string path = "in/benchmarks/store_stress/store_stress.txt";
bench_name = "store_stress";
inFile.open(path);
if(!add_instructions(inFile,instruction_queue,instruct))
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
fila = true;
});
bench_sub->append("Stall por hazard estrutural (Adds)",[&](menu::item_proxy &ip){
string path = "in/benchmarks/res_stations_stall.txt";
inFile.open(path);
if(!add_instructions(inFile,instruction_queue,instruct))
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
fila = true;
});
bench_sub->append("Busca Linear",[&](menu::item_proxy &ip){
string path = "in/benchmarks/linear_search/linear_search.txt";
bench_name = "linear_search";
inFile.open(path);
if(!add_instructions(inFile,instruction_queue,instruct))
show_message("Arquivo inválido","Não foi possível abrir o arquivo");
else
fila = true;
path = "in/benchmarks/linear_search/memory.txt";
inFile.open(path);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
int i = 0;
int value;
while(inFile >> value && i < 500)
{
memory.Set(i,std::to_string(value));
i++;
}
for(; i < 500 ; i++)
{
memory.Set(i,"0");
}
inFile.close();
}
path = "in/benchmarks/linear_search/regi_i.txt";
inFile.open(path);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
auto reg_gui = reg.at(0);
int value,i = 0;
while(inFile >> value && i < 32)
{
reg_gui.at(i).text(1,std::to_string(value));
i++;
}
for(; i < 32 ; i++)
reg_gui.at(i).text(1,"0");
inFile.close();
}
});
bench_sub->append("Busca Binária",[&](menu::item_proxy &ip){
string path = "in/benchmarks/binary_search/binary_search.txt";
bench_name = "binary_search";
inFile.open(path);
if(!add_instructions(inFile,instruction_queue,instruct))
show_message("Arquivo inválido","Não foi possível abrir o arquivo");
else
fila = true;
path = "in/benchmarks/binary_search/memory.txt";
inFile.open(path);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
int i = 0;
int value;
while(inFile >> value && i < 500)
{
memory.Set(i,std::to_string(value));
i++;
}
for(; i < 500 ; i++)
{
memory.Set(i,"0");
}
inFile.close();
}
path = "in/benchmarks/binary_search/regs.txt";
inFile.open(path);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
auto reg_gui = reg.at(0);
int value,i = 0;
while(inFile >> value && i < 32)
{
reg_gui.at(i).text(1,std::to_string(value));
i++;
}
for(; i < 32 ; i++)
reg_gui.at(i).text(1,"0");
inFile.close();
}
});
bench_sub->append("Matriz Search",[&](menu::item_proxy &ip){
string path = "in/benchmarks/matriz_search/matriz_search.txt";
bench_name = "matriz_search";
inFile.open(path);
if(!add_instructions(inFile,instruction_queue,instruct))
show_message("Arquivo inválido","Não foi possível abrir o arquivo");
else
fila = true;
path = "in/benchmarks/matriz_search/memory.txt";
inFile.open(path);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
int i = 0;
int value;
while(inFile >> value && i < 500)
{
memory.Set(i,std::to_string(value));
i++;
}
for(; i < 500 ; i++)
{
memory.Set(i,"0");
}
inFile.close();
}
path = "in/benchmarks/matriz_search/regs.txt";
inFile.open(path);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
auto reg_gui = reg.at(0);
int value,i = 0;
while(inFile >> value && i < 32)
{
reg_gui.at(i).text(1,std::to_string(value));
i++;
}
for(; i < 32 ; i++)
reg_gui.at(i).text(1,"0");
inFile.close();
}
});
bench_sub->append("Bubble Sort",[&](menu::item_proxy &ip){
string path = "in/benchmarks/bubble_sort/bubble_sort.txt";
bench_name = "bubble_sort";
inFile.open(path);
if(!add_instructions(inFile,instruction_queue,instruct))
show_message("Arquivo inválido","Não foi possível abrir o arquivo");
else
fila = true;
path = "in/benchmarks/bubble_sort/memory.txt";
|
inFile.open(path);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
int i = 0;
int value;
while(inFile >> value && i < 500)
{
memory.Set(i,std::to_string(value));
i++;
}
for(; i < 500 ; i++)
{
memory.Set(i,"0");
}
inFile.close();
}
path = "in/benchmarks/bubble_sort/regs.txt";
inFile.open(path);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
auto reg_gui = reg.at(0);
int value,i = 0;
while(inFile >> value && i < 32)
{
reg_gui.at(i).text(1,std::to_string(value));
i++;
}
for(; i < 32 ; i++)
reg_gui.at(i).text(1,"0");
inFile.close();
}
});
bench_sub->append("Insertion Sort",[&](menu::item_proxy &ip){
string path = "in/benchmarks/insertion_sort/insertion_sort.txt";
bench_name = "insertion_sort";
inFile.open(path);
if(!add_instructions(inFile,instruction_queue,instruct))
show_message("Arquivo inválido","Não foi possível abrir o arquivo");
else
fila = true;
path = "in/benchmarks/insertion_sort/memory.txt";
inFile.open(path);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
int i = 0;
int value;
while(inFile >> value && i < 500)
{
memory.Set(i,std::to_string(value));
i++;
}
for(; i < 500 ; i++)
{
memory.Set(i,"0");
}
inFile.close();
}
path = "in/benchmarks/insertion_sort/regs.txt";
inFile.open(path);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
auto reg_gui = reg.at(0);
int value,i = 0;
while(inFile >> value && i < 32)
{
reg_gui.at(i).text(1,std::to_string(value));
i++;
}
for(; i < 32 ; i++)
reg_gui.at(i).text(1,"0");
inFile.close();
}
});
bench_sub->append("Tick Tack",[&](menu::item_proxy &ip){
string path = "in/benchmarks/tick_tack/tick_tack.txt";
bench_name = "tick_tack";
inFile.open(path);
if(!add_instructions(inFile,instruction_queue,instruct))
show_message("Arquivo inválido","Não foi possível abrir o arquivo");
else
fila = true;
path = "in/benchmarks/tick_tack/regs.txt";
inFile.open(path);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
auto reg_gui = reg.at(0);
int value,i = 0;
while(inFile >> value && i < 32)
{
reg_gui.at(i).text(1,std::to_string(value));
i++;
}
for(; i < 32 ; i++)
reg_gui.at(i).text(1,"0");
inFile.close();
}
});
vector<string> columns = {"#","Name","Busy","Op","Vj","Vk","Qj","Qk","A"};
for(unsigned int i = 0 ; i < columns.size() ; i++)
{
table.append_header(columns[i].c_str());
if(i && i != 3)
table.column_at(i).width(45);
else if (i == 3)
table.column_at(i).width(60);
else
table.column_at(i).width(30);
}
columns = {"","Value","Qi"};
sizes = {30,75,40};
for(unsigned int k = 0 ; k < 2 ; k++)
for(unsigned int i = 0 ; i < columns.size() ; i++)
{
reg.append_header(columns[i]);
reg.column_at(k*columns.size() + i).width(sizes[i]);
}
auto reg_gui = reg.at(0);
for(int i = 0 ; i < 32 ;i++)
{
string index = std::to_string(i);
reg_gui.append("R" + index);
reg_gui.at(i).text(3,"F" + index);
}
columns = {"Instruction","Issue","Execute","Write Result"};
sizes = {140,60,70,95};
for(unsigned int i = 0 ; i < columns.size() ; i++)
{
instruct.append_header(columns[i]);
instruct.column_at(i).width(sizes[i]);
}
columns = {"Entry","Busy","Instruction","State","Destination","Value"};
sizes = {45,45,120,120,90,60};
for(unsigned int i = 0 ; i < columns.size() ; i++)
{
rob.append_header(columns[i]);
rob.column_at(i).width(sizes[i]);
}
srand(static_cast <unsigned> (time(0)));
for(int i = 0 ; i < 32 ; i++)
{
if(i)
reg_gui.at(i).text(1,std::to_string(rand()%100));
else
reg_gui.at(i).text(1,std::to_string(0));
reg_gui.at(i).text(2,"0");
reg_gui.at(i).text(4,std::to_string(static_cast <float> (rand()) / static_cast <float> (RAND_MAX/100.0)));
reg_gui.at(i).text(5,"0");
}
for(int i = 0 ; i < 500 ; i++)
memory.Push(std::to_string(rand()%100));
for(int k = 1; k < argc; k+=2)
{
int i;
if (strlen(argv[k]) > 2)
show_message("Opção inválida",string("Opção \"") + string(argv[k]) + string("\" inválida"));
else
{
char c = argv[k][1];
switch(c)
{
case 'q':
inFile.open(argv[k+1]);
if(!add_instructions(inFile,instruction_queue,instruct))
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
fila = true;
break;
case 'i':
inFile.open(argv[k+1]);
int value;
i = 0;
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
while(inFile >> value && i < 32)
{
reg_gui.at(i).text(1,std::to_string(value));
i++;
}
for(; i < 32 ; i++)
reg_gui.at(i).text(1,"0");
inFile.close();
}
break;
case 'f':
float value_fp;
i = 0;
inFile.open(argv[k+1]);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
while(inFile >> value_fp && i < 32)
{
reg_gui.at(i).text(4,std::to_string(value_fp));
i++;
}
for(; i < 32 ; i++)
reg_gui.at(i).text(4,"0");
inFile.close();
}
break;
case 'm':
inFile.open(argv[k+1]);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
int value;
i = 0;
while(inFile >> value && i < 500)
{
memory.Set(i,std::to_string(value));
i++;
}
for(; i < 500 ; i++)
{
memory.Set(i,"0");
}
inFile.close();
}
break;
case 'r':
inFile.open(argv[k+1]);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
int value;
if(inFile >> value && value <= 10 && value > 0)
nadd = value;
if(inFile >> value && value <= 10 && value > 0)
nmul = value;
if(inFile >> value && value <= 10 && value > 0)
nls = value;
inFile.close();
}
break;
case 's':
spec = true;
set_spec(plc,spec);
//spec_ip.checked(true);
k--;
break;
case 'l':
inFile.open(argv[k+1]);
if(!inFile.is_open())
show_message("Arquivo inválido","Não foi possível abrir o arquivo!");
else
{
string inst;
int value;
while(inFile >> inst)
{
if(inFile >> value && instruct_time.count(inst))
instruct_time[inst] = value;
}
}
inFile.close();
break;
default:
show_message("Opção inválida",string("Opção \"") + string(argv[k]) + string("\" inválida"));
break;
}
}
}
clock_control.enabled(false);
run_all.enabled(false);
start.events().click([&]
{
if(fila)
{
start.enabled(false);
clock_control.enabled(true);
run_all.enabled(true);
//Desativa os menus apos inicio da execucao
op.enabled(0,false);
op.enabled(1,false);
op.enabled(3,false);
for(int i = 0; i < 2; i++)
spec_sub->enabled(i, false);
for(int i = 0 ; i < 8 ; i++)
sub->enabled(i,false);
for(int i = 0 ; i < 10 ; i++)
bench_sub->enabled(i,false);
if(spec){
// Flag mode setada pela escolha no menu
if(mode == 1)
top1.rob_mode(n_bits,nadd,nmul,nls,instruct_time,instruction_queue,table,memory,reg,instruct,clock_count,rob);
else if(mode == 2)
top1.rob_mode_bpb(n_bits, bpb_size, nadd,nmul,nls,instruct_time,instruction_queue,table,memory,reg,instruct,clock_count,rob);
}
else
top1.simple_mode(nadd,nmul,nls,instruct_time,instruction_queue,table,memory,reg,instruct,clock_count);
sc_start();
}
else
show_message("Fila de instruções vazia","A fila de instruções está vazia. Insira um conjunto de instruções para iniciar.");
});
clock_control.events().click([&]
{
if(top1.get_queue().queue_is_empty() && top1.get_rob().rob_is_empty())
return;
if(sc_is_running())
sc_start();
});
run_all.events().click([&]{
// enquanto queue e rob nao estao vazios, roda ate o fim
while(!(top1.get_queue().queue_is_empty() && top1.get_rob().rob_is_empty())){
if(sc_is_running())
sc_start();
}
top1.metrics(cpu_freq, mode, bench_name, n_bits);
});
exit.events().click([]
{
sc_stop();
API::exit();
});
fm.show();
exec();
return 0;
}
|
#include <string>
#include "systemc.h"
#include "system.h"
#include "sc_trace.hpp"
#include "noc_tile.h"
// comparison counters
uint32_t n_bytes_cmp = 0;
uint32_t n_err_bytes = 0;
noc_commander::noc_commander(sc_module_name name) : noc_tile(name) {
SC_THREAD(main);
SC_THREAD(recv_listener);
// read buffers
_write_buf_size = read_input_files(_write_buf);
_exp_buf_size = read_expected_output_file(_exp_buf);
// print buffers
int i = 0;
printf( "Encryption key: ");
for (int j = 0; j < AES_256_KEY_LEN; ++j, ++i) {
printf("%02x ", _write_buf[i]);
}
printf("\nIV: ");
for (int j = 0; j < AES_BLOCK_LEN; ++j, ++i) {
printf("%02x ", _write_buf[i]);
}
printf("\nInput: ");
for (int j = 0; j < _write_buf_size - AES_BLOCK_LEN - AES_256_KEY_LEN; ++j, ++i) {
printf("%02x ", _write_buf[i]);
}
printf("\nExpected output: ");
for (int j = 0; j < _exp_buf_size; ++j) {
printf("%02x ", _exp_buf[j]);
}
printf("\n");
// initial state
_state = NOC_COMMANDER_IDLE;
_in_fifo_head = 0;
_in_fifo_tail = 0;
}
void noc_commander::signal(uint32_t signal) {
LOGF("[%s]: Received interrupt with signal %d", this->name(), signal);
if (signal == 1) {
_state == NOC_COMMANDER_IDLE;
recv_processor();
}
}
void noc_commander::transmit_to_responders(noc_data_t *packets, uint32_t n) {
// determine number of packets
n = (n / NOC_DSIZE) + ((n % NOC_DSIZE) ? 1 : 0);
// interleave requests
uint32_t noc_responder0_addr = NOC_BASE_ADDR_RESPONDER0;
while (n) {
adapter_if->write_packet(0, noc_responder0_addr, packets, NOC_DSIZE, REDUNDANT_COMMAND);
// increment counters
n--;
noc_responder0_addr += NOC_DSIZE;
packets++;
}
//adapter_if->write_packet(0, NOC_BASE_ADDR_RESPONDER0, packets, n, REDUNDANT_COMMAND);
}
void noc_commander::main() {
LOG("Hello, world!");
POSEDGE();
// write command
_state = NOC_COMMANDER_WRITE_DATA;
_cur_cmd.skey = NOC_CMD_SKEY;
_cur_cmd.cmd = 0;
_cur_cmd.size = _write_buf_size;
_cur_cmd.tx_addr = 0x0;
_cur_cmd.trans_id = 1;
_cur_cmd.status = 0;
_cur_cmd.ekey = NOC_CMD_EKEY;
_cur_cmd.chksum = CALC_CMD_CHKSUM(_cur_cmd);
transmit_to_responders((noc_data_t *)&_cur_cmd, sizeof(noc_cmd_t));
// write payload
transmit_to_responders((noc_data_t *)_write_buf, _write_buf_size);
}
void noc_commander::recv_listener() {
// NoC packets
uint32_t src_addr;
uint32_t rel_addr;
noc_data_t data;
while (true) {
// receive packet
if (adapter_if->read_packet(src_addr, rel_addr, data)) {
// capture in logger
LOGF("[%s]: Received request containing %016lx to %08x from %08x", this->name(), data, rel_addr, src_addr);
rel_addr += NOC_BASE_ADDR_COMMANDER;
latency_tracker::capture(&data, &rel_addr);
rel_addr -= NOC_BASE_ADDR_COMMANDER;
// compare bytes
for (int i = 0; i < NOC_DSIZE;
++i, data >>= 8, n_bytes_cmp++) {
if ((uint8_t)data != _exp_buf[n_bytes_cmp]) {
printf("Error in byte %08x, expected %02x, got %02x\n", n_bytes_cmp, _exp_buf[n_bytes_cmp], (uint8_t)data);
n_err_bytes++;
}
}
if (n_bytes_cmp >= _exp_buf_size) {
LOG("Setting to IDLE");
_state == NOC_COMMANDER_IDLE;
break;
}
}
}
recv_processor();
}
void noc_commander::recv_processor() {
// compare received and expected buffer
LOG("Completed simulation, checking output...");
printf("Final report: %d bytes compared, %d errors\n", n_bytes_cmp, n_err_bytes);
sc_stop();
}
|
/*
* Copyright (c) 2010 TIMA Laboratory
*
* This file is part of Rabbits.
*
* Rabbits is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Rabbits is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Rabbits. If not, see <http://www.gnu.org/licenses/>.
*/
#include <systemc.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sl_block_device.h>
/* #define DEBUG_DEVICE_BLOCK */
#ifdef DEBUG_DEVICE_BLOCK
#define DPRINTF(fmt, args...) \
do { printf("sl_block_device: " fmt , ##args); } while (0)
#define DCOUT if (1) cout
#else
#define DPRINTF(fmt, args...) do {} while(0)
#define DCOUT if (0) cout
#endif
#define EPRINTF(fmt, args...) \
do { fprintf(stderr, "sl_block_device: " fmt , ##args); } while (0)
sl_block_device::sl_block_device (sc_module_name _name, uint32_t master_id,
const char *fname, uint32_t block_size)
:sc_module(_name)
{
char *buf = new char[strlen(_name) + 3];
m_cs_regs = new sl_block_device_CSregs_t;
m_cs_regs->m_status = 0;
m_cs_regs->m_buffer = 0;
m_cs_regs->m_op = 0;
m_cs_regs->m_lba = 0;
m_cs_regs->m_count = 0;
m_cs_regs->m_size = 0;
m_cs_regs->m_block_size = block_size;
m_cs_regs->m_irqen = 0;
m_cs_regs->m_irq = 0;
strcpy(buf, _name);
buf[strlen(_name)] = '_';
buf[strlen(_name)+1] = 'm';
buf[strlen(_name)+2] = '\0';
master = new sl_block_device_master(buf, master_id);
buf[strlen(_name)+1] = 's';
slave = new sl_block_device_slave(buf, m_cs_regs, &ev_op_start, &ev_irq_update);
m_fd = -1;
open_host_file (fname);
SC_THREAD (irq_update_thread);
SC_THREAD (control_thread);
}
sl_block_device::~sl_block_device ()
{
DPRINTF("destructor called\n");
}
static off_t get_file_size (int fd)
{
off_t old_pos = lseek (fd, 0, SEEK_CUR);
off_t ret = lseek (fd, 0, SEEK_END);
lseek (fd, old_pos, SEEK_SET);
return ret;
}
void sl_block_device::open_host_file (const char *fname)
{
if (m_fd != -1)
{
::close (m_fd);
m_fd = -1;
}
if (fname)
{
m_fd = ::open(fname, O_RDWR | O_CREAT, 0644);
if(m_fd < 0)
{
EPRINTF("Impossible to open file : %s\n", fname);
return;
}
m_cs_regs->m_size = get_file_size (m_fd) / m_cs_regs->m_block_size;
}
}
master_device *
sl_block_device::get_master ()
{
return (master_device *)master;
}
slave_device *
sl_block_device::get_slave ()
{
return (slave_device *)slave;
}
void
sl_block_device::control_thread ()
{
uint32_t offset, addr, transfer_size;
uint8_t *data_buff;
int func_ret;
while(1)
{
switch(m_cs_regs->m_op)
{
case BLOCK_DEVICE_NOOP:
DPRINTF("Got a BLOCK_DEVICE_NOOP\n");
wait(ev_op_start);
break;
case BLOCK_DEVICE_READ:
m_cs_regs->m_status = BLOCK_DEVICE_BUSY;
transfer_size = m_cs_regs->m_count * m_cs_regs->m_block_size;
data_buff = new uint8_t[transfer_size + 4];
DPRINTF("Got a BLOCK_DEVICE_READ of size %x\n", transfer_size);
/* Read in device */
lseek(m_fd, m_cs_regs->m_lba*m_cs_regs->m_block_size, SEEK_SET);
func_ret = ::read(m_fd, data_buff, transfer_size);
addr = m_cs_regs->m_buffer;
if (func_ret < 0)
{
EPRINTF("Error in ::read()\n");
m_cs_regs->m_op = BLOCK_DEVICE_NOOP;
m_cs_regs->m_status = BLOCK_DEVICE_READ_ERROR;
m_cs_regs->m_count = 0;
break;
}
m_cs_regs->m_count = func_ret / m_cs_regs->m_block_size;
transfer_size = func_ret;
if (transfer_size)
{
/* Send data in memory */
uint32_t up_4align_limit = transfer_size & ~3;
for(offset = 0; offset < up_4align_limit; offset += 4)
{
func_ret = master->cmd_write(addr + offset, data_buff + offset, 4);
if(!func_ret)
break;
}
for (; offset < transfer_size; offset++)
{
func_ret = master->cmd_write(addr + offset, data_buff + offset, 1);
if(!func_ret)
break;
}
if(!func_ret)
{
EPRINTF("Error in Read\n");
m_cs_regs->m_op = BLOCK_DEVICE_NOOP;
m_cs_regs->m_status = BLOCK_DEVICE_READ_ERROR;
m_cs_regs->m_count = offset / m_cs_regs->m_block_size;
break;
}
}
/* Update everything */
if(m_cs_regs->m_irqen)
{
m_cs_regs->m_irq = 1;
ev_irq_update.notify();
}
m_cs_regs->m_op = BLOCK_DEVICE_NOOP;
m_cs_regs->m_status = BLOCK_DEVICE_READ_SUCCESS;
delete data_buff;
break;
case BLOCK_DEVICE_WRITE:
DPRINTF("Got a BLOCK_DEVICE_WRITE\n");
m_cs_regs->m_status = BLOCK_DEVICE_BUSY;
transfer_size = m_cs_regs->m_count * m_cs_regs->m_block_size;
data_buff = new uint8_t[transfer_size + 4];
addr = m_cs_regs->m_buffer;
/* Read data from memory */
for(offset = 0; offset < transfer_size; offset += 4)
{
func_ret = master->cmd_read(addr + offset, data_buff + offset, 4);
if(!func_ret)
break;
}
if(!func_ret)
{
m_cs_regs->m_op = BLOCK_DEVICE_NOOP;
m_cs_regs->m_status = BLOCK_DEVICE_WRITE_ERROR;
break;
}
/* Write in the device */
lseek(m_fd, m_cs_regs->m_lba*m_cs_regs->m_block_size, SEEK_SET);
::write(m_fd, data_buff, transfer_size);
m_cs_regs->m_size = get_file_size (m_fd) / m_cs_regs->m_block_size;
/* Update everything */
if(m_cs_regs->m_irqen)
{
m_cs_regs->m_irq = 1;
ev_irq_update.notify();
}
m_cs_regs->m_op = BLOCK_DEVICE_NOOP;
m_cs_regs->m_status = BLOCK_DEVICE_WRITE_SUCCESS;
delete data_buff;
break;
case BLOCK_DEVICE_FILE_NAME:
DPRINTF("Got a BLOCK_DEVICE_FILE_NAME\n");
m_cs_regs->m_status = BLOCK_DEVICE_BUSY;
transfer_size = m_cs_regs->m_count * m_cs_regs->m_block_size;
data_buff = new uint8_t[transfer_size + 4];
addr = m_cs_regs->m_buffer;
/* Read data from memory */
for(offset = 0; offset < transfer_size; offset += 4)
{
func_ret = master->cmd_read(addr + offset, data_buff + offset, 4);
if(!func_ret)
break;
}
if (func_ret)
open_host_file ((const char*) data_buff);
if(!func_ret || m_fd == -1)
{
m_cs_regs->m_op = BLOCK_DEVICE_NOOP;
m_cs_regs->m_status = BLOCK_DEVICE_WRITE_ERROR;
break;
}
m_cs_regs->m_op = BLOCK_DEVICE_NOOP;
m_cs_regs->m_status = BLOCK_DEVICE_WRITE_SUCCESS;
delete data_buff;
break;
default:
EPRINTF("Error in command\n");
}
}
}
void sl_block_device::irq_update_thread ()
{
while(1)
{
wait(ev_irq_update);
if(m_cs_regs->m_irq == 1)
{
DPRINTF("Raising IRQ\n");
irq = 1;
}
else
{
DPRINTF("Clearing IRQ\n");
irq = 0;
}
}
return;
}
/*
* sl_block_device_master
*/
sl_block_device_master::sl_block_device_master (const char *_name, uint32_t node_id)
: master_device(_name)
{
m_crt_tid = 0;
m_status = MASTER_READY;
m_node_id = node_id;
}
sl_block_device_master::~sl_block_device_master()
{
}
int
sl_block_device_master::cmd_write (uint32_t addr, uint8_t *data, uint8_t nbytes)
{
DPRINTF("Write to %x [0x%08x]\n", addr, *(uint32_t *)data);
send_req (m_crt_tid, addr, data, nbytes, 1);
wait (ev_cmd_done);
if(m_status != MASTER_CMD_SUCCESS)
return 0;
return 1;
}
int
sl_block_device_master::cmd_read (uint32_t addr, uint8_t *data, uint8_t nbytes)
{
m_tr_nbytes = nbytes;
m_tr_rdata = 0;
DPRINTF ("Read from %x\n", addr);
send_req (m_crt_tid, addr, NULL, nbytes, 0);
wait (ev_cmd_done);
for (int i = 0; i < nbytes; i++)
data[i] = ((unsigned char *) &m_tr_rdata)[i];
if (m_status != MASTER_CMD_SUCCESS)
return 0;
return 1;
}
void
sl_block_device_master::rcv_rsp (uint8_t tid, uint8_t *data,
bool bErr, bool bWrite)
{
if (tid != m_crt_tid)
{
EPRINTF ("Bad tid (%d / %d)\n", tid, m_crt_tid);
}
if (bErr)
{
DPRINTF("Cmd KO\n");
m_status = MASTER_CMD_ERROR;
}
else
{
//DPRINTF("Cmd OK\n");
m_status = MASTER_CMD_SUCCESS;
}
if (!bWrite)
{
for (int i = 0; i < m_tr_nbytes; i++)
((unsigned char *) &m_tr_rdata)[i] = data[i];
}
m_crt_tid++;
ev_cmd_done.notify ();
}
/*
* sl_block_device_slave
*/
sl_block_device_slave::sl_block_device_slave (const char *_name,
sl_block_device_CSregs_t *cs_regs, sc_event *op_start, sc_event *irq_update)
: slave_device (_name)
{
m_cs_regs = cs_regs;
ev_op_start = op_start;
ev_irq_update = irq_update;
}
sl_block_device_slave::~sl_block_device_slave()
{
}
void sl_block_device_slave::write (unsigned long ofs, unsigned char be,
unsigned char *data, bool &bErr)
{
uint32_t *val = (uint32_t *) data;
uint32_t lofs = ofs;
uint8_t lbe = be;
bErr = false;
lofs >>= 2;
if (lbe & 0xF0)
{
lofs += 1;
lbe >>= 4;
val++;
}
switch(lofs)
{
case BLOCK_DEVICE_BUFFER :
DPRINTF("BLOCK_DEVICE_BUFFER write: %x\n", *val);
m_cs_regs->m_buffer = *val;
break;
case BLOCK_DEVICE_LBA :
DPRINTF("BLOCK_DEVICE_LBA write: %x\n", *val);
m_cs_regs->m_lba = *val;
break;
case BLOCK_DEVICE_COUNT :
DPRINTF("BLOCK_DEVICE_COUNT write: %x\n", *val);
m_cs_regs->m_count = *val;
break;
case BLOCK_DEVICE_OP :
DPRINTF("BLOCK_DEVICE_OP write: %x\n", *val);
if(m_cs_regs->m_status != BLOCK_DEVICE_IDLE)
{
EPRINTF("Got a command while executing another one\n");
break;
}
m_cs_regs->m_op = *val;
ev_op_start->notify();
break;
case BLOCK_DEVICE_IRQ_ENABLE :
DPRINTF("BLOCK_DEVICE_IRQ_ENABLE write: %x\n", *val);
m_cs_regs->m_irqen = *val;
ev_irq_update->notify();
break;
case BLOCK_DEVICE_STATUS :
case BLOCK_DEVICE_SIZE :
case BLOCK_DEVICE_BLOCK_SIZE :
default:
EPRINTF("Bad %s::%s ofs=0x%X, be=0x%X\n", name (), __FUNCTION__,
(unsigned int) ofs, (unsigned int) be);
}
}
void sl_block_device_slave::read (unsigned long ofs, unsigned char be,
unsigned char *data, bool &bErr)
{
uint32_t *val = (uint32_t *)data;
uint32_t lofs = ofs;
uint8_t lbe = be;
bErr = false;
lofs >>= 2;
if (lbe & 0xF0)
{
lofs += 1;
lbe >>= 4;
val++;
}
switch(lofs)
{
case BLOCK_DEVICE_BUFFER :
*val = m_cs_regs->m_buffer;
DPRINTF("BLOCK_DEVICE_BUFFER read: %x\n", *val);
break;
case BLOCK_DEVICE_LBA :
*val = m_cs_regs->m_lba;
DPRINTF("BLOCK_DEVICE_LBA read: %x\n", *val);
break;
case BLOCK_DEVICE_COUNT :
*val = m_cs_regs->m_count;
DPRINTF("BLOCK_DEVICE_COUNT read: %x\n", *val);
break;
case BLOCK_DEVICE_OP :
*val = m_cs_regs->m_op;
DPRINTF("BLOCK_DEVICE_OP read: %x\n", *val);
break;
case BLOCK_DEVICE_STATUS :
*val = m_cs_regs->m_status;
DPRINTF("BLOCK_DEVICE_STATUS read: %x\n", *val);
if(m_cs_regs->m_status != BLOCK_DEVICE_BUSY)
{
m_cs_regs->m_status = BLOCK_DEVICE_IDLE;
m_cs_regs->m_irq = 0;
ev_irq_update->notify();
}
break;
case BLOCK_DEVICE_IRQ_ENABLE :
*val = m_cs_regs->m_irqen;
DPRINTF("BLOCK_DEVICE_IRQ_ENABLE read: %x\n", *val);
break;
case BLOCK_DEVICE_SIZE :
*val = m_cs_regs->m_size;
DPRINTF("BLOCK_DEVICE_SIZE read: %x\n", *val);
break;
case BLOCK_DEVICE_BLOCK_SIZE :
*val = m_cs_regs->m_block_size;
DPRINTF("BLOCK_DEVICE_BLOCK_SIZE read: %x\n", *val);
break;
default:
EPRINTF("Bad %s::%s ofs=0x%X, be=0x%X\n", name (), __FUNCTION__,
(unsigned int) ofs, (unsigned int) be);
}
}
void sl_block_device_slave::rcv_rqst (unsigned long ofs, unsigned char be,
unsigned char *data, bool bWrite)
{
bool bErr = false;
if(bWrite)
this->write(ofs, be, data, bErr);
else
this->read(ofs, be, data, bErr);
send_rsp(bErr);
return;
}
/*
* Vim standard variables
* vim:set ts=4 expandtab tw=80 cindent syntax=c:
*
* Emacs standard variables
* Local Variables:
* mode: c
* tab-width: 4
* c-basic-offset: 4
* indent-tabs-mode: nil
* End:
*/
|
/* This file is part of EXT_systemc
Copyright (C) 2017 Julien Thevenon ( julien_thevenon at yahoo.fr )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#ifdef EXT_SYSTEMC_SELF_TEST
#include "systemc.h"
#include <iostream>
class top: public sc_module
{
public:
SC_HAS_PROCESS(top);
top(const sc_module_name & p_name):
sc_module(p_name),
m_input0("input0"),
m_input1("input1"),
m_output("output")
{
SC_THREAD(generate_input0);
SC_THREAD(generate_input1);
SC_THREAD(control_simu);
SC_THREAD(compute);
sensitive << m_input0;
sensitive << m_input1;
}
void control_simu(void)
{
wait(80,SC_NS);
sc_stop();
}
void compute(void)
{
while (1)
{
std::cout << sc_time_stamp() << "\tInput0 : " << m_input0 << "\tInput1 : " << m_input1 << std::endl;
bool l_output = m_input0 & m_input1;
std::cout << "==> output : " << l_output << std::endl;
m_output.write(l_output);
wait();
}
}
void generate_input0(void)
{
for(unsigned int l_i =0;
l_i < 4;
++l_i)
{
m_input0.write(false);
wait(10,
SC_NS
);
m_input0.write(true);
wait(10,
SC_NS
);
}
}
void generate_input1(void)
{
for(unsigned int l_i =0;
l_i < 2;
++l_i)
{
m_input1.write(false);
wait(20,
SC_NS
);
m_input1.write(true);
wait(20,
SC_NS
);
}
}
private:
sc_signal<bool> m_input0;
sc_signal<bool> m_input1;
sc_signal<bool> m_output;
};
//------------------------------------------------------------------------------
int sc_main(int argc,char ** argv)
{
top l_top("top");
std::cout << "Starting simulation" << std::endl;
sc_start();
return 0;
}
#endif // EXT_SYSTEMC_SELF_TEST
//EOF
|
// **************************************************************************************
// User-defined memory manager, which maintains a pool of transactions
// From TLM Duolos tutorials
// **************************************************************************************
#ifndef TRANSACTION_MEMORY_MANAGER_CPP
#define TRANSACTION_MEMORY_MANAGER_CPP
#include <systemc.h>
using namespace sc_core;
using namespace sc_dt;
using namespace std;
#include <tlm.h>
#include <tlm_utils/simple_initiator_socket.h>
#include <tlm_utils/simple_target_socket.h>
#include <tlm_utils/peq_with_cb_and_phase.h>
class mm: public tlm::tlm_mm_interface
{
typedef tlm::tlm_generic_payload gp_t;
public:
mm() : free_list(0), empties(0)
#ifdef DEBUG
, count(0)
#endif
{}
gp_t* allocate()
{
#ifdef DEBUG
cout << "----------------------------- Called allocate(), #trans = " << ++count << endl;
#endif
gp_t* ptr;
if (free_list)
{
ptr = free_list->trans;
empties = free_list;
free_list = free_list->next;
}
else
{
ptr = new gp_t(this);
}
return ptr;
}
void free(gp_t* trans)
{
#ifdef DEBUG
cout << "----------------------------- Called free(), #trans = " << --count << endl;
#endif
if (!empties)
{
empties = new access;
empties->next = free_list;
empties->prev = 0;
if (free_list)
free_list->prev = empties;
}
free_list = empties;
free_list->trans = trans;
empties = free_list->prev;
}
private:
struct access
{
gp_t* trans;
access* next;
access* prev;
};
access* free_list;
access* empties;
#ifdef DEBUG
int count;
#endif
};
#endif |
//-----------------------------------------------------
#include "systemc.h"
SC_MODULE (ram) {
//-----------Internal variables-------------------
int * mem;
// Constructor for memory
//SC_CTOR(ram) {
SC_HAS_PROCESS(ram);
ram(sc_module_name ram, int size=8) : sc_module(ram) {
mem = new int [size];
} // End of Constructor
//------------Code Starts Here-------------------------
void wr(int address, int data) {
sleep(1); //will not move time stamp either
mem [address] = data;
}
int rd(int address) {
return mem [address];
}
}; // End of Module memory
|
#include <top.h>
#include "systemc.h"
int sc_main(int argc, char* argv[]){
sc_time clkprd(10, SC_NS);
sc_time clkdly(0, SC_NS);
sc_clock clk("clk", clkprd, 0.5, clkdly, true);
// sc_signal<bool> reset;
top *t;
t = new top("top");
t->clk(clk);
sc_start(5000, SC_NS);
return(0);
}
|
/*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
/*****************************************************************************
main.cpp - This file instantiates all processes and ties them together
with signals.
Original Author: Rashmi Goswami, Synopsys, Inc.
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
#include "systemc.h"
#include "pkt.h"
#include "switch_clk.h"
#include "sender.h"
#include "receiver.h"
#include "switch.h"
int
sc_main(int, char *[])
{
sc_signal<pkt> pkt_in0;
sc_signal<pkt> pkt_in1;
sc_signal<pkt> pkt_in2;
sc_signal<pkt> pkt_in3;
sc_signal<pkt> pkt_out0;
sc_signal<pkt> pkt_out1;
sc_signal<pkt> pkt_out2;
sc_signal<pkt> pkt_out3;
sc_signal<sc_int<4> > id0, id1, id2, id3;
sc_signal<bool> switch_cntrl;
sc_clock clock1("CLOCK1", 75, SC_NS, 0.5, 0.0, SC_NS);
sc_clock clock2("CLOCK2", 30, SC_NS, 0.5, 10.0, SC_NS);
// Module instiatiations follow
// Note that modules can be connected by hooking up ports
// to signals by name or by using a positional notation
sender sender0("SENDER0");
// hooking up signals to ports by name
sender0.pkt_out(pkt_in0);
sender0.source_id(id0);
sender0.CLK(clock1);
sender sender1("SENDER1");
// hooking up signals to ports by position
sender1(pkt_in1, id1, clock1);
sender sender2("SENDER2");
// hooking up signals to ports by name
sender2.pkt_out(pkt_in2);
sender2.source_id(id2);
sender2.CLK(clock1);
sender sender3("SENDER3");
// hooking up signals to ports by position
sender3( pkt_in3, id3, clock1 );
switch_clk switch_clk1("SWITCH_CLK");
// hooking up signals to ports by name
switch_clk1.switch_cntrl(switch_cntrl);
switch_clk1.CLK(clock2);
mcast_pkt_switch switch1("SWITCH");
// hooking up signals to ports by name
switch1.switch_cntrl(switch_cntrl);
switch1.in0(pkt_in0);
switch1.in1(pkt_in1);
switch1.in2(pkt_in2);
switch1.in3(pkt_in3);
switch1.out0(pkt_out0);
switch1.out1(pkt_out1);
switch1.out2(pkt_out2);
switch1.out3(pkt_out3);
receiver receiver0("RECEIVER0");
// hooking up signals to ports by name
receiver0.pkt_in(pkt_out0);
receiver0.sink_id(id0);
receiver receiver1("RECEIVER1");
// hooking up signals to ports by position
receiver1( pkt_out1, id1 );
receiver receiver2("RECEIVER2");
// hooking up signals to ports by name
receiver2.pkt_in(pkt_out2);
receiver2.sink_id(id2);
receiver receiver3("RECEIVER3");
// hooking up signals to ports by position
receiver3( pkt_out3, id3 );
sc_start(0, SC_NS);
#ifndef __SUNPRO_CC
id0.write(0);
id1.write(1);
id2.write(2);
id3.write(3);
#else
// you cannot do that with SC5.0
// since it doesn't support member templates
id0.write(sc_int<4>(0));
id0.write(sc_int<4>(1));
id0.write(sc_int<4>(2));
id0.write(sc_int<4>(3));
#endif
sc_start();
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "systemc.h"
#define SIZE_I_IN 4
#define SIZE_J_IN 4
#define SIZE_K_IN 4
SC_MODULE(tensor_subtractor) {
sc_in_clk clock;
sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN];
sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN];
sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN][SIZE_K_IN];
SC_CTOR(tensor_subtractor) {
SC_METHOD(subtractor);
sensitive << clock.pos();
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
sensitive << data_a_in[i][j][k];
sensitive << data_b_in[i][j][k];
}
}
}
}
void subtractor() {
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
for (int k = 0; k < SIZE_K_IN; k++) {
data_out[i][j][k].write(data_a_in[i][j][k].read() - data_b_in[i][j][k].read());
}
}
}
}
};
|
#include <fstream>
#include <iomanip>
#include <iostream>
#include "colors.h"
#include "cpu.h"
#include "elflib.h"
#include "systemc.h"
#include <unordered_map>
/*
--------------Main file handling simulation---------------
Arguments :
- A riscv-elf executable to load in memory
- (optional) --riscof [signature file], for use within the riscof test suite
*/
using namespace std;
int sc_main(int argc, char** argv) {
bool riscof;
string signature_name;
string executable_name = argv[1];
uint32_t rvtest_entry_point = 0;
uint32_t good_adr;
uint32_t bad_adr;
uint32_t begin_signature;
uint32_t end_signature;
uint32_t rvtest_code_end;
std::unordered_map<int, int> ram;
// Receiving arguments
if (argc >= 4 && strcmp(argv[2], "--riscof") == 0) {
signature_name = argv[3];
riscof = true;
} else
riscof = false;
// Reading elf file, parsing it and getting sections and segments
FILE_READ* structure = (FILE_READ*)malloc(sizeof(FILE_READ));
structure = Read_Elf32(executable_name.c_str());
printf("Number of Instruction : %d\n", (structure->size) / 4);
good_adr = mem_goodadr();
bad_adr = mem_badadr();
int i = 0;
int j = 0;
int* instruction = (int*)malloc(((structure->size) / 4) * sizeof(int));
int* adresses = (int*)malloc(((structure->size) / 4) * sizeof(int));
// Sections loading
Elf32_Obj* pObj = structure->pObj_struct;
for (int i = 0; i < pObj->Head.e_shnum; i++) {
for (int j = 0; j < (pObj->size[i]); j += 4) {
ram[pObj->Section_Hdr[i]->sh_addr + j] = mem_lw(pObj->Section_Hdr[i]->sh_addr + j);
}
}
if (Elf32_SymAdr(pObj, &begin_signature, "begin_signature") == 0)
fprintf(stderr, "Found begin_signature at : 0x%8x\n", begin_signature);
if (Elf32_SymAdr(pObj, &rvtest_code_end, "rvtest_code_end") == 0)
fprintf(stderr, "Found rvtest_code_end at : 0x%8x\n", rvtest_code_end);
if (Elf32_SymAdr(pObj, &rvtest_entry_point, "rvtest_entry_point") == 0)
fprintf(stderr, "Found rvtest_entry_point at : 0x%8x\n", rvtest_entry_point);
if (Elf32_SymAdr(pObj, &end_signature, "end_signature") == 0)
fprintf(stderr, "Found end_signature at : 0x%8x\n", end_signature);
cpu cpu_inst("cpu");
sc_trace_file* tf;
tf = sc_create_vcd_trace_file("tf");
sc_signal<sc_uint<32>> MEM_ADR;
sc_signal<sc_uint<32>> MEM_DATA;
sc_signal<bool> MEM_ADR_VALID, MEM_STORE, MEM_LOAD;
sc_signal<sc_uint<2>> MEM_SIZE_SM;
sc_signal<sc_uint<32>> MEM_RESULT;
sc_signal<bool> MEM_STALL;
// Icache interface
sc_signal<sc_uint<32>> IF_ADR;
sc_signal<bool> IF_ADR_VALID;
sc_signal<sc_bv<32>> IC_INST;
sc_signal<bool> IC_STALL;
sc_signal<sc_uint<32>> PC_RESET;
sc_signal<sc_uint<32>> PC_VALUE;
sc_clock CLK("clk", 1, SC_NS);
sc_signal<bool> RESET;
cpu_inst.MCACHE_ADR_SM(MEM_ADR);
cpu_inst.MCACHE_DATA_SM(MEM_DATA);
cpu_inst.MCACHE_ADR_VALID_SM(MEM_ADR_VALID);
cpu_inst.MCACHE_STORE_SM(MEM_STORE);
cpu_inst.MCACHE_LOAD_SM(MEM_LOAD);
cpu_inst.MCACHE_RESULT_SM(MEM_RESULT);
cpu_inst.MCACHE_STALL_SM(MEM_STALL);
cpu_inst.MEM_SIZE_SM(MEM_SIZE_SM);
cpu_inst.ADR_SI(IF_ADR);
cpu_inst.ADR_VALID_SI(IF_ADR_VALID);
cpu_inst.IC_INST_SI(IC_INST);
cpu_inst.IC_STALL_SI(IC_STALL);
cpu_inst.READ_PC_SR(PC_VALUE);
cpu_inst.CLK(CLK);
cpu_inst.RESET(RESET);
cpu_inst.trace(tf);
cout << "Reseting...";
RESET.write(false); // reset
sc_start(3, SC_NS); // wait for 1 cycle
RESET.write(true); // end of reset
cerr << "done." << endl;
// STATS
int NB_CYCLES = 0;
//
int cycles = 0;
int countdown;
int if_adr;
int if_result;
int mem_adr;
int mem_size;
while (1) {
if (countdown) countdown--;
cycles++;
mem_adr = MEM_ADR.read() & 0XfffffffC; // removing the least 2 significant bits
mem_size = MEM_SIZE_SM.read();
bool mem_adr_valid = MEM_ADR_VALID.read();
unsigned int mem_data = MEM_DATA.read();
bool mem_store = MEM_STORE.read();
bool mem_load = MEM_LOAD.read();
unsigned int mem_result;
if_adr = IF_ADR.read();
bool if_afr_valid = IF_ADR_VALID.read();
unsigned int pc_adr = PC_VALUE.read();
NB_CYCLES = sc_time_stamp().to_double() / 1000;
if (signature_name == "" && pc_adr == bad_adr) {
cout << FRED("Error ! ") << "Found bad at adr 0x" << std::hex << pc_adr << endl;
sc_start(3, SC_NS);
exit(1);
} else if (signature_name == "" && pc_adr == good_adr) {
cout << FGRN("Success ! ") << "Found good at adr 0x" << std::hex << pc_adr << endl;
sc_start(3, SC_NS);
exit(0);
} else if (countdown == 0 && signature_name != "" &&
(pc_adr == rvtest_code_end || cycles > 2000000)) {
cerr << "inside if : " << endl;
countdown = 20;
cout << "coutndown value : " << countdown << endl;
} else if (countdown == 1) {
cout << "Test ended at " << std::hex << pc_adr << endl;
sc_start(3, SC_NS);
ofstream signature;
signature.open(signature_name, ios::out | ios::trunc);
cout << "signature_name :" << signature_name << endl;
cout << "begin_signature :" << begin_signature << endl;
cout << "end_signature :" << end_signature << endl;
int j = 1;
for (int i = begin_signature; i < end_signature; i += 4) {
j++;
}
for (int i = begin_signature; i < end_signature; i += 4) {
signature << setfill('0') << setw(8) << hex << ram[i] << endl;
}
exit(0);
}
if (mem_store && mem_adr_valid) {
int temporary_value = ram[mem_adr];
unsigned int temporary_store_value = mem_data;
if (mem_size == 2) { // access in byte
// doing a mask on the least 2 significant bits
int mask_adr = MEM_ADR.read() & 0x00000003;
// The switch will allow to keep only the bits we want to store
switch (mask_adr) {
case 0:
temporary_store_value = temporary_store_value & 0x000000FF;
temporary_value = 0xFFFFFF00 & temporary_value;
ram[mem_adr] = temporary_value | temporary_store_value;
break;
case 1:
temporary_store_value = temporary_store_value & 0x0000FF00;
temporary_value = 0xFFFF00FF & temporary_value;
ram[mem_adr] = temporary_value | temporary_store_value;
break;
case 2:
temporary_store_value = temporary_store_value & 0x00FF0000;
temporary_value = 0xFF00FFFF & temporary_value;
ram[mem_adr] = temporary_value | temporary_store_value;
break;
case 3:
temporary_store_value = temporary_store_value & 0xFF000000;
temporary_value = 0x00FFFFFF & temporary_value;
ram[mem_adr] = temporary_value | temporary_store_value;
break;
default: break;
}
} else if (mem_size == 1) { // access in half word
int mask_adr = MEM_ADR.read() & 0x00000003;
switch (mask_adr) {
case 0:
temporary_store_value = temporary_store_value & 0x0000FFFF;
temporary_value = 0xFFFF0000 & temporary_value;
ram[mem_adr] = temporary_value | temporary_store_value;
break;
case 2:
temporary_store_value = temporary_store_value & 0xFFFF0000;
temporary_value = 0x00000FFFF & temporary_value;
ram[mem_adr] = temporary_value | temporary_store_value;
break;
default: break;
}
} else // access in word
{
ram[mem_adr] = mem_data;
}
}
mem_result = ram[mem_adr];
MEM_RESULT.write(mem_result);
MEM_STALL.write(false);
if_result = ram[if_adr];
IC_INST.write(if_result);
IC_STALL.write(false);
sc_start(500, SC_PS);
}
return 0;
} |
/********************************************************************************
* University of L'Aquila - HEPSYCODE Source Code License *
* *
* *
* (c) 2018-2019 Centre of Excellence DEWS All rights reserved *
********************************************************************************
* <one line to give the program's name and a brief idea of what it does.> *
* Copyright (C) 2022 Vittoriano Muttillo, Luigi Pomante * *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
********************************************************************************
* *
* Created on: 09/May/2023 *
* Authors: Vittoriano Muttillo, Marco Santic, Luigi Pomante *
* *
* email: [email protected] *
* [email protected] *
* [email protected] *
* *
********************************************************************************
* This code has been developed from an HEPSYCODE model used as demonstrator by *
* University of L'Aquila. *
*******************************************************************************/
#include <systemc.h>
#include "../mainsystem.h"
#include <math.h>
#define cD_02_ANN_INPUTS 2 // Number of inputs
#define cD_02_ANN_OUTPUTS 1 // Number of outputs
//-----------------------------------------------------------------------------
// Physical constants
//-----------------------------------------------------------------------------
static double cD_02_I_0 = 77.3 ; // [A] Nominal current
static double cD_02_T_0 = 298.15 ; // [K] Ambient temperature
static double cD_02_R_0 = 0.01 ; // [Ω] Data-sheet R_DS_On (Drain-Source resistance in the On State)
static double cD_02_V_0 = 47.2 ; // [V] Nominal voltage
static double cD_02_Alpha = 0.002 ; // [Ω/K] Temperature coefficient of Drain-Source resistance in the On State
static double cD_02_ThermalConstant = 0.75 ;
static double cD_02_Tau = 0.02 ; // [s] Sampling period
//-----------------------------------------------------------------------------
// Status descriptors
//-----------------------------------------------------------------------------
typedef struct cD_02_DEVICE // Descriptor of the state of the device
{
double t ; // Operating temperature
double r ; // Operating Drain-Source resistance in the On State
double i ; // Operating current
double v ; // Operating voltage
double time_Ex ;
int fault ;
} cD_02_DEVICE ;
static cD_02_DEVICE cD_02_device;
//-----------------------------------------------------------------------------
// Mnemonics to access the array that contains the sampled data
//-----------------------------------------------------------------------------
#define cD_02_SAMPLE_LEN 3 // Array of SAMPLE_LEN elements
#define cD_02_I_INDEX 0 // Current
#define cD_02_V_INDEX 1 // Voltage
#define cD_02_TIME_INDEX 2 // Time
///-----------------------------------------------------------------------------
// Forward references
//-----------------------------------------------------------------------------
static int cD_02_initDescriptors(cD_02_DEVICE device) ;
//static void getSample(int index, double sample[SAMPLE_LEN]) ;
static void cD_02_cleanData(int index, double sample[cD_02_SAMPLE_LEN]) ;
static double cD_02_extractFeatures(double tPrev, double iPrev, double iNow, double rPrev) ;
static void cD_02_normalize(int index, double x[cD_02_ANN_INPUTS]) ;
static double cD_02_degradationModel(double tNow) ;
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
int cD_02_initDescriptors(cD_02_DEVICE device)
{
// for (int i = 0; i < NUM_DEV; i++)
// {
device.t = cD_02_T_0 ; // Operating temperature = Ambient temperature
device.r = cD_02_R_0 ; // Operating R_DS_On = Data-sheet R_DS_On
// printf("Init %d \n",i);
// }
return( EXIT_SUCCESS );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void cD_02_cleanData(int index, double sample[cD_02_SAMPLE_LEN])
{
// the parameter "index" could be useful to retrieve the characteristics of the device
if ( sample[cD_02_I_INDEX] < 0 )
sample[cD_02_I_INDEX] = 0 ;
else if ( sample[cD_02_I_INDEX] > (2.0 * cD_02_I_0) )
sample[cD_02_I_INDEX] = (2.0 * cD_02_I_0) ;
// Postcondition: (0 <= sample[I_INDEX] <= 2.0*I_0)
if ( sample[cD_02_V_INDEX] < 0 )
sample[cD_02_V_INDEX] = 0 ;
else if ( sample[cD_02_V_INDEX] > (2.0 * cD_02_V_0 ) )
sample[cD_02_V_INDEX] = (2.0 * cD_02_V_0) ;
// Postcondition: (0 <= sample[V_INDEX] <= 2.0*V_0)
}
//-----------------------------------------------------------------------------
// Input:
// - tPrev = temperature at previous step
// - iPrev = current at previous step
// - iNow = current at this step
// - rPrev = resistance at the previous step
// Return:
// - The new temperature
// Very simple model:
// - one constant for dissipation and heat capacity
// - temperature considered constant during the step
//-----------------------------------------------------------------------------
double cD_02_extractFeatures(double tPrev, double iPrev, double iNow, double rPrev)
{
double t ; // Temperature
double i = 0.5*(iPrev + iNow); // Average current
//printf("cD_02_extractFeatures tPrev=%f\n",tPrev);
t = tPrev + // Previous temperature
rPrev * (i * i) * cD_02_Tau - // Heat generated: P = I·R^2
cD_02_ThermalConstant * (tPrev - cD_02_T_0) * cD_02_Tau ; // Dissipation and heat capacity
return( t );
}
//-----------------------------------------------------------------------------
// Input:
// - tNow: temperature at this step
// Return:
// - the resistance
// The model isn't realistic because the even the simpler law is exponential
//-----------------------------------------------------------------------------
double cD_02_degradationModel(double tNow)
{
double r ;
//r = R_0 + Alpha * tNow ;
r = cD_02_R_0 * ( 2 - exp(-cD_02_Alpha*tNow) );
return( r );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void cD_02_normalize(int index, double sample[cD_02_ANN_INPUTS])
{
double i ; double v ;
// Precondition: (0 <= sample[I_INDEX] <= 2*I_0) && (0 <= sample[V_INDEX] <= 2*V_0)
i = sample[cD_02_I_INDEX] <= cD_02_I_0 ? 0.0 : 1.0;
v = sample[cD_02_V_INDEX] <= cD_02_V_0 ? 0.0 : 1.0;
// Postcondition: (i in {0.0, 1.0}) and (v in {0.0, 1.0})
sample[cD_02_I_INDEX] = i ;
sample[cD_02_V_INDEX] = v ;
}
void mainsystem::cleanData_02_main()
{
// datatype for channels
sampleTimCord_cleanData_xx_payload sampleTimCord_cleanData_xx_payload_var;
cleanData_xx_ann_xx_payload cleanData_xx_ann_xx_payload_var;
//device var
uint8_t dev;
//step var
uint16_t step;
// ex_time (for extractFeatures...)
double ex_time;
//samples i and v
double sample_i;
double sample_v;
//var for samples, to re-use cleanData()
double cD_02_sample[cD_02_SAMPLE_LEN] ;
double x[cD_02_ANN_INPUTS + cD_02_ANN_OUTPUTS] ;
// NOTE: commented, should be changed param by ref...
//cD_02_initDescriptors(cD_02_device);
cD_02_device.t = cD_02_T_0 ; // Operating temperature = Ambient temperature
cD_02_device.r = cD_02_R_0 ; // Operating R_DS_On = Data-sheet R_DS_On
// ### added for time related dynamics
//static double cD_02_Tau = 0.02 ; // [s] Sampling period
double cD_02_last_sample_time = 0;
//implementation
HEPSY_S(cleanData_02_id) while(1)
{HEPSY_S(cleanData_02_id)
// content
sampleTimCord_cleanData_xx_payload_var = sampleTimCord_cleanData_02_channel->read();
dev = sampleTimCord_cleanData_xx_payload_var.dev;
step = sampleTimCord_cleanData_xx_payload_var.step;
ex_time = sampleTimCord_cleanData_xx_payload_var.ex_time;
sample_i = sampleTimCord_cleanData_xx_payload_var.sample_i;
sample_v = sampleTimCord_cleanData_xx_payload_var.sample_v;
// cout << "cleanData_02 rcv \t dev: " << dev
// <<"\t step: " << step
// <<"\t time_ex:" << ex_time
// <<"\t i:" << sample_i
// <<"\t v:" << sample_v
// << endl;
// reconstruct sample
cD_02_sample[cD_02_I_INDEX] = sample_i;
cD_02_sample[cD_02_V_INDEX] = sample_v;
cD_02_sample[cD_02_TIME_INDEX] = ex_time;
// ### C L E A N D A T A (0 <= I <= 2.0*I_0) and (0 <= V <= 2.0*V_0)
cD_02_cleanData(dev, cD_02_sample) ;
cD_02_device.time_Ex = cD_02_sample[cD_02_TIME_INDEX] ;
cD_02_device.i = cD_02_sample[cD_02_I_INDEX] ;
cD_02_device.v = cD_02_sample[cD_02_V_INDEX] ;
// ### added for time related dynamics
//static double cD_02_Tau = 0.02 ; // [s] Sampling period
cD_02_Tau = ex_time - cD_02_last_sample_time;
cD_02_last_sample_time = ex_time;
// ### F E A T U R E S E X T R A C T I O N (compute the temperature)
cD_02_device.t = cD_02_extractFeatures( cD_02_device.t, // Previous temperature
cD_02_device.i, // Previous current
cD_02_sample[cD_02_I_INDEX], // Current at this step
cD_02_device.r) ; // Previous resistance
// ### D E G R A D A T I O N M O D E L (compute R_DS_On)
cD_02_device.r = cD_02_degradationModel(cD_02_device.t) ;
// ### N O R M A L I Z E: (x[0] in {0.0, 1.0}) and (x[1] in {0.0, 1.0})
x[0] = cD_02_device.i ;
x[1] = cD_02_device.v ;
cD_02_normalize(dev, x) ;
// // ### P R E D I C T (simple XOR)
// if ( annRun(index, x) != EXIT_SUCCESS ){
//prepare out data payload
cleanData_xx_ann_xx_payload_var.dev = dev;
cleanData_xx_ann_xx_payload_var.step = step;
cleanData_xx_ann_xx_payload_var.ex_time = ex_time;
cleanData_xx_ann_xx_payload_var.device_i = cD_02_device.i;
cleanData_xx_ann_xx_payload_var.device_v = cD_02_device.v;
cleanData_xx_ann_xx_payload_var.device_t = cD_02_device.t;
cleanData_xx_ann_xx_payload_var.device_r = cD_02_device.r;
cleanData_xx_ann_xx_payload_var.x_0 = x[0];
cleanData_xx_ann_xx_payload_var.x_1 = x[1];
cleanData_xx_ann_xx_payload_var.x_2 = x[2];
cleanData_02_ann_02_channel->write(cleanData_xx_ann_xx_payload_var);
HEPSY_P(cleanData_02_id)
}
}
//END
|
#include <systemc.h>
#include "counter.h"
#include "counter_tb.h"
#include "constants.h"
int sc_main(int argc, char* argv[]){
CounterModule* counter = new CounterModule("Counter");
CounterTestbench* testbench = new CounterTestbench("Testbench");
sc_clock Clock("Clock", 10, SC_NS, 0.5, 10, SC_NS, false);
sc_signal<bool> Reset;
sc_signal<bool> Count_Enable;
sc_signal<bool> Up_Down_Ctrl;
sc_signal<sc_uint<N> > Count_Out;
sc_signal<bool> Overflow_Intr;
sc_signal<bool> Underflow_Intr;
counter->clk(Clock);
counter->reset(Reset);
counter->count_enable(Count_Enable);
counter->up_down_ctrl(Up_Down_Ctrl);
counter->count_out(Count_Out);
counter->overflow_intr(Overflow_Intr);
counter->underflow_intr(Underflow_Intr);
testbench->clk(Clock);
testbench->reset(Reset);
testbench->count_enable(Count_Enable);
testbench->up_down_ctrl(Up_Down_Ctrl);
testbench->count_out(Count_Out);
testbench->overflow_intr(Overflow_Intr);
testbench->underflow_intr(Underflow_Intr);
cout << "Starting simulation" << endl;
sc_start();
return 0;
}
|
/*
* Copyright (c) 2010 TIMA Laboratory
*
* This file is part of Rabbits.
*
* Rabbits is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Rabbits is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Rabbits. If not, see <http://www.gnu.org/licenses/>.
*/
#include <systemc.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sl_block_device.h>
/* #define DEBUG_DEVICE_BLOCK */
#ifdef DEBUG_DEVICE_BLOCK
#define DPRINTF(fmt, args...) \
do { printf("sl_block_device: " fmt , ##args); } while (0)
#define DCOUT if (1) cout
#else
#define DPRINTF(fmt, args...) do {} while(0)
#define DCOUT if (0) cout
#endif
#define EPRINTF(fmt, args...) \
do { fprintf(stderr, "sl_block_device: " fmt , ##args); } while (0)
sl_block_device::sl_block_device (sc_module_name _name, uint32_t master_id,
const char *fname, uint32_t block_size)
:sc_module(_name)
{
char *buf = new char[strlen(_name) + 3];
m_cs_regs = new sl_block_device_CSregs_t;
m_cs_regs->m_status = 0;
m_cs_regs->m_buffer = 0;
m_cs_regs->m_op = 0;
m_cs_regs->m_lba = 0;
m_cs_regs->m_count = 0;
m_cs_regs->m_size = 0;
m_cs_regs->m_block_size = block_size;
m_cs_regs->m_irqen = 0;
m_cs_regs->m_irq = 0;
strcpy(buf, _name);
buf[strlen(_name)] = '_';
buf[strlen(_name)+1] = 'm';
buf[strlen(_name)+2] = '\0';
master = new sl_block_device_master(buf, master_id);
buf[strlen(_name)+1] = 's';
slave = new sl_block_device_slave(buf, m_cs_regs, &ev_op_start, &ev_irq_update);
m_fd = -1;
open_host_file (fname);
SC_THREAD (irq_update_thread);
SC_THREAD (control_thread);
}
sl_block_device::~sl_block_device ()
{
DPRINTF("destructor called\n");
}
static off_t get_file_size (int fd)
{
off_t old_pos = lseek (fd, 0, SEEK_CUR);
off_t ret = lseek (fd, 0, SEEK_END);
lseek (fd, old_pos, SEEK_SET);
return ret;
}
void sl_block_device::open_host_file (const char *fname)
{
if (m_fd != -1)
{
::close (m_fd);
m_fd = -1;
}
if (fname)
{
m_fd = ::open(fname, O_RDWR | O_CREAT, 0644);
if(m_fd < 0)
{
EPRINTF("Impossible to open file : %s\n", fname);
return;
}
m_cs_regs->m_size = get_file_size (m_fd) / m_cs_regs->m_block_size;
}
}
master_device *
sl_block_device::get_master ()
{
return (master_device *)master;
}
slave_device *
sl_block_device::get_slave ()
{
return (slave_device *)slave;
}
void
sl_block_device::control_thread ()
{
uint32_t offset, addr, transfer_size;
uint8_t *data_buff;
int func_ret;
while(1)
{
switch(m_cs_regs->m_op)
{
case BLOCK_DEVICE_NOOP:
DPRINTF("Got a BLOCK_DEVICE_NOOP\n");
wait(ev_op_start);
break;
case BLOCK_DEVICE_READ:
m_cs_regs->m_status = BLOCK_DEVICE_BUSY;
transfer_size = m_cs_regs->m_count * m_cs_regs->m_block_size;
data_buff = new uint8_t[transfer_size + 4];
DPRINTF("Got a BLOCK_DEVICE_READ of size %x\n", transfer_size);
/* Read in device */
lseek(m_fd, m_cs_regs->m_lba*m_cs_regs->m_block_size, SEEK_SET);
func_ret = ::read(m_fd, data_buff, transfer_size);
addr = m_cs_regs->m_buffer;
if (func_ret < 0)
{
EPRINTF("Error in ::read()\n");
m_cs_regs->m_op = BLOCK_DEVICE_NOOP;
m_cs_regs->m_status = BLOCK_DEVICE_READ_ERROR;
m_cs_regs->m_count = 0;
break;
}
m_cs_regs->m_count = func_ret / m_cs_regs->m_block_size;
transfer_size = func_ret;
if (transfer_size)
{
/* Send data in memory */
uint32_t up_4align_limit = transfer_size & ~3;
for(offset = 0; offset < up_4align_limit; offset += 4)
{
func_ret = master->cmd_write(addr + offset, data_buff + offset, 4);
if(!func_ret)
break;
}
for (; offset < transfer_size; offset++)
{
func_ret = master->cmd_write(addr + offset, data_buff + offset, 1);
if(!func_ret)
break;
}
if(!func_ret)
{
EPRINTF("Error in Read\n");
m_cs_regs->m_op = BLOCK_DEVICE_NOOP;
m_cs_regs->m_status = BLOCK_DEVICE_READ_ERROR;
m_cs_regs->m_count = offset / m_cs_regs->m_block_size;
break;
}
}
/* Update everything */
if(m_cs_regs->m_irqen)
{
m_cs_regs->m_irq = 1;
ev_irq_update.notify();
}
m_cs_regs->m_op = BLOCK_DEVICE_NOOP;
m_cs_regs->m_status = BLOCK_DEVICE_READ_SUCCESS;
delete data_buff;
break;
case BLOCK_DEVICE_WRITE:
DPRINTF("Got a BLOCK_DEVICE_WRITE\n");
m_cs_regs->m_status = BLOCK_DEVICE_BUSY;
transfer_size = m_cs_regs->m_count * m_cs_regs->m_block_size;
data_buff = new uint8_t[transfer_size + 4];
addr = m_cs_regs->m_buffer;
/* Read data from memory */
for(offset = 0; offset < transfer_size; offset += 4)
{
func_ret = master->cmd_read(addr + offset, data_buff + offset, 4);
if(!func_ret)
break;
}
if(!func_ret)
{
m_cs_regs->m_op = BLOCK_DEVICE_NOOP;
m_cs_regs->m_status = BLOCK_DEVICE_WRITE_ERROR;
break;
}
/* Write in the device */
lseek(m_fd, m_cs_regs->m_lba*m_cs_regs->m_block_size, SEEK_SET);
::write(m_fd, data_buff, transfer_size);
m_cs_regs->m_size = get_file_size (m_fd) / m_cs_regs->m_block_size;
/* Update everything */
if(m_cs_regs->m_irqen)
{
m_cs_regs->m_irq = 1;
ev_irq_update.notify();
}
m_cs_regs->m_op = BLOCK_DEVICE_NOOP;
m_cs_regs->m_status = BLOCK_DEVICE_WRITE_SUCCESS;
delete data_buff;
break;
case BLOCK_DEVICE_FILE_NAME:
DPRINTF("Got a BLOCK_DEVICE_FILE_NAME\n");
m_cs_regs->m_status = BLOCK_DEVICE_BUSY;
transfer_size = m_cs_regs->m_count * m_cs_regs->m_block_size;
data_buff = new uint8_t[transfer_size + 4];
addr = m_cs_regs->m_buffer;
/* Read data from memory */
for(offset = 0; offset < transfer_size; offset += 4)
{
func_ret = master->cmd_read(addr + offset, data_buff + offset, 4);
if(!func_ret)
break;
}
if (func_ret)
open_host_file ((const char*) data_buff);
if(!func_ret || m_fd == -1)
{
m_cs_regs->m_op = BLOCK_DEVICE_NOOP;
m_cs_regs->m_status = BLOCK_DEVICE_WRITE_ERROR;
break;
}
m_cs_regs->m_op = BLOCK_DEVICE_NOOP;
m_cs_regs->m_status = BLOCK_DEVICE_WRITE_SUCCESS;
delete data_buff;
break;
default:
EPRINTF("Error in command\n");
}
}
}
void sl_block_device::irq_update_thread ()
{
while(1)
{
wait(ev_irq_update);
if(m_cs_regs->m_irq == 1)
{
DPRINTF("Raising IRQ\n");
irq = 1;
}
else
{
DPRINTF("Clearing IRQ\n");
irq = 0;
}
}
return;
}
/*
* sl_block_device_master
*/
sl_block_device_master::sl_block_device_master (const char *_name, uint32_t node_id)
: master_device(_name)
{
m_crt_tid = 0;
m_status = MASTER_READY;
m_node_id = node_id;
}
sl_block_device_master::~sl_block_device_master()
{
}
int
sl_block_device_master::cmd_write (uint32_t addr, uint8_t *data, uint8_t nbytes)
{
DPRINTF("Write to %x [0x%08x]\n", addr, *(uint32_t *)data);
send_req (m_crt_tid, addr, data, nbytes, 1);
wait (ev_cmd_done);
if(m_status != MASTER_CMD_SUCCESS)
return 0;
return 1;
}
int
sl_block_device_master::cmd_read (uint32_t addr, uint8_t *data, uint8_t nbytes)
{
m_tr_nbytes = nbytes;
m_tr_rdata = 0;
DPRINTF ("Read from %x\n", addr);
send_req (m_crt_tid, addr, NULL, nbytes, 0);
wait (ev_cmd_done);
for (int i = 0; i < nbytes; i++)
data[i] = ((unsigned char *) &m_tr_rdata)[i];
if (m_status != MASTER_CMD_SUCCESS)
return 0;
return 1;
}
void
sl_block_device_master::rcv_rsp (uint8_t tid, uint8_t *data,
bool bErr, bool bWrite)
{
if (tid != m_crt_tid)
{
EPRINTF ("Bad tid (%d / %d)\n", tid, m_crt_tid);
}
if (bErr)
{
DPRINTF("Cmd KO\n");
m_status = MASTER_CMD_ERROR;
}
else
{
//DPRINTF("Cmd OK\n");
m_status = MASTER_CMD_SUCCESS;
}
if (!bWrite)
{
for (int i = 0; i < m_tr_nbytes; i++)
((unsigned char *) &m_tr_rdata)[i] = data[i];
}
m_crt_tid++;
ev_cmd_done.notify ();
}
/*
* sl_block_device_slave
*/
sl_block_device_slave::sl_block_device_slave (const char *_name,
sl_block_device_CSregs_t *cs_regs, sc_event *op_start, sc_event *irq_update)
: slave_device (_name)
{
m_cs_regs = cs_regs;
ev_op_start = op_start;
ev_irq_update = irq_update;
}
sl_block_device_slave::~sl_block_device_slave()
{
}
void sl_block_device_slave::write (unsigned long ofs, unsigned char be,
unsigned char *data, bool &bErr)
{
uint32_t *val = (uint32_t *) data;
uint32_t lofs = ofs;
uint8_t lbe = be;
bErr = false;
lofs >>= 2;
if (lbe & 0xF0)
{
lofs += 1;
lbe >>= 4;
val++;
}
switch(lofs)
{
case BLOCK_DEVICE_BUFFER :
DPRINTF("BLOCK_DEVICE_BUFFER write: %x\n", *val);
m_cs_regs->m_buffer = *val;
break;
case BLOCK_DEVICE_LBA :
DPRINTF("BLOCK_DEVICE_LBA write: %x\n", *val);
m_cs_regs->m_lba = *val;
break;
case BLOCK_DEVICE_COUNT :
DPRINTF("BLOCK_DEVICE_COUNT write: %x\n", *val);
m_cs_regs->m_count = *val;
break;
case BLOCK_DEVICE_OP :
DPRINTF("BLOCK_DEVICE_OP write: %x\n", *val);
if(m_cs_regs->m_status != BLOCK_DEVICE_IDLE)
{
EPRINTF("Got a command while executing another one\n");
break;
}
m_cs_regs->m_op = *val;
ev_op_start->notify();
break;
case BLOCK_DEVICE_IRQ_ENABLE :
DPRINTF("BLOCK_DEVICE_IRQ_ENABLE write: %x\n", *val);
m_cs_regs->m_irqen = *val;
ev_irq_update->notify();
break;
case BLOCK_DEVICE_STATUS :
case BLOCK_DEVICE_SIZE :
case BLOCK_DEVICE_BLOCK_SIZE :
default:
EPRINTF("Bad %s::%s ofs=0x%X, be=0x%X\n", name (), __FUNCTION__,
(unsigned int) ofs, (unsigned int) be);
}
}
void sl_block_device_slave::read (unsigned long ofs, unsigned char be,
unsigned char *data, bool &bErr)
{
uint32_t *val = (uint32_t *)data;
uint32_t lofs = ofs;
uint8_t lbe = be;
bErr = false;
lofs >>= 2;
if (lbe & 0xF0)
{
lofs += 1;
lbe >>= 4;
val++;
}
switch(lofs)
{
case BLOCK_DEVICE_BUFFER :
*val = m_cs_regs->m_buffer;
DPRINTF("BLOCK_DEVICE_BUFFER read: %x\n", *val);
break;
case BLOCK_DEVICE_LBA :
*val = m_cs_regs->m_lba;
DPRINTF("BLOCK_DEVICE_LBA read: %x\n", *val);
break;
case BLOCK_DEVICE_COUNT :
*val = m_cs_regs->m_count;
DPRINTF("BLOCK_DEVICE_COUNT read: %x\n", *val);
break;
case BLOCK_DEVICE_OP :
*val = m_cs_regs->m_op;
DPRINTF("BLOCK_DEVICE_OP read: %x\n", *val);
break;
case BLOCK_DEVICE_STATUS :
*val = m_cs_regs->m_status;
DPRINTF("BLOCK_DEVICE_STATUS read: %x\n", *val);
if(m_cs_regs->m_status != BLOCK_DEVICE_BUSY)
{
m_cs_regs->m_status = BLOCK_DEVICE_IDLE;
m_cs_regs->m_irq = 0;
ev_irq_update->notify();
}
break;
case BLOCK_DEVICE_IRQ_ENABLE :
*val = m_cs_regs->m_irqen;
DPRINTF("BLOCK_DEVICE_IRQ_ENABLE read: %x\n", *val);
break;
case BLOCK_DEVICE_SIZE :
*val = m_cs_regs->m_size;
DPRINTF("BLOCK_DEVICE_SIZE read: %x\n", *val);
break;
case BLOCK_DEVICE_BLOCK_SIZE :
*val = m_cs_regs->m_block_size;
DPRINTF("BLOCK_DEVICE_BLOCK_SIZE read: %x\n", *val);
break;
default:
EPRINTF("Bad %s::%s ofs=0x%X, be=0x%X\n", name (), __FUNCTION__,
(unsigned int) ofs, (unsigned int) be);
}
}
void sl_block_device_slave::rcv_rqst (unsigned long ofs, unsigned char be,
unsigned char *data, bool bWrite)
{
bool bErr = false;
if(bWrite)
this->write(ofs, be, data, bErr);
else
this->read(ofs, be, data, bErr);
send_rsp(bErr);
return;
}
/*
* Vim standard variables
* vim:set ts=4 expandtab tw=80 cindent syntax=c:
*
* Emacs standard variables
* Local Variables:
* mode: c
* tab-width: 4
* c-basic-offset: 4
* indent-tabs-mode: nil
* End:
*/
|
/********************************************************************************
* University of L'Aquila - HEPSYCODE Source Code License *
* *
* *
* (c) 2018-2019 Centre of Excellence DEWS All rights reserved *
********************************************************************************
* <one line to give the program's name and a brief idea of what it does.> *
* Copyright (C) 2022 Vittoriano Muttillo, Luigi Pomante * *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
********************************************************************************
* *
* Created on: 09/May/2023 *
* Authors: Vittoriano Muttillo, Marco Santic, Luigi Pomante *
* *
* email: [email protected] *
* [email protected] *
* [email protected] *
* *
********************************************************************************
* This code has been developed from an HEPSYCODE model used as demonstrator by *
* University of L'Aquila. *
*******************************************************************************/
#include <systemc.h>
#include "../mainsystem.h"
#include <math.h>
#define cD_03_ANN_INPUTS 2 // Number of inputs
#define cD_03_ANN_OUTPUTS 1 // Number of outputs
//-----------------------------------------------------------------------------
// Physical constants
//-----------------------------------------------------------------------------
static double cD_03_I_0 = 77.3 ; // [A] Nominal current
static double cD_03_T_0 = 298.15 ; // [K] Ambient temperature
static double cD_03_R_0 = 0.01 ; // [Ω] Data-sheet R_DS_On (Drain-Source resistance in the On State)
static double cD_03_V_0 = 47.2 ; // [V] Nominal voltage
static double cD_03_Alpha = 0.002 ; // [Ω/K] Temperature coefficient of Drain-Source resistance in the On State
static double cD_03_ThermalConstant = 0.75 ;
static double cD_03_Tau = 0.02 ; // [s] Sampling period
//-----------------------------------------------------------------------------
// Status descriptors
//-----------------------------------------------------------------------------
typedef struct cD_03_DEVICE // Descriptor of the state of the device
{
double t ; // Operating temperature
double r ; // Operating Drain-Source resistance in the On State
double i ; // Operating current
double v ; // Operating voltage
double time_Ex ;
int fault ;
} cD_03_DEVICE ;
static cD_03_DEVICE cD_03_device;
//-----------------------------------------------------------------------------
// Mnemonics to access the array that contains the sampled data
//-----------------------------------------------------------------------------
#define cD_03_SAMPLE_LEN 3 // Array of SAMPLE_LEN elements
#define cD_03_I_INDEX 0 // Current
#define cD_03_V_INDEX 1 // Voltage
#define cD_03_TIME_INDEX 2 // Time
///-----------------------------------------------------------------------------
// Forward references
//-----------------------------------------------------------------------------
static int cD_03_initDescriptors(cD_03_DEVICE device) ;
//static void getSample(int index, double sample[SAMPLE_LEN]) ;
static void cD_03_cleanData(int index, double sample[cD_03_SAMPLE_LEN]) ;
static double cD_03_extractFeatures(double tPrev, double iPrev, double iNow, double rPrev) ;
static void cD_03_normalize(int index, double x[cD_03_ANN_INPUTS]) ;
static double cD_03_degradationModel(double tNow) ;
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
int cD_03_initDescriptors(cD_03_DEVICE device)
{HEPSY_S(cleanData_03_id)
// for (int i = 0; i < NUM_DEV; i++)
// {
HEPSY_S(cleanData_03_id) device.t = cD_03_T_0 ; // Operating temperature = Ambient temperature
HEPSY_S(cleanData_03_id) device.r = cD_03_R_0 ; // Operating R_DS_On = Data-sheet R_DS_On
// printf("Init %d \n",i);
// }
HEPSY_S(cleanData_03_id) return( EXIT_SUCCESS );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void cD_03_cleanData(int index, double sample[cD_03_SAMPLE_LEN])
{HEPSY_S(cleanData_03_id)
// the parameter "index" could be useful to retrieve the characteristics of the device
HEPSY_S(cleanData_03_id) if ( sample[cD_03_I_INDEX] < 0 )
{HEPSY_S(cleanData_03_id)
HEPSY_S(cleanData_03_id) sample[cD_03_I_INDEX] = 0 ;
HEPSY_S(cleanData_03_id)}
else if ( sample[cD_03_I_INDEX] > (2.0 * cD_03_I_0) )
{HEPSY_S(cleanData_03_id)
HEPSY_S(cleanData_03_id) sample[cD_03_I_INDEX] = (2.0 * cD_03_I_0) ;
// Postcondition: (0 <= sample[I_INDEX] <= 2.0*I_0)
HEPSY_S(cleanData_03_id)}
HEPSY_S(cleanData_03_id) if ( sample[cD_03_V_INDEX] < 0 )
{HEPSY_S(cleanData_03_id)
HEPSY_S(cleanData_03_id) sample[cD_03_V_INDEX] = 0 ;
HEPSY_S(cleanData_03_id)}
else if ( sample[cD_03_V_INDEX] > (2.0 * cD_03_V_0 ) )
{HEPSY_S(cleanData_03_id)
HEPSY_S(cleanData_03_id) sample[cD_03_V_INDEX] = (2.0 * cD_03_V_0) ;
// Postcondition: (0 <= sample[V_INDEX] <= 2.0*V_0)
HEPSY_S(cleanData_03_id)}
}
//-----------------------------------------------------------------------------
// Input:
// - tPrev = temperature at previous step
// - iPrev = current at previous step
// - iNow = current at this step
// - rPrev = resistance at the previous step
// Return:
// - The new temperature
// Very simple model:
// - one constant for dissipation and heat capacity
// - temperature considered constant during the step
//-----------------------------------------------------------------------------
double cD_03_extractFeatures(double tPrev, double iPrev, double iNow, double rPrev)
{HEPSY_S(cleanData_03_id)
HEPSY_S(cleanData_03_id) double t ; // Temperature
HEPSY_S(cleanData_03_id)
HEPSY_S(cleanData_03_id) double i = 0.5*(iPrev + iNow); // Average current
// printf("cD_03_extractFeatures tPrev=%f\n",tPrev);
HEPSY_S(cleanData_03_id)
HEPSY_S(cleanData_03_id)
HEPSY_S(cleanData_03_id)
HEPSY_S(cleanData_03_id)
HEPSY_S(cleanData_03_id)
HEPSY_S(cleanData_03_id)
HEPSY_S(cleanData_03_id) t = tPrev + // Previous temperature
rPrev * (i * i) * cD_03_Tau - // Heat generated: P = I·R^2
cD_03_ThermalConstant * (tPrev - cD_03_T_0) * cD_03_Tau ; // Dissipation and heat capacity
HEPSY_S(cleanData_03_id) return( t );
}
//-----------------------------------------------------------------------------
// Input:
// - tNow: temperature at this step
// Return:
// - the resistance
// The model isn't realistic because the even the simpler law is exponential
//-----------------------------------------------------------------------------
double cD_03_degradationModel(double tNow)
{HEPSY_S(cleanData_03_id)
HEPSY_S(cleanData_03_id) double r ;
//r = R_0 + Alpha * tNow ;
HEPSY_S(cleanData_03_id)
HEPSY_S(cleanData_03_id)
HEPSY_S(cleanData_03_id) r = cD_03_R_0 * ( 2 - exp(-cD_03_Alpha*tNow) );
HEPSY_S(cleanData_03_id) return( r );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void cD_03_normalize(int index, double sample[cD_03_ANN_INPUTS])
{HEPSY_S(cleanData_03_id)
HEPSY_S(cleanData_03_id) double i ; double v ;
// Precondition: (0 <= sample[I_INDEX] <= 2*I_0) && (0 <= sample[V_INDEX] <= 2*V_0)
HEPSY_S(cleanData_03_id)
HEPSY_S(cleanData_03_id) i = sample[cD_03_I_INDEX] <= cD_03_I_0 ? 0.0 : 1.0;
HEPSY_S(cleanData_03_id)
HEPSY_S(cleanData_03_id)
HEPSY_S(cleanData_03_id) v = sample[cD_03_V_INDEX] <= cD_03_V_0 ? 0.0 : 1.0;
HEPSY_S(cleanData_03_id)
// Postcondition: (i in {0.0, 1.0}) and (v in {0.0, 1.0})
HEPSY_S(cleanData_03_id) sample[cD_03_I_INDEX] = i ;
HEPSY_S(cleanData_03_id) sample[cD_03_V_INDEX] = v ;
}
void mainsystem::cleanData_03_main()
{
// datatype for channels
sampleTimCord_cleanData_xx_payload sampleTimCord_cleanData_xx_payload_var;
cleanData_xx_ann_xx_payload cleanData_xx_ann_xx_payload_var;
//device var
uint8_t dev;
//step var
uint16_t step;
// ex_time (for extractFeatures...)
double ex_time;
//samples i and v
double sample_i;
double sample_v;
//var for samples, to re-use cleanData()
double cD_03_sample[cD_03_SAMPLE_LEN] ;
double x[cD_03_ANN_INPUTS + cD_03_ANN_OUTPUTS] ;
// NOTE: commented, should be changed param by ref...
//cD_03_initDescriptors(cD_03_device);
HEPSY_S(cleanData_03_id) cD_03_device.t = cD_03_T_0 ; // Operating temperature = Ambient temperature
HEPSY_S(cleanData_03_id) cD_03_device.r = cD_03_R_0 ; // Operating R_DS_On = Data-sheet R_DS_On
// ### added for time related dynamics
//static double cD_03_Tau = 0.02 ; // [s] Sampling period
HEPSY_S(cleanData_03_id) double cD_03_last_sample_time = 0;
//implementation
HEPSY_S(cleanData_03_id) while(1)
{HEPSY_S(cleanData_03_id)
// content
HEPSY_S(cleanData_03_id) sampleTimCord_cleanData_xx_payload_var = sampleTimCord_cleanData_03_channel->read();
HEPSY_S(cleanData_03_id) dev = sampleTimCord_cleanData_xx_payload_var.dev;
HEPSY_S(cleanData_03_id) step = sampleTimCord_cleanData_xx_payload_var.step;
HEPSY_S(cleanData_03_id) ex_time = sampleTimCord_cleanData_xx_payload_var.ex_time;
HEPSY_S(cleanData_03_id) sample_i = sampleTimCord_cleanData_xx_payload_var.sample_i;
HEPSY_S(cleanData_03_id) sample_v = sampleTimCord_cleanData_xx_payload_var.sample_v;
// cout << "cleanData_03 rcv \t dev: " << dev
// <<"\t step: " << step
// <<"\t time_ex:" << ex_time
// <<"\t i:" << sample_i
// <<"\t v:" << sample_v
// << endl;
// reconstruct sample
HEPSY_S(cleanData_03_id) cD_03_sample[cD_03_I_INDEX] = sample_i;
HEPSY_S(cleanData_03_id) cD_03_sample[cD_03_V_INDEX] = sample_v;
HEPSY_S(cleanData_03_id) cD_03_sample[cD_03_TIME_INDEX] = ex_time;
// ### C L E A N D A T A (0 <= I <= 2.0*I_0) and (0 <= V <= 2.0*V_0)
HEPSY_S(cleanData_03_id) cD_03_cleanData(dev, cD_03_sample) ;
HEPSY_S(cleanData_03_id) cD_03_device.time_Ex = cD_03_sample[cD_03_TIME_INDEX] ;
HEPSY_S(cleanData_03_id) cD_03_device.i = cD_03_sample[cD_03_I_INDEX] ;
HEPSY_S(cleanData_03_id) cD_03_device.v = cD_03_sample[cD_03_V_INDEX] ;
// ### added for time related dynamics
//static double cD_03_Tau = 0.02 ; // [s] Sampling period
HEPSY_S(cleanData_03_id) cD_03_Tau = ex_time - cD_03_last_sample_time;
HEPSY_S(cleanData_03_id) cD_03_last_sample_time = ex_time;
// ### F E A T U R E S E X T R A C T I O N (compute the temperature)
HEPSY_S(cleanData_03_id) cD_03_device.t = cD_03_extractFeatures( cD_03_device.t, // Previous temperature
cD_03_device.i, // Previous current
cD_03_sample[cD_03_I_INDEX], // Current at this step
cD_03_device.r) ; // Previous resistance
// ### D E G R A D A T I O N M O D E L (compute R_DS_On)
HEPSY_S(cleanData_03_id) cD_03_device.r = cD_03_degradationModel(cD_03_device.t) ;
// ### N O R M A L I Z E: (x[0] in {0.0, 1.0}) and (x[1] in {0.0, 1.0})
HEPSY_S(cleanData_03_id) x[0] = cD_03_device.i ;
HEPSY_S(cleanData_03_id) x[1] = cD_03_device.v ;
HEPSY_S(cleanData_03_id) cD_03_normalize(dev, x) ;
// // ### P R E D I C T (simple XOR)
// if ( annRun(index, x) != EXIT_SUCCESS ){
//prepare out data payload
HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.dev = dev;
HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.step = step;
HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.ex_time = ex_time;
HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.device_i = cD_03_device.i;
HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.device_v = cD_03_device.v;
HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.device_t = cD_03_device.t;
HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.device_r = cD_03_device.r;
HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.x_0 = x[0];
HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.x_1 = x[1];
HEPSY_S(cleanData_03_id) cleanData_xx_ann_xx_payload_var.x_2 = x[2];
HEPSY_S(cleanData_03_id) cleanData_03_ann_03_channel->write(cleanData_xx_ann_xx_payload_var);
HEPSY_P(cleanData_03_id)
}
}
//END
|
#include "systemc.h"
#include "system.h"
#include "checksum.hpp"
#include "noc_if.h"
#include "noc_adapter.h"
noc_adapter::noc_adapter(sc_module_name name, uint32_t x, uint32_t y)
: sc_module(name), _x(x), _y(y), _is_redundant(false), _out_fifo_head(0), _out_fifo_tail(0) {}
void noc_adapter::configure_redundancy(uint32_t redundant_base_addrs[3], noc_routing_alg_e routing_algs[3]) {
_is_redundant = true;
_base_redundant_addr = redundant_base_addrs[0];
for (int i = 0; i < 3; ++i) {
_redundant_dst_x[i] = NOC_GET_X_ADDR(redundant_base_addrs[i]);
_redundant_dst_y[i] = NOC_GET_Y_ADDR(redundant_base_addrs[i]);
_redundant_routing_alg[i] = routing_algs[i];
}
SC_THREAD(main);
}
/** noc_if.read_port */
void noc_adapter::read_port(noc_dir_e dir, noc_data_t& data, noc_link_ctrl_t& link_ctrl) {
link_ctrl = _w_link_ctrl;
data = _w_data;
if (dir == NOC_DIR_TILE0) {
link_ctrl.ctrl = _w_link_ctrl_ctrl[0];
// x and y destinations set by default in _write_packet
//link_ctrl.dst.x = _redundant_dst_x[0];
//link_ctrl.dst.y = _redundant_dst_y[0];
link_ctrl.routing_alg = _redundant_routing_alg[0];
}
else if (_is_redundant && dir == NOC_DIR_TILE1) {
link_ctrl.ctrl = _w_link_ctrl_ctrl[1];
link_ctrl.dst.x = _redundant_dst_x[1];
link_ctrl.dst.y = _redundant_dst_y[1];
link_ctrl.routing_alg = _redundant_routing_alg[1];
}
else if (_is_redundant && dir == NOC_DIR_TILE2) {
link_ctrl.ctrl = _w_link_ctrl_ctrl[2];
link_ctrl.dst.x = _redundant_dst_x[2];
link_ctrl.dst.y = _redundant_dst_y[2];
link_ctrl.routing_alg = _redundant_routing_alg[2];
}
}
/** noc_adapter_if.read_packet */
bool noc_adapter::_read_packet(uint32_t& src_addr, uint32_t& rel_addr, noc_data_t& data) {
if (_is_redundant) {
// dequeue from FIFO
if (_out_fifo_head != _out_fifo_tail) {
src_addr = _out_fifo_src_addr[_out_fifo_head & RESPONSE_FIFO_PTR_MASK];
rel_addr = _out_fifo_rel_addr[_out_fifo_head & RESPONSE_FIFO_PTR_MASK];
data = _out_fifo_data[_out_fifo_head & RESPONSE_FIFO_PTR_MASK];
_out_fifo_head++;
POSEDGE();
return true;
}
POSEDGE();
return false;
}
else {
// read from the router
router_if->read_port(NOC_DIR_TILE0, _r_data, _r_link_ctrl);
POSEDGE();
// if packet is enabled
if (_r_link_ctrl.ctrl) {
// parse packet
src_addr = NOC_RECOVER_RAW_ADDR(_r_link_ctrl.src);
rel_addr = _r_link_ctrl.dst.rel;
data = _r_data;
return true;
}
return false;
}
}
/** noc_adapter_if.write_packet */
bool noc_adapter::_write_packet(uint32_t src, uint32_t addr, noc_data_t *data, uint32_t n) {
// activate packet
_w_link_ctrl_ctrl[0] = true;
_w_link_ctrl.ctrl = false;
_w_link_ctrl.head = true;
// determine number of packets
n = (n / NOC_DSIZE) + ((n % NOC_DSIZE) ? 1 : 0);
// determine if redundant packet
if (_is_redundant) {
uint32_t rel_addr = NOC_GET_REL_ADDR(addr);
// check if redundant packet (targeted to a redundant module)
if (NOC_GET_X_ADDR(addr) == _redundant_dst_x[0] && NOC_GET_Y_ADDR(addr) == _redundant_dst_y[0]) {
_w_link_ctrl_ctrl[1] = true;
_w_link_ctrl_ctrl[2] = true;
}
}
while (n) {
// construct current packet
_w_link_ctrl.tail = (n == 1);
_w_link_ctrl.src.rel = src;
_w_link_ctrl.src.x = _x;
_w_link_ctrl.src.y = _y;
_w_link_ctrl.dst.rel = NOC_GET_REL_ADDR(addr);
_w_link_ctrl.dst.x = NOC_GET_X_ADDR(addr);
_w_link_ctrl.dst.y = NOC_GET_Y_ADDR(addr);
_w_data = *data;
// increment counters
n--;
addr += NOC_DSIZE;
data++;
// wait for next CC
POSEDGE();
_w_link_ctrl.head = false;
}
// disable packet
_w_link_ctrl_ctrl[0] = false;
_w_link_ctrl_ctrl[1] = false;
_w_link_ctrl_ctrl[2] = false;
_w_link_ctrl.ctrl = false;
return true;
}
void noc_adapter::main() {
// NoC packets
uint32_t rel_addr;
noc_data_t data;
// keep track of redundant communications
int32_t redundant_src_idx;
uint32_t checkpoint_size_bytes = CHECKPOINT_SIZE_PKTS * NOC_DSIZE;
tmr_packet_status_e status;
tmr_state_collection<noc_data_t> states(CHECKPOINT_SIZE_PKTS, MAX_OUT_SIZE / checkpoint_size_bytes);
// buffer
uint32_t out_addr = 0;
noc_data_t rsp_buf[CHECKPOINT_SIZE_PKTS];
while (true) {
// read from the router
router_if->read_port(NOC_DIR_TILE0, _r_data, _r_link_ctrl);
if (_r_link_ctrl.ctrl) {
// parse packet
rel_addr = _r_link_ctrl.dst.rel;
data = _r_data;
// determine source
for (redundant_src_idx = 2; redundant_src_idx >= 0; redundant_src_idx--) {
if (_r_link_ctrl.src.x == _redundant_dst_x[redundant_src_idx] && _r_link_ctrl.src.y == _redundant_dst_y[redundant_src_idx]) break;
}
if (redundant_src_idx >= 0) {
// update CRC
status = states.update(redundant_src_idx, data, rsp_buf);
if (status == TMR_STATUS_COMMIT) {
// enqueue in output FIFO
for (int i = 0; i < CHECKPOINT_SIZE_PKTS; ++i) {
_out_fifo_src_addr[_out_fifo_tail & RESPONSE_FIFO_PTR_MASK] = _base_redundant_addr;
_out_fifo_rel_addr[_out_fifo_tail & RESPONSE_FIFO_PTR_MASK] = out_addr;
_out_fifo_data[_out_fifo_tail &
RESPONSE_FIFO_PTR_MASK] = rsp_buf[i];
_out_fifo_tail++;
out_addr += NOC_DSIZE;
}
}
else if (status == TMR_STATUS_INVALID) {
// TODO: interrupt
LOGF("Error detected in checkpoint at byte %08x", out_addr);
tile_if->signal(1);
}
}
else {
// normal packet to enqueue in output FIFO
_out_fifo_src_addr[_out_fifo_tail & RESPONSE_FIFO_PTR_MASK] = NOC_RECOVER_RAW_ADDR(_r_link_ctrl.src);
_out_fifo_rel_addr[_out_fifo_tail & RESPONSE_FIFO_PTR_MASK] = rel_addr;
_out_fifo_data[_out_fifo_tail & RESPONSE_FIFO_PTR_MASK] = data;
_out_fifo_tail++;
}
}
POSEDGE();
}
}
|
#include <iostream>
#include <iomanip>
#include "systemc.h"
#include "IDFT.h"
#include "DFTModule.h"
#include "FPU32.h"
#include "DSP.h"
#include "ALU.h"
int sc_main(int argc, char* argv[])
{
//General Signals
sc_signal<bool> clk;
sc_signal<sc_uint<64>> inst;
//FFT and IFFT
sc_signal<bool> flag_en_IDFT;
sc_signal<bool> flag_reset_IDFT;
sc_signal<bool> flag_en_DFT;
sc_signal<bool> flag_reset_DFT;
sc_signal<int> DFT_N;
sc_signal<bool> rxIDFT;
sc_signal<bool> rxDFT;
sc_signal<bool> calculatingFlagIDFT;
sc_signal<bool> calculatingFlagDFT;
sc_signal<double> InRealBus;
sc_signal<double> inImaginaryBus;
sc_signal<double> outRealBus_DFT;
sc_signal<double> outImaginaryBus_DFT;
sc_signal<double> outRealBus_IDFT;
sc_signal<double> outImaginaryBus_IDFT;
// FPU32 & ALU
sc_signal< sc_uint<32> > OpA;
sc_signal< sc_uint<32> > OpB;
sc_signal< sc_uint<4> > OpCodeAlu;
sc_signal< sc_uint<32> > OutALU;
sc_signal< sc_uint<32> > OutFPU;
sc_signal< sc_uint<1> > Overflow;
sc_signal< sc_uint<1> > Underflow;
sc_signal < bool > ZERO;
DSP dsp("DSP");
dsp.flag_en_IDFT(flag_en_IDFT);
dsp.flag_en_DFT(flag_en_DFT);
dsp.flag_reset_IDFT(flag_reset_IDFT);
dsp.flag_reset_DFT(flag_reset_DFT);
dsp.NForFourier(DFT_N);
dsp.clock(clk);
dsp.instruction(inst);
dsp.InRealBus(InRealBus);
dsp.inImaginaryBus(inImaginaryBus);
dsp.outImaginaryBus_DFT(outImaginaryBus_DFT);
dsp.outImaginaryBus_IDFT(outImaginaryBus_IDFT);
dsp.outRealBus_DFT(outRealBus_DFT);
dsp.outRealBus_IDFT(outRealBus_IDFT);
dsp.rxSamplesFlag(rxIDFT);
dsp.rxSamplesFlag_DFT(rxDFT);
dsp.calculatingFlag(calculatingFlagIDFT);
dsp.calculatingFlag_DFT(calculatingFlagDFT);
dsp.OpA(OpA);
dsp.OpB(OpB);
dsp.OpCodeAlu(OpCodeAlu);
dsp.OutFPU(OutFPU);
dsp.OutALU(OutALU);
dsp.Overflow(Overflow);
dsp.Underflow(Underflow);
dsp.fillMemory();
IDFT pIDFT("IDFFT");
pIDFT.clock(clk);
pIDFT.f_Enable(flag_en_IDFT);
pIDFT.reset(flag_reset_IDFT);
pIDFT.N(DFT_N);
pIDFT.InReal(InRealBus);
pIDFT.InImaginary(inImaginaryBus);
pIDFT.OutReal(outRealBus_IDFT);
pIDFT.OutImaginary(outImaginaryBus_IDFT);
pIDFT.rxSamplesFlag(rxIDFT);
pIDFT.calculatingFlag(calculatingFlagIDFT);
DFTModule pDFTMod("DFT");
pDFTMod.clock(clk);
pDFTMod.f_Enable(flag_en_DFT);
pDFTMod.f_RxSamples(rxDFT);
pDFTMod.f_Calculate(calculatingFlagDFT);
pDFTMod.Reset(flag_reset_DFT);
pDFTMod.N(DFT_N);
pDFTMod.Sample(InRealBus);
pDFTMod.OutReal(outRealBus_DFT);
pDFTMod.OutImg(outImaginaryBus_DFT);
// DUT
FPU32 Fpu32("FPU32");
Fpu32.OpA(OpA);
Fpu32.OpB(OpB);
Fpu32.Out(OutFPU);
Fpu32.OpCode(OpCodeAlu);
Fpu32.Overflow(Overflow);
Fpu32.Underflow(Underflow);
ALU alu("ALU");
alu.OP(OpCodeAlu);
alu.OPa(OpA);
alu.OPb(OpB);
alu.ZERO(ZERO);
alu.RESULT(OutALU);
// Initialice before tracing
clk = 0;
rxIDFT = 0;
rxDFT = 0;
calculatingFlagIDFT = 0;
calculatingFlagDFT = 0;
flag_reset_IDFT = 0;
flag_reset_DFT = 0;
// Starting trace
sc_trace_file *wf = sc_create_vcd_trace_file("IDFTing");
wf->set_time_unit(1, SC_NS);
sc_trace(wf, clk, "Clock");
sc_trace(wf, flag_en_DFT, "DFT_Enable");
sc_trace(wf, flag_en_IDFT, "IDFT_Enable");
sc_trace(wf, InRealBus, "InputDataFT");
sc_trace(wf, outRealBus_DFT, "OutputData_DFT");
sc_trace(wf, outRealBus_IDFT, "OutputData_IDFT");
sc_trace(wf, rxIDFT, "rxIDFT");
sc_trace(wf, rxDFT, "rxDFT");
sc_trace(wf, calculatingFlagIDFT, "IDFT_Working");
sc_trace(wf, calculatingFlagDFT, "DFT_Working");
sc_trace(wf, OpA, "OpA");
sc_trace(wf, OpB, "OpB");
sc_trace(wf, OutALU, "OutALU");
sc_trace(wf, OutFPU, "OutFPU");
sc_trace(wf, OpCodeAlu, "OpCodeAlu");
sc_trace(wf, Overflow, "Overflow");
sc_trace(wf, Underflow, "Underflow");
sc_start(1, SC_NS);
inst = 0x1000000000000005;
for (int i=0;i<17;i++) {
clk = 0;
sc_start(1,SC_NS);
clk = 1;
sc_start(1,SC_NS);
inst = 0xFFFFFFFFFFFFFFFF;
}
inst = 0x2000000000000005;
for (int i=0;i<17;i++) {
clk = 0;
sc_start(1,SC_NS);
clk = 1;
sc_start(1,SC_NS);
inst = 0xFFFFFFFFFFFFFFFF;
}
//Suma de FPU
inst = 0x300000A0000B00FF;
for (int i=0;i<5;i++) {
clk = 0;
sc_start(1,SC_NS);
clk = 1;
sc_start(1,SC_NS);
}
//Suma de FPU
inst = 0x310000C0000D00FF;
for (int i=0;i<5;i++) {
clk = 0;
sc_start(1,SC_NS);
clk = 1;
sc_start(1,SC_NS);
}
inst = 0x400000F0001000FF;
for (int i=0;i<5;i++) {
clk = 0;
sc_start(1,SC_NS);
clk = 1;
sc_start(1,SC_NS);
}
inst = 0x440000F0001000FF;
for (int i=0;i<5;i++) {
clk = 0;
sc_start(1,SC_NS);
clk = 1;
sc_start(1,SC_NS);
}
// inst = 0x1000000000200005;
// for (int i=0;i<30;i++) {
// clk = 0;
// sc_start(1,SC_NS);
// clk = 1;
// sc_start(1,SC_NS);
// }
std::cout << "Hellow World, SystemC" << std::endl;
// // Finishing trace
sc_close_vcd_trace_file(wf);
// std::cout << "Hellow World, SystemC" << std::endl;
return 0;
}
|
//--------Thread function definitions-----------------------------
//-----You must modify this file as indicated by TODO comments----
//must include to use the systemc library
#include "systemc.h"
#include "CPU.h"
#include "Block.h"
#include "ReadBmp_aux.h"
#include <string.h>
void CPU::Read_thread(){
cout << sc_time_stamp() << ": Thread Read BMP is initialized\n";
//initial part before the loop
ReadBmpHeader();
ImageWidth = BmpInfoHeader[1];
ImageHeight = BmpInfoHeader[2];
InitGlobals();
NumberMDU = MDUWide * MDUHigh;
//local
Block block;
for(int iter = 0; iter < 180; iter++)
{
ReadBmpBlock(iter);
memcpy(block.data, bmpinput, sizeof(block.data));
cout << sc_time_stamp() << ": Thread Read BMP attempting to send frame" << iter << " to DCT\n";
// TODO: Insert appropriate channel call here
Read2DCT->write(block);
cout << sc_time_stamp() << ": Thread Read BMP has sent frame" << iter << " to DCT\n";
}
wait();
}
void CPU::DCT_thread(){
//local
Block block;
int in_block[64], out_block[64];
cout << sc_time_stamp() << ": Thread DCT is initialized\n";
for(int iter = 0; iter < 180; iter++)
{
cout << sc_time_stamp() << ": Thread DCT is attempting to receive frame" << iter << " from Read BMP\n";
// TODO: Insert appropriate channel call here
Read2DCT->read(block);
cout << sc_time_stamp() << ": Thread DCT has received frame" << iter << " from Read BMP\n";
memcpy(in_block, block.data, sizeof(in_block));
chendct(in_block,out_block);
memcpy(block.data, out_block, sizeof(block.data));
cout << sc_time_stamp() << ": Thread DCT is attempting to send frame" << iter << " to Quantize\n";
// TODO: Insert appropriate channel call here
DCT2Quant->write(block);
cout << sc_time_stamp() << ": Thread DCT has sent frame" << iter << " to Quantize\n";
}
wait();
}
void CPU::Quant_thread(){
Block block;
int in_block[64], out_block[64];
cout << sc_time_stamp() << ": Thread Quantize is initialized\n";
for(int iter = 0; iter < 180; iter++)
{
cout << sc_time_stamp() << ": Thread Quantize is attempting to receive frame" << iter << " from DCT\n";
// TODO: Insert appropriate channel call here
DCT2Quant->read(block);
cout << sc_time_stamp() << ": Thread Quantize has received frame" << iter << " from DCT\n";
// TODO: Copy over block received from channel into local in_block
memcpy(in_block, block.data, sizeof(in_block));
quantize(in_block,out_block);
// TODO: Copy over out_block to block for sending over the channel below
memcpy(block.data, out_block, sizeof(block.data));
cout << sc_time_stamp() << ": Thread Quantize is attempting to send frame" << iter << " to ZigZag\n";
// TODO: Insert appropriate channel call here
Quant2Zigzag->write(block);
cout << sc_time_stamp() << ": Thread Quantize has sent frame" << iter << " to ZigZag\n";
}
wait();
}
void CPU::Zigzag_thread(){
Block block;
int in_block[64], out_block[64];
cout << sc_time_stamp() << ": Thread ZigZag is initialized\n";
for(int iter = 0; iter < 180; iter++)
{
cout << sc_time_stamp() << ": Thread ZigZag is attempting to receive frame" << iter << " from Quantize\n";
// TODO: Insert appropriate channel call here
Quant2Zigzag->read(block);
cout << sc_time_stamp() << ": Thread ZigZag has received frame" << iter << " from Quantize\n";
// TODO: Copy over block received from channel into local in_block
memcpy(in_block, block.data, sizeof(in_block));
zigzag(in_block,out_block);
// TODO: Copy over out_block to block for sending over the channel below
memcpy(block.data, out_block, sizeof(block.data));
cout << sc_time_stamp() << ": Thread ZigZag is attempting to send frame" << iter << " to Huffman\n";
// TODO: Insert appropriate channel call here
Zigzag2Huff->write(block);
cout << sc_time_stamp() << ": Thread ZigZag has sent frame" << iter << " to Huffman\n";
}
wait();
}
void CPU::Huff_thread(){
Block block;
int in_block[64];
cout << sc_time_stamp() << ": Thread Huffman is initialized\n";
for(int iter = 0; iter < 180; iter++)
{
cout << sc_time_stamp() << ": Thread Huffman is attempting to receive frame" << iter << " from ZigZag\n";
// TODO: Insert appropriate channel call here
Zigzag2Huff->read(block);
cout << sc_time_stamp() << ": Thread Huffman has received frame" << iter << " from ZigZag\n";
// TODO: Copy over block received from channel into local in_block
memcpy(in_block, block.data, sizeof(in_block));
huffencode(in_block);
}
cout << sc_time_stamp() << ": Thread Huffman is writing encoded JPEG to file\n";
FileWrite();
cout << sc_time_stamp() << ": JPEG encoding completed\n";
wait();
}
//----------------End of thread function definitions--------------
|
/*******************************************************************************
* pcf8574.cpp -- Copyright 2020 (c) Glenn Ramalho - RFIDo Design
*******************************************************************************
* Description:
* This is a crude model for the PN532 with firmware v1.6. It will work for
* basic work with a PN532 system.
*******************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************
*/
#include <systemc.h>
#include "pcf8574.h"
#include "info.h"
unsigned char pcf8574::sampleport() {
unsigned char samp = 0;
int cnt;
for(cnt = 0; cnt < sig.size(); cnt = cnt + 1) {
if (!sig[cnt]->read().islogic()) {
PRINTF_WARN("PCF8574", "Sampled a signal at level %c",
sig[cnt]->read().to_char());
}
else if (sig[cnt]->read().ishigh()) samp = samp | (1 << cnt);
}
return samp;
}
void pcf8574::intr_th() {
intr.write(GN_LOGIC_Z);
while(1) {
switch (sig.size()) {
case 0: wait(clearintr_ev); break;
case 1:
wait(clearintr_ev | sig[0]->default_event());
break;
case 2:
wait(clearintr_ev |
sig[0]->default_event() | sig[1]->default_event());
break;
case 3:
wait(clearintr_ev |
sig[0]->default_event() | sig[1]->default_event() |
sig[2]->default_event());
break;
case 4:
wait(clearintr_ev |
sig[0]->default_event() | sig[1]->default_event() |
sig[2]->default_event() | sig[3]->default_event());
break;
case 5:
wait(clearintr_ev |
sig[0]->default_event() | sig[1]->default_event() |
sig[2]->default_event() | sig[3]->default_event() |
sig[4]->default_event());
break;
case 6:
wait(clearintr_ev |
sig[0]->default_event() | sig[1]->default_event() |
sig[2]->default_event() | sig[3]->default_event() |
sig[4]->default_event() | sig[5]->default_event());
break;
case 7:
wait(clearintr_ev |
sig[0]->default_event() | sig[1]->default_event() |
sig[2]->default_event() | sig[3]->default_event() |
sig[4]->default_event() | sig[5]->default_event() |
sig[6]->default_event());
break;
default:
wait(clearintr_ev |
sig[0]->default_event() | sig[1]->default_event() |
sig[2]->default_event() | sig[3]->default_event() |
sig[4]->default_event() | sig[5]->default_event() |
sig[6]->default_event() | sig[7]->default_event());
break;
}
/* If we got a lowerintr we lower the line. Anything else raises it.
* Note that we do not raise the interrupt while we were writing.
*/
if (clearintr_ev.triggered()) intr.write(GN_LOGIC_Z);
else if (i2cstate != WRDATA && i2cstate != ACKWRD && i2cstate != ACKWR)
intr.write(GN_LOGIC_0);
}
}
void pcf8574::i2c_th(void) {
int i;
unsigned int devid, data;
/* We begin initializing all ports to weak 1. */
for(i = 0; i < sig.size(); i = i + 1) {
sig[i]->write(GN_LOGIC_W1);
}
/* The interrupt begins as Z. */
intr.write(GN_LOGIC_Z);
/* Then we begin waiting for the I2C commands. */
while(1) {
/* We wait for a change on either the SDA or the SCL. */
wait();
state.write((int)i2cstate);
/* If we get Z or X, we ignore it. */
if (!scl.read().islogic()) {
PRINTF_WARN("PN532", "SCL is not defined");
}
else if (!sda.read().islogic()) {
PRINTF_WARN("PN532", "SDA is not defined");
}
/* At any time a start or stop bit can come in. */
else if (scl.read().ishigh() && sda.value_changed_event().triggered()) {
if (sda.read().islow()) {
/* START BIT */
i2cstate = DEVID;
i = 7;
devid = 0;
}
/* STOP BIT */
else i2cstate = IDLE;
}
/* The rest has to be data changes. For simplicity all data in and flow
* control is here. The data returned is done on another branch.
*/
else if (scl.value_changed_event().triggered() && scl.read().ishigh())
switch(i2cstate) {
case IDLE: break;
case DEVID:
/* We collect all bits of the device ID. The last bit is the R/W
* bit.
*/
if (i > 0) devid = (devid << 1) + ((sda.read().ishigh())?1:0);
/* If the ID matches, we can process it. */
else if (devid == device_id && sda.read().ishigh()) i2cstate=ACKRD;
else if (devid == device_id && sda.read().islow()) i2cstate=ACKWR;
/* If the devid does not match, we return Z. */
else i2cstate = RETZ;
i = i - 1;
break;
/* If the address does not match, we return Z. */
case RETZ:
i2cstate = IDLE;
break;
/* When we recognize the ACKRD, we sample the pins. This will be
* returned via the I2C.
*/
case ACKRD:
i = 7;
i2cstate = READ;
data = sampleport();
/* We also clear the interrupt. */
clearintr_ev.notify();
break;
/* When we hit the ACKWR, all we do is clear the shiftregister to
* begin to receive data.
*/
case ACKWR:
i = 7;
data = 0;
i2cstate = WRDATA;
/* We also clear the interrupt. */
clearintr_ev.notify();
break;
/* Each bit is taken. */
case WRDATA:
/* Just when we enter the WRDATA phase we need to release the SDA */
if (i == 7) sda.write(GN_LOGIC_Z);
/* And the data we collect to drive in the WRD phase. */
data = (data << 1) + ((sda.read().ishigh())?1:0);
if (i == 0) i2cstate = ACKWRD;
else i = i - 1;
break;
/* When we have finished a write, we send back an ACK to the master.
* We also will drive all pins strong.
*/
case ACKWRD: {
/* We first take in the new drive value received. */
drive = data;
/* In the ACKWRD state, we drive all pins strong, once we exit, we
* lower the logic 1s to weak so that they can be read.
*/
if (i2cstate == ACKWRD) {
int cnt;
for (cnt = 0; cnt < sig.size(); cnt = cnt + 1) {
sig[cnt]->write(((drive & (1<<cnt))>0)?GN_LOGIC_1:GN_LOGIC_0);
}
}
/* Then we clear the shiftregister to begin to collect data from
* the master.
*/
data = 0;
i = 7;
i2cstate = WRDATA;
/* We also clear the interrupt. */
clearintr_ev.notify();
break;
}
/* Depending on the acknack we either return more data or not. */
case ACKNACK:
if (sda.read().ishigh()) i2cstate = IDLE;
else {
/* If we got the ACK, we then clear the registers, sample the
* I/Os and return to the read state.
*/
i2cstate = READ;
i = 7;
data = sampleport();
}
break;
/* On reads, we send the data after each bit change. Note: the driving
* is done on the other edge.
*/
case READ:
if (i == 0) i2cstate = ACKNACK;
else i = i - 1;
break;
}
/* Anytime the clock drops, we return data. We only do the data return
* to keep the FSM simpler.
*/
else if (scl.value_changed_event().triggered() && scl.read().islow())
switch (i2cstate) {
/* If we get an illegal code, we return Z. We remain here until
* we get.
*/
case RETZ: sda.write(GN_LOGIC_Z); break;
/* ACKWRD, ACKWR and ACKRD we return a 0. */
case ACKRD:
case ACKWR:
case ACKWRD:
sda.write(GN_LOGIC_0);
break;
/* For the WRITE state, all we do is release the SDA so that the
* master can write. */
case WRDATA:
/* When we enter the WRDATA, we need to weaken the driving logic 1s.
* We then scan through them and redrive any of them from 1 to W1.
* We only need to do this if it is not all 0s.
*/
if (i == 7 && drive != 0x0) {
int cnt;
for (cnt = 0; cnt < sig.size(); cnt = cnt + 1) {
if ((drive & (1<<cnt))>0) sig[cnt]->write(GN_LOGIC_W1);
}
}
break;
case ACKNACK:
/* The SDA we float. */
sda.write(GN_LOGIC_Z);
break;
/* Each bit is returned. */
case READ:
if ((data & (1 << i))>0) sda.write(GN_LOGIC_Z);
else sda.write(GN_LOGIC_0);
break;
default: ; /* For the others we do nothing. */
}
}
}
void pcf8574::trace(sc_trace_file *tf) {
sc_trace(tf, state, state.name());
}
|
//****************************************************************************************
// MIT License
//****************************************************************************************
// Copyright (c) 2012-2020 University of Bremen, Germany.
// Copyright (c) 2015-2020 DFKI GmbH Bremen, Germany.
// Copyright (c) 2020 Johannes Kepler University Linz, Austria.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//****************************************************************************************
#include <crave/experimental/SystemC.hpp>
#include <crave/ConstrainedRandom.hpp>
#include <systemc.h>
#include <boost/timer.hpp>
#include <crave/experimental/Experimental.hpp>
using crave::crv_sequence_item;
using crave::crv_constraint;
using crave::crv_variable;
using crave::crv_object_name;
using sc_dt::sc_bv;
using sc_dt::sc_uint;
struct ALU16 : public crv_sequence_item {
crv_variable<sc_bv<2> > op;
crv_variable<sc_uint<16> > a, b;
crv_constraint c_add{ "add" };
crv_constraint c_sub{ "sub" };
crv_constraint c_mul{ "mul" };
crv_constraint c_div{ "div" };
ALU16(crv_object_name) {
c_add = {(op() != 0x0) || (65535 >= a() + b()) };
c_sub = {(op() != 0x1) || ((65535 >= a() - b()) && (b() <= a())) };
c_mul = {(op() != 0x2) || (65535 >= a() * b()) };
c_div = {(op() != 0x3) || (b() != 0) };
}
friend std::ostream& operator<<(std::ostream& o, ALU16 const& alu) {
o << alu.op << ' ' << alu.a << ' ' << alu.b;
return o;
}
};
int sc_main(int argc, char** argv) {
crave::init("crave.cfg");
boost::timer timer;
ALU16 c("ALU");
CHECK(c.randomize());
std::cout << "first: " << timer.elapsed() << "\n";
for (int i = 0; i < 1000; ++i) {
CHECK(c.randomize());
}
std::cout << "complete: " << timer.elapsed() << "\n";
return 0;
}
|
//-----------------------------------------------------
// This is my second Systemc Example
// Design Name : first_counter
// File Name : first_counter.cpp
// Function : This is a 4 bit up-counter with
// Synchronous active high reset and
// with active high enable signal
//-----------------------------------------------------
#include "systemc.h"
SC_MODULE (first_counter) {
sc_in_clk clock ; // Clock input of the design
sc_in<bool> reset ; // active high, synchronous Reset input
sc_in<bool> enable; // Active high enable signal for counter
sc_out<sc_uint<4> > counter_out; // 4 bit vector output of the counter
//------------Local Variables Here---------------------
sc_uint<4> count;
//------------Code Starts Here-------------------------
// Below function implements actual counter logic
void incr_count () {
// At every rising edge of clock we check if reset is active
// If active, we load the counter output with 4'b0000
if (reset == 1) {
count = 0;
counter_out.write(count);
// If enable is active, then we increment the counter
} else if (enable == 1) {
count = count + 1;
counter_out.write(count);
//cout<<"@" << sc_time_stamp() <<" :: Incremented Counter "
// <<counter_out.read()<<endl;
}
} // End of function incr_count
// Constructor for the counter
// Since this counter is a positive edge trigged one,
// We trigger the below block with respect to positive
// edge of the clock and also when ever reset changes state
SC_CTOR(first_counter) {
cout<<"Executing new"<<endl;
SC_METHOD(incr_count);
sensitive << reset;
sensitive << clock.pos();
} // End of Constructor
}; // End of Module counter
|
#include <systemc.h>
#include "counter.cpp"
int sc_main (int argc, char* argv[]) {
sc_signal<bool> clock;
sc_signal<bool> reset;
sc_signal<bool> enable;
sc_signal<sc_uint<4> > counter_out;
int i = 0;
// Connect the DUT
first_counter counter("COUNTER");
counter.clock(clock);
counter.reset(reset);
counter.enable(enable);
counter.counter_out(counter_out);
// Open VCD file
sc_trace_file *wf = sc_create_vcd_trace_file("counter");
wf->set_time_unit(1, SC_NS);
// Dump the desired signals
sc_trace(wf, clock, "clock");
sc_trace(wf, reset, "reset");
sc_trace(wf, enable, "enable");
sc_trace(wf, counter_out, "count");
sc_start(1,SC_NS);
// Initialize all variables
reset = 0; // initial value of reset
enable = 0; // initial value of enable
for (i=0;i<5;i++) {
clock = 0;
sc_start(1,SC_NS);
clock = 1;
sc_start(1,SC_NS);
}
reset = 1; // Assert the reset
cout << "@" << sc_time_stamp() <<" Asserting reset\n" << endl;
for (i=0;i<10;i++) {
clock = 0;
sc_start(1,SC_NS);
clock = 1;
sc_start(1,SC_NS);
}
reset = 0; // De-assert the reset
cout << "@" << sc_time_stamp() <<" De-Asserting reset\n" << endl;
for (i=0;i<5;i++) {
clock = 0;
sc_start(1,SC_NS);
clock = 1;
sc_start(1,SC_NS);
}
cout << "@" << sc_time_stamp() <<" Asserting Enable\n" << endl;
enable = 1; // Assert enable
for (i=0;i<20;i++) {
clock = 0;
sc_start(1,SC_NS);
clock = 1;
sc_start(1,SC_NS);
}
cout << "@" << sc_time_stamp() <<" De-Asserting Enable\n" << endl;
enable = 0; // De-assert enable
cout << "@" << sc_time_stamp() <<" Terminating simulation\n" << endl;
sc_close_vcd_trace_file(wf);
return 0;// Terminate simulation
} |
/*******************************************************************************
* esp_wifi.cpp -- Copyright 2019 Glenn Ramalho - RFIDo Design
*******************************************************************************
* Description:
* This file ports the esp_wifi functions for the ESP32 to the ESPMOD SystemC
* model. It was based off the functions from Espressif Systems.
*******************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file was based off the work covered by the license below:
* Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <systemc.h>
#include "WiFi.h"
#include "info.h"
#include <IPAddress.h>
#include "esp_system.h"
#include "esp_err.h"
#include "WiFiType.h"
#include "esp_wifi_types.h"
#include "wifistat.h"
#include "esp_wifi.h"
#include "lwip/sockets.h"
#include <string.h>
wifistat_t wifistat;
/**
* @brief Init WiFi
* Alloc resource for WiFi driver, such as WiFi control structure, RX/TX buffer,
* WiFi NVS structure etc, this WiFi also start WiFi task
*
* @attention 1. This API must be called before all other WiFi API can be called
* @attention 2. Always use WIFI_INIT_CONFIG_DEFAULT macro to init the config to default values, this can
* guarantee all the fields got correct value when more fields are added into wifi_init_config_t
* in future release. If you want to set your owner initial values, overwrite the default values
* which are set by WIFI_INIT_CONFIG_DEFAULT, please be notified that the field 'magic' of
* wifi_init_config_t should always be WIFI_INIT_CONFIG_MAGIC!
*
* @param config pointer to WiFi init configuration structure; can point to a temporary variable.
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_NO_MEM: out of memory
* - others: refer to error code esp_err.h
*/
esp_err_t esp_wifi_init(const wifi_init_config_t *config) {
PRINTF_INFO("WIFI", "Initializing");
wifistat.initialized = true;
wifistat.started = false;
wifistat.stat = WL_IDLE_STATUS;
return ESP_OK;
}
/**
* @brief Deinit WiFi
* Free all resource allocated in esp_wifi_init and stop WiFi task
*
* @attention 1. This API should be called if you want to remove WiFi driver from the system
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
*/
esp_err_t esp_wifi_deinit(void) {
SC_REPORT_INFO("WIFI", "De-Init");
if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT;
wifistat.initialized = false;
wifistat.started = false;
wifistat.connected = false;
return ESP_OK;
}
/**
* @brief Set the WiFi operating mode
*
* Set the WiFi operating mode as station, soft-AP or station+soft-AP,
* The default mode is soft-AP mode.
*
* @param mode WiFi operating mode
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: invalid argument
* - others: refer to error code in esp_err.h
*/
esp_err_t esp_wifi_set_mode(wifi_mode_t mode) {
if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT;
else switch(mode) {
case WIFI_MODE_STA:
SC_REPORT_INFO("WIFI", "Setting WiFi to Station Mode");
wifistat.mode = mode;
return ESP_OK;
case WIFI_MODE_NULL:
SC_REPORT_INFO("WIFI", "Switching WiFi Off");
wifistat.mode = mode;
return ESP_OK;
case WIFI_MODE_AP:
SC_REPORT_INFO("WIFI", "Setting WiFi to AP Mode");
wifistat.mode = mode;
return ESP_OK;
case WIFI_MODE_APSTA:
SC_REPORT_INFO("WIFI", "Setting WiFi to AP/STA Mode");
wifistat.mode = mode;
return ESP_OK;
default:
return ESP_ERR_INVALID_ARG;
}
}
/**
* @brief Get current operating mode of WiFi
*
* @param[out] mode store current WiFi mode
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: invalid argument
*/
esp_err_t esp_wifi_get_mode(wifi_mode_t *mode) {
if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT;
else if (mode == NULL) return ESP_ERR_INVALID_ARG;
else *mode = wifistat.mode;
return ESP_OK;
}
/**
* @brief Start WiFi according to current configuration
* If mode is WIFI_MODE_STA, it create station control block and start station
* If mode is WIFI_MODE_AP, it create soft-AP control block and start soft-AP
* If mode is WIFI_MODE_APSTA, it create soft-AP and station control block and start soft-AP and station
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: invalid argument
* - ESP_ERR_NO_MEM: out of memory
* - ESP_ERR_WIFI_CONN: WiFi internal error, station or soft-AP control block wrong
* - ESP_FAIL: other WiFi internal errors
*/
esp_err_t esp_wifi_start(void) {
system_event_t ev;
/* This is actually done by the init before the firmware loads, but we do
* it here for lack of a better place.
*/
if (!wifistat.initialized) esp_wifi_init(NULL);
/* Now we start the interface. */
if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT;
wifistat.started = true;
wifistat.connected = false;
if (wifistat.mode == WIFI_MODE_STA || wifistat.mode == WIFI_MODE_APSTA) {
ev.event_id = SYSTEM_EVENT_STA_START;
WiFiClass::_eventCallback(NULL, &ev);
}
if (wifistat.mode == WIFI_MODE_AP || wifistat.mode == WIFI_MODE_APSTA) {
ev.event_id = SYSTEM_EVENT_AP_START;
WiFiClass::_eventCallback(NULL, &ev);
}
return ESP_OK;
}
/**
* @brief Stop WiFi
* If mode is WIFI_MODE_STA, it stop station and free station control block
* If mode is WIFI_MODE_AP, it stop soft-AP and free soft-AP control block
* If mode is WIFI_MODE_APSTA, it stop station/soft-AP and free station/soft-AP control block
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
*/
esp_err_t esp_wifi_stop(void) {
if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT;
else return ESP_OK;
}
/**
* @brief Restore WiFi stack persistent settings to default values
*
* This function will reset settings made using the following APIs:
* - esp_wifi_get_auto_connect,
* - esp_wifi_set_protocol,
* - esp_wifi_set_config related
* - esp_wifi_set_mode
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
*/
esp_err_t esp_wifi_restore(void) {
if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT;
/* Set default settings. */
return ESP_OK;
}
/**
* @brief Connect the ESP32 WiFi station to the AP.
*
* @attention 1. This API only impact WIFI_MODE_STA or WIFI_MODE_APSTA mode
* @attention 2. If the ESP32 is connected to an AP, call esp_wifi_disconnect to disconnect.
* @attention 3. The scanning triggered by esp_wifi_start_scan() will not be effective until connection between ESP32 and the AP is established.
* If ESP32 is scanning and connecting at the same time, ESP32 will abort scanning and return a warning message and error
* number ESP_ERR_WIFI_STATE.
* If you want to do reconnection after ESP32 received disconnect event, remember to add the maximum retry time, otherwise the called
* scan will not work. This is especially true when the AP doesn't exist, and you still try reconnection after ESP32 received disconnect
* event with the reason code WIFI_REASON_NO_AP_FOUND.
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start
* - ESP_ERR_WIFI_CONN: WiFi internal error, station or soft-AP control block wrong
* - ESP_ERR_WIFI_SSID: SSID of AP which station connects is invalid
*/
esp_err_t esp_wifi_connect(void) {
system_event_t ev;
if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT;
if (!wifistat.started) return ESP_ERR_WIFI_NOT_STARTED;
if (wifistat.conf.sta.ssid[0] == '\0'
|| strlen((const char *)wifistat.conf.sta.ssid)>31)
return ESP_ERR_WIFI_SSID;
if (strchr((const char *)wifistat.conf.sta.ssid, ' ') != NULL)
PRINTF_WARN("WIFI",
"Found a space in the SSID, what is legal but often not supported.");
/* If we are running a DHCP, we need to set the IP addresses. We then
* pick something as we do not actually have a server.
*/
if (wifistat.dhcp_c) {
wifistat.ip_info.ip.addr = IPAddress(192, 76, 0, 100);
wifistat.ip_info.gw.addr = IPAddress(192, 76, 0, 1);
wifistat.ip_info.netmask.addr = IPAddress(255, 255, 255, 0);
}
/* We call the callback */
ev.event_id = SYSTEM_EVENT_STA_GOT_IP;
ev.event_info.got_ip.ip_info.ip = wifistat.ip_info.ip;
ev.event_info.got_ip.ip_info.gw = wifistat.ip_info.gw;
ev.event_info.got_ip.ip_info.netmask = wifistat.ip_info.netmask;
/* If the IP changed we note tag it. */
if (wifistat.current_ip != wifistat.ip_info.ip.addr)
ev.event_info.got_ip.ip_changed = true;
else ev.event_info.got_ip.ip_changed = false;
WiFiClass::_eventCallback(NULL, &ev);
/* And we do the connection. */
wifistat.connected = true;
wifistat.current_ip = wifistat.ip_info.ip.addr;
return ESP_OK;
}
/**
* @brief Disconnect the ESP32 WiFi station from the AP.
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi was not initialized by esp_wifi_init
* - ESP_ERR_WIFI_NOT_STARTED: WiFi was not started by esp_wifi_start
* - ESP_FAIL: other WiFi internal errors
*/
esp_err_t esp_wifi_disconnect(void) {
system_event_t ev;
if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT;
if (!wifistat.started) return ESP_ERR_WIFI_NOT_STARTED;
/* We call the callback */
ev.event_id = SYSTEM_EVENT_STA_DISCONNECTED;
/* For now it is the only one */
ev.event_info.disconnected.reason = WIFI_REASON_UNSPECIFIED;
WiFiClass::_eventCallback(NULL, &ev);
/* And we do the connection. */
wifistat.connected = false;
return ESP_OK;
}
/**
* @brief Currently this API is just an stub API
*
* @return
* - ESP_OK: succeed
* - others: fail
*/
esp_err_t esp_wifi_clear_fast_connect(void);
/**
* @brief deauthenticate all stations or associated id equals to aid
*
* @param aid when aid is 0, deauthenticate all stations, otherwise deauthenticate station whose associated id is aid
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_WIFI_NOT_STARTED: WiFi was not started by esp_wifi_start
* - ESP_ERR_INVALID_ARG: invalid argument
* - ESP_ERR_WIFI_MODE: WiFi mode is wrong
*/
esp_err_t esp_wifi_deauth_sta(uint16_t aid);
/**
* @brief Scan all available APs.
*
* @attention If this API is called, the found APs are stored in WiFi driver dynamic allocated memory and the
* will be freed in esp_wifi_scan_get_ap_records, so generally, call esp_wifi_scan_get_ap_records to cause
* the memory to be freed once the scan is done
* @attention The values of maximum active scan time and passive scan time per channel are limited to 1500 milliseconds.
* Values above 1500ms may cause station to disconnect from AP and are not recommended.
*
* @param config configuration of scanning
* @param block if block is true, this API will block the caller until the scan is done, otherwise
* it will return immediately
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_WIFI_NOT_STARTED: WiFi was not started by esp_wifi_start
* - ESP_ERR_WIFI_TIMEOUT: blocking scan is timeout
* - ESP_ERR_WIFI_STATE: wifi still connecting when invoke esp_wifi_scan_start
* - others: refer to error code in esp_err.h
*/
esp_err_t esp_wifi_scan_start(const wifi_scan_config_t *config, bool block);
/**
* @brief Stop the scan in process
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_WIFI_NOT_STARTED: WiFi is not started by esp_wifi_start
*/
esp_err_t esp_wifi_scan_stop(void);
/**
* @brief Get number of APs found in last scan
*
* @param[out] number store number of APIs found in last scan
*
* @attention This API can only be called when the scan is completed, otherwise it may get wrong value.
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_WIFI_NOT_STARTED: WiFi is not started by esp_wifi_start
* - ESP_ERR_INVALID_ARG: invalid argument
*/
esp_err_t esp_wifi_scan_get_ap_num(uint16_t *number);
/**
* @brief Get AP list found in last scan
*
* @param[inout] number As input param, it stores max AP number ap_records can hold.
* As output param, it receives the actual AP number this API returns.
* @param ap_records wifi_ap_record_t array to hold the found APs
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_WIFI_NOT_STARTED: WiFi is not started by esp_wifi_start
* - ESP_ERR_INVALID_ARG: invalid argument
* - ESP_ERR_NO_MEM: out of memory
*/
esp_err_t esp_wifi_scan_get_ap_records(uint16_t *number, wifi_ap_record_t *ap_records);
/**
* @brief Get information of AP which the ESP32 station is associated with
*
* @param ap_info the wifi_ap_record_t to hold AP information
* sta can get the connected ap's phy mode info through the struct member
* phy_11b,phy_11g,phy_11n,phy_lr in the wifi_ap_record_t struct.
* For example, phy_11b = 1 imply that ap support 802.11b mode
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_CONN: The station interface don't initialized
* - ESP_ERR_WIFI_NOT_CONNECT: The station is in disconnect status
*/
esp_err_t esp_wifi_sta_get_ap_info(wifi_ap_record_t *ap_info) {
if (!wifistat.initialized) return ESP_ERR_WIFI_CONN;
if (!wifistat.started) return ESP_ERR_WIFI_CONN;
if (!wifistat.connected) return ESP_ERR_WIFI_NOT_CONNECT;
if (ap_info == NULL) return ESP_ERR_INVALID_ARG; /* NOT IN THE LIST */
memcpy((void *)ap_info, (void *)&wifistat.ap_info, sizeof(wifi_ap_record_t));
return ESP_OK;
}
/**
* @brief Set current WiFi power save type
*
* @attention Default power save type is WIFI_PS_MIN_MODEM.
*
* @param type power save type
*
* @return ESP_OK: succeed
*/
esp_err_t esp_wifi_set_ps(wifi_ps_type_t type) {
wifistat.pstype = type;
return ESP_OK;
}
/**
* @brief Get current WiFi power save type
*
* @attention Default power save type is WIFI_PS_MIN_MODEM.
*
* @param[out] type: store current power save type
*
* @return ESP_OK: succeed
*/
esp_err_t esp_wifi_get_ps(wifi_ps_type_t *type) {
if (type == NULL) return ESP_ERR_INVALID_ARG; /* NOT IN THE LIST */
*type = wifistat.pstype;
return ESP_OK;
}
/**
* @brief Set protocol type of specified interface
* The default protocol is (WIFI_PROTOCOL_11B|WIFI_PROTOCOL_11G|WIFI_PROTOCOL_11N)
*
* @attention Currently we only support 802.11b or 802.11bg or 802.11bgn mode
*
* @param ifx interfaces
* @param protocol_bitmap WiFi protocol bitmap
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_WIFI_IF: invalid interface
* - others: refer to error codes in esp_err.h
*/
esp_err_t esp_wifi_set_protocol(wifi_interface_t ifx, uint8_t protocol_bitmap);
/**
* @brief Get the current protocol bitmap of the specified interface
*
* @param ifx interface
* @param[out] protocol_bitmap store current WiFi protocol bitmap of interface ifx
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_WIFI_IF: invalid interface
* - ESP_ERR_INVALID_ARG: invalid argument
* - others: refer to error codes in esp_err.h
*/
esp_err_t esp_wifi_get_protocol(wifi_interface_t ifx, uint8_t *protocol_bitmap);
/**
* @brief Set the bandwidth of ESP32 specified interface
*
* @attention 1. API return false if try to configure an interface that is not enabled
* @attention 2. WIFI_BW_HT40 is supported only when the interface support 11N
*
* @param ifx interface to be configured
* @param bw bandwidth
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_WIFI_IF: invalid interface
* - ESP_ERR_INVALID_ARG: invalid argument
* - others: refer to error codes in esp_err.h
*/
esp_err_t esp_wifi_set_bandwidth(wifi_interface_t ifx, wifi_bandwidth_t bw);
/**
* @brief Get the bandwidth of ESP32 specified interface
*
* @attention 1. API return false if try to get a interface that is not enable
*
* @param ifx interface to be configured
* @param[out] bw store bandwidth of interface ifx
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_WIFI_IF: invalid interface
* - ESP_ERR_INVALID_ARG: invalid argument
*/
esp_err_t esp_wifi_get_bandwidth(wifi_interface_t ifx, wifi_bandwidth_t *bw);
/**
* @brief Set primary/secondary channel of ESP32
*
* @attention 1. This is a special API for sniffer
* @attention 2. This API should be called after esp_wifi_start() or esp_wifi_set_promiscuous()
*
* @param primary for HT20, primary is the channel number, for HT40, primary is the primary channel
* @param second for HT20, second is ignored, for HT40, second is the second channel
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_WIFI_IF: invalid interface
* - ESP_ERR_INVALID_ARG: invalid argument
*/
esp_err_t esp_wifi_set_channel(uint8_t primary, wifi_second_chan_t second) {
if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT;
if (!wifistat.started) return ESP_ERR_WIFI_CONN;
if (primary > 13) return ESP_ERR_INVALID_ARG;
wifistat.conf.sta.channel = primary;
return ESP_OK;
}
/**
* @brief Get the primary/secondary channel of ESP32
*
* @attention 1. API return false if try to get a interface that is not enable
*
* |
@param primary store current primary channel
* @param[out] second store current second channel
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: invalid argument
*/
esp_err_t esp_wifi_get_channel(uint8_t *primary, wifi_second_chan_t *second) {
if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT;
else if (primary == NULL || second == NULL) return ESP_ERR_INVALID_ARG;
*primary = wifistat.conf.sta.channel;
*second = WIFI_SECOND_CHAN_NONE;
return ESP_OK;
}
/**
* @brief configure country info
*
* @attention 1. The default country is {.cc="CN", .schan=1, .nchan=13, policy=WIFI_COUNTRY_POLICY_AUTO}
* @attention 2. When the country policy is WIFI_COUNTRY_POLICY_AUTO, the country info of the AP to which
* the station is connected is used. E.g. if the configured country info is {.cc="USA", .schan=1, .nchan=11}
* and the country info of the AP to which the station is connected is {.cc="JP", .schan=1, .nchan=14}
* then the country info that will be used is {.cc="JP", .schan=1, .nchan=14}. If the station disconnected
* from the AP the country info is set back back to the country info of the station automatically,
* {.cc="USA", .schan=1, .nchan=11} in the example.
* @attention 3. When the country policy is WIFI_COUNTRY_POLICY_MANUAL, always use the configured country info.
* @attention 4. When the country info is changed because of configuration or because the station connects to a different
* external AP, the country IE in probe response/beacon of the soft-AP is changed also.
* @attention 5. The country configuration is not stored into flash
* @attention 6. This API doesn't validate the per-country rules, it's up to the user to fill in all fields according to
* local regulations.
*
* @param country the configured country info
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: invalid argument
*/
esp_err_t esp_wifi_set_country(const wifi_country_t *country);
/**
* @brief get the current country info
*
* @param country country info
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: invalid argument
*/
esp_err_t esp_wifi_get_country(wifi_country_t *country);
/**
* @brief Set MAC address of the ESP32 WiFi station or the soft-AP interface.
*
* @attention 1. This API can only be called when the interface is disabled
* @attention 2. ESP32 soft-AP and station have different MAC addresses, do not set them to be the same.
* @attention 3. The bit 0 of the first byte of ESP32 MAC address can not be 1. For example, the MAC address
* can set to be "1a:XX:XX:XX:XX:XX", but can not be "15:XX:XX:XX:XX:XX".
*
* @param ifx interface
* @param mac the MAC address
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: invalid argument
* - ESP_ERR_WIFI_IF: invalid interface
* - ESP_ERR_WIFI_MAC: invalid mac address
* - ESP_ERR_WIFI_MODE: WiFi mode is wrong
* - others: refer to error codes in esp_err.h
*/
esp_err_t esp_wifi_set_mac(wifi_interface_t ifx, const uint8_t mac[6]) {
if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT;
if (ifx != WIFI_IF_STA && ifx != WIFI_IF_AP)
return ESP_ERR_INVALID_ARG;
PRINTF_WARN("WIFI", "esp_wifi_set_mac currently is unsupported.");
return ESP_OK;
}
/**
* @brief Get mac of specified interface
*
* @param ifx interface
* @param[out] mac store mac of the interface ifx
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: invalid argument
* - ESP_ERR_WIFI_IF: invalid interface
*/
esp_err_t esp_wifi_get_mac(wifi_interface_t ifx, uint8_t mac[6]) {
if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT;
if (ifx != WIFI_IF_STA && ifx != WIFI_IF_AP)
return ESP_ERR_INVALID_ARG;
switch(ifx) {
case WIFI_IF_STA:
mac[0] = 0x55;
mac[1] = 0x37;
mac[2] = 0xce;
mac[3] = 0x99;
mac[4] = 0x75;
mac[5] = 0x1E;
return ESP_OK;
case WIFI_IF_AP:
mac[0] = 0x55;
mac[1] = 0x37;
mac[2] = 0xce;
mac[3] = 0x99;
mac[4] = 0x75;
mac[5] = 0x39;
return ESP_OK;
default: return ESP_ERR_INVALID_ARG;
}
}
/**
* @brief The RX callback function in the promiscuous mode.
* Each time a packet is received, the callback function will be called.
*
* @param buf Data received. Type of data in buffer (wifi_promiscuous_pkt_t or wifi_pkt_rx_ctrl_t) indicated by 'type' parameter.
* @param type promiscuous packet type.
*
*/
typedef void (* wifi_promiscuous_cb_t)(void *buf, wifi_promiscuous_pkt_type_t type);
/**
* @brief Register the RX callback function in the promiscuous mode.
*
* Each time a packet is received, the registered callback function will be called.
*
* @param cb callback
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
*/
esp_err_t esp_wifi_set_promiscuous_rx_cb(wifi_promiscuous_cb_t cb);
/**
* @brief Enable the promiscuous mode.
*
* @param en false - disable, true - enable
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
*/
esp_err_t esp_wifi_set_promiscuous(bool en);
/**
* @brief Get the promiscuous mode.
*
* @param[out] en store the current status of promiscuous mode
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: invalid argument
*/
esp_err_t esp_wifi_get_promiscuous(bool *en);
/**
* @brief Enable the promiscuous mode packet type filter.
*
* @note The default filter is to filter all packets except WIFI_PKT_MISC
*
* @param filter the packet type filtered in promiscuous mode.
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
*/
esp_err_t esp_wifi_set_promiscuous_filter(const wifi_promiscuous_filter_t *filter);
/**
* @brief Get the promiscuous filter.
*
* @param[out] filter store the current status of promiscuous filter
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: invalid argument
*/
esp_err_t esp_wifi_get_promiscuous_filter(wifi_promiscuous_filter_t *filter);
/**
* @brief Enable subtype filter of the control packet in promiscuous mode.
*
* @note The default filter is to filter none control packet.
*
* @param filter the subtype of the control packet filtered in promiscuous mode.
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
*/
esp_err_t esp_wifi_set_promiscuous_ctrl_filter(const wifi_promiscuous_filter_t *filter);
/**
* @brief Get the subtype filter of the control packet in promiscuous mode.
*
* @param[out] filter store the current status of subtype filter of the control packet in promiscuous mode
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: invalid argument
*/
esp_err_t esp_wifi_get_promiscuous_ctrl_filter(wifi_promiscuous_filter_t *filter);
/**
* @brief Set the configuration of the ESP32 STA or AP
*
* @attention 1. This API can be called only when specified interface is enabled, otherwise, API fail
* @attention 2. For station configuration, bssid_set needs to be 0; and it needs to be 1 only when users need to check the MAC address of the AP.
* @attention 3. ESP32 is limited to only one channel, so when in the soft-AP+station mode, the soft-AP will adjust its channel automatically to be the same as
* the channel of the ESP32 station.
*
* @param interface interface
* @param conf station or soft-AP configuration
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: invalid argument
* - ESP_ERR_WIFI_IF: invalid interface
* - ESP_ERR_WIFI_MODE: invalid mode
* - ESP_ERR_WIFI_PASSWORD: invalid password
* - ESP_ERR_WIFI_NVS: WiFi internal NVS error
* - others: refer to the erro code in esp_err.h
*/
esp_err_t esp_wifi_set_config(wifi_interface_t interface, wifi_config_t *conf) {
if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT;
if (conf == NULL) return ESP_ERR_INVALID_ARG;
if (interface == WIFI_IF_STA) {
if (strlen((const char *)(conf->sta.password)) > 64) {
return ESP_ERR_WIFI_PASSWORD;
}
}
else if (interface == WIFI_IF_AP) {
if (strlen((char *)conf->ap.password) > 0
&& strlen((char *)conf->ap.password) < 8
|| strlen((char *)conf->ap.password) > 64)
return ESP_ERR_WIFI_PASSWORD;
/* We have no DHCP server, so for lack of a better place, we also set the
* IP here.
*/
if (!wifistat.dhcp_s) {
wifistat.ip_info.ip.addr = IPAddress(192, 76, 0, 1);
wifistat.ip_info.gw.addr = IPAddress(192, 76, 0, 1);
wifistat.ip_info.netmask.addr = IPAddress(255, 255, 255, 0);
}
}
else return ESP_ERR_INVALID_ARG;
memcpy((void *)&wifistat.conf, (void *)conf, sizeof(wifi_config_t));
return ESP_OK;
}
/**
* @brief Get configuration of specified interface
*
* @param interface interface
* @param[out] conf station or soft-AP configuration
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: invalid argument
* - ESP_ERR_WIFI_IF: invalid interface
*/
esp_err_t esp_wifi_get_config(wifi_interface_t interface, wifi_config_t *conf) {
if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT;
if (conf == NULL) return ESP_ERR_INVALID_ARG;
if (interface != WIFI_IF_STA && interface != WIFI_IF_AP)
return ESP_ERR_INVALID_ARG;
if (interface == WIFI_IF_STA) {
if (wifistat.mode != WIFI_MODE_STA && wifistat.mode != WIFI_MODE_APSTA) {
return ESP_ERR_WIFI_IF;
}
}
else if (interface == WIFI_IF_AP) {
if (wifistat.mode != WIFI_MODE_AP && wifistat.mode != WIFI_MODE_APSTA) {
return ESP_ERR_WIFI_IF;
}
}
else return ESP_ERR_INVALID_ARG;
memcpy((void *)conf, (void *)&wifistat.conf, sizeof(wifi_config_t));
return ESP_OK;
}
/**
* @brief Get STAs associated with soft-AP
*
* @attention SSC only API
*
* @param[out] sta station list
* ap can get the connected sta's phy mode info through the struct member
* phy_11b,phy_11g,phy_11n,phy_lr in the wifi_sta_info_t struct.
* For example, phy_11b = 1 imply that sta support 802.11b mode
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: invalid argument
* - ESP_ERR_WIFI_MODE: WiFi mode is wrong
* - ESP_ERR_WIFI_CONN: WiFi internal error, the station/soft-AP control block is invalid
*/
esp_err_t esp_wifi_ap_get_sta_list(wifi_sta_list_t *sta) {
if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT;
if (sta == NULL) return ESP_ERR_INVALID_ARG;
if (wifistat.mode == WIFI_MODE_STA) return ESP_ERR_WIFI_MODE;
memcpy((void *)sta, (void *)&wifistat.sta_list, sizeof(wifi_sta_list_t));
return ESP_OK;
}
/**
* @brief Set the WiFi API configuration storage type
*
* @attention 1. The default value is WIFI_STORAGE_FLASH
*
* @param storage : storage type
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: invalid argument
*/
esp_err_t esp_wifi_set_storage(wifi_storage_t storage);
/**
* @brief Set auto connect
* The default value is true
*
* @param en : true - enable auto connect / false - disable auto connect
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_WIFI_MODE: WiFi internal error, the station/soft-AP control block is invalid
* - others: refer to error code in esp_err.h
*/
esp_err_t esp_wifi_set_auto_connect(bool en) {
return ESP_OK;
}
/**
* @brief Get the auto connect flag
*
* @param[out] en store current auto connect configuration
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: invalid argument
*/
esp_err_t esp_wifi_get_auto_connect(bool *en) {
return ESP_OK;
}
/**
* @brief Set 802.11 Vendor-Specific Information Element
*
* @param enable If true, specified IE is enabled. If false, specified IE is removed.
* @param type Information Element type. Determines the frame type to associate with the IE.
* @param idx Index to set or clear. Each IE type can be associated with up to two elements (indices 0 & 1).
* @param vnd_ie Pointer to vendor specific element data. First 6 bytes should be a header with fields matching vendor_ie_data_t.
* If enable is false, this argument is ignored and can be NULL. Data does not need to remain valid after the function returns.
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init()
* - ESP_ERR_INVALID_ARG: Invalid argument, including if first byte of vnd_ie is not WIFI_VENDOR_IE_ELEMENT_ID (0xDD)
* or second byte is an invalid length.
* - ESP_ERR_NO_MEM: Out of memory
*/
esp_err_t esp_wifi_set_vendor_ie(bool enable, wifi_vendor_ie_type_t type, wifi_vendor_ie_id_t idx, const void *vnd_ie);
/**
* @brief Function signature for received Vendor-Specific Information Element callback.
* @param ctx Context argument, as passed to esp_wifi_set_vendor_ie_cb() when registering callback.
* @param type Information element type, based on frame type received.
* @param sa Source 802.11 address.
* @param vnd_ie Pointer to the vendor specific element data received.
* @param rssi Received signal strength indication.
*/
typedef void (*esp_vendor_ie_cb_t) (void *ctx, wifi_vendor_ie_type_t type, const uint8_t sa[6], const vendor_ie_data_t *vnd_ie, int rssi);
/**
* @brief Register Vendor-Specific Information Element monitoring callback.
*
* @param cb Callback function
* @param ctx Context argument, passed to callback function.
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
*/
esp_err_t esp_wifi_set_vendor_ie_cb(esp_vendor_ie_cb_t cb, void *ctx);
/**
* @brief Set maximum WiFi transmiting power
*
* @attention WiFi transmiting power is divided to six levels in phy init data.
* Level0 represents highest transmiting power and level5 represents lowest
* transmiting power. Packets of different rates are transmitted in
* different powers according to the configuration in phy init data.
* This API only sets maximum WiFi transmiting power. If this API is called,
* the transmiting power of every packet will be less than or equal to the
* value set by this API. If this API is not called, the value of maximum
* transmitting power set in phy_init_data.bin or menuconfig (depend on
* whether to use phy init data in partition or not) will be used. Default
* value is level0. Values passed in power are mapped to transmit power
* levels as follows:
* - [78, 127]: level0
* - [76, 77]: level1
* - [74, 75]: level2
* - [68, 73]: level3
* - [60, 67]: level4
* - [52, 59]: level5
* - [44, 51]: level5 - 2dBm
* - [34, 43]: level5 - 4.5dBm
* - [28, 33]: level5 - 6dBm
* - [20, 27]: level5 - 8dBm
* - [8, 19]: level5 - 11dBm
* - [-128, 7]: level5 - 14dBm
*
* @param power Maximum WiFi transmiting power.
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start
*/
esp_err_t esp_wifi_set_max_tx_power(int8_t power) {
if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT;
if (!wifistat.started) return ESP_ERR_WIFI_NOT_STARTED;
wifistat.power = power;
return ESP_OK;
}
/**
* @brief Get maximum WiFi transmiting power
*
* @attention This API gets maximum WiFi transmiting power. Values got
* from power are mapped to transmit power levels as follows:
* - 78: 19.5dBm
* - 76: 19dBm
* - 74: 18.5dBm
* - 68: 17dBm
* - 60: 15dBm
* - 52: 13dBm
* - 44: 11dBm
* - 34: 8.5dBm
* - 28: 7dBm
* - 20: 5dBm
* - 8: 2dBm
* - -4: -1dBm
*
* @param power Maximum WiFi transmiting power.
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start
* - ESP_ERR_INVALID_ARG: invalid argument
*/
esp_err_t esp_wifi_get_max_tx_power(int8_t *power) {
if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT;
if (!wifistat.started) return ESP_ERR_WIFI_NOT_STARTED;
if (power == NULL) return ESP_ERR_INVALID_ARG;
*power = wifistat.power;
return ESP_OK;
}
/**
* @brief Set mask to enable or disable some WiFi events
*
* @attention 1. Mask can be created by logical OR of various WIFI_EVENT_MASK_ constants.
* Events which have corresponding bit set in the mask will not be delivered to the system event handler.
* @attention 2. Default WiFi event mask is WIFI_EVENT_MASK_AP_PROBEREQRECVED.
* @attention 3. There may be lots of stations sending probe request data around.
* Don't unmask this event unless you need to receive probe request data.
*
* @param mask WiFi event mask.
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
*/
esp_err_t esp_wifi_set_event_mask(uint32_t mask) {
if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT;
wifistat.mask = mask;
return ESP_OK;
}
/**
* @brief Get mask of WiFi events
*
* @param mask WiFi event mask.
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: invalid argument
*/
esp_err_t esp_wifi_get_event_mask(uint32_t *mask) {
if (!wifistat.initialized) return ESP_ERR_WIFI_NOT_INIT;
if (mask == NULL) return ESP_ERR_INVALID_ARG;
*mask = wifistat.mask;
return ESP_OK;
}
/**
* @brief Send raw ieee80211 data
*
* @attention Currently only support for sending beacon/probe request/probe response/action and non-QoS
* data frame
*
* @param ifx interface if the Wi-Fi mode is Station, the ifx should be WIFI_IF_STA. If the Wi-Fi
* mode is SoftAP, the ifx should be WIFI_IF_AP. If the Wi-Fi mode is Station+SoftAP, the
* ifx should be W |
IFI_IF_STA or WIFI_IF_AP. If the ifx is wrong, the API returns ESP_ERR_WIFI_IF.
* @param buffer raw ieee80211 buffer
* @param len the length of raw buffer, the len must be <= 1500 Bytes and >= 24 Bytes
* @param en_sys_seq indicate whether use the internal sequence number. If en_sys_seq is false, the
* sequence in raw buffer is unchanged, otherwise it will be overwritten by WiFi driver with
* the system sequence number.
* Generally, if esp_wifi_80211_tx is called before the Wi-Fi connection has been set up, both
* en_sys_seq==true and en_sys_seq==false are fine. However, if the API is called after the Wi-Fi
* connection has been set up, en_sys_seq must be true, otherwise ESP_ERR_INVALID_ARG is returned.
*
* @return
* - ESP_OK: success
* - ESP_ERR_WIFI_IF: Invalid interface
* - ESP_ERR_INVALID_ARG: Invalid parameter
* - ESP_ERR_WIFI_NO_MEM: out of memory
*/
esp_err_t esp_wifi_80211_tx(wifi_interface_t ifx, const void *buffer, int len, bool en_sys_seq);
/**
* @brief The RX callback function of Channel State Information(CSI) data.
*
* Each time a CSI data is received, the callback function will be called.
*
* @param ctx context argument, passed to esp_wifi_set_csi_rx_cb() when registering callback function.
* @param data CSI data received. The memory that it points to will be deallocated after callback function returns.
*
*/
typedef void (* wifi_csi_cb_t)(void *ctx, wifi_csi_info_t *data);
/**
* @brief Register the RX callback function of CSI data.
*
* Each time a CSI data is received, the callback function will be called.
*
* @param cb callback
* @param ctx context argument, passed to callback function
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
*/
esp_err_t esp_wifi_set_csi_rx_cb(wifi_csi_cb_t cb, void *ctx);
/**
* @brief Set CSI data configuration
*
* @param config configuration
*
* return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start or promiscuous mode is not enabled
* - ESP_ERR_INVALID_ARG: invalid argument
*/
esp_err_t esp_wifi_set_csi_config(const wifi_csi_config_t *config);
/**
* @brief Enable or disable CSI
*
* @param en true - enable, false - disable
*
* return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start or promiscuous mode is not enabled
* - ESP_ERR_INVALID_ARG: invalid argument
*/
esp_err_t esp_wifi_set_csi(bool en);
/**
* @brief Set antenna GPIO configuration
*
* @param config Antenna GPIO configuration.
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: Invalid argument, e.g. parameter is NULL, invalid GPIO number etc
*/
esp_err_t esp_wifi_set_ant_gpio(const wifi_ant_gpio_config_t *config);
/**
* @brief Get current antenna GPIO configuration
*
* @param config Antenna GPIO configuration.
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: invalid argument, e.g. parameter is NULL
*/
esp_err_t esp_wifi_get_ant_gpio(wifi_ant_gpio_config_t *config);
/**
* @brief Set antenna configuration
*
* @param config Antenna configuration.
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: Invalid argument, e.g. parameter is NULL, invalid antenna mode or invalid GPIO number
*/
esp_err_t esp_wifi_set_ant(const wifi_ant_config_t *config);
/**
* @brief Get current antenna configuration
*
* @param config Antenna configuration.
*
* @return
* - ESP_OK: succeed
* - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
* - ESP_ERR_INVALID_ARG: invalid argument, e.g. parameter is NULL
*/
esp_err_t esp_wifi_get_ant(wifi_ant_config_t *config);
|
/**************************************************************************
* *
* Catapult(R) Machine Learning Reference Design Library *
* *
* Software Version: 1.8 *
* *
* Release Date : Sun Jul 16 19:01:51 PDT 2023 *
* Release Type : Production Release *
* Release Build : 1.8.0 *
* *
* Copyright 2021 Siemens *
* *
**************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *
* implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
**************************************************************************
* *
* The most recent version of this package is available at github. *
* *
*************************************************************************/
#include <systemc.h>
#include "types.h"
#include "axi/axi4.h"
#include "axi4_segment.h"
#include "sysbus_axi_struct.h"
#include "systemc_subsystem.h"
class systemc_subsystem_wrapper : public sc_module, public sysbus_axi {
public:
//== Ports
sc_in <bool> clk;
sc_in <bool> reset_bar;
sc_in <sc_lv<44>> aw_msg_port;
sc_in <bool> aw_valid_port;
sc_out<bool> aw_ready_port;
sc_in <sc_lv<37>> w_msg_port;
sc_in <bool> w_valid_port;
sc_out<bool> w_ready_port;
sc_out<sc_lv<6>> b_msg_port;
sc_out<bool> b_valid_port;
sc_in <bool> b_ready_port;
sc_in <sc_lv<44>> ar_msg_port;
sc_in <bool> ar_valid_port;
sc_out<bool> ar_ready_port;
sc_out<sc_lv<39>> r_msg_port;
sc_out<bool> r_valid_port;
sc_in <bool> r_ready_port;
sc_clock connections_clk;
sc_event check_event;
virtual void start_of_simulation() {
Connections::get_sim_clk().add_clock_alias(
connections_clk.posedge_event(), clk.posedge_event());
}
void check_clock() { check_event.notify(2, SC_PS);} // Let SC and Vlog delta cycles settle.
void check_event_method() {
if (connections_clk.read() == clk.read()) return;
CCS_LOG("clocks misaligned!:" << connections_clk.read() << " " << clk.read());
}
systemc_subsystem CCS_INIT_S1(scs);
SC_CTOR(systemc_subsystem_wrapper)
: connections_clk("connections_clk", CLOCK_PERIOD, SC_NS, 0.5, 0, SC_NS, true)
{
SC_METHOD(check_clock);
sensitive << connections_clk;
sensitive << clk;
SC_METHOD(check_event_method);
sensitive << check_event;
scs.clk(connections_clk);
scs.reset_bar(reset_bar);
scs.w_cpu.aw.dat(aw_msg_port);
scs.w_cpu.aw.vld(aw_valid_port);
scs.w_cpu.aw.rdy(aw_ready_port);
scs.w_cpu.w.dat(w_msg_port);
scs.w_cpu.w.vld(w_valid_port);
scs.w_cpu.w.rdy(w_ready_port);
scs.w_cpu.b.dat(b_msg_port);
scs.w_cpu.b.vld(b_valid_port);
scs.w_cpu.b.rdy(b_ready_port);
scs.r_cpu.ar.dat(ar_msg_port);
scs.r_cpu.ar.vld(ar_valid_port);
scs.r_cpu.ar.rdy(ar_ready_port);
scs.r_cpu.r.dat(r_msg_port);
scs.r_cpu.r.vld(r_valid_port);
scs.r_cpu.r.rdy(r_ready_port);
}
};
#ifdef QUESTA
SC_MODULE_EXPORT(systemc_subsystem_wrapper);
#endif
|
//****************************************************************************************
// MIT License
//****************************************************************************************
// Copyright (c) 2012-2020 University of Bremen, Germany.
// Copyright (c) 2015-2020 DFKI GmbH Bremen, Germany.
// Copyright (c) 2020 Johannes Kepler University Linz, Austria.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//****************************************************************************************
#include <crave/SystemC.hpp>
#include <crave/ConstrainedRandom.hpp>
#include <systemc.h>
#include <boost/timer.hpp>
using crave::rand_obj;
using crave::randv;
using sc_dt::sc_bv;
using sc_dt::sc_uint;
struct ALU32 : public rand_obj {
randv<sc_bv<2> > op;
randv<sc_uint<32> > a, b;
ALU32(rand_obj* parent = 0) : rand_obj(parent), op(this), a(this), b(this) {
constraint((op() != 0x0) || (4294967295u >= a() + b()));
constraint((op() != 0x1) || ((4294967295u >= a() - b()) && (b() <= a())));
constraint((op() != 0x2) || (4294967295u >= a() * b()));
constraint((op() != 0x3) || (b() != 0));
}
friend std::ostream& operator<<(std::ostream& o, ALU32 const& alu) {
o << alu.op << ' ' << alu.a << ' ' << alu.b;
return o;
}
};
int sc_main(int argc, char** argv) {
crave::init("crave.cfg");
boost::timer timer;
ALU32 c;
CHECK(c.next());
std::cout << "first: " << timer.elapsed() << "\n";
for (int i = 0; i < 1000; ++i) {
CHECK(c.next());
}
std::cout << "complete: " << timer.elapsed() << "\n";
return 0;
}
|
/******************************************************
* This is the main file for the mips1 ArchC model *
* This file is automatically generated by ArchC *
* WITHOUT WARRANTY OF ANY KIND, either express *
* or implied. *
* For more information on ArchC, please visit: *
* http://www.archc.org *
* *
* The ArchC Team *
* Computer Systems Laboratory (LSC) *
* IC-UNICAMP *
* http://www.lsc.ic.unicamp.br *
******************************************************/
// Rodolfo editou aqui
//
const char *project_name="mips";
const char *project_file="mips1.ac";
const char *archc_version="2.0beta1";
const char *archc_options="-abi -dy ";
#include <systemc.h>
#include <stdlib.h>
#include "mips.H"
#include "memory.h"
#include "peripheral.h"
#include "bus.h"
int sc_main(int ac, char *av[])
{
int ac2 = ac;
char** av2 = (char **) malloc((ac+1) * sizeof (*av2));
for(int i = 0; i < ac; ++i)
{
size_t length = strlen(av[i])+1;
av2[i] = (char *) malloc(length);
memcpy(av2[i], av[i], length);
}
av2[ac] = NULL;
//! ISA simulator
mips mips_proc1("mips1");
mips mips_proc2("mips2");
//! Bus
ac_tlm_bus bus("bus");
// Memory
ac_tlm_mem mem("mem");
// Peripheral
ac_tlm_peripheral peripheral("peripheral");
#ifdef AC_DEBUG
ac_trace("mips1_proc1.trace");
#endif
mips_proc1.DM(bus.target_export);
mips_proc2.DM(bus.target_export);
bus.MEM_port(mem.target_export);
bus.PERIPHERAL_port(peripheral.target_export);
mips_proc1.init(ac, av);
mips_proc1.set_prog_args();
cerr << endl;
mips_proc2.init(ac2, av2);
mips_proc2.set_prog_args();
cerr << endl;
sc_start();
mips_proc1.PrintStat();
mips_proc2.PrintStat();
cerr << endl;
#ifdef AC_STATS
mips1_proc1.ac_sim_stats.time = sc_simulation_time();
mips1_proc1.ac_sim_stats.print();
#endif
#ifdef AC_DEBUG
ac_close_trace();
#endif
return mips_proc1.ac_exit_status;
}
|
/*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
/*****************************************************************************
* simple example of async events
*
* Copyright (C) 2017, GreenSocs Ltd.
*
* Developped by Mark Burton [email protected]
*
*****************************************************************************/
#include "systemc.h"
#include "async_event.h"
#if SC_CPLUSPLUS >= 201103L
// this version properly uses separate host threads.
// Without host threads, the example simply notifys the async event
// directly from the constructor
#include <thread>
#include <chrono>
#endif
SC_MODULE(watchDog)
{
async_event when;
bool barked;
public:
SC_CTOR(watchDog) : barked(false)
{
SC_METHOD(call_stop);
sensitive << when;
dont_initialize();
}
#if SC_CPLUSPLUS >= 201103L // C++11 threading support
~watchDog()
{
m_thread.join();
}
private:
std::thread m_thread;
void start_of_simulation()
{
m_thread=std::thread( [this] { this->process(); } );
}
void process()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
// asynchronous notification from a separate thread
when.notify(sc_time(10,SC_NS));
}
#else
void start_of_simulation()
{
// no threading support, notifiy directly
when.notify(sc_time(10,SC_NS));
}
#endif // C++11 threading support
private:
void call_stop()
{
cout << "Asked to stop at time " << sc_time_stamp() << endl;
barked=true;
sc_stop();
}
void end_of_simulation()
{
sc_assert(barked==true);
cout << "The dog barks before the end of simulation" << endl;
}
};
SC_MODULE(activity)
{
SC_CTOR(activity)
{
SC_THREAD(busy);
}
void busy()
{
cout << "I'm busy!"<<endl;
}
};
int sc_main(int , char* [])
{
watchDog m_watchdog("WatchDog");
activity m_activity("Activity");
cout << "Start SystemC " << endl;
sc_start();
cout << "Program completed" << endl;
return 0;
}
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "ntm_fnn_design.cpp"
#include "systemc.h"
int sc_main(int argc, char *argv[]) {
adder adder("ADDER");
sc_signal<int> Ain;
sc_signal<int> Bin;
sc_signal<bool> clock;
sc_signal<int> out;
adder(clock, Ain, Bin, out);
Ain = 1;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
Ain = 2;
Bin = 2;
clock = 0;
sc_start(1, SC_NS);
clock = 1;
sc_start(1, SC_NS);
cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl;
return 0;
}
|
//
//------------------------------------------------------------//
// Copyright 2009-2012 Mentor Graphics Corporation //
// All Rights Reserved Worldwid //
// //
// Licensed under the Apache License, Version 2.0 (the //
// "License"); you may not use this file except in //
// compliance with the License. You may obtain a copy of //
// the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in //
// writing, software distributed under the License is //
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR //
// CONDITIONS OF ANY KIND, either express or implied. See //
// the License for the specific language governing //
// permissions and limitations under the License. //
//------------------------------------------------------------//
//-----------------------------------------------------------------------------
// Title: UVMC Connection Example - Native SC to SC
//
// This example serves as a review for how to make 'native' TLM connections
// between two SystemC components (does not use UVMC).
//
// (see UVMC_Connections_SC2SC-native.png)
//
// In SystemC, a ~port~ is connected to an ~export~ or an ~interface~ using
// the port's ~bind~ function. An sc_module's port can also be connected to
// a port in a parent module, which effectively promotes the port up one
// level of hierarchy.
//
// In this particular example, ~sc_main~ does the following
//
// - Instantiates ~producer~ and ~consumer~ sc_modules
//
// - Binds the producer's ~out~ port to the consumer's ~in~ export
//
// - Calls ~sc_start~ to start the SystemC portion of our testbench.
//
// The ~bind~ call looks the same for all port-to-export/interface connections,
// regardless of the port types and transaction types. The C++ compiler
// will let you know if you've attempted an incompatible connection.
//-----------------------------------------------------------------------------
// (inline source)
#include <systemc.h>
using namespace sc_core;
#include "consumer.h"
#include "producer.h"
int sc_main(int argc, char* argv[])
{
producer prod("prod");
consumer cons("cons");
prod.out.bind(cons.in);
sc_start(-1);
return 0;
}
|
/*******************************************************************************
* dns.cpp -- Copyright 2019 Glenn Ramalho - RFIDo Design
*******************************************************************************
* Description:
* This is a stubfile that sets several defines for a simplified version of
* the LwIP to compile on the ESPMOD SystemC model. This is not a port of
* the LwIP.
*******************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file was based off the work covered by the license below:
*
* Author: Jim Pettinato
* April 2007
*
* ported from uIP resolv.c Copyright (c) 2002-2003, Adam Dunkels.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <systemc.h>
#include "dns.h"
#include <IPAddress.h>
#include "info.h"
#include "esp_wifi_types.h"
#include "esp_wifi.h"
/**
* @brief Set the DNS server.
**/
void dns_setserver(uint8_t numdns, const ip_addr_t *dnsserver) {
if (dnsserver == NULL) PRINTF_ERROR("WIFI", "Invalid DNS server pointer");
PRINTF_INFO("WIFI", "Setting DNS server %d to %s", numdns,
IPAddress(dnsserver->u_addr.ip4.addr).toString().c_str());
}
|
#ifndef IMG_ROUTER_CPP
#define IMG_ROUTER_CPP
// #include "tlm_transaction.cpp"
#include "transaction_memory_manager.cpp"
#include <systemc.h>
using namespace sc_core;
using namespace sc_dt;
using namespace std;
#include <tlm.h>
#include <tlm_utils/simple_initiator_socket.h>
#include <tlm_utils/simple_target_socket.h>
#include <tlm_utils/peq_with_cb_and_phase.h>
#include <ostream>
#include "common_func.hpp"
#include "img_generic_extension.hpp"
//#include "tlm_queue.cpp"
#include "important_defines.hpp"
//const char* tlm_enum_names[] = {"TLM_ACCEPTED", "TLM_UPDATED", "TLM_COMPLETED"};
struct tlm_item{
tlm::tlm_generic_payload *transaction;
tlm::tlm_phase phase;
sc_time delay;
tlm_item(tlm::tlm_generic_payload *transaction = 0, tlm::tlm_phase phase = tlm::BEGIN_REQ, sc_time delay = sc_time(0, SC_NS)){}
tlm_item& operator=(const tlm_item& rhs){
transaction = rhs.transaction;
phase = rhs.phase;
delay = rhs.delay;
return *this;
}
bool operator==(const tlm_item& rhs){
return transaction == rhs.transaction && phase == rhs.phase && delay == rhs.delay;
}
friend std::ostream& operator<<(std::ostream& os, const tlm_item& val) {
os << "Transaction Pointer = " << val.transaction << "; phase = " << val.phase << "; delay = " << val.delay << std::endl;
return os;
}
};
// inline void sc_trace(sc_trace_file*& f, const tlm_item& val, std::string name) {
// sc_trace(f, val.transaction, name + ".transaction");
// sc_trace(f, val.phase, name + ".phase");
// sc_trace(f, val.delay, name + ".delay");
// }
// Initiator module generating generic payload transactions
template<unsigned int N_TARGETS>
struct img_router: sc_module
{
// TLM2.0 Socket
tlm_utils::simple_target_socket<img_router> target_socket;
tlm_utils::simple_initiator_socket<img_router>* initiator_socket[N_TARGETS];
//Memory Manager for transaction memory allocation
mm memory_manager;
//Payload event queue with callback and phase
tlm_utils::peq_with_cb_and_phase<img_router> bw_m_peq; //For initiator access
tlm_utils::peq_with_cb_and_phase<img_router> fw_m_peq; //For target access
//Delay
sc_time bw_delay;
sc_time fw_delay;
//TLM Items queue
sc_fifo<tlm_item> fw_fifo;
sc_fifo<tlm_item> bw_fifo;
//DEBUG
unsigned int transaction_in_fw_path_id = 0;
unsigned int transaction_in_bw_path_id = 0;
bool use_prints;
//Constructor
SC_CTOR(img_router)
: target_socket("socket"), bw_m_peq(this, &img_router::bw_peq_cb), fw_m_peq(this, &img_router::fw_peq_cb), fw_fifo(10), bw_fifo(2), use_prints(true) // Construct and name socket
{
// Register callbacks for incoming interface method calls
target_socket.register_nb_transport_fw(this, &img_router::nb_transport_fw);
for (unsigned int i = 0; i < N_TARGETS; i++) {
char txt[20];
sprintf(txt, "socket_%d", i);
initiator_socket[i] = new tlm_utils::simple_initiator_socket<img_router>(txt);
(*initiator_socket[i]).register_nb_transport_bw(this, &img_router::nb_transport_bw);
}
SC_THREAD(fw_thread);
SC_THREAD(bw_thread);
#ifdef DISABLE_ROUTER_DEBUG
this->use_prints = false;
#endif //DISABLE_ROUTER_DEBUG
checkprintenable(use_prints);
}
//Address Decoding
#define IMG_FILTER_INITIATOR_ID 0
#define IMG_SOBEL_INITIATOR_ID 1
#define IMG_MEMORY_INITIATOR_ID 2
#define IMG_ETHERNET_INITIATOR_ID 3
#define IMG_VGA_INITIATOR_ID 4
#define INVALID_INITIATOR_ID 5
unsigned int decode_address (sc_dt::uint64 address)
{
switch(address) {
// To Filter
case IMG_FILTER_KERNEL_ADDRESS_LO: {
dbgmodprint(use_prints, "Decoded address %016llX corresponds to Filter module.", address);
return IMG_FILTER_INITIATOR_ID;
}
// To/from Sobel
case SOBEL_INPUT_0_ADDRESS_LO:
case SOBEL_INPUT_1_ADDRESS_LO:
case SOBEL_OUTPUT_ADDRESS_LO: {
dbgmodprint(use_prints, "Decoded address %016llX corresponds to Sobel module.", address);
return IMG_SOBEL_INITIATOR_ID;
}
case IMG_OUTPUT_ADDRESS_LO ... (IMG_OUTPUT_ADDRESS_HI - 1):
case IMG_OUTPUT_SIZE_ADDRESS_LO:
case IMG_OUTPUT_DONE_ADDRESS_LO:
case IMG_OUTPUT_STATUS_ADDRESS_LO:
{
dbgmodprint(use_prints, "Decoded address %016llX corresponds to Ethernet module.", address);
return IMG_ETHERNET_INITIATOR_ID;
}
// To/from Input Image
case IMG_INPUT_ADDRESS_LO ... (IMG_INPUT_ADDRESS_HI - 1):
case IMG_INPUT_START_ADDRESS_LO:
case IMG_INPUT_DONE_ADDRESS_LO:
{
dbgmodprint(use_prints, "Decoded address %016llX corresponds to VGA module.", address);
return IMG_VGA_INITIATOR_ID;
}
// To/From Memory Valid addresses
case MEMORY_ADDRESS_LO ... (MEMORY_ADDRESS_HI - 1) : {
dbgmodprint(use_prints, "Decoded address %016llX corresponds to Memory.", address);
return IMG_MEMORY_INITIATOR_ID;
}
default: {
dbgmodprint(true, "[ERROR] Decoding invalid address %016llX.", address);
SC_REPORT_FATAL("[IMG ROUTER]", "Received address is invalid, does not match any hardware block");
return INVALID_INITIATOR_ID;
}
}
}
// TLM2 backward path non-blocking transport method
virtual tlm::tlm_sync_enum nb_transport_bw(tlm::tlm_generic_payload& trans,
tlm::tlm_phase& phase, sc_time& delay )
{
img_generic_extension* img_ext;
//Call event queue
tlm_item item;
item.transaction = &trans;
item.phase = phase;
item.delay = delay;
trans.get_extension(img_ext);
if (bw_fifo.num_free() == 0) {
dbgmodprint(use_prints, "[BW_FIFO] FIFO is FULL. Waiting...");
wait(bw_fifo.data_read_event());
}
bw_fifo.nb_write(item);
wait(bw_fifo.data_written_event());
dbgmodprint(use_prints, "[BW_FIFO] Pushed transaction #%0d", img_ext->transaction_number);
return tlm::TLM_ACCEPTED;
}
// TLM2 forward path non-blocking transport method
virtual tlm::tlm_sync_enum nb_transport_fw(tlm::tlm_generic_payload& trans,
tlm::tlm_phase& phase, sc_time& delay )
{
img_generic_extension* img_ext;
//Call event queue
tlm_item item;
item.transaction = &trans;
item.phase = phase;
item.delay = delay;
trans.get_extension(img_ext);
if (fw_fifo.num_free() == 0) {
dbgmodprint(use_prints, "[FW_FIFO] FIFO is FULL. Waiting...");
wait(fw_fifo.data_read_event());
}
fw_fifo.nb_write(item);
wait(fw_fifo.data_written_event());
dbgmodprint(use_prints, "[FW_FIFO] Pushed transaction #%0d", img_ext->transaction_number);
return tlm::TLM_ACCEPTED;
}
void fw_thread() {
while(true) {
img_generic_extension* img_ext;
tlm::tlm_generic_payload* trans_ptr = new tlm::tlm_generic_payload;
tlm::tlm_phase phase;
sc_time delay;
tlm_item item;
if (fw_fifo.num_available() == 0) {
wait(fw_fifo.data_written_event());
}
fw_fifo.nb_read(item);
wait(fw_fifo.data_read_event());
trans_ptr = item.transaction;
phase = item.phase;
delay = item.delay;
(*trans_ptr).get_extension(img_ext);
dbgmodprint(use_prints, "[FW_FIFO] Popped transaction #%0d", img_ext->transaction_number);
fw_m_peq.notify(*trans_ptr, phase, delay);
wait(fw_delay);
}
}
void bw_thread() {
while(true) {
img_generic_extension* img_ext;
tlm::tlm_generic_payload* trans_ptr = new tlm::tlm_generic_payload;
tlm::tlm_phase phase;
sc_time delay;
tlm_item item;
if (bw_fifo.num_available() == 0) {
wait(bw_fifo.data_written_event());
}
bw_fifo.nb_read(item);
wait(bw_fifo.data_read_event());
trans_ptr = item.transaction;
phase = item.phase;
delay = item.delay;
(*trans_ptr).get_extension(img_ext);
dbgmodprint(use_prints, "[BW_FIFO] Popped transaction #%0d", img_ext->transaction_number);
bw_m_peq.notify(*trans_ptr, phase, delay);
wait(bw_delay);
}
}
//Payload event and queue callback to handle transactions received from target
void bw_peq_cb(tlm::tlm_generic_payload& trans, const tlm::tlm_phase& phase)
{
img_generic_extension* img_ext;
trans.get_extension(img_ext);
tlm::tlm_phase local_phase = phase;
sc_dt::uint64 address = trans.get_address();
this->transaction_in_bw_path_id = img_ext->transaction_number;
dbgmodprint(use_prints, "Received transaction #%0d with address %016llX in backward path. Redirecting transaction to CPU", img_ext->transaction_number, address);
target_socket->nb_transport_bw(trans, local_phase, this->bw_delay);
}
void fw_peq_cb(tlm::tlm_generic_payload& trans, const tlm::tlm_phase& phase)
{
img_generic_extension* img_ext;
trans.get_extension(img_ext);
tlm::tlm_phase local_phase = phase;
sc_dt::uint64 address = trans.get_address();
this->transaction_in_fw_path_id = img_ext->transaction_number;
unsigned int initiator_id = decode_address(address);
dbgmodprint(use_prints, "Received transaction #%0d with address %016llX in forward path. Redirecting transaction through initiator %d", img_ext->transaction_number, address, initiator_id);
(*initiator_socket[initiator_id])->nb_transport_fw(trans, local_phase, this->fw_delay);
}
void set_delays(sc_time fw_delay, sc_time bw_delay)
{
this->bw_delay = bw_delay;
this->fw_delay = fw_delay;
}
} ;
#endif
|
/*******************************************************************************
* i2c.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design
*******************************************************************************
* Description:
* Model for a I2C.
*******************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************
*/
#include <systemc.h>
#include "i2c.h"
#include "info.h"
void i2c::transfer_th() {
unsigned char p;
bool rwbit;
sda_en_o.write(false);
scl_en_o.write(false);
state = IDLE;
while(true) {
p = to.read();
snd.write(p);
/* For the start and stop bit, we could be in the middle of a command,
* therefore we cannot assume the bits are correct.
*/
if (p == 'S') {
sda_en_o.write(false);
scl_en_o.write(false);
wait(625, SC_NS); sda_en_o.write(true);
wait(625, SC_NS); scl_en_o.write(true);
wait(1250, SC_NS);
state = DEVID;
}
else if (p == 'P') {
/* If the SDA is high, we need to take it low first. If not, we cam
* go straight into the stop bit.
*/
wait(625, SC_NS); sda_en_o.write(true);
wait(625, SC_NS); scl_en_o.write(false);
wait(625, SC_NS); sda_en_o.write(false);
wait(1250, SC_NS);
state = IDLE;
}
else if (state == DEVID || state == WRITING) {
if (p == '1') {
wait(625, SC_NS); sda_en_o.write(false);
wait(625, SC_NS); scl_en_o.write(false);
wait(1250, SC_NS); scl_en_o.write(true);
rwbit = true;
}
else if (p == '0') {
wait(625, SC_NS); sda_en_o.write(true);
wait(625, SC_NS); scl_en_o.write(false);
wait(1250, SC_NS); scl_en_o.write(true);
rwbit = false;
}
else if (p == 'Z') {
sda_en_o.write(false);
/* Then we tick the clock. */
wait(1250, SC_NS); scl_en_o.write(false);
/* After the clock, we sample it. */
if (sda_i.read()) {
snd.write('N');
from.write('N');
state = IDLE;
}
else {
snd.write('A');
from.write('A');
/* If the readwrite bit is low and we are in the DEVID state
* we go to the WRITING state. If we are already in the WRITING
* state we remain in it.
*/
if (state == DEVID && !rwbit || state == WRITING) state= WRITING;
else state = READING;
}
wait(1250, SC_NS); scl_en_o.write(true);
}
else wait(2500, SC_NS);
}
else if (state == READING) {
if (p == 'N') {
wait(625, SC_NS); sda_en_o.write(false);
wait(625, SC_NS); scl_en_o.write(false);
wait(1250, SC_NS); scl_en_o.write(true);
state = IDLE;
}
else if (p == 'A') {
wait(625, SC_NS); sda_en_o.write(true);
wait(625, SC_NS); scl_en_o.write(false);
wait(1250, SC_NS); scl_en_o.write(true);
}
else if (p == 'Z') {
sda_en_o.write(false);
wait(1250, SC_NS); scl_en_o.write(false);
if (sda_i.read()) {
from.write('1');
snd.write('1');
}
else {
from.write('0');
snd.write('0');
}
wait(1250, SC_NS); scl_en_o.write(true);
}
else wait(2500, SC_NS);
}
}
}
void i2c::trace(sc_trace_file *tf) {
sc_trace(tf, snd, snd.name());
}
|
#include <string>
#include <algorithm>
#include <sstream>
#include <vector>
#include <systemc.h>
#include "sc_qt_adaptor.h"
#include "sc_config.h"
#include "sc_run.h"
#include "sc_debug_object.h"
void scQtAdaptor::trace_module (sc_module *module) {
auto children = module->get_child_objects();
sc_object * o;
for (size_t nchildren=0; nchildren < children.size(); nchildren++) {
o = children.at(nchildren);
debug_object debobj(o);
register_object(debobj);
if (debobj.isModule()) {
trace_module(dynamic_cast<sc_module *>(o));
}
}
}
void scQtAdaptor::AdaptorThread () {
sc_time ustep = sc_getMicrostep();
sc_time now;
while (sc_waitStateChange() == SC_ST_COMMAND_EXIT) {
wait();
}
hierarchy();
report(now);
sc_NotifyUIFromSC();
wait(1, SC_PS);
while (1) {
while (sc_waitStateChange() == SC_ST_COMMAND_EXIT) {
wait();
}
wait(ustep-sc_time(1, SC_PS));
now = sc_time_stamp();
wait(1, SC_PS);
report(now);
sc_NotifyUIFromSC();
}
}
void scQtAdaptor::end_of_elaboration() {
sc_simcontext* simc = simcontext();
std::vector<sc_object *> objects = sc_get_top_level_objects(simc);
sc_object * o;
if (simc != nullptr) {
for (size_t i=0; i < objects.size(); i++){
o = objects.at(i);
debug_object debobj(o);
register_object(debobj);
if (debobj.isModule()) {
trace_module(dynamic_cast<sc_module *>(o));
}
}
}
}
void scQtAdaptor::register_object(debug_object &object)
{
if (object.isHierarchy()) {
m_hierarchy_objects.push_back(object);
}
if (object.isTraceable()) {
m_traceable_objects.push_back(object);
}
}
void scQtAdaptor::report(sc_time &now)
{
std::vector<std::string> rep;
//rep.push_back(sc_time_stamp().to_string());
rep.push_back(now.to_string());
//cout << "TRACE :: @" << sc_time_stamp() << endl;
for (size_t i = 0; i < m_traceable_objects.size(); i++) {
std::string value(m_traceable_objects.at(i).report_value());
rep.push_back(value);
//cout << " " << value << endl;
}
sc_setReportFromSC(rep);
}
void scQtAdaptor::hierarchy()
{
std::vector<std::string> hier;
//cout << "HIERARCHY :: " << endl;
for (size_t i = 0; i < m_hierarchy_objects.size(); i++) {
std::string prefix;
std::string node;
std::string name(m_hierarchy_objects.at(i).name());
std::string::difference_type n = std::count(name.begin(), name.end(), '.');
prefix.append(3*n, '-');
if (m_hierarchy_objects.at(i).isModule()) {
node = " (node)";
}
hier.push_back(m_hierarchy_objects.at(i).name());
//cout << " " << prefix << name << node << endl;
}
sc_setHierarchyFromSC(hier);
}
|
#ifndef PACKET_GENERATOR_CPP
#define PACKET_GENERATOR_CPP
#include <systemc-ams.h>
#include <systemc.h>
#include "packetGenerator.h"
void packetGenerator::set_attributes()
{
// Set a timestep for the TDF module
set_timestep(sample_time);
}
void packetGenerator::fill_data(unsigned char* data, int packet_length)
{
local_data = new unsigned char[packet_length];
memcpy(local_data, data, packet_length * sizeof(char));
actual_data_length = packet_length;
bytes_sent = 0;
// Insert first the preamble
create_pack_of_data(preamble_data, 8);
preamble_in_process = true;
}
void packetGenerator::create_pack_of_data(unsigned char* data, int packet_length)
{
int actual_length = (packet_length * 2 > N) ? N : packet_length * 2;
unsigned char tmp_data;
sc_dt::sc_bv<N * 4> tmp_data_in = 0;
sc_dt::sc_bv<N> tmp_data_valid = 0;
for (int i = 0; i < actual_length; i++)
{
tmp_data = *(data + (i/2));
if ((i % 2) == 1)
{
tmp_data = tmp_data >> 4;
}
tmp_data_in.range(i * 4 + 3, i * 4) = tmp_data;
tmp_data_valid[i] = 1;
}
data_to_send = tmp_data_in;
data_valid_to_send = tmp_data_valid;
n2_data_valid = data_valid_to_send;
n1_data_valid = n2_data_valid;
}
void packetGenerator::processing()
{
sc_dt::sc_bv<N * 4> tmp_data_to_send = data_to_send;
sc_dt::sc_bv<N> tmp_data_valid_to_send = data_valid_to_send;
bool manual_update = false;
if ((tmp_data_valid_to_send.or_reduce() == 0) && (preamble_in_process == true))
{
sc_dt::sc_bv<32> local_length = 0;
preamble_in_process = false;
local_length = (unsigned int)actual_data_length;
data_to_send = 0;
data_to_send.range(31, 0) = local_length;
data_valid_to_send = "11111111";
tmp_data_to_send = data_to_send;
tmp_data_valid_to_send = data_valid_to_send;
n2_data_valid = data_valid_to_send;
n1_data_valid = n2_data_valid;
}
else if ((tmp_data_valid_to_send.or_reduce() == 0) && (actual_data_length > 0))
{
if (actual_data_length > 8)
{
create_pack_of_data((local_data + bytes_sent), 8);
actual_data_length -= 8;
bytes_sent += 8;
}
else
{
create_pack_of_data((local_data + bytes_sent), actual_data_length);
actual_data_length = 0;
delete[] local_data;
}
}
n1_data_out = n2_data_out;
n1_data_out_valid = n2_data_out_valid;
n1_data_valid = n2_data_valid;
if (tmp_data_valid_to_send.or_reduce())
{
for (int i = 0; i < N; i++)
{
if (tmp_data_valid_to_send[i] == 1)
{
if ((bitCount == 0) && (tmp_data_out_valid == false) && (n1_data_out_valid == false))
{
tmp_data_valid_to_send[i] = 0;
n2_data_out = tmp_data_to_send.range(i * 4 + 3, i * 4);
n2_data_out_valid = true;
n2_data_valid = tmp_data_valid_to_send;
#ifndef USING_TLM_TB_EN
std::cout << "@" << sc_time_stamp() << " Inside generate_packet(): data to sent " << n2_data_out << std::endl;
#endif // USING_TLM_TB_EN
break;
}
else if ((bitCount == 0) && (tmp_data_out_valid == true))
{
tmp_data_valid_to_send[i] = 0;
data_out.write(tmp_data_to_send.range(i * 4 + 3, i * 4));
data_out_valid.write(1);
tmp_data_out_valid = true;
data_valid_to_send_ = tmp_data_valid_to_send;
n2_data_out = tmp_data_to_send.range(i * 4 + 3, i * 4);
n2_data_out_valid = true;
n2_data_valid = tmp_data_valid_to_send;
n1_data_out = n2_data_out;
n1_data_out_valid = n2_data_out_valid;
n1_data_valid = n2_data_valid;
manual_update = true;
#ifndef USING_TLM_TB_EN
std::cout << "@" << sc_time_stamp() << " Inside generate_packet(): data to sent " << n2_data_out << std::endl;
#endif // USING_TLM_TB_EN
break;
}
}
}
}
if (!manual_update)
{
data_out_valid.write(n1_data_out_valid);
tmp_data_out_valid = n1_data_out_valid;
}
if (tmp_data_out_valid == true)
{
bitCount++;
}
if (bitCount == 5)
{
bitCount = 0;
if (!manual_update)
{
n2_data_out_valid = false;
n1_data_out_valid = n2_data_out_valid;
data_out_valid.write(true);
tmp_data_out_valid = true;
}
}
if (!manual_update)
{
data_valid_to_send = n1_data_valid;
data_out.write(n1_data_out);
}
n1_sigBitCount = n2_sigBitCount;
n2_sigBitCount = bitCount;
n1_sigBitCount_.write(n1_sigBitCount);
n2_sigBitCount_.write(n2_sigBitCount);
sigBitCount.write(n1_sigBitCount);
tmp_data_out_valid_.write(tmp_data_out_valid);
n2_data_out_valid_.write(n2_data_out_valid);
n2_data_out_.write(n2_data_out);
n2_data_valid_.write(n2_data_valid);
n1_data_out_valid_.write(n1_data_out_valid);
n1_data_out_.write(n1_data_out);
n1_data_valid_.write(n1_data_valid);
data_in_.write(data_in);
data_in_valid_.write(data_in_valid);
data_to_send_.write(data_to_send);
data_valid_to_send_.write(data_valid_to_send);
remaining_bytes_to_send.write(actual_data_length);
}
#endif // PACKET_GENERATOR_CPP
|
#ifndef IMG_TARGET_CPP
#define IMG_TARGET_CPP
#include <systemc.h>
using namespace sc_core;
using namespace sc_dt;
using namespace std;
#include <tlm.h>
#include <tlm_utils/simple_initiator_socket.h>
#include <tlm_utils/simple_target_socket.h>
#include <tlm_utils/peq_with_cb_and_phase.h>
#include "common_func.hpp"
#include "img_generic_extension.hpp"
//For an internal response phase
DECLARE_EXTENDED_PHASE(internal_processing_ph);
// Initiator module generating generic payload transactions
struct img_target: sc_module
{
// TLM2.0 Socket
tlm_utils::simple_target_socket<img_target> socket;
//Pointer to transaction in progress
tlm::tlm_generic_payload* response_transaction;
//Payload event queue with callback and phase
tlm_utils::peq_with_cb_and_phase<img_target> m_peq;
//Delay
sc_time response_delay;
sc_time receive_delay;
//SC_EVENT
sc_event send_response_e;
//DEBUG
unsigned int transaction_in_progress_id = 0;
bool use_prints;
//Constructor
SC_CTOR(img_target)
: socket("socket"), response_transaction(0), m_peq(this, &img_target::peq_cb), use_prints(true) // Construct and name socket
{
// Register callbacks for incoming interface method calls
socket.register_nb_transport_fw(this, &img_target::nb_transport_fw);
SC_THREAD(send_response);
}
tlm::tlm_sync_enum nb_transport_fw(tlm::tlm_generic_payload& trans,
tlm::tlm_phase& phase, sc_time& delay)
{
if (trans.get_byte_enable_ptr() != 0) {
trans.set_response_status(tlm::TLM_BYTE_ENABLE_ERROR_RESPONSE);
return tlm::TLM_COMPLETED;
}
if (trans.get_streaming_width() < trans.get_data_length()) {
trans.set_response_status(tlm::TLM_BURST_ERROR_RESPONSE);
return tlm::TLM_COMPLETED;
}
// Queue the transaction
m_peq.notify(trans, phase, delay);
return tlm::TLM_ACCEPTED;
}
//Payload and Queue Callback
void peq_cb(tlm::tlm_generic_payload& trans, const tlm::tlm_phase& phase)
{
sc_time delay;
img_generic_extension* img_ext;
switch (phase) {
//Case 1: Target is receiving the first transaction of communication -> BEGIN_REQ
case tlm::BEGIN_REQ: {
//Check for errors here
// Increment the transaction reference count
trans.acquire();
trans.get_extension(img_ext);
dbgmodprint(use_prints, "BEGIN_REQ RECEIVED TRANS ID %0d", img_ext->transaction_number);
//Queue a response
tlm::tlm_phase int_phase = internal_processing_ph;
m_peq.notify(trans, int_phase, receive_delay);
break;
}
case tlm::END_RESP:
case tlm::END_REQ:
case tlm::BEGIN_RESP:{
SC_REPORT_FATAL("TLM-2", "Illegal transaction phase received by target");
break;
}
default: {
if (phase == internal_processing_ph){
dbgmodprint(use_prints, "INTERNAL PHASE: PROCESSING TRANSACTION");
process_transaction(trans);
}
break;
}
}
}
//Response function
void send_response()
{
while(true){
wait(send_response_e);
tlm::tlm_sync_enum status;
tlm::tlm_phase response_phase;
img_generic_extension* img_ext;
response_phase = tlm::BEGIN_RESP;
status = socket->nb_transport_bw(*response_transaction, response_phase, response_delay);
//Check Initiator response
switch(status) {
case tlm::TLM_ACCEPTED: {
// Target only care about acknowledge of the succesful response
(*response_transaction).release();
(*response_transaction).get_extension(img_ext);
dbgmodprint(use_prints, "TLM_ACCEPTED RECEIVED TRANS ID %0d", img_ext->transaction_number);
break;
}
//Not implementing Updated and Completed Status
default: {
dbgmodprint(use_prints, "[ERROR] Invalid status received at target");
break;
}
}
}
}
virtual void do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address){
}
virtual void do_when_write_transaction(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address){
}
//Thread to call nb_transport on the backward path -> here the module process data and responds to initiator
void process_transaction(tlm::tlm_generic_payload& trans)
{
//Status and Phase
tlm::tlm_phase phase;
img_generic_extension* img_ext;
//get variables from transaction
tlm::tlm_command cmd = trans.get_command();
sc_dt::uint64 addr = trans.get_address();
unsigned char* data_ptr = trans.get_data_ptr();
unsigned int len = trans.get_data_length();
trans.get_extension(img_ext);
dbgmodprint(use_prints, "Processing transaction: %0d", img_ext->transaction_number);
this->transaction_in_progress_id = img_ext->transaction_number;
//Process transaction
switch(cmd) {
case tlm::TLM_READ_COMMAND: {
unsigned char* response_data_ptr;
response_data_ptr = new unsigned char[len];
this->do_when_read_transaction(response_data_ptr, len, addr);
//Add read according to length
//-----------DEBUG-----------
dbgmodprint(use_prints, "[DEBUG] Reading: ");
for (long unsigned int i = 0; i < len/sizeof(int); ++i){
dbgmodprint(use_prints, "%02x", *(reinterpret_cast<int*>(response_data_ptr)+i));
}
//-----------DEBUG-----------
trans.set_data_ptr(response_data_ptr);
break;
}
case tlm::TLM_WRITE_COMMAND: {
this->do_when_write_transaction(data_ptr, len, addr);
//-----------DEBUG-----------
dbgmodprint(use_prints, "[DEBUG] Writing: ");
for (long unsigned int i = 0; i < len/sizeof(int); ++i){
dbgmodprint(use_prints, "%02x", *(reinterpret_cast<int*>(data_ptr)+i));
}
//-----------DEBUG-----------
break;
}
default: {
dbgmodprint(use_prints, "ERROR Command %0d is NOT valid", cmd);
}
}
//Send response
dbgmodprint(use_prints, "BEGIN_RESP SENT TRANS ID %0d", img_ext->transaction_number);
response_transaction = &trans;
//send_response(trans);
send_response_e.notify();
}
void set_delays(sc_time resp_delay, sc_time rec_delay)
{
this->response_delay = resp_delay;
this->receive_delay = rec_delay;
}
};
#endif
|
/********************************************************************************
* University of L'Aquila - HEPSYCODE Source Code License *
* *
* *
* (c) 2018-2019 Centre of Excellence DEWS All rights reserved *
********************************************************************************
* <one line to give the program's name and a brief idea of what it does.> *
* Copyright (C) 2022 Vittoriano Muttillo, Luigi Pomante * *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
********************************************************************************
* *
* Created on: 09/May/2023 *
* Authors: Vittoriano Muttillo, Marco Santic, Luigi Pomante *
* *
* email: [email protected] *
* [email protected] *
* [email protected] *
* *
********************************************************************************
* This code has been developed from an HEPSYCODE model used as demonstrator by *
* University of L'Aquila. *
*******************************************************************************/
#include <systemc.h>
#include "../mainsystem.h"
#include <math.h>
//-----------------------------------------------------------------------------
// Physical constants
//-----------------------------------------------------------------------------
static double sTC_I_0 = 77.3 ; // [A] Nominal current
//static double sTC_T_0 = 298.15 ; // [K] Ambient temperature
//static double sTC_R_0 = 0.01 ; // [Ω] Data-sheet R_DS_On (Drain-Source resistance in the On State)
static double sTC_V_0 = 47.2 ; // [V] Nominal voltage
//static double sTC_Alpha = 0.002 ; // [Ω/K] Temperature coefficient of Drain-Source resistance in the On State
//static double sTC_ThermalConstant = 0.75 ;
//static double sTC_Tau = 0.02 ; // [s] Sampling period
//-----------------------------------------------------------------------------
// Simulation related data
//-----------------------------------------------------------------------------
//#define N_CYCLES 1000 // Change by command line option -n<number>
#define sTC_NOISE 0.2 // Measurement noise = 10%
static double sTC_time_Ex = 0 ; // Simple time simulation
//-----------------------------------------------------------------------------
// Mnemonics to access the array that contains the sampled data
//-----------------------------------------------------------------------------
#define sTC_SAMPLE_LEN 3 // Array of SAMPLE_LEN elements
#define sTC_I_INDEX 0 // Current
#define sTC_V_INDEX 1 // Voltage
#define sTC_TIME_INDEX 2 // Time
///-----------------------------------------------------------------------------
// Forward references
//-----------------------------------------------------------------------------
//static int sTC_initDescriptors(void) ;
static void sTC_getSample(int index, double sample[sTC_SAMPLE_LEN]) ;
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void sTC_getSample(int index, double sample[sTC_SAMPLE_LEN])
{HEPSY_S(sampleTimCord_id)
// the parameter "index" is needed as device identifier
HEPSY_S(sampleTimCord_id) sample[sTC_TIME_INDEX] = sTC_time_Ex ;
// Random generation of i (current)
HEPSY_S(sampleTimCord_id) double i; double v ; double noise ;
// Random i
HEPSY_S(sampleTimCord_id) i = (double)rand() / (double)RAND_MAX ; // 0.0 <= i <= 1.0
HEPSY_S(sampleTimCord_id) i *= 2.0 ; // 0.0 <= i <= 2.0
HEPSY_S(sampleTimCord_id) i *= sTC_I_0 ; // 0.0 <= i <= 2.0*I_0
// Postcondition: (0 <= i <= 2.0*I_0)
// Add some noise every 3 samples
HEPSY_S(sampleTimCord_id)
HEPSY_S(sampleTimCord_id) noise = rand() % 3 == 0 ? 1.0 : 0.0 ;
HEPSY_S(sampleTimCord_id)
HEPSY_S(sampleTimCord_id)
HEPSY_S(sampleTimCord_id) noise *= (double)rand() / (double)RAND_MAX ;
HEPSY_S(sampleTimCord_id) noise *= 2.0 ;
HEPSY_S(sampleTimCord_id) noise -= 1.0 ;
HEPSY_S(sampleTimCord_id)
HEPSY_S(sampleTimCord_id) noise *= (sTC_NOISE * sTC_I_0 ) ; // NOISE as % of I_0
HEPSY_S(sampleTimCord_id) i += noise ;
// Postcondition: (-NOISE*I_0 <= i <= (2.0+NOISE)*I_0 )
// Random v
HEPSY_S(sampleTimCord_id) v = (double)rand() / (double)RAND_MAX ; // 0.0 <= i <= 1.0
HEPSY_S(sampleTimCord_id) v *= 2.0 ; // 0.0 <= i <= 2.0
HEPSY_S(sampleTimCord_id) v *= sTC_V_0 ; // 0.0 <= i <= 2.0*I_0
// Postcondition: (0 <= i <= 2.0*I_0)
// Add some noise every 3 samples
HEPSY_S(sampleTimCord_id)
HEPSY_S(sampleTimCord_id) noise = rand() % 3 == 0 ? 1.0 : 0.0 ;
HEPSY_S(sampleTimCord_id)
HEPSY_S(sampleTimCord_id)
HEPSY_S(sampleTimCord_id) noise *= (double)rand() / (double)RAND_MAX ;
HEPSY_S(sampleTimCord_id) noise *= 2.0 ;
HEPSY_S(sampleTimCord_id) noise -= 1.0 ;
HEPSY_S(sampleTimCord_id)
HEPSY_S(sampleTimCord_id) noise *= (sTC_NOISE * sTC_V_0 ) ; // NOISE as % of I_0
HEPSY_S(sampleTimCord_id) v += noise ;
// Postcondition: (-NOISE*V_0 <= v <= (2.0+NOISE)*V_0 )
HEPSY_S(sampleTimCord_id) sample[sTC_I_INDEX] = i ;
HEPSY_S(sampleTimCord_id) sample[sTC_V_INDEX] = v ;
}
void mainsystem::sampleTimCord_main()
{
// datatype for channels
stimulus_system_payload stimulus_system_payload_var;
sampleTimCord_cleanData_xx_payload sampleTimCord_cleanData_xx_payload_var;
//step var
uint16_t step;
//device var
int dev;
// ex_time (for extractFeatures...)
double ex_time;
//var for samples, to re-use getSample()
double sample[sTC_SAMPLE_LEN] ;
srand(1);
//implementation
HEPSY_S(sampleTimCord_id) while(1)
{HEPSY_S(sampleTimCord_id)
// content
HEPSY_S(sampleTimCord_id) stimulus_system_payload_var = stimulus_system_port_out->read();
HEPSY_S(sampleTimCord_id) dev = 0;
HEPSY_S(sampleTimCord_id) step = stimulus_system_payload_var.example; //step
HEPSY_S(sampleTimCord_id) ex_time = sc_time_stamp().to_seconds();
//providing sample to ward device 0 (cleanData_01)
HEPSY_S(sampleTimCord_id) sTC_getSample(dev, sample);
// cout << "sampleTimCord \t dev: " << dev
// <<"\t s0:" << sample[0]
// <<"\t s1:" << sample[1]
// <<"\t s3:" << sample[2]
// << endl;
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.dev = dev++;
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.step = step;
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.ex_time = ex_time;
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.sample_i = sample[sTC_I_INDEX];
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.sample_v = sample[sTC_V_INDEX];
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_01_channel->write(sampleTimCord_cleanData_xx_payload_var);
//providing sample to ward device 1 (cleanData_02)
HEPSY_S(sampleTimCord_id) sTC_getSample(dev, sample);
// cout << "sampleTimCord \t dev: " << dev
// <<"\t s0:" << sample[0]
// <<"\t s1:" << sample[1]
// <<"\t s3:" << sample[2]
// << endl;
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.dev = dev++;
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.step = step;
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.ex_time = ex_time;
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.sample_i = sample[sTC_I_INDEX];
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.sample_v = sample[sTC_V_INDEX];
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_02_channel->write(sampleTimCord_cleanData_xx_payload_var);
//providing sample to ward device 2 (cleanData_03)
HEPSY_S(sampleTimCord_id) sTC_getSample(dev, sample);
// cout << "sampleTimCord \t dev: " << dev
// <<"\t s0:" << sample[0]
// <<"\t s1:" << sample[1]
// <<"\t s3:" << sample[2]
// << endl;
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.dev = dev++;
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.step = step;
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.ex_time = ex_time;
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.sample_i = sample[sTC_I_INDEX];
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.sample_v = sample[sTC_V_INDEX];
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_03_channel->write(sampleTimCord_cleanData_xx_payload_var);
//providing sample to ward device 3 (cleanData_04)
HEPSY_S(sampleTimCord_id) sTC_getSample(dev, sample);
// cout << "sampleTimCord \t dev: " << dev
// <<"\t s0:" << sample[0]
// <<"\t s1:" << sample[1]
// <<"\t s3:" << sample[2]
// << endl;
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.dev = dev++;
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.step = step;
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.ex_time = ex_time;
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.sample_i = sample[sTC_I_INDEX];
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_xx_payload_var.sample_v = sample[sTC_V_INDEX];
HEPSY_S(sampleTimCord_id) sampleTimCord_cleanData_04_channel->write(sampleTimCord_cleanData_xx_payload_var);
HEPSY_P(sampleTimCord_id)
}
}
//END
|
#ifndef IMG_TARGET_CPP
#define IMG_TARGET_CPP
#include <systemc.h>
using namespace sc_core;
using namespace sc_dt;
using namespace std;
#include <tlm.h>
#include <tlm_utils/simple_initiator_socket.h>
#include <tlm_utils/simple_target_socket.h>
#include <tlm_utils/peq_with_cb_and_phase.h>
#include "common_func.hpp"
#include "img_generic_extension.hpp"
//For an internal response phase
DECLARE_EXTENDED_PHASE(internal_processing_ph);
// Initiator module generating generic payload transactions
struct img_target: sc_module
{
// TLM2.0 Socket
tlm_utils::simple_target_socket<img_target> socket;
//Pointer to transaction in progress
tlm::tlm_generic_payload* response_transaction;
//Payload event queue with callback and phase
tlm_utils::peq_with_cb_and_phase<img_target> m_peq;
//Delay
sc_time response_delay;
sc_time receive_delay;
//SC_EVENT
sc_event send_response_e;
//DEBUG
unsigned int transaction_in_progress_id = 0;
bool use_prints;
//Constructor
SC_CTOR(img_target)
: socket("socket"), response_transaction(0), m_peq(this, &img_target::peq_cb), use_prints(true) // Construct and name socket
{
// Register callbacks for incoming interface method calls
socket.register_nb_transport_fw(this, &img_target::nb_transport_fw);
SC_THREAD(send_response);
}
tlm::tlm_sync_enum nb_transport_fw(tlm::tlm_generic_payload& trans,
tlm::tlm_phase& phase, sc_time& delay)
{
if (trans.get_byte_enable_ptr() != 0) {
trans.set_response_status(tlm::TLM_BYTE_ENABLE_ERROR_RESPONSE);
return tlm::TLM_COMPLETED;
}
if (trans.get_streaming_width() < trans.get_data_length()) {
trans.set_response_status(tlm::TLM_BURST_ERROR_RESPONSE);
return tlm::TLM_COMPLETED;
}
// Queue the transaction
m_peq.notify(trans, phase, delay);
return tlm::TLM_ACCEPTED;
}
//Payload and Queue Callback
void peq_cb(tlm::tlm_generic_payload& trans, const tlm::tlm_phase& phase)
{
sc_time delay;
img_generic_extension* img_ext;
switch (phase) {
//Case 1: Target is receiving the first transaction of communication -> BEGIN_REQ
case tlm::BEGIN_REQ: {
//Check for errors here
// Increment the transaction reference count
trans.acquire();
trans.get_extension(img_ext);
dbgmodprint(use_prints, "BEGIN_REQ RECEIVED TRANS ID %0d", img_ext->transaction_number);
//Queue a response
tlm::tlm_phase int_phase = internal_processing_ph;
m_peq.notify(trans, int_phase, receive_delay);
break;
}
case tlm::END_RESP:
case tlm::END_REQ:
case tlm::BEGIN_RESP:{
SC_REPORT_FATAL("TLM-2", "Illegal transaction phase received by target");
break;
}
default: {
if (phase == internal_processing_ph){
dbgmodprint(use_prints, "INTERNAL PHASE: PROCESSING TRANSACTION");
process_transaction(trans);
}
break;
}
}
}
//Response function
void send_response()
{
while(true){
wait(send_response_e);
tlm::tlm_sync_enum status;
tlm::tlm_phase response_phase;
img_generic_extension* img_ext;
response_phase = tlm::BEGIN_RESP;
status = socket->nb_transport_bw(*response_transaction, response_phase, response_delay);
//Check Initiator response
switch(status) {
case tlm::TLM_ACCEPTED: {
// Target only care about acknowledge of the succesful response
(*response_transaction).release();
(*response_transaction).get_extension(img_ext);
dbgmodprint(use_prints, "TLM_ACCEPTED RECEIVED TRANS ID %0d", img_ext->transaction_number);
break;
}
//Not implementing Updated and Completed Status
default: {
dbgmodprint(use_prints, "[ERROR] Invalid status received at target");
break;
}
}
}
}
virtual void do_when_read_transaction(unsigned char*& data, unsigned int data_length, sc_dt::uint64 address){
}
virtual void do_when_write_transaction(unsigned char*&data, unsigned int data_length, sc_dt::uint64 address){
}
//Thread to call nb_transport on the backward path -> here the module process data and responds to initiator
void process_transaction(tlm::tlm_generic_payload& trans)
{
//Status and Phase
tlm::tlm_phase phase;
img_generic_extension* img_ext;
//get variables from transaction
tlm::tlm_command cmd = trans.get_command();
sc_dt::uint64 addr = trans.get_address();
unsigned char* data_ptr = trans.get_data_ptr();
unsigned int len = trans.get_data_length();
trans.get_extension(img_ext);
dbgmodprint(use_prints, "Processing transaction: %0d", img_ext->transaction_number);
this->transaction_in_progress_id = img_ext->transaction_number;
//Process transaction
switch(cmd) {
case tlm::TLM_READ_COMMAND: {
unsigned char* response_data_ptr;
response_data_ptr = new unsigned char[len];
this->do_when_read_transaction(response_data_ptr, len, addr);
//Add read according to length
//-----------DEBUG-----------
dbgmodprint(use_prints, "[DEBUG] Reading: ");
for (long unsigned int i = 0; i < len/sizeof(int); ++i){
dbgmodprint(use_prints, "%02x", *(reinterpret_cast<int*>(response_data_ptr)+i));
}
//-----------DEBUG-----------
trans.set_data_ptr(response_data_ptr);
break;
}
case tlm::TLM_WRITE_COMMAND: {
this->do_when_write_transaction(data_ptr, len, addr);
//-----------DEBUG-----------
dbgmodprint(use_prints, "[DEBUG] Writing: ");
for (long unsigned int i = 0; i < len/sizeof(int); ++i){
dbgmodprint(use_prints, "%02x", *(reinterpret_cast<int*>(data_ptr)+i));
}
//-----------DEBUG-----------
break;
}
default: {
dbgmodprint(use_prints, "ERROR Command %0d is NOT valid", cmd);
}
}
//Send response
dbgmodprint(use_prints, "BEGIN_RESP SENT TRANS ID %0d", img_ext->transaction_number);
response_transaction = &trans;
//send_response(trans);
send_response_e.notify();
}
void set_delays(sc_time resp_delay, sc_time rec_delay)
{
this->response_delay = resp_delay;
this->receive_delay = rec_delay;
}
};
#endif
|
/*******************************************************************************
* mux_in.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design
*******************************************************************************
* Description:
* Model for the PCNT mux in the GPIO matrix.
*******************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************
*/
#include <systemc.h>
#include "info.h"
#include "mux_in.h"
void mux_in::mux(int gpiosel) {
if (gpiosel >= min_i.size()) {
PRINTF_WARN("MUXPCNT",
"Attempting to set GPIO Matrix to illegal pin %d.", gpiosel);
return;
}
function = gpiosel;
fchange_ev.notify();
}
void mux_in::transfer() {
bool nxval;
while(true) {
/* We simply copy the input onto the output. */
nxval = min_i[function]->read();
out_o.write(nxval);
if (debug) {
PRINTF_INFO("MUXIN", "mux_in %s is driving %c, function %d", name(),
(nxval)?'H':'L', function);
}
/* We wait for a function change or a signal change. */
wait(fchange_ev | min_i[function]->value_changed_event());
}
}
|
#include <systemc.h>
#include <string>
#include <vector>
#include <map>
#include <fstream>
#include <nana/gui.hpp>
#include <nana/gui/widgets/button.hpp>
#include <nana/gui/widgets/menubar.hpp>
#include <nana/gui/widgets/group.hpp>
#include <nana/gui/widgets/textbox.hpp>
#include <nana/gui/filebox.hpp>
#include "top.hpp"
#include "gui.hpp"
using std::fstream;
using std::map;
using std::string;
using std::vector;
int sc_main(int argc, char *argv[])
{
using namespace nana;
vector<string> instruction_queue;
string bench_name = "";
int nadd, nmul, nls, n_bits, bpb_size, cpu_freq, m_size;
m_size = 2;
nadd = 3;
nmul = nls = 2;
n_bits = 2;
bpb_size = 4;
cpu_freq = 500; // definido em Mhz - 500Mhz default
std::vector<int> sizes;
bool spec = false;
int mode = 0;
bool fila = false;
ifstream inFile;
form fm(API::make_center(1024, 700));
place plc(fm);
place upper(fm);
place lower(fm);
listbox table(fm);
listbox reg(fm);
listbox instruct(fm);
listbox rob(fm);
menubar mnbar(fm);
button start(fm);
button run_all(fm);
button clock_control(fm);
button exit(fm);
group clock_group(fm);
label clock_count(clock_group);
fm.caption("TFSim");
clock_group.caption("Ciclo");
clock_group.div("count");
grid memory(fm, rectangle(), 10, 50);
// Tempo de latencia de uma instrucao
// Novas instrucoes devem ser inseridas manualmente aqui
map<string, int> instruct_time{{"DADD", 4}, {"DADDI", 4}, {"DSUB", 6}, {"DSUBI", 6}, {"DMUL", 10}, {"DDIV", 16}, {"MEM", 2}, {"SLT", 1}, {"SGT", 1}};
// Responsavel pelos modos de execução
top top1("top");
start.caption("Start");
clock_control.caption("Next cycle");
run_all.caption("Run all");
exit.caption("Exit");
plc["rst"] << table;
plc["btns"] << start << clock_control << run_all << exit;
plc["memor"] << memory;
plc["regs"] << reg;
plc["rob"] << rob;
plc["instr"] << instruct;
plc["clk_c"] << clock_group;
clock_group["count"] << clock_count;
clock_group.collocate();
spec = false;
// set_spec eh so visual
set_spec(plc, spec);
plc.collocate();
mnbar.push_back("Opções");
menu &op = mnbar.at(0);
// menu::item_proxy spec_ip =
op.append("Especulação");
auto spec_sub = op.create_sub_menu(0);
// Modo com 1 preditor para todos os branchs
spec_sub->append("1 Preditor", [&](menu::item_proxy &ip)
{
if(ip.checked()){
spec = true;
mode = 1;
spec_sub->checked(1, false);
spec_sub->checked(2, false);
}
else{
spec = false;
mode = 0;
}
set_spec(plc,spec); });
spec_sub->append("2 Preditor M,N", [&](menu::item_proxy &ip)
{
if (ip.checked())
{
spec = true;
mode = 3;
spec_sub->checked(0, false);
spec_sub->checked(2, false);
}
else
{
spec = false;
mode = 0;
}
set_spec(plc,spec); });
// Modo com o bpb
spec_sub->append("Branch Prediction Buffer", [&](menu::item_proxy &ip)
{
if (ip.checked())
{
spec = true;
mode = 2;
spec_sub->checked(0, false);
spec_sub->checked(1, false);
}
else
{
spec = false;
mode = 0;
}
set_spec(plc, spec); });
spec_sub->check_style(0, menu::checks::highlight);
spec_sub->check_style(1, menu::checks::highlight);
spec_sub->check_style(2, menu::checks::highlight);
op.append("Modificar valores...");
// novo submenu para escolha do tamanho do bpb e do preditor
auto sub = op.create_sub_menu(1);
sub->append("Tamanho do BPB e Preditor", [&](menu::item_proxy &ip)
{
inputbox ibox(fm, "", "Definir tamanhos");
inputbox::integer size("BPB", bpb_size, 2, 10, 2);
inputbox::integer bits("N_BITS", n_bits, 1, 3, 1);
inputbox::integer m_size_input("M_SIZE", m_size, 1, 8, 1);
if (ibox.show_modal(size, bits, m_size_input))
{
bpb_size = size.value();
n_bits = bits.value();
m_size = m_size_input.value();
} });
sub->append("Número de Estações de Reserva", [&](menu::item_proxy ip)
{
inputbox ibox(fm, "", "Quantidade de Estações de Reserva");
inputbox::integer add("ADD/SUB", nadd, 1, 10, 1);
inputbox::integer mul("MUL/DIV", nmul, 1, 10, 1);
inputbox::integer sl("LOAD/STORE", nls, 1, 10, 1);
if (ibox.show_modal(add, mul, sl))
{
nadd = add.value();
nmul = mul.value();
nls = sl.value();
} });
// Menu de ajuste dos tempos de latencia na interface
// Novas instrucoes devem ser adcionadas manualmente aqui
sub->append("Tempos de latência", [&](menu::item_proxy &ip)
{
inputbox ibox(fm, "", "Tempos de latência para instruções");
inputbox::text dadd_t("DADD", std::to_string(instruct_time["DADD"]));
inputbox::text daddi_t("DADDI", std::to_string(instruct_time["DADDI"]));
inputbox::text dsub_t("DSUB", std::to_string(instruct_time["DSUB"]));
inputbox::text dsubi_t("DSUBI", std::to_string(instruct_time["DSUBI"]));
inputbox::text dmul_t("DMUL", std::to_string(instruct_time["DMUL"]));
inputbox::text ddiv_t("DDIV", std::to_string(instruct_time["DDIV"]));
inputbox::text mem_t("Load/Store", std::to_string(instruct_time["MEM"]));
if (ibox.show_modal(dadd_t, daddi_t, dsub_t, dsubi_t, dmul_t, ddiv_t, mem_t))
{
instruct_time["DADD"] = std::stoi(dadd_t.value());
instruct_time["DADDI"] = std::stoi(daddi_t.value());
instruct_time["DSUB"] = std::stoi(dsub_t.value());
instruct_time["DSUBI"] = std::stoi(dsubi_t.value());
instruct_time["DMUL"] = std::stoi(dmul_t.value());
instruct_time["DDIV"] = std::stoi(ddiv_t.value());
instruct_time["MEM"] = std::stoi(mem_t.value());
} });
sub->append("Frequência CPU", [&](menu::item_proxy &ip)
{
inputbox ibox(fm, "Em Mhz", "Definir frequência da CPU");
inputbox::text freq("Frequência", std::to_string(cpu_freq));
if (ibox.show_modal(freq))
{
cpu_freq = std::stoi(freq.value());
} });
sub->append("Fila de instruções", [&](menu::item_proxy &ip)
{
filebox fb(0, true);
inputbox ibox(fm, "Localização do arquivo com a lista de instruções:");
inputbox::path caminho("", fb);
if (ibox.show_modal(caminho))
{
auto path = caminho.value();
inFile.open(path);
if (!add_instructions(inFile, instruction_queue, instruct))
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
fila = true;
} });
sub->append("Valores de registradores inteiros", [&](menu::item_proxy &ip)
{
filebox fb(0, true);
inputbox ibox(fm, "Localização do arquivo de valores de registradores inteiros:");
inputbox::path caminho("", fb);
if (ibox.show_modal(caminho))
{
auto path = caminho.value();
inFile.open(path);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
auto reg_gui = reg.at(0);
int value, i = 0;
while (inFile >> value && i < 32)
{
reg_gui.at(i).text(1, std::to_string(value));
i++;
}
for (; i < 32; i++)
reg_gui.at(i).text(1, "0");
inFile.close();
}
} });
sub->append("Valores de registradores PF", [&](menu::item_proxy &ip)
{
filebox fb(0, true);
inputbox ibox(fm, "Localização do arquivo de valores de registradores PF:");
inputbox::path caminho("", fb);
if (ibox.show_modal(caminho))
{
auto path = caminho.value();
inFile.open(path);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
auto reg_gui = reg.at(0);
int i = 0;
float value;
while (inFile >> value && i < 32)
{
reg_gui.at(i).text(4, std::to_string(value));
i++;
}
for (; i < 32; i++)
reg_gui.at(i).text(4, "0");
inFile.close();
}
} });
sub->append("Valores de memória", [&](menu::item_proxy &ip)
{
filebox fb(0, true);
inputbox ibox(fm, "Localização do arquivo de valores de memória:");
inputbox::path caminho("", fb);
if (ibox.show_modal(caminho))
{
auto path = caminho.value();
inFile.open(path);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
int i = 0;
int value;
while (inFile >> value && i < 500)
{
memory.Set(i, std::to_string(value));
i++;
}
for (; i < 500; i++)
{
memory.Set(i, "0");
}
inFile.close();
}
} });
op.append("Verificar conteúdo...");
auto new_sub = op.create_sub_menu(2);
new_sub->append("Valores de registradores", [&](menu::item_proxy &ip)
{
filebox fb(0, true);
inputbox ibox(fm, "Localização do arquivo de valores de registradores:");
inputbox::path caminho("", fb);
if (ibox.show_modal(caminho))
{
auto path = caminho.value();
inFile.open(path);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
string str;
int reg_pos, i;
bool is_float, ok;
ok = true;
while (inFile >> str)
{
if (str[0] == '$')
{
if (str[1] == 'f')
{
i = 2;
is_float = true;
}
else
{
i = 1;
is_float = false;
}
reg_pos = std::stoi(str.substr(i, str.size() - i));
auto reg_gui = reg.at(0);
string value;
inFile >> value;
if (!is_float)
{
if (reg_gui.at(reg_pos).text(1) != value)
{
ok = false;
break;
}
}
else
{
if (std::stof(reg_gui.at(reg_pos).text(4)) != std::stof(value))
{
ok = false;
break;
}
}
}
}
inFile.close();
msgbox msg("Verificação de registradores");
if (ok)
{
msg << "Registradores especificados apresentam valores idênticos!";
msg.icon(msgbox::icon_information);
}
else
{
msg << "Registradores especificados apresentam valores distintos!";
msg.icon(msgbox::icon_error);
}
msg.show();
}
} });
new_sub->append("Valores de memória", [&](menu::item_proxy &ip)
{
filebox fb(0, true);
inputbox ibox(fm, "Localização do arquivo de valores de memória:");
inputbox::path caminho("", fb);
if (ibox.show_modal(caminho))
{
auto path = caminho.value();
inFile.open(path);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
string value;
bool ok;
ok = true;
for (int i = 0; i < 500; i++)
{
inFile >> value;
if (std::stoi(memory.Get(i)) != (int)std::stol(value, nullptr, 16))
{
ok = false;
break;
}
}
inFile.close();
msgbox msg("Verificação de memória");
if (ok)
{
msg << "Endereços de memória especificados apresentam valores idênticos!";
msg.icon(msgbox::icon_information);
}
else
{
msg << "Endereços de memória especificados apresentam valores distintos!";
msg.icon(msgbox::icon_error);
}
msg.show();
}
} });
op.append("Benchmarks");
auto bench_sub = op.create_sub_menu(3);
bench_sub->append("Fibonacci", [&](menu::item_proxy &ip)
{
string path = "in/benchmarks/fibonacci/fibonacci.txt";
bench_name = "fibonacci";
inFile.open(path);
if (!add_instructions(inFile, instruction_queue, instruct))
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
fila = true; });
bench_sub->append("Stall por Divisão", [&](menu::item_proxy &ip)
{
string path = "in/benchmarks/division_stall.txt";
inFile.open(path);
if (!add_instructions(inFile, instruction_queue, instruct))
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
fila = true; });
bench_sub->append("Stress de Memória (Stores)", [&](menu::item_proxy &ip)
{
string path = "in/benchmarks/store_stress/store_stress.txt";
bench_name = "store_stress";
inFile.open(path);
if (!add_instructions(inFile, instruction_queue, instruct))
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
fila = true; });
bench_sub->append("Stall por hazard estrutural (Adds)", [&](menu::item_proxy &ip)
{
string path = "in/benchmarks/res_stations_stall.txt";
inFile.open(path);
if (!add_instructions(inFile, instruction_queue, instruct))
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
fila = true; });
bench_sub->append("Busca Linear", [&](menu::item_proxy &ip)
{
string path = "in/benchmarks/linear_search/linear_search.txt";
bench_name = "linear_search";
inFile.open(path);
if (!add_instructions(inFile, instruction_queue, instruct))
show_message("Arquivo inválido", "Não foi possível abrir o arquivo");
else
fila = true;
path = "in/benchmarks/linear_search/memory.txt";
inFile.open(path);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
int i = 0;
int value;
while (inFile >> value && i < 500)
{
memory.Set(i, std::to_string(value));
i++;
}
for (; i < 500; i++)
{
memory.Set(i, "0");
}
inFile.close();
}
path = "in/benchmarks/linear_search/regi_i.txt";
inFile.open(path);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
auto reg_gui = reg.at(0);
int value, i = 0;
while (inFile >> value && i < 32)
{
reg_gui.at(i).text(1, std::to_string(value));
i++;
}
for (; i < 32; i++)
reg_gui.at(i).text(1, "0");
inFile.close();
} });
bench_sub->append("Busca Binária", [&](menu::item_proxy &ip)
{
string path = "in/benchmarks/binary_search/binary_search.txt";
bench_name = "binary_search";
inFile.open(path);
if (!add_instructions(inFile, instruction_queue, instruct))
show_message("Arquivo inválido", "Não foi possível abrir o arquivo");
else
fila = true;
path = "in/benchmarks/binary_search/memory.txt";
inFile.open(path);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
int i = 0;
int value;
while (inFile >> value && i < 500)
{
memory.Set(i, std::to_string(value));
i++;
}
for (; i < 500; i++)
{
memory.Set(i, "0");
}
inFile.close();
}
path = "in/benchmarks/binary_search/regs.txt";
inFile.open(path);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
auto reg_gui = reg.at(0);
int value, i = 0;
while (inFile >> value && i < 32)
{
reg_gui.at(i).text(1, std::to_string(value));
i++;
}
for (; i < 32; i++)
reg_gui.at(i).text(1, "0");
inFile.close();
} });
bench_sub->append("Matriz Search", [&](menu::item_proxy &ip)
{
string path = "in/benchmarks/matriz_search/matriz_search.txt";
bench_name = "matriz_search";
inFile.open(path);
if (!add_instructions(inFile, instruction_queue, instruct))
show_message("Arquivo inválido", "Não foi possível abrir o arquivo");
else
fila = true;
path = "in/benchmarks/matriz_search/memory.txt";
inFile.open(path);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
int i = 0;
int value;
while (inFile >> value && i < 500)
{
memory.Set(i, std::to_string(value));
i++;
}
for (; i < 500; i++)
{
memory.Set(i, "0");
}
inFile.close();
}
path = "in/benchmarks/matriz_search/regs.txt";
inFile.open(path);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
auto reg_gui = reg.at(0);
int value, i = 0;
while (inFile >> value |
&& i < 32)
{
reg_gui.at(i).text(1, std::to_string(value));
i++;
}
for (; i < 32; i++)
reg_gui.at(i).text(1, "0");
inFile.close();
} });
bench_sub->append("Bubble Sort", [&](menu::item_proxy &ip)
{
string path = "in/benchmarks/bubble_sort/bubble_sort.txt";
bench_name = "bubble_sort";
inFile.open(path);
if (!add_instructions(inFile, instruction_queue, instruct))
show_message("Arquivo inválido", "Não foi possível abrir o arquivo");
else
fila = true;
path = "in/benchmarks/bubble_sort/memory.txt";
inFile.open(path);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
int i = 0;
int value;
while (inFile >> value && i < 500)
{
memory.Set(i, std::to_string(value));
i++;
}
for (; i < 500; i++)
{
memory.Set(i, "0");
}
inFile.close();
}
path = "in/benchmarks/bubble_sort/regs.txt";
inFile.open(path);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
auto reg_gui = reg.at(0);
int value, i = 0;
while (inFile >> value && i < 32)
{
reg_gui.at(i).text(1, std::to_string(value));
i++;
}
for (; i < 32; i++)
reg_gui.at(i).text(1, "0");
inFile.close();
} });
bench_sub->append("Insertion Sort", [&](menu::item_proxy &ip)
{
string path = "in/benchmarks/insertion_sort/insertion_sort.txt";
bench_name = "insertion_sort";
inFile.open(path);
if (!add_instructions(inFile, instruction_queue, instruct))
show_message("Arquivo inválido", "Não foi possível abrir o arquivo");
else
fila = true;
path = "in/benchmarks/insertion_sort/memory.txt";
inFile.open(path);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
int i = 0;
int value;
while (inFile >> value && i < 500)
{
memory.Set(i, std::to_string(value));
i++;
}
for (; i < 500; i++)
{
memory.Set(i, "0");
}
inFile.close();
}
path = "in/benchmarks/insertion_sort/regs.txt";
inFile.open(path);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
auto reg_gui = reg.at(0);
int value, i = 0;
while (inFile >> value && i < 32)
{
reg_gui.at(i).text(1, std::to_string(value));
i++;
}
for (; i < 32; i++)
reg_gui.at(i).text(1, "0");
inFile.close();
} });
bench_sub->append("Tick Tack", [&](menu::item_proxy &ip)
{
string path = "in/benchmarks/tick_tack/tick_tack.txt";
bench_name = "tick_tack";
inFile.open(path);
if (!add_instructions(inFile, instruction_queue, instruct))
show_message("Arquivo inválido", "Não foi possível abrir o arquivo");
else
fila = true;
path = "in/benchmarks/tick_tack/regs.txt";
inFile.open(path);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
auto reg_gui = reg.at(0);
int value, i = 0;
while (inFile >> value && i < 32)
{
reg_gui.at(i).text(1, std::to_string(value));
i++;
}
for (; i < 32; i++)
reg_gui.at(i).text(1, "0");
inFile.close();
} });
bench_sub->append("Double Interaction", [&](menu::item_proxy &ip)
{
string path = "in/benchmarks/double_interaction/double_interaction.txt";
bench_name = "double_interaction";
inFile.open(path);
if (!add_instructions(inFile, instruction_queue, instruct))
show_message("Arquivo inválido", "Não foi possível abrir o arquivo");
else
fila = true; });
bench_sub->append("Linear Search Extended", [&](menu::item_proxy &ip)
{
string path = "in/benchmarks/linear_search_extended/linear_search_extended.txt";
bench_name = "linear_search_extended";
inFile.open(path);
if (!add_instructions(inFile, instruction_queue, instruct))
show_message("Arquivo inválido", "Não foi possível abrir o arquivo");
else
fila = true; });
bench_sub->append("Log Calc", [&](menu::item_proxy &ip)
{
string path = "in/benchmarks/log_calc/log_calc.txt";
bench_name = "log_calc";
inFile.open(path);
if (!add_instructions(inFile, instruction_queue, instruct))
show_message("Arquivo inválido", "Não foi possível abrir o arquivo");
else
fila = true; });
bench_sub->append("Simple Loop", [&](menu::item_proxy &ip)
{
string path = "in/benchmarks/simple_loop/simple_loop.txt";
bench_name = "simple_loop";
inFile.open(path);
if (!add_instructions(inFile, instruction_queue, instruct))
show_message("Arquivo inválido", "Não foi possível abrir o arquivo");
else
fila = true; });
vector<string> columns = {"#", "Name", "Busy", "Op", "Vj", "Vk", "Qj", "Qk", "A"};
for (unsigned int i = 0; i < columns.size(); i++)
{
table.append_header(columns[i].c_str());
if (i && i != 3)
table.column_at(i).width(45);
else if (i == 3)
table.column_at(i).width(60);
else
table.column_at(i).width(30);
}
columns = {"", "Value", "Qi"};
sizes = {30, 75, 40};
for (unsigned int k = 0; k < 2; k++)
for (unsigned int i = 0; i < columns.size(); i++)
{
reg.append_header(columns[i]);
reg.column_at(k * columns.size() + i).width(sizes[i]);
}
auto reg_gui = reg.at(0);
for (int i = 0; i < 32; i++)
{
string index = std::to_string(i);
reg_gui.append("R" + index);
reg_gui.at(i).text(3, "F" + index);
}
columns = {"Instruction", "Issue", "Execute", "Write Result"};
sizes = {140, 60, 70, 95};
for (unsigned int i = 0; i < columns.size(); i++)
{
instruct.append_header(columns[i]);
instruct.column_at(i).width(sizes[i]);
}
columns = {"Entry", "Busy", "Instruction", "State", "Destination", "Value"};
sizes = {45, 45, 120, 120, 90, 60};
for (unsigned int i = 0; i < columns.size(); i++)
{
rob.append_header(columns[i]);
rob.column_at(i).width(sizes[i]);
}
srand(static_cast<unsigned>(time(0)));
for (int i = 0; i < 32; i++)
{
if (i)
reg_gui.at(i).text(1, std::to_string(rand() % 100));
else
reg_gui.at(i).text(1, std::to_string(0));
reg_gui.at(i).text(2, "0");
reg_gui.at(i).text(4, std::to_string(static_cast<float>(rand()) / static_cast<float>(RAND_MAX / 100.0)));
reg_gui.at(i).text(5, "0");
}
for (int i = 0; i < 500; i++)
memory.Push(std::to_string(rand() % 100));
for (int k = 1; k < argc; k += 2)
{
int i;
if (strlen(argv[k]) > 2)
show_message("Opção inválida", string("Opção \"") + string(argv[k]) + string("\" inválida"));
else
{
char c = argv[k][1];
switch (c)
{
case 'q':
inFile.open(argv[k + 1]);
if (!add_instructions(inFile, instruction_queue, instruct))
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
fila = true;
break;
case 'i':
inFile.open(argv[k + 1]);
int value;
i = 0;
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
while (inFile >> value && i < 32)
{
reg_gui.at(i).text(1, std::to_string(value));
i++;
}
for (; i < 32; i++)
reg_gui.at(i).text(1, "0");
inFile.close();
}
break;
case 'f':
float value_fp;
i = 0;
inFile.open(argv[k + 1]);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
while (inFile >> value_fp && i < 32)
{
reg_gui.at(i).text(4, std::to_string(value_fp));
i++;
}
for (; i < 32; i++)
reg_gui.at(i).text(4, "0");
inFile.close();
}
break;
case 'm':
inFile.open(argv[k + 1]);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
int value;
i = 0;
while (inFile >> value && i < 500)
{
memory.Set(i, std::to_string(value));
i++;
}
for (; i < 500; i++)
{
memory.Set(i, "0");
}
inFile.close();
}
break;
case 'r':
inFile.open(argv[k + 1]);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
int value;
if (inFile >> value && value <= 10 && value > 0)
nadd = value;
if (inFile >> value && value <= 10 && value > 0)
nmul = value;
if (inFile >> value && value <= 10 && value > 0)
nls = value;
inFile.close();
}
break;
case 's':
spec = true;
set_spec(plc, spec);
// spec_ip.checked(true);
k--;
break;
case 'l':
inFile.open(argv[k + 1]);
if (!inFile.is_open())
show_message("Arquivo inválido", "Não foi possível abrir o arquivo!");
else
{
string inst;
int value;
while (inFile >> inst)
{
if (inFile >> value && instruct_time.count(inst))
instruct_time[inst] = value;
}
}
inFile.close();
break;
default:
show_message("Opção inválida", string("Opção \"") + string(argv[k]) + string("\" inválida"));
break;
}
}
}
clock_control.enabled(false);
run_all.enabled(false);
start.events().click([&]
{
if (fila)
{
start.enabled(false);
clock_control.enabled(true);
run_all.enabled(true);
// Desativa os menus apos inicio da execucao
op.enabled(0, false);
op.enabled(1, false);
op.enabled(3, false);
for (int i = 0; i < 2; i++)
spec_sub->enabled(i, false);
for (int i = 0; i < 8; i++)
sub->enabled(i, false);
for (int i = 0; i < 10; i++)
bench_sub->enabled(i, false);
if (spec)
{
// Flag mode setada pela escolha no menu
if (mode == 1)
top1.rob_mode(n_bits, nadd, nmul, nls, instruct_time, instruction_queue, table, memory, reg, instruct, clock_count, rob);
else if(mode == 3)
top1.rob_mode_mn(n_bits,nadd,nmul,nls,instruct_time,instruction_queue,table,memory,reg,instruct,clock_count,rob, m_size);
else if (mode == 2)
top1.rob_mode_bpb(n_bits, bpb_size, nadd, nmul, nls, instruct_time, instruction_queue, table, memory, reg, instruct, clock_count, rob);
}
else
top1.simple_mode(nadd, nmul, nls, instruct_time, instruction_queue, table, memory, reg, instruct, clock_count);
sc_start();
}
else
show_message("Fila de instruções vazia", "A fila de instruções está vazia. Insira um conjunto de instruções para iniciar."); });
clock_control.events().click([&]
{
if (top1.get_queue().queue_is_empty() && top1.get_rob().rob_is_empty())
return;
if (sc_is_running())
sc_start(); });
run_all.events().click([&]
{
// enquanto queue e rob nao estao vazios, roda ate o fim
while (!(top1.get_queue().queue_is_empty() && top1.get_rob().rob_is_empty()))
{
if (sc_is_running())
sc_start();
}
top1.metrics(cpu_freq, mode, bench_name, n_bits); });
exit.events().click([]
{
sc_stop();
API::exit(); });
fm.show();
exec();
return 0;
}
|
/*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
/*****************************************************************************
stage1.cpp -- This is the implementation file for the stage1 module.
Original Author: Amit Rao, Synopsys, Inc.
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
#include "systemc.h"
#include "stage1.h"
//Definition of addsub method
void stage1::addsub()
{
double a;
double b;
a = in1.read();
b = in2.read();
sum.write(a+b);
diff.write(a-b);
} // end of addsub method
|
/*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
/*****************************************************************************
stage1.cpp -- This is the implementation file for the stage1 module.
Original Author: Amit Rao, Synopsys, Inc.
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
#include "systemc.h"
#include "stage1.h"
//Definition of addsub method
void stage1::addsub()
{
double a;
double b;
a = in1.read();
b = in2.read();
sum.write(a+b);
diff.write(a-b);
} // end of addsub method
|
/*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
/*****************************************************************************
stage1.cpp -- This is the implementation file for the stage1 module.
Original Author: Amit Rao, Synopsys, Inc.
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
#include "systemc.h"
#include "stage1.h"
//Definition of addsub method
void stage1::addsub()
{
double a;
double b;
a = in1.read();
b = in2.read();
sum.write(a+b);
diff.write(a-b);
} // end of addsub method
|
/*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
/*****************************************************************************
stage1.cpp -- This is the implementation file for the stage1 module.
Original Author: Amit Rao, Synopsys, Inc.
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
#include "systemc.h"
#include "stage1.h"
//Definition of addsub method
void stage1::addsub()
{
double a;
double b;
a = in1.read();
b = in2.read();
sum.write(a+b);
diff.write(a-b);
} // end of addsub method
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "systemc.h"
#define SIZE_I_IN 4
#define SIZE_J_IN 4
SC_MODULE(matrix_multiplier) {
sc_in_clk clock;
sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN];
sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN];
sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN];
SC_CTOR(matrix_multiplier) {
SC_METHOD(multiplier);
sensitive << clock.pos();
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
sensitive << data_a_in[i][j];
sensitive << data_b_in[i][j];
}
}
}
void multiplier() {
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
data_out[i][j].write(data_a_in[i][j].read() * data_b_in[i][j].read());
}
}
}
};
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "systemc.h"
#define SIZE_I_IN 4
#define SIZE_J_IN 4
SC_MODULE(matrix_multiplier) {
sc_in_clk clock;
sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN];
sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN];
sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN];
SC_CTOR(matrix_multiplier) {
SC_METHOD(multiplier);
sensitive << clock.pos();
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
sensitive << data_a_in[i][j];
sensitive << data_b_in[i][j];
}
}
}
void multiplier() {
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
data_out[i][j].write(data_a_in[i][j].read() * data_b_in[i][j].read());
}
}
}
};
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "systemc.h"
#define SIZE_I_IN 4
#define SIZE_J_IN 4
SC_MODULE(matrix_multiplier) {
sc_in_clk clock;
sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN];
sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN];
sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN];
SC_CTOR(matrix_multiplier) {
SC_METHOD(multiplier);
sensitive << clock.pos();
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
sensitive << data_a_in[i][j];
sensitive << data_b_in[i][j];
}
}
}
void multiplier() {
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
data_out[i][j].write(data_a_in[i][j].read() * data_b_in[i][j].read());
}
}
}
};
|
///////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Peripheral-NTM for MPSoC //
// Neural Turing Machine for MPSoC //
// //
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2020-2024 by the author(s) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //
// THE SOFTWARE. //
// //
// ============================================================================= //
// Author(s): //
// Paco Reina Campo <[email protected]> //
// //
///////////////////////////////////////////////////////////////////////////////////
#include "systemc.h"
#define SIZE_I_IN 4
#define SIZE_J_IN 4
SC_MODULE(matrix_multiplier) {
sc_in_clk clock;
sc_in<sc_int<64>> data_a_in[SIZE_I_IN][SIZE_J_IN];
sc_in<sc_int<64>> data_b_in[SIZE_I_IN][SIZE_J_IN];
sc_out<sc_int<64>> data_out[SIZE_I_IN][SIZE_J_IN];
SC_CTOR(matrix_multiplier) {
SC_METHOD(multiplier);
sensitive << clock.pos();
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
sensitive << data_a_in[i][j];
sensitive << data_b_in[i][j];
}
}
}
void multiplier() {
for (int i = 0; i < SIZE_I_IN; i++) {
for (int j = 0; j < SIZE_J_IN; j++) {
data_out[i][j].write(data_a_in[i][j].read() * data_b_in[i][j].read());
}
}
}
};
|
// ================================================================
// NVDLA Open Source Project
//
// Copyright(c) 2016 - 2017 NVIDIA Corporation. Licensed under the
// NVDLA Open Hardware License; Check "LICENSE" which comes with
// this distribution for more information.
// ================================================================
// File Name: cdp_hls_wrapper.cpp
#include "log.h"
#include "ac_int.h"
#include "ac_channel.h"
#include "log.h"
#include <systemc.h>
#include "arnvdla.h"
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include "vlibs.h"
#include "cdp_hls_wrapper.h"
#pragma CTC SKIP
int half2single(void *target, void *source, int numel)
{
unsigned short *hp = (unsigned short *) source; // Type pun input as an unsigned 16-bit int
unsigned int *xp = (unsigned int *) target; // Type pun output as an unsigned 32-bit int
unsigned short h, hs, he, hm;
unsigned int xs, xe, xm;
int xes;
int e;
static int checkieee = 1; // Flag to check for IEEE754, Endian, and word size
double one = 1.0; // Used for checking IEEE754 floating point format
unsigned int *ip; // Used for checking IEEE754 floating point format
if( checkieee ) { // 1st call, so check for IEEE754, Endian, and word size
ip = (unsigned int *) &one;
if( *ip ) { // If Big Endian, then no adjustment
} else { // If Little Endian, then adjustment will be necessary
ip++;
}
if( *ip != 0x3FF00000u ) { // Check for exact IEEE 754 bit pattern of 1.0
return 1; // Floating point bit pattern is not IEEE 754
}
if( sizeof(short) != 2 || sizeof(int) != 4 ) {
return 1; // short is not 16-bits, or long is not 32-bits.
}
checkieee = 0; // Everything checks out OK
}
if( source == NULL || target == NULL ) // Nothing to convert (e.g., imag part of pure real)
return 0;
while( numel-- ) {
h = *hp++;
if( (h & 0x7FFFu) == 0 ) { // Signed zero
*xp++ = ((unsigned int) h) << 16; // Return the signed zero
} else { // Not zero
hs = h & 0x8000u; // Pick off sign bit
he = h & 0x7C00u; // Pick off exponent bits
hm = h & 0x03FFu; // Pick off mantissa bits
if( he == 0 ) { // Denormal will convert to normalized
e = -1; // The following loop figures out how much extra to adjust the exponent
do {
e++;
hm <<= 1;
} while( (hm & 0x0400u) == 0 ); // Shift until leading bit overflows into exponent bit
xs = ((unsigned int) hs) << 16; // Sign bit
xes = ((int) (he >> 10)) - 15 + 127 - e; // Exponent unbias the halfp, then bias the single
xe = (unsigned int) (xes << 23); // Exponent
xm = ((unsigned int) (hm & 0x03FFu)) << 13; // Mantissa
*xp++ = (xs | xe | xm); // Combine sign bit, exponent bits, and mantissa bits
} else if( he == 0x7C00u ) { // Inf or NaN (all the exponent bits are set)
if( hm == 0 ) { // If mantissa is zero ...
*xp++ = (((unsigned int) hs) << 16) | ((unsigned int) 0x7F800000u); // Signed Inf
} else {
*xp++ = (unsigned int) 0xFFC00000u; // NaN, only 1st mantissa bit set
}
} else { // Normalized number
xs = ((unsigned int) hs) << 16; // Sign bit
xes = ((int) (he >> 10)) - 15 + 127; // Exponent unbias the halfp, then bias the single
xe = (unsigned int) (xes << 23); // Exponent
xm = ((unsigned int) hm) << 13; // Mantissa
*xp++ = (xs | xe | xm); // Combine sign bit, exponent bits, and mantissa bits
}
}
}
return 0;
}
int single2half(void *target, void *source, int numel)
{
unsigned short *hp = (unsigned short *) target; // Type pun output as an unsigned 16-bit int
unsigned int *xp = (unsigned int *) source; // Type pun input as an unsigned 32-bit int
unsigned short hs, he, hm;
unsigned int x, xs, xe, xm;
int hes;
static int checkieee = 1; // Flag to check for IEEE754, Endian, and word size
double one = 1.0; // Used for checking IEEE754 floating point format
unsigned int *ip; // Used for checking IEEE754 floating point format
if( checkieee ) { // 1st call, so check for IEEE754, Endian, and word size
ip = (unsigned int *) &one;
if( *ip ) { // If Big Endian, then no adjustment
} else { // If Little Endian, then adjustment will be necessary
ip++;
}
if( *ip != 0x3FF00000u ) { // Check for exact IEEE 754 bit pattern of 1.0
return 1; // Floating point bit pattern is not IEEE 754
}
if( sizeof(short) != 2 || sizeof(int) != 4 ) {
return 1; // short is not 16-bits, or long is not 32-bits.
}
checkieee = 0; // Everything checks out OK
}
if( source == NULL || target == NULL ) { // Nothing to convert (e.g., imag part of pure real)
return 0;
}
while( numel-- ) {
x = *xp++;
if( (x & 0x7FFFFFFFu) == 0 ) { // Signed zero
*hp++ = (unsigned short) (x >> 16); // Return the signed zero
} else { // Not zero
xs = x & 0x80000000u; // Pick off sign bit
xe = x & 0x7F800000u; // Pick off exponent bits
xm = x & 0x007FFFFFu; // Pick off mantissa bits
if( xe == 0 ) { // Denormal will underflow, return a signed zero
*hp++ = (unsigned short) (xs >> 16);
} else if( xe == 0x7F800000u ) { // Inf or NaN (all the exponent bits are set)
if( xm == 0 ) { // If mantissa is zero ...
*hp++ = (unsigned short) ((xs >> 16) | 0x7C00u); // Signed Inf
} else {
*hp++ = (unsigned short) 0xFE00u; // NaN, only 1st mantissa bit set
}
} else { // Normalized number
hs = (unsigned short) (xs >> 16); // Sign bit
hes = ((int)(xe >> 23)) - 127 + 15; // Exponent unbias the single, then bias the halfp
if( hes >= 0x1F ) { // Overflow
*hp++ = (unsigned short) ((xs >> 16) | 0x7C00u); // Signed Inf
} else if( hes <= 0 ) { // Underflow
if( (14 - hes) > 24 ) { // Mantissa shifted all the way off & no rounding possibility
hm = (unsigned short) 0u; // Set mantissa to zero
} else {
xm |= 0x00800000u; // Add the hidden leading bit
hm = (unsigned short) (xm >> (14 - hes)); // Mantissa
if( (xm >> (13 - hes)) & 0x00000001u ) // Check for rounding
hm += (unsigned short) 1u; // Round, might overflow into exp bit, but this is OK
}
*hp++ = (hs | hm); // Combine sign bit and mantissa bits, biased exponent is zero
} else {
he = (unsigned short) (hes << 10); // Exponent
hm = (unsigned short) (xm >> 13); // Mantissa
if( xm & 0x00001000u ) // Check for rounding
*hp++ = (hs | he | hm) + (unsigned short) 1u; // Round, might overflow to inf, this is OK
else
*hp++ = (hs | he | hm); // No rounding
}
}
}
}
return 0;
}
#pragma CTC ENDSKIP
// Inputs: 12 HLS_FP17 after icvt
// Outputs: 1 HLS_FP17 after Interplolation
void HLS_CDP_lookup_lut (
vFp32Type square_sum,
uint16_t lut_upper_index,
bool le, // True: linear_exp table
bool exp_mode, // Only for linear_exp table
int16_t* lut, // LUT table
uint64_t lut_start,
uint64_t lut_end,
int16_t slope_uflow_scale, // It's accutally signed value
int16_t slope_oflow_scale,
int16_t index_offset,
int8_t index_select,
// Outputs
bool & underflow,
bool & overflow,
bool & lut_hit,
ac_channel<vFp17Type> & chn_result_fp17)
{
#if !ASSERT_WAR_CONSTRAIN
// assert(density_end - pow(2, cdp_lut_lo_index_select_ + 8) == density_start);
#endif
// Variables for sub input_offset
vFp32Type lut_start_fp32, lut_end_fp32;
vFp32Type lut_sub_result_fp32;
ac_channel<vFp32Type> chn_square_sum_fp32;
ac_channel<vFp32Type> chn_lut_start_fp32, chn_lut_end_fp32;
ac_channel<vFp32Type> chn_lut_sub_result_fp32;
ac_channel<vFp17Type> chn_lut_sub_result_fp17;
float lut_sub_result_float;
float lut_shifted;
uint16_t lut_offset;
int32_t lut_index;
ac_channel<vFp17Type> chn_lut_offset_fp17;
// Varibales for underflow/overflow
vFp16Type slope_fp16;
ac_channel<vFp16Type> chn_slope_fp16;
ac_channel<vFp17Type> chn_slope_fp17;
ac_channel<vFp17Type> chn_lo_sub_result_fp17;
ac_channel<vFp17Type> chn_mul_result_fp17;
ac_channel<vFp17Type> chn_result_lut_underflow;
ac_channel<vFp17Type> chn_result_lut_overflow;
// Variables for Interpolation
uint16_t result_0, result_1;
vFp16Type result_0_fp16, result_1_fp16;
ac_channel<vFp16Type> chn_result_0_fp16, chn_result_1_fp16;
vFp32Type result_0_fp32, result_1_fp32;
ac_channel<vFp32Type> chn_result_0_fp32, chn_result_1_fp32;
ac_channel<vFp17Type> chn_result_0_fp17;
ac_channel<vFp17Type> chn_result_1_fp17;
// ac_channel<vFp17Type> chn_result_underflow_fp17;
// ac_channel<vFp17Type> chn_result_overflow_fp17;
ac_channel<vFp32Type> chn_L1_minus_L0_fp32;
ac_channel<vFp17Type> chn_L1_minus_L0_fp17;
ac_channel<vFp17Type> chn_result_lut_tmp;
//--------------------------------------------
underflow = false;
overflow = false;
//exp_underflow = false;
//exp_overflow = false;
lut_hit = false;
//--------------------------------------------
// 1. sub offset
lut_start_fp32 = lut_start;
chn_lut_start_fp32.write(lut_start_fp32);
chn_square_sum_fp32.write(square_sum);
HLS_fp32_sub(chn_square_sum_fp32, chn_lut_start_fp32, chn_lut_sub_result_fp32);
lut_sub_result_fp32 = chn_lut_sub_result_fp32.read();
lut_sub_result_float = *(float *)(&lut_sub_result_fp32); // vFp32Type is actually integer type
cslDebug((70, "lut_start=0x%x, lut_sub_result=0x%x\n", (uint32_t)lut_start_fp32, (uint32_t)lut_sub_result_fp32));
if(lut_sub_result_float <= 0 || std::isnan(lut_sub_result_float))
{
underflow = true;
}
if (!underflow) {
if (le && exp_mode) {
// Log2. If lo_sub_result_float is 0, exp will be 0
uint32_t tmp_uint32 = *(uint32_t*)(&lut_sub_result_float);
int32_t exp_raw = (tmp_uint32 >> 23) & 0xff; // 8bits
//int32_t exp = (exp_raw == 0)? 0 : exp_raw - 127;
int32_t exp = exp_raw - 127;
lut_index = exp - index_offset;
lut_offset = (tmp_uint32 >> 7) & 0xffff;
if(lut_index < 0)
{
lut_offset >>= -lut_index;
lut_index = 0;
underflow = true;
}
else if (lut_index >= lut_upper_index)
{
overflow = true;
}
cslDebug((70, "exp=%d, index_offset=%d, lut_index=%d, lut_offset=%d\n", exp, index_offset, lut_index, lut_offset));
}
else {
// lo or (le && linear_mode)
// To int and Shift using float of C++
// In RTL, HLS is not used in below code
if(index_select >= 0)
lut_shifted = lut_sub_result_float / pow(2, index_select);
else
lut_shifted = lut_sub_result_float * pow(2, -index_select);
overflow = lut_shifted >= lut_upper_index;
lut_index = lut_shifted;
lut_offset = (lut_shifted - int32_t(lut_shifted)) * 0x10000; // 16 MSB bits of fraction
cslDebug((70, "index_select=%d, lut_shifted=%f, lut_index=%d, lut_offset=%d\n", index_select, lut_shifted, lut_index, lut_offset));
}
}
// Convert Fraction from special INT16 to HLS_FP17
vU16Type lut_offset_u16 = lut_offset;
ac_channel<vU16Type> chn_lut_offset_u16;
chn_lut_offset_u16.write(lut_offset_u16);
HLS_uint16_to_fp17(chn_lut_offset_u16, chn_lut_offset_fp17);
//if ((underflow || (le&&exp_underflow))) {
if (underflow) {
result_0 = lut[0];
result_0_fp16 = result_0;
chn_result_0_fp16.write(result_0_fp16);
cslDebug((70, "L0=0x%x\n", result_0));
// Convert result_lo_0 of HLS FP16 to HLS_FP17
HLS_fp16_to_fp17(chn_result_0_fp16, chn_result_0_fp17);
slope_fp16 = (int16_t)slope_uflow_scale;
chn_slope_fp16.write(slope_fp16);
// Convert FP16 to HLS_FP17
HLS_fp16_to_fp17(chn_slope_fp16, chn_slope_fp17);
// Convert FP32 to HLS_FP17
if(le && exp_mode)
{
float offset;
#pragma CTC SKIP
if(index_offset <= -127)
{
offset = 0;
}
#pragma CTC ENDSKIP
else
{
offset = pow(2, index_offset);
}
ac_channel<vFp32Type> chn_offset, chn_offset_adj;
chn_offset.write(*(vFp32Type *)(&offset));
chn_lut_start_fp32.write(lut_start_fp32);
HLS_fp32_add(chn_lut_start_fp32, chn_offset, chn_offset_adj);
chn_square_sum_fp32.write(square_sum);
HLS_fp32_sub(chn_square_sum_fp32, chn_offset_adj, chn_lut_sub_result_fp32);
}
else
{
chn_lut_sub_result_fp32.write(lut_sub_result_fp32);
}
HLS_fp32_to_fp17(chn_lut_sub_result_fp32, chn_lut_sub_result_fp17);
// chn_gap * slope
HLS_fp17_mul(chn_lut_sub_result_fp17, chn_slope_fp17, chn_mul_result_fp17);
HLS_fp17_add(chn_mul_result_fp17, chn_result_0_fp17, chn_result_fp17);
}
//else if ((overflow || (le&&exp_overflow))) {
else if (overflow) {
result_1 = lut[lut_upper_index];
result_1_fp16 = result_1;
chn_result_1_fp16.write(result_1_fp16);
cslDebug((70, "L1=0x%x\n", result_1));
// Convert result_lo_0 of HLS FP16 to HLS_FP17
HLS_fp16_to_fp17(chn_result_1_fp16, chn_result_1_fp17);
slope_fp16 = (int16_t)slope_oflow_scale;
chn_slope_fp16.write(slope_fp16);
// Convert FP16 to HLS_FP17
HLS_fp16_to_fp17(chn_slope_fp16, chn_slope_fp17);
// Convert FP32 to HLS_FP17
lut_end_fp32 = lut_end;
chn_lut_end_fp32.write(lut_end_fp32);
chn_square_sum_fp32.write(square_sum);
HLS_fp32_sub(chn_square_sum_fp32, chn_lut_end_fp32, chn_lut_sub_result_fp32);
HLS_fp32_to_fp17(chn_lut_sub_result_fp32, chn_lut_sub_result_fp17);
// chn_gap * slope
HLS_fp17_mul(chn_lut_sub_result_fp17, chn_slope_fp17, chn_mul_result_fp17);
HLS_fp17_add(chn_mul_result_fp17, chn_result_1_fp17, chn_result_fp17);
}
else {
result_0 = lut[lut_index];
result_1 = lut[lut_index+1];
result_0_fp16 = result_0;
result_1_fp16 = result_1;
chn_result_0_fp16.write(result_0_fp16);
chn_result_1_fp16.write(result_1_fp16);
cslDebug((70, "L0=0x%x, L1=0x%x\n", result_0, result_1));
// Convert HLS_FP16 to HLS_FP32
HLS_fp16_to_fp32(chn_result_0_fp16, chn_result_0_fp32);
HLS_fp16_to_fp32(chn_result_1_fp16, chn_result_1_fp32);
// Convert result_lo_0 of HLS FP16 to HLS_FP17
chn_result_0_fp16.write(result_0_fp16);
HLS_fp16_to_fp17(chn_result_0_fp16, chn_result_0_fp17);
// Interpolation
HLS_fp32_sub(chn_result_1_fp32, chn_result_0_fp32, chn_L1_minus_L0_fp32);
//vFp32Type L1_minus_L0_fp32 = chn_L1_minus_L0_fp32.read();
//cslDebug((70,"L1_minus_L0_fp32=0x%x\n", L1_minus_L0_fp32));
//chn_L1_minus_L0_fp32.write(L1_minus_L0_fp32);
HLS_fp32_to_fp17(chn_L1_minus_L0_fp32, chn_L1_minus_L0_fp17);
HLS_fp17_mul(chn_L1_minus_L0_fp17, chn_lut_offset_fp17, chn_result_lut_tmp);
HLS_fp17_add(chn_result_lut_tmp, chn_result_0_fp17, chn_result_fp17);
lut_hit = true;
/*
float L0_float, L1_float, L1_minus_L0_float, result_float;
half2single(&L0_float,&result_0_fp16, 1);
cslDebug((70,"L0: %f(0x%x)\n", L0_float, *(int *)(&L0_float) ));
half2single(&L1_float,&result_1_fp16, 1);
cslDebug((70,"L1: %f(0x%x)\n", L1_float, *(int *)(&L1_float) ));
L1_minus_L0_float = L1_float - L0_float;
cslDebug((70,"L1-L1: %f(0x%x)\n", L1_minus_L0_float, *(int *)(&L1_minus_L0_float) ));
result_float = L0_float + L1_minus_L0_float * lut_offset;
cslDebug((70,"result: %f(0x%x)\n", result_float, *(int *)(&result_float) ));*/
}
}
void HLS_CDP_lookup_fp16 (
int16_t *data_in, // 12 * fp17
int16_t *le_lut,
int16_t *lo_lut,
// Configurations
uint16_t normalz_len,
uint16_t raw_method,
bool lut_uflow_priority,
bool lut_oflow_priority,
bool lut_hybrid_priority,
uint64_t le_start,
int16_t le_index_offset,
int8_t le_index_select,
uint64_t le_end,
uint64_t lo_start,
int8_t lo_index_select,
uint64_t lo_end,
uint16_t datin_offset,
uint16_t datin_scale,
uint8_t datin_shifter,
uint32_t datout_offset,
uint16_t datout_scale,
uint8_t datout_shifter,
int16_t le_slope_uflow_scale,
int16_t le_slope_oflow_scale,
int16_t lo_slope_uflow_scale,
int16_t lo_slope_oflow_scale,
bool sqsum_bypass,
bool mul_bypass,
int16_t *normalz_out,
uint32_t *lut_u_flow,
uint32_t *lut_o_flow,
uint32_t *lut_le_hit,
uint32_t *lut_lo_hit,
uint32_t *lut_hybrid_hit) // 16bits
{
int i;
// Outputs
bool le_underflow;
bool le_overflow;
//bool exp_underflow;
//bool exp_overflow;
bool lo_underflow;
bool lo_overflow;
bool le_hit;
bool lo_hit;
// Variables
int32_t icvt_data_out[12];
ac_channel<vFp32Type> fp17tofp32_out[12];
ac_channel<vFp32Type> square_array[12];
//ac_channel<vFp32Type> square_sum;
vFp32Type square_result[12];
// Outputs of lut tables
ac_channel<vFp17Type> chn_result_le_fp17;
ac_channel<vFp17Type> chn_result_lo_fp17;
// ac_channel<vFp17Type> chn_result_fp17;
ac_channel<vFp17Type> chn_result_to_ocvt_fp17;
ac_channel<vFp17Type> chn_ocvt_out_fp17;
#if 0
// Initialization
le_underflow = false;
le_overflow = false;
exp_underflow = false;
exp_overflow = false;
lo_underflow = false;
lo_overflow = false;
le_hit = false;
lo_hit = false;
#endif
vFp32Type icvt_data_out_fp32[12];
float tmp[12], din_offset, din_scale;
half2single(&din_offset, &datin_offset, 1);
half2single(&din_scale, &datin_scale, 1);
cslDebug((70, "Data before input converter(float)\n"));
for(i=0; i<12; i++)
{
half2single(&tmp[i], &data_in[i], 1);
cslDebug((70, "%f(0x%x) ", tmp[i], *(int *)(&tmp[i]) ));
}
cslDebug((70, "\n"));
cslDebug((70, "Data after square(float)\n"));
for(i=0; i<12; i++)
{
tmp[i] = tmp[i] * tmp[i];
cslDebug((70, "%f(0x%x) ", tmp[i], *(int *)(&tmp[i]) ));
}
cslDebug((70, "\n"));
for(i=0; i<12; i++) {
//***** Input Convertor (FP16->FP17) ******
cdp_icvt_hls(&data_in[i], datin_offset, datin_scale, datin_shifter, NVDLA_CDP_RDMA_D_DATA_FORMAT_0_INPUT_DATA_FP16, &icvt_data_out[i]);
|
//***** Convert FP17 to FP32 ******
ac_channel<vFp17Type> chn_a;
chn_a.write(icvt_data_out[i]);
HLS_fp17_to_fp32(chn_a, fp17tofp32_out[i]);
icvt_data_out_fp32[i] = fp17tofp32_out[i].read();
ac_channel<vFp32Type> chn_b, chn_c;
chn_b.write(icvt_data_out_fp32[i]);
chn_c.write(icvt_data_out_fp32[i]);
if(sqsum_bypass)
{
square_result[i] = icvt_data_out_fp32[i];
}
else
{
HLS_fp32_mul(chn_b, chn_c, square_array[i]); // HLS_FP32 mul
square_result[i] = square_array[i].read(); //keep data to re-write the square_array later
}
}
// cslDebug((70, "Data after input convertor(FP17):\n"));
// for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&icvt_data_out[i]) ));
// cslDebug((70, "\n"));
cslDebug((70, "Data after input convertor(FP32):\n"));
for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&icvt_data_out_fp32[i]) ));
cslDebug((70, "\n"));
cslDebug((70, "Data after square:\n"));
for(int i=0;i<12;i++) cslDebug((70,"%x ", *(int*)(&square_result[i]) ));
cslDebug((70, "\n"));
//***** Per Element ******
for (i=0; i<4; i++) {
le_underflow = false;
le_overflow = false;
//exp_underflow = false;
//exp_overflow = false;
lo_underflow = false;
lo_overflow = false;
le_hit = false;
lo_hit = false;
//re-write square_array in each iteration since it is empty after read
for(int j=0; j<12; j++) square_array[j].write(square_result[j]);
//***** Sum ******
vFp32Type square_sum_result;
if(sqsum_bypass)
{
square_sum_result = square_array[i+4].read();
}
else
{
ac_channel<vFp32Type> square_sum_1, square_sum_2;
HLS_fp32_add(square_array[i+3], square_array[i+5], square_sum_1); //3 + 5
HLS_fp32_add(square_sum_1, square_array[i+4], square_sum_2); //sum3 = (3 + 5) + 4
ac_channel<vFp32Type> square_sum_3, square_sum_4;
if(normalz_len > 0) //5+ elements
{
HLS_fp32_add(square_array[i+2], square_array[i+6], square_sum_3); //2 + 6
HLS_fp32_add(square_sum_2, square_sum_3, square_sum_4); //sum5 = sum3 + (2 + 6)
}
ac_channel<vFp32Type> square_sum_5, square_sum_6;
if(normalz_len > 1) //7+ elements
{
HLS_fp32_add(square_array[i+1], square_array[i+7], square_sum_5); //1 + 7
HLS_fp32_add(square_sum_4, square_sum_5, square_sum_6); //sum7 = sum5 + (1 + 7)
}
ac_channel<vFp32Type> square_sum_7, square_sum_8;
if(normalz_len > 2) //9 elements
{
HLS_fp32_add(square_array[i+0], square_array[i+8], square_sum_7); //1 + 7
HLS_fp32_add(square_sum_6, square_sum_7, square_sum_8); //sum9 = sum7 + (0 + 8)
}
switch(normalz_len)
{
case 0: square_sum_result = square_sum_2.read(); break;
case 1: square_sum_result = square_sum_4.read(); break;
case 2: square_sum_result = square_sum_6.read(); break;
case 3: square_sum_result = square_sum_8.read(); break;
#pragma CTC SKIP
default: break;
#pragma CTC ENDSKIP
}
}
cslDebug((70, "Square sum: %x\n", *(int *)(&square_sum_result) ));
// Look up Raw table
if(NVDLA_CDP_S_LUT_CFG_0_LUT_LE_FUNCTION_EXPONENT == raw_method) { //raw lut is exponential
cslDebug((70, "Lookup exp table\n"));
HLS_CDP_lookup_lut(square_sum_result, 64, true, true, le_lut, le_start, le_end, le_slope_uflow_scale, le_slope_oflow_scale, le_index_offset, le_index_select, le_underflow, le_overflow, le_hit, chn_result_le_fp17);
}
else { // raw lut is linear
cslDebug((70, "Lookup lin table\n"));
HLS_CDP_lookup_lut(square_sum_result, 64, true, false, le_lut, le_start, le_end, le_slope_uflow_scale, le_slope_oflow_scale, le_index_offset, le_index_select, le_underflow, le_overflow, le_hit, chn_result_le_fp17);
}
cslDebug((70, "Lookup lo table\n"));
// Look up LO(Linear Only) table
HLS_CDP_lookup_lut(square_sum_result, 256, false, false, lo_lut, lo_start, lo_end, lo_slope_uflow_scale, lo_slope_oflow_scale, 0, lo_index_select, lo_underflow, lo_overflow, lo_hit, chn_result_lo_fp17);
vFp17Type result_le = chn_result_le_fp17.read();
vFp17Type result_lo = chn_result_lo_fp17.read();
vFp17Type result_out;
// Select result between RAW table and Density Table
if(le_underflow && lo_underflow) {
result_out = lut_uflow_priority? result_lo : result_le;
(*lut_u_flow)++;
}
else if(le_overflow && lo_overflow) {
result_out = lut_oflow_priority? result_lo : result_le;
(*lut_o_flow)++;
}
else {
if(le_hit ^ lo_hit) {
result_out = le_hit? result_le : result_lo;
if(le_hit)
{
(*lut_le_hit)++;
}
else
{
(*lut_lo_hit)++;
}
}
else {
if(lut_hybrid_priority)
result_out = result_lo;
else
result_out = result_le;
(*lut_hybrid_hit)++;
}
}
cslDebug((70, "le:%x, lo:%x, out:%x\n" , *(int *)(&result_le), *(int *)(&result_lo), *(int *)(&result_out) ));
if(mul_bypass)
{
float icvt_data_out_float = *(float *)&icvt_data_out_fp32[i+4];
if(std::isnan(icvt_data_out_float))
{
chn_result_to_ocvt_fp17.write(icvt_data_out[i+4]);
}
else
{
chn_result_to_ocvt_fp17.write(result_out);
}
}
else
{
ac_channel<vFp17Type> chn_result_fp17, chn_icvt_data_out_fp17;
chn_result_fp17.write(result_out);
vFp17Type icvt_data_out_fp17 = icvt_data_out[i+4];
chn_icvt_data_out_fp17.write(icvt_data_out_fp17);
HLS_fp17_mul(chn_icvt_data_out_fp17, chn_result_fp17, chn_result_to_ocvt_fp17);
}
// Output Converter
int64_t ocvt_data_in = chn_result_to_ocvt_fp17.read();
cslDebug((70, "ocvt_data_in:%x\n", (int)ocvt_data_in));
uint8_t flag;
cdp_ocvt_hls(&ocvt_data_in, datout_offset, datout_scale, datout_shifter, NVDLA_CDP_RDMA_D_DATA_FORMAT_0_INPUT_DATA_FP16, &normalz_out[i], &flag);
}
}
|
/*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
/*****************************************************************************
main.cpp - This file instantiates all processes and ties them together
with signals.
Original Author: Rashmi Goswami, Synopsys, Inc.
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date:
Description of Modification:
*****************************************************************************/
#include "systemc.h"
#include "pkt.h"
#include "switch_clk.h"
#include "sender.h"
#include "receiver.h"
#include "switch.h"
int
sc_main(int, char *[])
{
sc_signal<pkt> pkt_in0;
sc_signal<pkt> pkt_in1;
sc_signal<pkt> pkt_in2;
sc_signal<pkt> pkt_in3;
sc_signal<pkt> pkt_out0;
sc_signal<pkt> pkt_out1;
sc_signal<pkt> pkt_out2;
sc_signal<pkt> pkt_out3;
sc_signal<sc_int<4> > id0, id1, id2, id3;
sc_signal<bool> switch_cntrl;
sc_clock clock1("CLOCK1", 75, SC_NS, 0.5, 0.0, SC_NS);
sc_clock clock2("CLOCK2", 30, SC_NS, 0.5, 10.0, SC_NS);
// Module instiatiations follow
// Note that modules can be connected by hooking up ports
// to signals by name or by using a positional notation
sender sender0("SENDER0");
// hooking up signals to ports by name
sender0.pkt_out(pkt_in0);
sender0.source_id(id0);
sender0.CLK(clock1);
sender sender1("SENDER1");
// hooking up signals to ports by position
sender1(pkt_in1, id1, clock1);
sender sender2("SENDER2");
// hooking up signals to ports by name
sender2.pkt_out(pkt_in2);
sender2.source_id(id2);
sender2.CLK(clock1);
sender sender3("SENDER3");
// hooking up signals to ports by position
sender3( pkt_in3, id3, clock1 );
switch_clk switch_clk1("SWITCH_CLK");
// hooking up signals to ports by name
switch_clk1.switch_cntrl(switch_cntrl);
switch_clk1.CLK(clock2);
mcast_pkt_switch switch1("SWITCH");
// hooking up signals to ports by name
switch1.switch_cntrl(switch_cntrl);
switch1.in0(pkt_in0);
switch1.in1(pkt_in1);
switch1.in2(pkt_in2);
switch1.in3(pkt_in3);
switch1.out0(pkt_out0);
switch1.out1(pkt_out1);
switch1.out2(pkt_out2);
switch1.out3(pkt_out3);
receiver receiver0("RECEIVER0");
// hooking up signals to ports by name
receiver0.pkt_in(pkt_out0);
receiver0.sink_id(id0);
receiver receiver1("RECEIVER1");
// hooking up signals to ports by position
receiver1( pkt_out1, id1 );
receiver receiver2("RECEIVER2");
// hooking up signals to ports by name
receiver2.pkt_in(pkt_out2);
receiver2.sink_id(id2);
receiver receiver3("RECEIVER3");
// hooking up signals to ports by position
receiver3( pkt_out3, id3 );
sc_start(0, SC_NS);
#ifndef __SUNPRO_CC
id0.write(0);
id1.write(1);
id2.write(2);
id3.write(3);
#else
// you cannot do that with SC5.0
// since it doesn't support member templates
id0.write(sc_int<4>(0));
id0.write(sc_int<4>(1));
id0.write(sc_int<4>(2));
id0.write(sc_int<4>(3));
#endif
sc_start();
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.