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_output_v_trainer_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/***************************************************************************** The following code is derived, directly or indirectly, from the SystemC source code Copyright (c) 1996-2014 by all Contributors. All Rights reserved. The contents of this file are subject to the restrictions and limitations set forth in the SystemC Open Source License (the "License"); You may not use this file except in compliance with such restrictions and limitations. You may obtain instructions on how to receive a copy of the License at http://www.accellera.org/. Software distributed by Contributors under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. *****************************************************************************/ /***************************************************************************** stage3.cpp -- This is the implementation file for the stage3 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 <math.h> #include "systemc.h" #include "stage3.h" //Definition of power method void stage3::power() { double a; double b; double c; a = prod.read(); b = quot.read(); c = (a>0 && b>0)? pow(a, b) : 0.; powr.write(c); } // end of power method
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "ntm_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; }
#include <systemc.h> #include "main.h" /********************** * Function: setup() * * Main setup. Does nothing. Used mainly for compatabvility with the SystemC * model. */ void setup() { } /********************** * Function: loop() * * Calls the firmware. Then it stops simulations. */ void loop() { app_main(); sc_stop(); }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // 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 "dnc_usage_vector_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "dnc_usage_vector_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "dnc_usage_vector_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // Peripheral-NTM for MPSoC // // Neural Turing Machine for MPSoC // // // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // // // Copyright (c) 2020-2024 by the author(s) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // // ============================================================================= // // Author(s): // // Paco Reina Campo <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////////// #include "dnc_usage_vector_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { adder adder("ADDER"); sc_signal<int> Ain; sc_signal<int> Bin; sc_signal<bool> clock; sc_signal<int> out; adder(clock, Ain, Bin, out); Ain = 1; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; Ain = 2; Bin = 2; clock = 0; sc_start(1, SC_NS); clock = 1; sc_start(1, SC_NS); cout << "@" << sc_time_stamp() << ": A + B = " << out.read() << endl; return 0; }
/***************************************************************************** The following code is derived, directly or indirectly, from the SystemC source code Copyright (c) 1996-2014 by all Contributors. All Rights reserved. The contents of this file are subject to the restrictions and limitations set forth in the SystemC Open Source License (the "License"); You may not use this file except in compliance with such restrictions and limitations. You may obtain instructions on how to receive a copy of the License at http://www.accellera.org/. Software distributed by Contributors under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. *****************************************************************************/ /***************************************************************************** bios.cpp -- System Bios. 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 "bios.h" #include "directive.h" void bios::entry() { unsigned address; while (true) { do { wait(); } while ( !(cs == true) ); address = addr.read(); if (address < BOOT_LENGTH) { // in BOOTING STAGE if (we.read() == true) { // Write operation wait(wait_cycles-1); imemory[address] = datain.read(); } else { // Read operation if (wait_cycles > 2) wait(wait_cycles-2); // Introduce delay needed dataout.write(imemory[address]); if (PRINT_BIOS) { printf("------------------------\n"); printf("BIOS: fetching mem[%d]\n", address); printf("BIOS: (%0x)", imemory[address]); cout.setf(ios::dec,ios::basefield); cout << " at CSIM " << sc_time_stamp() << endl; printf("------------------------\n"); } bios_valid.write(true); wait(); bios_valid.write(false); wait(); } } else { bios_valid.write(false); wait(); } } } // end of entry function
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // 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; }
/* ============================================================================ Name : displayYUV.c Author : mpelcat & kdesnos & jheulot Modified by : jserot (for use in the HoCL framework) Version : Copyright : CECILL-C Description : Displaying YUV frames one next to another in a row ============================================================================ */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "yuvDisplay.h" //#include "clock.h" #include <SDL.h> #include <SDL_ttf.h> #ifdef SYSTEMC_TARGET #include <systemc.h> #endif //#define FPS_MEAN 49 int quitViewer = 0; /** * Structure representing one display */ typedef struct YuvDisplay { SDL_Texture* textures[NB_DISPLAY]; // One overlay per frame SDL_Window *screen; // SDL surface where to display SDL_Renderer *renderer; TTF_Font *text_font; int currentXMin; // Position for next display int initialized; // Initialization done ? int stampId; int frameCnt; } YuvDisplay; // Initialize static YuvDisplay display; int exitCallBack(void* userdata, SDL_Event* event){ if (event->type == SDL_QUIT){ printf("Exit request from GUI.\n"); #ifdef SYSTEMC_TARGET sc_stop(); #else quitViewer = 1; #endif return 0; } return 1; } /** * Initializes a display frame. Be careful, once a window size has been chosen, * all videos must share the same window size * * @param id display unique identifier * @param width width * @param height heigth */ void yuvDisplayInit(int id, int width, int height) { if (display.initialized == 0) { display.currentXMin = 0; } if (height > DISPLAY_H) { fprintf(stderr, "SDL screen is not high enough for display %d.\n", id); exit(1); } else if (id >= NB_DISPLAY) { fprintf(stderr, "The number of displays is limited to %d.\n", NB_DISPLAY); exit(1); } else if (display.currentXMin + width > DISPLAY_W) { fprintf(stderr, "The number is not wide enough for display %d.\n", NB_DISPLAY); exit(1); } #ifdef VERBOSE printf("SDL screen height OK, width OK, number of displays OK.\n"); #endif if (display.initialized == 0) { // Generating window name char* name = "Display"; display.initialized = 1; printf("SDL_Init_Start\n"); if (SDL_Init(SDL_INIT_VIDEO)) { fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError()); exit(1); } printf("SDL_Init_end\n"); /* Initialize SDL TTF for text display */ if (TTF_Init()) { printf("TTF initialization failed: %s\n", TTF_GetError()); } printf("TTF_Init\n"); /* Initialize Font for text display */ display.text_font = TTF_OpenFont(PATH_TTF, 20); if (!display.text_font) { printf("TTF_OpenFont: %s\n", TTF_GetError()); } display.screen = SDL_CreateWindow(name, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, DISPLAY_W, DISPLAY_H, SDL_WINDOW_SHOWN); if (!display.screen) { fprintf(stderr, "SDL: could not set video mode - exiting\n"); exit(1); } display.renderer = SDL_CreateRenderer(display.screen, -1, SDL_RENDERER_ACCELERATED); if (!display.renderer) { fprintf(stderr, "SDL: could not create renderer - exiting\n"); exit(1); } } if (display.textures[id] == NULL) { display.textures[id] = SDL_CreateTexture(display.renderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING, width, height); if (!display.textures[id]) { fprintf(stderr, "SDL: could not create texture - exiting\n"); exit(1); } display.currentXMin += width; } display.stampId = 0; display.frameCnt = 0; /* for (int i = 0; i<FPS_MEAN; i++){ */ /* startTiming(i + 1); */ /* } */ SDL_SetEventFilter(exitCallBack, NULL); printf("yuvDisplayInit done\n"); } void yuvDisplay(int id, int width, int height, unsigned char *y, unsigned char *u, unsigned char *v){ yuvDisplayWithNbSlice(id, -1, y, u, v); display.frameCnt++; } void yuvDisplayWithNbSlice(int id, int nbSlice, unsigned char *y, unsigned char *u, unsigned char *v) { SDL_Texture* texture = display.textures[id]; int w, h; // Retrieve texture attribute SDL_QueryTexture(texture, NULL, NULL, &w, &h); SDL_UpdateYUVTexture( texture, NULL, y, w, u, w / 2, v, w / 2 ); SDL_Rect screen_rect; screen_rect.w = w; screen_rect.h = h; screen_rect.x = w*id; screen_rect.y = 0; SDL_RenderCopy(display.renderer, texture, NULL, &screen_rect); SDL_Color colorWhite = { 255, 255, 255, 255 }; /* /\* Draw FPS text *\/ */ /* char fps_text[20]; */ /* int time = stopTiming(display.stampId + 1); */ /* sprintf(fps_text, "FPS: %.2f", 1. / (time / 1000000. / FPS_MEAN)); */ /* startTiming(display.stampId + 1); */ /* display.stampId = (display.stampId + 1) % FPS_MEAN; */ /* SDL_Surface* fpsText = TTF_RenderText_Blended(display.text_font, fps_text, colorWhite); */ /* SDL_Texture* fpsTexture = SDL_CreateTextureFromSurface(display.renderer, fpsText); */ /* int fpsWidth, fpsHeight; */ /* SDL_QueryTexture(fpsTexture, NULL, NULL, &fpsWidth, &fpsHeight); */ /* SDL_Rect fpsTextRect; */ /* fpsTextRect.x = 0; */ /* fpsTextRect.y = 0; */ /* fpsTextRect.w = fpsWidth; */ /* fpsTextRect.h = fpsHeight; */ /* SDL_RenderCopy(display.renderer, fpsTexture, NULL, &fpsTextRect); */ /* /\* Free resources *\/ */ /* SDL_FreeSurface(fpsText); */ /* SDL_DestroyTexture(fpsTexture); */ /* Draw frame cnt Text */ char frame_text[20]; sprintf(frame_text, "frame #%4d", display.frameCnt); SDL_Surface* frameText = TTF_RenderText_Blended(display.text_font, frame_text, colorWhite); SDL_Texture* frameTexture = SDL_CreateTextureFromSurface(display.renderer, frameText); int frameWidth, frameHeight; SDL_QueryTexture(frameTexture, NULL, NULL, &frameWidth, &frameHeight); SDL_Rect frameTextRect; frameTextRect.x = 0; frameTextRect.y = 0; frameTextRect.w = frameWidth; frameTextRect.h = frameHeight; SDL_RenderCopy(display.renderer, frameTexture, NULL, &frameTextRect); /* Free resources */ SDL_FreeSurface(frameText); SDL_DestroyTexture(frameTexture); SDL_RenderPresent(display.renderer); SDL_Event event; // Grab all the events off the queue. while (SDL_PollEvent(&event)) { // printf("Goto SDL event %d\n", event.type); switch (event.type) { default: break; } } } void yuvFinalize(int id) { SDL_DestroyTexture(display.textures[id]); SDL_DestroyRenderer(display.renderer); SDL_DestroyWindow(display.screen); }
// BEGIN engine.cpp ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // $Copyright: (c)2003-2006 Eklectically, Inc. $ // $License: May be used under the same terms as SystemC library. $ #include <systemc.h> #include <iomanip> //-------------------------------------------------------------------- // This SystemC code is designed to illustrate the operation of // the SystemC simulation kernel. This is the BASIC uninstrumented // code shown in the presentation. See engine+.cpp for an example // that has hooks to show activity as the design simulates. //-------------------------------------------------------------------- SC_MODULE(M) { sc_in<bool> ckp; sc_out<int> s1p; sc_signal<int> s2; sc_event e1, e2; void P1_meth(void); void P3_thrd(void); void P2_thrd(void); SC_CTOR(M):count(0),temp(9) { cout << "T-5:---- Elaborating (CTOR Registering P3_thrd)" << std::endl; SC_THREAD(P3_thrd); cout << "T-4:---- Elaborating (CTOR Registering P2_thrd)" << std::endl; SC_THREAD(P2_thrd); sensitive << ckp.pos(); cout << "T-3:---- Elaborating (CTOR Registering P1_meth)" << std::endl; SC_METHOD(P1_meth); dont_initialize(); sensitive << s2; }//end SC_CTOR unsigned int count; private: int temp; };//end SC_MODULE void M::P1_meth(void) { temp = s2.read(); s1p->write(temp+1); e2.notify(2,SC_NS); } void M::P2_thrd(void) { A: s2.write(5); e1.notify();//immediate wait(); B: for (int i=7;i<9;i++){ s2.write(i); wait(1,SC_NS); C: e1.notify(SC_ZERO_TIME);//delta cycle wait();//static sensitive }//endfor } void M::P3_thrd(void) { D: while(true) { wait(e1|e2); E: cout << "NOTE " << sc_time_stamp() << std::endl; }//endwhile } // The purpose of sc_main() is to start up the simulation. This is // where the design is constructed during the "elaboration phase", // before simulation starts. int sc_main(int argc __attribute__((unused)),char *argv[] __attribute__((unused))) { cout << "T-6:---- MAIN Elaboration begins" << std::endl; cout << "T-6:---- MAIN Elaborating (constructing/binding)" << std::endl; sc_clock ck("ck",sc_time(6,SC_NS),0.5,sc_time(3,SC_NS)); sc_signal<int> s1; M m("m"); cout << "T-2:---- MAIN Elaborating (Connecting ck)" << std::endl; m.ckp(ck); cout << "T-1:---- MAIN Elaborating (Connecting s1)" << std::endl; m.s1p(s1); cout << "T_0:---- MAIN Elaboration finished" << std::endl; cout << "T_0:---- MAIN Starting simulation" << std::endl; // Begin simulation... sc_start(30,SC_NS); // Simulate for 30 nano-seconds // Simulation complete! cout << "T" << ++m.count << ":" << int(sc_time_stamp()/sc_time(1,SC_NS)) << "ns" << " MAIN Simulation stopped" << std::endl; return 0; }//end sc_main() // END engine.cpp ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // 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 "systemc.h" SC_MODULE(scalar_subtractor) { sc_in_clk clock; sc_in<int> data_a_in; sc_in<int> data_b_in; sc_out<int> data_out; SC_CTOR(scalar_subtractor) { SC_METHOD(subtractor); sensitive << clock.pos(); sensitive << data_a_in; sensitive << data_b_in; } void subtractor() { data_out.write(data_a_in.read() - data_b_in.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" SC_MODULE(scalar_subtractor) { sc_in_clk clock; sc_in<int> data_a_in; sc_in<int> data_b_in; sc_out<int> data_out; SC_CTOR(scalar_subtractor) { SC_METHOD(subtractor); sensitive << clock.pos(); sensitive << data_a_in; sensitive << data_b_in; } void subtractor() { data_out.write(data_a_in.read() - data_b_in.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" SC_MODULE(scalar_subtractor) { sc_in_clk clock; sc_in<int> data_a_in; sc_in<int> data_b_in; sc_out<int> data_out; SC_CTOR(scalar_subtractor) { SC_METHOD(subtractor); sensitive << clock.pos(); sensitive << data_a_in; sensitive << data_b_in; } void subtractor() { data_out.write(data_a_in.read() - data_b_in.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" SC_MODULE(scalar_subtractor) { sc_in_clk clock; sc_in<int> data_a_in; sc_in<int> data_b_in; sc_out<int> data_out; SC_CTOR(scalar_subtractor) { SC_METHOD(subtractor); sensitive << clock.pos(); sensitive << data_a_in; sensitive << data_b_in; } void subtractor() { data_out.write(data_a_in.read() - data_b_in.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 #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; } } } } };
/** * Author: Anubhav Tomar * * Robot Navigation Testbench **/ #include<systemc.h> #include<SERVER.h> #include<ROBOT.h> #include<ENVIRONMENT.h> // template < > class _robotNavigation : public sc_module { public: /*Signals for Module Interconnections*/ // FIFO sc_fifo<int> _serverToRobot1 , _envToRobot1 , _robot1ToServer , _robotToEnv1; sc_fifo<int> _serverToRobot2 , _envToRobot2 , _robot2ToServer , _robotToEnv2; sc_fifo<int> _serverToRobot3 , _envToRobot3 , _robot3ToServer , _robotToEnv3; sc_fifo<int> _serverToRobot4 , _envToRobot4 , _robot4ToServer , _robotToEnv4; // Server sc_signal<bool> _enableServerToRobot1 , _enableServerToRobot2 , _enableServerToRobot3 , _enableServerToRobot4; // Robot sc_signal<bool> _enableFromServer , _enableFromEnv; // Environment sc_signal<bool> _clock , _enableEnvToRobot1 , _enableEnvToRobot2 , _enableEnvToRobot3 , _enableEnvToRobot4; /*Module Instantiation*/ _serverBlock* _s; _environmentBlock* _e; _robotBlock* _r1; _robotBlock* _r2; _robotBlock* _r3; _robotBlock* _r4; SC_HAS_PROCESS(_robotNavigation); _robotNavigation(sc_module_name name) : sc_module(name) { /** * Module Instances Created **/ _s = new _serverBlock ("_server_"); _e = new _environmentBlock ("_environment_"); _r1 = new _robotBlock ("_robot1_" , 1); _r2 = new _robotBlock ("_robot2_" , 2); _r3 = new _robotBlock ("_robot3_" , 3); _r4 = new _robotBlock ("_robot4_" , 4); /** * Server -> Robots **/ _s->_serverToRobot1(_serverToRobot1); _r1->_serverToRobot(_serverToRobot1); _s->_serverToRobot2(_serverToRobot2); _r2->_serverToRobot(_serverToRobot2); _s->_serverToRobot3(_serverToRobot3); _r3->_serverToRobot(_serverToRobot3); _s->_serverToRobot4(_serverToRobot4); _r4->_serverToRobot(_serverToRobot4); _s->_enableServerToRobot1(_enableServerToRobot1); _r1->_enableFromServer(_enableServerToRobot1); _s->_enableServerToRobot2(_enableServerToRobot2); _r2->_enableFromServer(_enableServerToRobot2); _s->_enableServerToRobot3(_enableServerToRobot3); _r3->_enableFromServer(_enableServerToRobot3); _s->_enableServerToRobot4(_enableServerToRobot4); _r4->_enableFromServer(_enableServerToRobot4); /** * Robot -> Server **/ _r1->_robotToServer(_robot1ToServer); _s->_robot1ToServer(_robot1ToServer); _r2->_robotToServer(_robot2ToServer); _s->_robot2ToServer(_robot2ToServer); _r3->_robotToServer(_robot3ToServer); _s->_robot3ToServer(_robot3ToServer); _r4->_robotToServer(_robot4ToServer); _s->_robot4ToServer(_robot4ToServer); /** * Environment -> Robots **/ _e->_envToRobot1(_envToRobot1); _r1->_envToRobot(_envToRobot1); _e->_envToRobot2(_envToRobot2); _r2->_envToRobot(_envToRobot2); _e->_envToRobot3(_envToRobot3); _r3->_envToRobot(_envToRobot3); _e->_envToRobot4(_envToRobot4); _r4->_envToRobot(_envToRobot4); _e->_enableEnvToRobot1(_enableEnvToRobot1); _r1->_enableFromEnv(_enableEnvToRobot1); _e->_enableEnvToRobot2(_enableEnvToRobot2); _r2->_enableFromEnv(_enableEnvToRobot2); _e->_enableEnvToRobot3(_enableEnvToRobot3); _r3->_enableFromEnv(_enableEnvToRobot3); _e->_enableEnvToRobot4(_enableEnvToRobot4); _r4->_enableFromEnv(_enableEnvToRobot4); /** * Robots -> Environment **/ _r1->_robotToEnv(_robotToEnv1); _e->_robot1ToEnv(_robotToEnv1); _r2->_robotToEnv(_robotToEnv2); _e->_robot2ToEnv(_robotToEnv2); _r3->_robotToEnv(_robotToEnv3); _e->_robot3ToEnv(_robotToEnv3); _r4->_robotToEnv(_robotToEnv4); _e->_robot4ToEnv(_robotToEnv4); /** * Clock -> Environment & Server **/ _e->_clock(_clock); _s->_clock(_clock); SC_THREAD(clockSignal); sc_fifo<int> _serverToRobot1 (50) , _envToRobot1 (50) , _robotToServer1 (50) , _robotToEnv1 (50); sc_fifo<int> _serverToRobot2 (50) , _envToRobot2 (50) , _robotToServer2 (50) , _robotToEnv2 (50); sc_fifo<int> _serverToRobot3 (50) , _envToRobot3 (50) , _robotToServer3 (50) , _robotToEnv3 (50); sc_fifo<int> _serverToRobot4 (50) , _envToRobot4 (50) , _robotToServer4 (50) , _robotToEnv4 (50); }; void clockSignal() { while (true){ wait(0.5 , SC_MS); _clock = false; wait(0.5 , SC_MS); _clock = true; } }; }; int sc_main(int argc , char* argv[]) { cout<<"@ "<<sc_time_stamp()<<"----------Start---------"<<endl<<endl<<endl; _robotNavigation _robotNav("_robotNavigation_"); cout<<"@ "<<sc_time_stamp()<<"----------Start Simulation---------"<<endl<<endl<<endl; sc_start(10000 , SC_MS); cout<<"@ "<<sc_time_stamp()<<"----------End Simulation---------"<<endl<<endl<<endl; return 0; }
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** simple_bus_main.cpp : sc_main Original Author: Ric Hilderink, Synopsys, Inc., 2001-10-11 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc.h" #include "simple_bus_test.h" int sc_main(int, char **) { simple_bus_test top("top"); sc_start(10000, SC_NS); return 0; }
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** simple_bus_main.cpp : sc_main Original Author: Ric Hilderink, Synopsys, Inc., 2001-10-11 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc.h" #include "simple_bus_test.h" int sc_main(int, char **) { simple_bus_test top("top"); sc_start(10000, SC_NS); return 0; }
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** simple_bus_main.cpp : sc_main Original Author: Ric Hilderink, Synopsys, Inc., 2001-10-11 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include "systemc.h" #include "simple_bus_test.h" int sc_main(int, char **) { simple_bus_test top("top"); sc_start(10000, SC_NS); return 0; }
/* * @ASCK */ #include <systemc.h> SC_MODULE (ID) { sc_in_clk clk; sc_in <sc_int<8>> prev_A; sc_in <sc_int<8>> prev_B; sc_in <sc_int<13>> prev_Imm; sc_in <sc_uint<3>> prev_Sa; sc_in <sc_uint<5>> prev_AluOp; sc_in <bool> prev_r; sc_in <bool> prev_w; sc_in <bool> prev_AluMux; sc_in <bool> prev_WbMux; sc_in <bool> prev_call; sc_in <bool> prev_regWrite; sc_in <sc_uint<3>> prev_rd; sc_out <sc_int<8>> next_A; sc_out <sc_int<8>> next_B; sc_out <sc_int<13>> next_Imm; sc_out <sc_uint<3>> next_Sa; sc_out <sc_uint<5>> next_AluOp; sc_out <bool> next_r; sc_out <bool> next_w; sc_out <bool> next_AluMux; sc_out <bool> next_WbMux; sc_out <bool> next_call; sc_out <bool> next_regWrite; sc_out <sc_uint<3>> next_rd; /* ** module global variables */ SC_CTOR (ID){ SC_THREAD (process); sensitive << clk.pos(); } void process () { while(true){ wait(); if(now_is_call){ wait(micro_acc_ev); } next_A.write(prev_A.read()); next_B.write(prev_B.read()); next_Imm.write(prev_Imm.read()); next_Sa.write(prev_Sa.read()); next_AluOp.write(prev_AluOp.read()); next_AluMux.write(prev_AluMux.read()); next_r.write(prev_r.read()); next_w.write(prev_w.read()); next_WbMux.write(prev_WbMux.read()); next_call.write(prev_call.read()); next_regWrite.write(prev_regWrite); next_rd.write(prev_rd.read()); } } };
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // 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_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; }
/***************************************************************************** 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 (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
/* * Copyright (C) 2020 GreenWaves Technologies, SAS, ETH Zurich and * University of Bologna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Authors: Germain Haugou, GreenWaves Technologies ([email protected]) */ #include <iostream> #include <sstream> #include <string> #include <stdio.h> #include <vp/vp.hpp> #include <stdio.h> #include "string.h" #include <iostream> #include <sstream> #include <string> #include <dlfcn.h> #include <algorithm> #include <string> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <poll.h> #include <signal.h> #include <regex> #include <gv/gvsoc_proxy.hpp> #include <gv/gvsoc.h> #include <sys/types.h> #include <unistd.h> #include <sys/prctl.h> #include <vp/time/time_scheduler.hpp> #include <vp/proxy.hpp> #include <vp/queue.hpp> #include <vp/signal.hpp> extern "C" long long int dpi_time_ps(); #ifdef __VP_USE_SYSTEMC #include <systemc.h> #endif #ifdef __VP_USE_SYSTEMV extern "C" void dpi_raise_event(); #endif char vp_error[VP_ERROR_SIZE]; static Gv_proxy *proxy = NULL; void vp::component::get_trace(std::vector<vp::trace *> &traces, std::string path) { if (this->get_path() != "" && path.find(this->get_path()) != 0) { return; } for (vp::component *component: this->get_childs()) { component->get_trace(traces, path); } for (auto x: this->traces.traces) { if (x.second->get_full_path().find(path) == 0) { traces.push_back(x.second); } } for (auto x: this->traces.trace_events) { if (x.second->get_full_path().find(path) == 0) { traces.push_back(x.second); } } } void vp::component::reg_step_pre_start(std::function<void()> callback) { this->pre_start_callbacks.push_back(callback); } void vp::component::register_build_callback(std::function<void()> callback) { this->build_callbacks.push_back(callback); } void vp::component::post_post_build() { traces.post_post_build(); } void vp::component::final_bind() { for (auto port : this->slave_ports) { port.second->final_bind(); } for (auto port : this->master_ports) { port.second->final_bind(); } for (auto &x : this->childs) { x->final_bind(); } } void vp::component::set_vp_config(js::config *config) { this->vp_config = config; } void vp::component::set_gv_conf(struct gv_conf *gv_conf) { if (gv_conf) { memcpy(&this->gv_conf, gv_conf, sizeof(struct gv_conf)); } else { memset(&this->gv_conf, 0, sizeof(struct gv_conf)); gv_init(&this->gv_conf); } } js::config *vp::component::get_vp_config() { if (this->vp_config == NULL) { if (this->parent != NULL) { this->vp_config = this->parent->get_vp_config(); } } vp_assert_always(this->vp_config != NULL, NULL, "No VP config found\n"); return this->vp_config; } void vp::component::load_all() { for (auto &x : this->childs) { x->load_all(); } this->load(); } int vp::component::build_new() { this->bind_comps(); this->post_post_build_all(); this->pre_start_all(); this->start_all(); this->final_bind(); return 0; } void vp::component::post_post_build_all() { for (auto &x : this->childs) { x->post_post_build_all(); } this->post_post_build(); } void vp::component::start_all() { for (auto &x : this->childs) { x->start_all(); } this->start(); } void vp::component::stop_all() { for (auto &x : this->childs) { x->stop_all(); } this->stop(); } void vp::component::flush_all() { for (auto &x : this->childs) { x->flush_all(); } this->flush(); } void vp::component::pre_start_all() { for (auto &x : this->childs) { x->pre_start_all(); } this->pre_start(); for (auto x : pre_start_callbacks) { x(); } } void vp::component_clock::clk_reg(component *_this, component *clock) { _this->clock = (clock_engine *)clock; for (auto &x : _this->childs) { x->clk_reg(x, clock); } } void vp::component::reset_all(bool active, bool from_itf) { // Small hack to not propagate the reset from top level if the reset has // already been done through the interface from another component. // This should be all implemented with interfaces to better control // the reset propagation. this->reset_done_from_itf |= from_itf; if (from_itf || !this->reset_done_from_itf) { this->get_trace()->msg("Reset\n"); this->pre_reset(); for (auto reg : this->regs) { reg->reset(active); } this->block::reset_all(active); if (active) { for (clock_event *event: this->events) { this->event_cancel(event); } } for (auto &x : this->childs) { x->reset_all(active); } } } void vp::component_clock::reset_sync(void *__this, bool active) { component *_this = (component *)__this; _this->reset_done_from_itf = true; _this->reset_all(active, true); } void vp::component_clock::pre_build(component *comp) { clock_port.set_reg_meth((vp::clk_reg_meth_t *)&component_clock::clk_reg); comp->new_slave_port("clock", &clock_port); reset_port.set_sync_meth(&component_clock::reset_sync); comp->new_slave_port("reset", &reset_port); comp->traces.new_trace("comp", comp->get_trace(), vp::DEBUG); comp->traces.new_trace("warning", &comp->warning, vp::WARNING); } int64_t vp::time_engine::get_next_event_time() { if (this->first_client) { return this->first_client->next_event_time; } return this->time; } bool vp::time_engine::dequeue(time_engine_client *client) { if (!client->is_enqueued) return false; client->is_enqueued = false; time_engine_client *current = this->first_client, *prev = NULL; while (current && current != client) { prev = current; current = current->next; } if (prev) prev->next = client->next; else this->first_client = client->next; return true; } bool vp::time_engine::enqueue(time_engine_client *client, int64_t time) { vp_assert(time >= 0, NULL, "Time must be positive\n"); int64_t full_time = this->get_time() + time; #ifdef __VP_USE_SYSTEMC // Notify to the engine that something has been pushed in case it is done // by an external systemC component and the engine needs to be waken up if (started) sync_event.notify(); #endif #ifdef __VP_USE_SYSTEMV dpi_raise_event(); #endif if (client->is_running()) return false; if (client->is_enqueued) { if (client->next_event_time <= full_time) return false; this->dequeue(client); } client->is_enqueued = true; time_engine_client *current = first_client, *prev = NULL; client->next_event_time = full_time; while (current && current->next_event_time < client->next_event_time) { prev = current; current = current->next; } if (prev) prev->next = client; else first_client = client; client->next = current; return true; } bool vp::clock_engine::dequeue_from_engine() { if (this->is_running() || !this->is_enqueued) return false; this->engine->dequeue(this); return true; } void vp::clock_engine::reenqueue_to_engine() { this->engine->enqueue(this, this->next_event_time); } void vp::clock_engine::apply_frequency(int frequency) { if (frequency > 0) { bool reenqueue = this->dequeue_from_engine(); int64_t period = this->period; this->freq = frequency; this->period = 1e12 / this->freq; if (reenqueue && period > 0) { int64_t cycles = (this->next_event_time - this->get_time()) / period; this->next_event_time = cycles * this->period; this->reenqueue_to_engine(); } else if (period == 0) { // Case where the clock engine was clock-gated // We need to reenqueue the engine in case it has pending events if (this->has_events()) { // Compute the time of the next event based on the new frequency this->next_event_time = (this->get_next_event()->get_cycle() - this->get_cycles()) * this->period; this->reenqueue_to_engine(); } } } else if (frequency == 0) { this->dequeue_from_engine(); this->period = 0; } } void vp::clock_engine::update() { if (this->period == 0) return; int64_t diff = this->get_time() - this->stop_time; #ifdef __VP_USE_SYSTEMC if ((int64_t)sc_time_stamp().to_double() > this->get_time()) diff = (int64_t)sc_time_stamp().to_double() - this->stop_time; engine->update((int64_t)sc_time_stamp().to_double()); #endif if (diff > 0) { int64_t cycles = (diff + this->period - 1) / this->period; this->stop_time += cycles * this->period; this->cycles += cycles; } } vp::clock_event *vp::clock_engine::enqueue_other(vp::clock_event *event, int64_t cycle) { // Slow case where the engine is not running or we must enqueue out of the // circular buffer. // First check if we have to enqueue it to the global time engine in case we // were not running. // Check if we can enqueue to the fast circular queue in case were not // running. bool can_enqueue_to_cycle = false; if (!this->is_running()) { //this->current_cycle = (this->get_cycles() + 1) & CLOCK_EVENT_QUEUE_MASK; //can_enqueue_to_cycle = this->current_cycle + cycle - 1 < CLOCK_EVENT_QUEUE_SIZE; } if (can_enqueue_to_cycle) { //this->current_cycle = (this->get_cycles() + cycle) & CLOCK_EVENT_QUEUE_MASK; this->enqueue_to_cycle(event, cycle - 1); if (this->period != 0) enqueue_to_engine(period); } else { this->must_flush_delayed_queue = true; if (this->period != 0) { enqueue_to_engine(cycle * period); } vp::clock_event *current = delayed_queue, *prev = NULL; int64_t full_cycle = cycle + get_cycles(); while (current && current->cycle < full_cycle) { prev = current; current = current->next; } if (prev) prev->next = event; else delayed_queue = event; event->next = current; event->cycle = full_cycle; } return event; } vp::clock_event *vp::clock_engine::get_next_event() { // There is no quick way of getting the next event. // We have to first check if there is an event in the circular buffer // and if not in the delayed queue if (this->nb_enqueued_to_cycle) { for (int i = 0; i < CLOCK_EVENT_QUEUE_SIZE; i++) { int cycle = (current_cycle + i) & CLOCK_EVENT_QUEUE_MASK; vp::clock_event *event = event_queue[cycle]; if (event) { return event; } } vp_assert(false, 0, "Didn't find any event in circular buffer while it is not empty\n"); } return this->delayed_queue; } void vp::clock_engine::cancel(vp::clock_event *event) { if (!event->is_enqueued()) return; // There is no way to know if the event is enqueued into the circular buffer // or in the delayed queue so first go through the delayed queue and if it is // not found, look in the circular buffer // First the delayed queue vp::clock_event *current = delayed_queue, *prev = NULL; while (current) { if (current == event) { if (prev) prev->next = event->next; else delayed_queue = event->next; goto end; } prev = current; current = current->next; } // Then in the circular buffer for (int i = 0; i < CLOCK_EVENT_QUEUE_SIZE; i++) { vp::clock_event *current = event_queue[i], *prev = NULL; while (current) { if (current == event) { if (prev) prev->next = event->next; else event_queue[i] = event->next; this->nb_enqueued_to_cycle--; goto end; } prev = current; current = current->next; } } vp_assert(0, NULL, "Didn't find event in any queue while canceling event\n"); end: event->enqueued = false; if (!this->has_events()) this->dequeue_from_engine(); } void vp::clock_engine::flush_delayed_queue() { clock_event *event = delayed_queue; this->must_flush_delayed_queue = false; while (event) { if (nb_enqueued_to_cycle == 0) cycles = event->cycle; uint64_t cycle_diff = event->cycle - get_cycles(); if (cycle_diff >= CLOCK_EVENT_QUEUE_SIZE) break; clock_event *next = event->next; enqueue_to_cycle(event, cycle_diff); event = next; delayed_queue = event; } } int64_t vp::clock_engine::exec() { vp_assert(this->has_events(), NULL, "Executing clock engine while it has no event\n"); vp_assert(this->get_next_event(), NULL, "Executing clock engine while it has no next event\n"); this->cycles_trace.event_real(this->cycles); // The clock engine has a circular buffer of events to be executed. // Events longer than the buffer as put temporarly in a queue. // Everytime we start again at the beginning of the buffer, we need // to check if events must be enqueued from the queue to the buffer // in case they fit the window. if (unlikely(this->must_flush_delayed_queue)) { this->flush_delayed_queue(); } vp_assert(this->get_next_event(), NULL, "Executing clock engine while it has no next event\n"); // Now take all events available at the current cycle and execute them all without returning // to the main engine to execute them faster. clock_event *current = event_queue[current_cycle]; while (likely(current != NULL)) { event_queue[current_cycle] = current->next; current->enqueued = false; nb_enqueued_to_cycle--; current->meth(current->_this, current); current = event_queue[current_cycle]; } // Now we need to tell the time engine when is the next event. // The most likely is that there is an event in the circular buffer, // in which case we just return the clock period, as we will go through // each element of the circular buffer, even if the next event is further in // the buffer. if (likely(nb_enqueued_to_cycle)) { cycles++; current_cycle = (current_cycle + 1) & CLOCK_EVENT_QUEUE_MASK; if (unlikely(current_cycle == 0)) this->must_flush_delayed_queue = true; return period; } else { // Otherwise if there is an event in the delayed queue, return the time // to this event. // In both cases, force the delayed queue flush so that the next event to be // executed is moved to the circular buffer. this->must_flush_delayed_queue = true; // Also remember the current time in order to resynchronize the clock engine // in case we enqueue and event from another engine. this->stop_time = this->get_time(); if (delayed_queue) { return (delayed_queue->cycle - get_cycles()) * period; } else { // In case there is no more event to execute, returns -1 to tell the time // engine we are done. return -1; } } } vp::clock_event::clock_event(component_clock *comp, clock_event_meth_t *meth) : comp(comp), _this((void *)static_cast<vp::component *>((vp::component_clock *)(comp))), meth(meth), enqueued(false) { comp->add_clock_event(this); } void vp::component_clock::add_clock_event(clock_event *event) { this->events.push_back(event); } vp::time_engine *vp::component::get_time_engine() { if (this->time_engine_ptr == NULL) { this->time_engine_ptr = (vp::time_engine*)this->get_service("time"); } return this->time_engine_ptr; } vp::master_port::master_port(vp::component *owner) : vp::port(owner) { } void vp::component::new_master_port(std::string name, vp::master_port *port) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New master port (name: %s, port: %p)\n", name.c_str(), port); port->set_owner(this); port->set_context(this); port->set_name(name); this->add_master_port(name, port); } void vp::component::new_master_port(void *comp, std::string name, vp::master_port *port) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New master port (name: %s, port: %p)\n", name.c_str(), port); port->set_owner(this); port->set_context(comp); port->set_name(name); this->add_master_port(name, port); } void vp::component::add_slave_port(std::string name, vp::slave_port *port) { vp_assert_always(port != NULL, this->get_trace(), "Adding NULL port\n"); //vp_assert_always(this->slave_ports[name] == NULL, this->get_trace(), "Adding already existing port\n"); this->slave_ports[name] = port; } void vp::component::add_master_port(std::string name, vp::master_port *port) { vp_assert_always(port != NULL, this->get_trace(), "Adding NULL port\n"); //vp_assert_always(this->master_ports[name] == NULL, this->get_trace(), "Adding already existing port\n"); this->master_ports[name] = port; } void vp::component::new_slave_port(std::string name, vp::slave_port *port) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New slave port (name: %s, port: %p)\n", name.c_str(), port); port->set_owner(this); port->set_context(this); port->set_name(name); this->add_slave_port(name, port); } void vp::component::new_slave_port(void *comp, std::string name, vp::slave_port *port) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New slave port (name: %s, port: %p)\n", name.c_str(), port); port->set_owner(this); port->set_context(comp); port->set_name(name); this->add_slave_port(name, port); } void vp::component::add_service(std::string name, void *service) { if (this->parent) this->parent->add_service(name, service); else if (all_services[name] == NULL) all_services[name] = service; } void vp::component::new_service(std::string name, void *service) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New service (name: %s, service: %p)\n", name.c_str(), service); if (this->parent) this->parent->add_service(name, service); all_services[name] = service; } void *vp::component::get_service(string name) { if (all_services[name]) return all_services[name]; if (this->parent) return this->parent->get_service(name); return NULL; } std::vector<std::string> split_name(const std:
:string &s, char delimiter) { std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(s); while (std::getline(tokenStream, token, delimiter)) { tokens.push_back(token); } return tokens; } vp::config *vp::config::create_config(jsmntok_t *tokens, int *_size) { jsmntok_t *current = tokens; config *config = NULL; switch (current->type) { case JSMN_PRIMITIVE: if (strcmp(current->str, "True") == 0 || strcmp(current->str, "False") == 0 || strcmp(current->str, "true") == 0 || strcmp(current->str, "false") == 0) { config = new config_bool(current); } else { config = new config_number(current); } current++; break; case JSMN_OBJECT: { int size; config = new config_object(current, &size); current += size; break; } case JSMN_ARRAY: { int size; config = new config_array(current, &size); current += size; break; } case JSMN_STRING: config = new config_string(current); current++; break; case JSMN_UNDEFINED: break; } if (_size) { *_size = current - tokens; } return config; } vp::config *vp::config_string::get_from_list(std::vector<std::string> name_list) { if (name_list.size() == 0) return this; return NULL; } vp::config *vp::config_number::get_from_list(std::vector<std::string> name_list) { if (name_list.size() == 0) return this; return NULL; } vp::config *vp::config_bool::get_from_list(std::vector<std::string> name_list) { if (name_list.size() == 0) return this; return NULL; } vp::config *vp::config_array::get_from_list(std::vector<std::string> name_list) { if (name_list.size() == 0) return this; return NULL; } vp::config *vp::config_object::get_from_list(std::vector<std::string> name_list) { if (name_list.size() == 0) return this; vp::config *result = NULL; std::string name; int name_pos = 0; for (auto &x : name_list) { if (x != "*" && x != "**") { name = x; break; } name_pos++; } for (auto &x : childs) { if (name == x.first) { result = x.second->get_from_list(std::vector<std::string>(name_list.begin() + name_pos + 1, name_list.begin() + name_list.size())); if (name_pos == 0 || result != NULL) return result; } else if (name_list[0] == "*") { result = x.second->get_from_list(std::vector<std::string>(name_list.begin() + 1, name_list.begin() + name_list.size())); if (result != NULL) return result; } else if (name_list[0] == "**") { result = x.second->get_from_list(name_list); if (result != NULL) return result; } } return result; } vp::config *vp::config_object::get(std::string name) { return get_from_list(split_name(name, '/')); } vp::config_string::config_string(jsmntok_t *tokens) { value = tokens->str; } vp::config_number::config_number(jsmntok_t *tokens) { value = atof(tokens->str); } vp::config_bool::config_bool(jsmntok_t *tokens) { value = strcmp(tokens->str, "True") == 0 || strcmp(tokens->str, "true") == 0; } vp::config_array::config_array(jsmntok_t *tokens, int *_size) { jsmntok_t *current = tokens; jsmntok_t *top = current++; for (int i = 0; i < top->size; i++) { int child_size; elems.push_back(create_config(current, &child_size)); current += child_size; } if (_size) { *_size = current - tokens; } } vp::config_object::config_object(jsmntok_t *tokens, int *_size) { jsmntok_t *current = tokens; jsmntok_t *t = current++; for (int i = 0; i < t->size; i++) { jsmntok_t *child_name = current++; int child_size; config *child_config = create_config(current, &child_size); current += child_size; if (child_config != NULL) { childs[child_name->str] = child_config; } } if (_size) { *_size = current - tokens; } } vp::config *vp::component::import_config(const char *config_string) { if (config_string == NULL) return NULL; jsmn_parser parser; jsmn_init(&parser); int nb_tokens = jsmn_parse(&parser, config_string, strlen(config_string), NULL, 0); jsmntok_t tokens[nb_tokens]; jsmn_init(&parser); nb_tokens = jsmn_parse(&parser, config_string, strlen(config_string), tokens, nb_tokens); char *str = strdup(config_string); for (int i = 0; i < nb_tokens; i++) { jsmntok_t *tok = &tokens[i]; tok->str = &str[tok->start]; str[tok->end] = 0; } return new vp::config_object(tokens); } void vp::component::conf(string name, string path, vp::component *parent) { this->name = name; this->parent = parent; this->path = path; if (parent != NULL) { parent->add_child(name, this); } } void vp::component::add_child(std::string name, vp::component *child) { this->childs.push_back(child); this->childs_dict[name] = child; } vp::component *vp::component::get_component(std::vector<std::string> path_list) { if (path_list.size() == 0) { return this; } std::string name = ""; unsigned int name_pos= 0; for (auto x: path_list) { if (x != "*" && x != "**") { name = x; break; } name_pos += 1; } for (auto x:this->childs) { vp::component *comp; if (name == x->get_name()) { comp = x->get_component({ path_list.begin() + name_pos + 1, path_list.end() }); } else if (path_list[0] == "**") { comp = x->get_component(path_list); } else if (path_list[0] == "*") { comp = x->get_component({ path_list.begin() + 1, path_list.end() }); } if (comp) { return comp; } } return NULL; } void vp::component::elab() { for (auto &x : this->childs) { x->elab(); } } void vp::component::new_reg_any(std::string name, vp::reg *reg, int bits, uint8_t *reset_val) { reg->init(this, name, bits, NULL, reset_val); this->regs.push_back(reg); } void vp::component::new_reg(std::string name, vp::reg_1 *reg, uint8_t reset_val, bool reset) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New register (name: %s, width: %d, reset_val: 0x%x, reset: %d)\n", name.c_str(), 1, reset_val, reset ); reg->init(this, name, reset ? (uint8_t *)&reset_val : NULL); this->regs.push_back(reg); } void vp::component::new_reg(std::string name, vp::reg_8 *reg, uint8_t reset_val, bool reset) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New register (name: %s, width: %d, reset_val: 0x%x, reset: %d)\n", name.c_str(), 8, reset_val, reset ); reg->init(this, name, reset ? (uint8_t *)&reset_val : NULL); this->regs.push_back(reg); } void vp::component::new_reg(std::string name, vp::reg_16 *reg, uint16_t reset_val, bool reset) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New register (name: %s, width: %d, reset_val: 0x%x, reset: %d)\n", name.c_str(), 16, reset_val, reset ); reg->init(this, name, reset ? (uint8_t *)&reset_val : NULL); this->regs.push_back(reg); } void vp::component::new_reg(std::string name, vp::reg_32 *reg, uint32_t reset_val, bool reset) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New register (name: %s, width: %d, reset_val: 0x%x, reset: %d)\n", name.c_str(), 32, reset_val, reset ); reg->init(this, name, reset ? (uint8_t *)&reset_val : NULL); this->regs.push_back(reg); } void vp::component::new_reg(std::string name, vp::reg_64 *reg, uint64_t reset_val, bool reset) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New register (name: %s, width: %d, reset_val: 0x%x, reset: %d)\n", name.c_str(), 64, reset_val, reset ); reg->init(this, name, reset ? (uint8_t *)&reset_val : NULL); this->regs.push_back(reg); } bool vp::reg::access_callback(uint64_t reg_offset, int size, uint8_t *value, bool is_write) { if (this->callback != NULL) this->callback(reg_offset, size, value, is_write); return this->callback != NULL; } void vp::reg::init(vp::component *top, std::string name, int bits, uint8_t *value, uint8_t *reset_value) { this->top = top; this->nb_bytes = (bits + 7) / 8; this->bits = bits; if (reset_value) this->reset_value_bytes = new uint8_t[this->nb_bytes]; else this->reset_value_bytes = NULL; if (value) this->value_bytes = value; else this->value_bytes = new uint8_t[this->nb_bytes]; this->name = name; if (reset_value) memcpy((void *)this->reset_value_bytes, (void *)reset_value, this->nb_bytes); top->traces.new_trace(name + "/trace", &this->trace, vp::TRACE); top->traces.new_trace_event(name, &this->reg_event, bits); } void vp::reg::reset(bool active) { if (active) { this->trace.msg("Resetting register\n"); if (this->reset_value_bytes) { memcpy((void *)this->value_bytes, (void *)this->reset_value_bytes, this->nb_bytes); } else { memset((void *)this->value_bytes, 0, this->nb_bytes); } if (this->reg_event.get_event_active()) { this->reg_event.event((uint8_t *)this->value_bytes); } } } void vp::reg_1::init(vp::component *top, std::string name, uint8_t *reset_val) { reg::init(top, name, 1, (uint8_t *)&this->value, reset_val); } void vp::reg_8::init(vp::component *top, std::string name, uint8_t *reset_val) { reg::init(top, name, 8, (uint8_t *)&this->value, reset_val); } void vp::reg_16::init(vp::component *top, std::string name, uint8_t *reset_val) { reg::init(top, name, 16, (uint8_t *)&this->value, reset_val); } void vp::reg_32::init(vp::component *top, std::string name, uint8_t *reset_val) { reg::init(top, name, 32, (uint8_t *)&this->value, reset_val); } void vp::reg_64::init(vp::component *top, std::string name, uint8_t *reset_val) { reg::init(top, name, 64, (uint8_t *)&this->value, reset_val); } void vp::reg_1::build(vp::component *top, std::string name) { top->new_reg(name, this, this->reset_val, this->do_reset); } void vp::reg_8::build(vp::component *top, std::string name) { top->new_reg(name, this, this->reset_val, this->do_reset); } void vp::reg_16::build(vp::component *top, std::string name) { top->new_reg(name, this, this->reset_val, this->do_reset); } void vp::reg_32::build(vp::component *top, std::string name) { top->new_reg(name, this, this->reset_val, this->do_reset); } void vp::reg_32::write(int reg_offset, int size, uint8_t *value) { uint8_t *dest = this->value_bytes+reg_offset; uint8_t *src = value; uint8_t *mask = ((uint8_t *)&this->write_mask) + reg_offset; for (int i=0; i<size; i++) { dest[i] = (dest[i] & ~mask[i]) | (src[i] & mask[i]); } this->dump_after_write(); if (this->reg_event.get_event_active()) { this->reg_event.event((uint8_t *)this->value_bytes); } } void vp::reg_64::build(vp::component *top, std::string name) { top->new_reg(name, this, this->reset_val, this->do_reset); } void vp::master_port::final_bind() { if (this->is_bound) { this->finalize(); } } void vp::slave_port::final_bind() { if (this->is_bound) this->finalize(); } extern "C" char *vp_get_error() { return vp_error; } extern "C" void vp_port_bind_to(void *_master, void *_slave, const char *config_str) { vp::master_port *master = (vp::master_port *)_master; vp::slave_port *slave = (vp::slave_port *)_slave; vp::config *config = NULL; if (config_str != NULL) { config = master->get_comp()->import_config(config_str); } master->bind_to(slave, config); slave->bind_to(master, config); } void vp::component::throw_error(std::string error) { throw std::invalid_argument("[\033[31m" + this->get_path() + "\033[0m] " + error); } void vp::component::build_instance(std::string name, vp::component *parent) { std::string comp_path = parent->get_path() != "" ? parent->get_path() + "/" + name : name == "" ? "" : "/" + name; this->conf(name, comp_path, parent); this->pre_pre_build(); this->pre_build(); this->build(); this->power.build(); for (auto x : build_callbacks) { x(); } } vp::component *vp::component::new_component(std::string name, js::config *config, std::string module_name) { if (module_name == "") { module_name = config->get_child_str("vp_component"); if (module_name == "") { module_name = "utils.composite_impl"; } } if (this->get_vp_config()->get_child_bool("sv-mode")) { module_name = "sv." + module_name; } else if (this->get_vp_config()->get_child_bool("debug-mode")) { module_name = "debug." + module_name; } this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "New component (name: %s, module: %s)\n", name.c_str(), module_name.c_str()); std::replace(module_name.begin(), module_name.end(), '.', '/'); std::string path = std::string(getenv("GVSOC_PATH")) + "/" + module_name + ".so"; void *module = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL | RTLD_DEEPBIND); if (module == NULL) { this->throw_error("ERROR, Failed to open periph model (module: " + module_name + ", error: " + std::string(dlerror()) + ")"); } vp::component *(*constructor)(js::config *) = (vp::component * (*)(js::config *)) dlsym(module, "vp_constructor"); if (constructor == NULL) { this->throw_error("ERROR, couldn't find vp_constructor in loaded module (module: " + module_name + ")"); } vp::component *instance = constructor(config); instance->build_instance(name, this); return instance; } vp::component::component(js::config *config) : block(NULL), traces(*this), power(*this), reset_done_from_itf(false) { this->comp_js_config = config; //this->conf(path, parent); } void vp::component::create_ports() { js::config *config = this->get_js_config(); js::config *ports = config->get("vp_ports"); if (ports == NULL) { ports = config->get("ports"); } if (ports != NULL) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating ports\n"); for (auto x : ports->get_elems()) { std::string port_name = x->get_str(); this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating port (name: %s)\n", port_name.c_str()); if (this->get_master_port(port_name) == NULL && this->get_slave_port(port_name) == NULL) this->add_master_port(port_name, new vp::virtual_port(this)); } } } void vp::component::create_bindings() { js::config *config = this->get_js_config(); js::config *bindings = config->get("vp_bindings"); if (bindings == NULL) { bindings = config->get("bindings"); } if (bindings != NULL) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating bindings\n"); for (auto x : bindings->get_elems()) { std::string master_binding = x->get_elem(0)->get_str(); std::string slave_binding = x->get_elem(1)->get_str(); int pos = master_binding.find_first_of("->"); std::string master_comp_name = master_binding.substr(0, pos); std::string master_port_name = master_binding.substr(pos + 2); pos = slave_binding.find_first_of("->"); std::string slave_comp_name = slave_binding.substr(0, pos); std::string slave_port_name = slave_binding.substr(pos + 2); this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating binding (%s:%s -> %s:%s)\n", master_comp_name.c_str(), master_port_name.c_str(), slave_comp_name.c_str(), slave_port_name.c_str() ); vp::component *master_comp = master_comp_name == "self" ? this : this->get_childs_dict()[master_comp_name]; vp::component *slave_comp = slave_comp_name == "self" ? this : this->get_childs_dict()[slave_comp_name]; vp_assert_always(master_comp != NULL, this->get_trace(), "Binding from invalid master\n"); vp_assert_always(slave_comp != NULL, this->get_trace(), "Binding from invalid slave\n"); vp::port *master_port = master_comp->get_master_port(master_port_name); vp::port *slave_port = slave_comp->get_slave_port(slave_port_name); vp_assert_always(master_port != NULL, this->get_trace(), "Binding from invalid master port\n"); vp_assert_always(slave_port != NULL, this->get_trace(), "Binding from invalid slave port\n"); master_port->bind_to_virtual(slave_port); } } } std::vector<vp::slave_port *> vp::slave_port::get_final_ports() { return { this }; } std::vector<vp::slave_port *> vp::master_port::get_final_ports() { std::vector<vp::slave_port *> result; for (auto x : this->slave_ports) { std::vector<vp::slave_port *> slave_ports = x->get_final_ports(); result.insert(result.end(), slave_ports.begin(), slave_ports.end()); } return result; } void vp::master_port::bind_to_slaves() { for (auto x : this->slave_ports) { for (auto y : x->get_final_ports()) { this->get_owner()->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating final binding (%s:%s -> %s:%s)\n", this->get_owner()->get_path().c_str(), this->get_name().c_str(), y->get_owner()->get_path().c_str(), y->get_name().c_str() ); this->bind_to(y, NULL); y->bind_to(this, NULL); } } } void vp::component::bind_comps() { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating final bindings\n"); for (auto x : this->get_childs()) { x->bind_comps(); } for (auto x : this->master_ports) { if (!x.second->is_virtual()) { x.second->bind_to_slaves(); } } } void *vp::component::external_bind(std::string comp_name, std::string itf_name, void *handle) { for (auto &x : this->childs) { void *result = x->external_bind(comp_name, itf_name, handle); if (result != NULL) return result; } return NULL; } void vp::master_port::bind_to_virtual(vp::port *port) { vp_assert_always(port != NULL, this->get_comp()->get_trace(), "Trying to bind master port to NULL\n"); this->slave_ports.push_back(port); } void vp::component::create_comps() { js::config *config = this->get_js_config(); js::config *comps = config->get("vp_comps"); if (comps == NULL) { comps = config->get("components"); } if (comps != NULL) { this->get_trace()->msg(vp::trace::LEVEL_DEBUG, "Creating components\n"); for (auto x : comps->get_elems()) { std::string comp_name = x->get_str(); js::config *comp_config = config->get(comp_name); std::string vp_component = comp_config->get_child_str("vp_component"); if (vp_component == "") vp_component = "utils.composite_impl"; this->new_component(comp_name, comp_config, vp_component); } } } void vp::component::dump_traces_recursive(FILE *file) { this->dump_traces(file); for
(auto& x: this->get_childs()) { x->dump_traces_recursive(file); } } vp::component *vp::__gv_create(std::string config_path, struct gv_conf *gv_conf) { setenv("PULP_CONFIG_FILE", config_path.c_str(), 1); js::config *js_config = js::import_config_from_file(config_path); if (js_config == NULL) { fprintf(stderr, "Invalid configuration."); return NULL; } js::config *gv_config = js_config->get("**/gvsoc"); std::string module_name = "vp.trace_domain_impl"; if (gv_config->get_child_bool("sv-mode")) { module_name = "sv." + module_name; } else if (gv_config->get_child_bool("debug-mode")) { module_name = "debug." + module_name; } std::replace(module_name.begin(), module_name.end(), '.', '/'); std::string path = std::string(getenv("GVSOC_PATH")) + "/" + module_name + ".so"; void *module = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL | RTLD_DEEPBIND); if (module == NULL) { throw std::invalid_argument("ERROR, Failed to open periph model (module: " + module_name + ", error: " + std::string(dlerror()) + ")"); } vp::component *(*constructor)(js::config *) = (vp::component * (*)(js::config *)) dlsym(module, "vp_constructor"); if (constructor == NULL) { throw std::invalid_argument("ERROR, couldn't find vp_constructor in loaded module (module: " + module_name + ")"); } vp::component *instance = constructor(js_config); vp::top *top = new vp::top(); top->top_instance = instance; top->power_engine = new vp::power::engine(instance); instance->set_vp_config(gv_config); instance->set_gv_conf(gv_conf); return (vp::component *)top; } extern "C" void *gv_create(const char *config_path, struct gv_conf *gv_conf) { return (void *)vp::__gv_create(config_path, gv_conf); } extern "C" void gv_destroy(void *arg) { } extern "C" void gv_start(void *arg) { vp::top *top = (vp::top *)arg; vp::component *instance = (vp::component *)top->top_instance; instance->pre_pre_build(); instance->pre_build(); instance->build(); instance->build_new(); if (instance->gv_conf.open_proxy || instance->get_vp_config()->get_child_bool("proxy/enabled")) { int in_port = instance->gv_conf.open_proxy ? 0 : instance->get_vp_config()->get_child_int("proxy/port"); int out_port; proxy = new Gv_proxy(instance, instance->gv_conf.req_pipe, instance->gv_conf.reply_pipe); if (proxy->open(in_port, &out_port)) { instance->throw_error("Failed to start proxy"); } if (instance->gv_conf.proxy_socket) { *instance->gv_conf.proxy_socket = out_port; } } } extern "C" void gv_reset(void *arg, bool active) { vp::top *top = (vp::top *)arg; vp::component *instance = (vp::component *)top->top_instance; instance->reset_all(active); } extern "C" void gv_step(void *arg, int64_t timestamp) { vp::top *top = (vp::top *)arg; vp::component *instance = (vp::component *)top->top_instance; instance->step(timestamp); } extern "C" int64_t gv_time(void *arg) { vp::top *top = (vp::top *)arg; vp::component *instance = (vp::component *)top->top_instance; return instance->get_time_engine()->get_next_event_time(); } extern "C" void *gv_open(const char *config_path, bool open_proxy, int *proxy_socket, int req_pipe, int reply_pipe) { struct gv_conf gv_conf; gv_conf.open_proxy = open_proxy; gv_conf.proxy_socket = proxy_socket; gv_conf.req_pipe = req_pipe; gv_conf.reply_pipe = reply_pipe; void *instance = gv_create(config_path, &gv_conf); if (instance == NULL) return NULL; gv_start(instance); return instance; } Gvsoc_proxy::Gvsoc_proxy(std::string config_path) : config_path(config_path) { } void Gvsoc_proxy::proxy_loop() { FILE *sock = fdopen(this->reply_pipe[0], "r"); while(1) { char line[1024]; if (!fgets(line, 1024, sock)) return ; std::string s = std::string(line); std::regex regex{R"([\s]+)"}; std::sregex_token_iterator it{s.begin(), s.end(), regex, -1}; std::vector<std::string> words{it, {}}; if (words.size() > 0) { if (words[0] == "stopped") { int64_t timestamp = std::atoll(words[1].c_str()); printf("GOT STOP AT %ld\n", timestamp); this->mutex.lock(); this->stopped_timestamp = timestamp; this->running = false; this->cond.notify_all(); this->mutex.unlock(); } else if (words[0] == "running") { int64_t timestamp = std::atoll(words[1].c_str()); printf("GOT RUN AT %ld\n", timestamp); this->mutex.lock(); this->running = true; this->cond.notify_all(); this->mutex.unlock(); } else if (words[0] == "req=") { } else { printf("Ignoring invalid command: %s\n", words[0].c_str()); } } } } int Gvsoc_proxy::open() { pid_t ppid_before_fork = getpid(); if (pipe(this->req_pipe) == -1) return -1; if (pipe(this->reply_pipe) == -1) return -1; pid_t child_id = fork(); if(child_id == -1) { return -1; } else if (child_id == 0) { int r = prctl(PR_SET_PDEATHSIG, SIGTERM); if (r == -1) { perror(0); exit(1); } // test in case the original parent exited just // before the prctl() call if (getppid() != ppid_before_fork) exit(1); void *instance = gv_open(this->config_path.c_str(), true, NULL, this->req_pipe[0], this->reply_pipe[1]); int retval = gv_run(instance); gv_stop(instance, retval); return retval; } else { this->running = false; this->loop_thread = new std::thread(&Gvsoc_proxy::proxy_loop, this); } return 0; } void Gvsoc_proxy::run() { dprintf(this->req_pipe[1], "cmd=run\n"); } int64_t Gvsoc_proxy::pause() { int64_t result; dprintf(this->req_pipe[1], "cmd=stop\n"); std::unique_lock<std::mutex> lock(this->mutex); while (this->running) { this->cond.wait(lock); } result = this->stopped_timestamp; lock.unlock(); return result; } void Gvsoc_proxy::close() { dprintf(this->req_pipe[1], "cmd=quit\n"); } void Gvsoc_proxy::add_event_regex(std::string regex) { dprintf(this->req_pipe[1], "cmd=event add %s\n", regex.c_str()); } void Gvsoc_proxy::remove_event_regex(std::string regex) { dprintf(this->req_pipe[1], "cmd=event remove %s\n", regex.c_str()); } void Gvsoc_proxy::add_trace_regex(std::string regex) { dprintf(this->req_pipe[1], "cmd=trace add %s\n", regex.c_str()); } void Gvsoc_proxy::remove_trace_regex(std::string regex) { dprintf(this->req_pipe[1], "cmd=trace remove %s\n", regex.c_str()); } vp::time_scheduler::time_scheduler(js::config *config) : time_engine_client(config), first_event(NULL) { } int64_t vp::time_scheduler::exec() { vp::time_event *current = this->first_event; while (current && current->time == this->get_time()) { this->first_event = current->next; current->meth(current->_this, current); current = this->first_event; } if (this->first_event == NULL) { return -1; } else { return this->first_event->time - this->get_time(); } } vp::time_event::time_event(time_scheduler *comp, time_event_meth_t *meth) : comp(comp), _this((void *)static_cast<vp::component *>((vp::time_scheduler *)(comp))), meth(meth), enqueued(false) { } vp::time_event *vp::time_scheduler::enqueue(time_event *event, int64_t time) { vp::time_event *current = this->first_event, *prev = NULL; int64_t full_time = time + this->get_time(); while (current && current->time < full_time) { prev = current; current = current->next; } if (prev) prev->next = event; else this->first_event = event; event->next = current; event->time = full_time; this->enqueue_to_engine(time); return event; } extern "C" int gv_run(void *arg) { vp::top *top = (vp::top *)arg; vp::component *instance = (vp::component *)top->top_instance; if (!proxy) { instance->run(); } return instance->join(); } extern "C" void gv_init(struct gv_conf *gv_conf) { gv_conf->open_proxy = 0; if (gv_conf->proxy_socket) { *gv_conf->proxy_socket = -1; } gv_conf->req_pipe = 0; gv_conf->reply_pipe = 0; } extern "C" void gv_stop(void *arg, int retval) { vp::top *top = (vp::top *)arg; vp::component *instance = (vp::component *)top->top_instance; if (proxy) { proxy->stop(retval); } instance->stop_all(); delete top->power_engine; } #ifdef __VP_USE_SYSTEMC static void *(*sc_entry)(void *); static void *sc_entry_arg; void set_sc_main_entry(void *(*entry)(void *), void *arg) { sc_entry = entry; sc_entry_arg = arg; } int sc_main(int argc, char *argv[]) { sc_entry(sc_entry_arg); return 0; } #endif void vp::fatal(const char *fmt, ...) { va_list ap; va_start(ap, fmt); if (vfprintf(stderr, fmt, ap) < 0) {} va_end(ap); abort(); } extern "C" void *gv_chip_pad_bind(void *handle, char *name, int ext_handle) { vp::top *top = (vp::top *)handle; vp::component *instance = (vp::component *)top->top_instance; return instance->external_bind(name, "", (void *)(long)ext_handle); }
/************************************************************************** * * * Catapult(R) Machine Learning Reference Design Library * * * * Software Version: 1.8 * * * * Release Date : Sun Jul 16 19:01:51 PDT 2023 * * Release Type : Production Release * * Release Build : 1.8.0 * * * * Copyright 2021 Siemens * * * ************************************************************************** * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * * implied. * * See the License for the specific language governing permissions and * * limitations under the License. * ************************************************************************** * * * The most recent version of this package is available at github. * * * *************************************************************************/ #include <systemc.h> #include "types.h" #include "axi/axi4.h" #include "axi4_segment.h" #include "sysbus_axi_struct.h" #include "systemc_subsystem.h" class systemc_subsystem_wrapper : public sc_module, public sysbus_axi { public: //== Ports sc_in <bool> clk; sc_in <bool> reset_bar; sc_in <sc_lv<44>> aw_msg_port; sc_in <bool> aw_valid_port; sc_out<bool> aw_ready_port; sc_in <sc_lv<37>> w_msg_port; sc_in <bool> w_valid_port; sc_out<bool> w_ready_port; sc_out<sc_lv<6>> b_msg_port; sc_out<bool> b_valid_port; sc_in <bool> b_ready_port; sc_in <sc_lv<44>> ar_msg_port; sc_in <bool> ar_valid_port; sc_out<bool> ar_ready_port; sc_out<sc_lv<39>> r_msg_port; sc_out<bool> r_valid_port; sc_in <bool> r_ready_port; sc_clock connections_clk; sc_event check_event; virtual void start_of_simulation() { Connections::get_sim_clk().add_clock_alias( connections_clk.posedge_event(), clk.posedge_event()); } void check_clock() { check_event.notify(2, SC_PS);} // Let SC and Vlog delta cycles settle. void check_event_method() { if (connections_clk.read() == clk.read()) return; CCS_LOG("clocks misaligned!:" << connections_clk.read() << " " << clk.read()); } systemc_subsystem CCS_INIT_S1(scs); SC_CTOR(systemc_subsystem_wrapper) : connections_clk("connections_clk", CLOCK_PERIOD, SC_NS, 0.5, 0, SC_NS, true) { SC_METHOD(check_clock); sensitive << connections_clk; sensitive << clk; SC_METHOD(check_event_method); sensitive << check_event; scs.clk(connections_clk); scs.reset_bar(reset_bar); scs.w_cpu.aw.dat(aw_msg_port); scs.w_cpu.aw.vld(aw_valid_port); scs.w_cpu.aw.rdy(aw_ready_port); scs.w_cpu.w.dat(w_msg_port); scs.w_cpu.w.vld(w_valid_port); scs.w_cpu.w.rdy(w_ready_port); scs.w_cpu.b.dat(b_msg_port); scs.w_cpu.b.vld(b_valid_port); scs.w_cpu.b.rdy(b_ready_port); scs.r_cpu.ar.dat(ar_msg_port); scs.r_cpu.ar.vld(ar_valid_port); scs.r_cpu.ar.rdy(ar_ready_port); scs.r_cpu.r.dat(r_msg_port); scs.r_cpu.r.vld(r_valid_port); scs.r_cpu.r.rdy(r_ready_port); } }; #ifdef QUESTA SC_MODULE_EXPORT(systemc_subsystem_wrapper); #endif
// //------------------------------------------------------------// // Copyright 2009-2012 Mentor Graphics Corporation // // All Rights Reserved Worldwid // // // // Licensed under the Apache License, Version 2.0 (the // // "License"); you may not use this file except in // // compliance with the License. You may obtain a copy of // // the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in // // writing, software distributed under the License is // // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // // CONDITIONS OF ANY KIND, either express or implied. See // // the License for the specific language governing // // permissions and limitations under the License. // //------------------------------------------------------------// #include "systemc.h" #include "tlm.h" using namespace sc_core; using namespace tlm; //----------------------------------------------------------------------------- // Title: UVMC Connection Example - Hierarchical Connection, SC side // // This example illustrates how to make hierarchical UVMC connections, i.e. how // to promote a ~port~, ~export~, ~imp~, or ~socket~ from a child component to // a parent that resides in the other language. In effect, we are using a // component written in SV as the implementation for a component in SC. // See <UVMC Connection Example - Hierarchical Connection, SV side> to see // the SC portion of the example. // // (see UVMC_Connections_SCwrapsSV.png) // // By hiding the SV implementation, we create what appears to be a pure SC-based // testbench, just like the <UVMC Connection Example - Native SC to SC>. // However, the SC producer is implemented in SV and uses UVMC to make a // behind-the-scenes connection. // // This example illustates good programming principles by exposing only standard // TLM interfaces to the user. The implementation of those interfaces is hidden // and therefore can change (or be implemented in another language) without // affecting end user code. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Class: producer // // Our ~producer~ module is merely a wrapper around an SV-side implementation, // but users of this producer will not be aware of that. The producer does not // actually instantiate a SV component. It simply promotes the socket in the // SV producer to a corresponding socket in the SC producer. From the outside, // the SC producer appears as an ordinary SC component with a TLM2 socket as // its public interface. //----------------------------------------------------------------------------- //(begin inline source) #include "uvmc.h" using namespace uvmc; #include "packet.h" class producer: public sc_module { public: sc_port<tlm_blocking_put_if<packet> > out; SC_CTOR(producer) : out("out") { uvmc_connect_hier(out,"sv_out"); } }; //(end inline source) //----------------------------------------------------------------------------- // Group: sc_main // // The ~sv_main~ top-level module below creates and starts the SV portion of this // example. It instantiates our "pure" SC producer and consumer, binds their // sockets to complete the local connection, then starts SC simulation. // // Notice that the code is identical to that used in the // <UVMC Connection Example - Native SC to SC> example. From the SC user's // perspective, there is no difference between the two testbenches. We've // hidden the UVMC implementation details from the user. //----------------------------------------------------------------------------- //(begin inline source) #include "consumer.h" int sc_main(int argc, char* argv[]) { producer prod("prod"); consumer cons("cons"); prod.out.bind(cons.in); sc_start(-1); return 0; }; //(end inline source)
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // 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_convolution) { 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_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++) { sensitive << data_a_in[i][j]; 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++) { int temporal = 0; for (int m = 0; m < i; m++) { for (int n = 0; n < j; n++) { temporal += data_a_in[m][n].read() * data_b_in[i - m][j - n].read(); } } data_out[i][j] = temporal; } } } };
//**************************************************************************************** // 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; }
//-----Function definitions for classes os, os_taski and os_sem--- //-----You must modify this file as indicated by TODO comments---- //-----You should reuse code from Programming Assignment 3-------- //-----as indicated by the REUSE comments------------------------- //-----Note that new code must be written for os_sem methods------ //-----The time_wait method in OS must be rewritten--------------- //-----to account for preemption---------------------------------- #include "systemc.h" #include "os.h" using namespace std; // implementation of os_task methods //placeholder constructor since we have a pool os_task::os_task() { } os_task::~os_task(){ } void os_task::instantiate(sc_core::sc_process_handle handle, const char *name, unsigned int priority){ static unsigned int count = 0; task_name = name; // All tasks are initially ready when created task_state = READY; task_id = count; task_priority = priority; task_handle = handle; activation_flag = rd_suspended_flag = wr_suspended_flag = false; count++; } const char *os_task::get_name(){ return task_name.data(); } enum state os_task::get_state(){ return task_state; } unsigned int os_task::get_id(){ return task_id; } unsigned int os_task::get_priority(){ return task_priority; } sc_core::sc_process_handle os_task::get_handle(){ return task_handle; } void os_task::activate(){ // REUSE: set the activation flag and notify the event // TODO: set the activation flag and notify the event activation_flag = true; activation_event.notify(); task_state = RUNNING; return; } void os_task::wait_for_activation(){ // REUSE: If the activation flag is not set, // REUSE: wait for it to be set if (activation_flag == false) { wait(activation_event); } // REUSE: reset the activation flag activation_flag = false; // REUSE: update the task state //task_state = SUSPENDED; return; } //os class method implementation os::os(){ // empty constructor } os::~os(){ } // dynamic task creation function // this function is called by the main SC thread in the top module // it may also be called by tasks to dynamically create children os_task *os::task_create( const char* name, unsigned int priority, sc_core::sc_process_handle h) { // get a task object from the pool static int count = 0; os_task *t = &(task_pool[count++]); // REUSE: instantiate the user task in the OS model t->instantiate(h, name, priority); // REUSE: add the task to the ALL_TASKS list ALL_TASKS.push_back(t); //newly created task is in the ready state // REUSE: add it to READY vector list READY_TASKS.push_back(t); // return the task pointer return t; } // task initialization function // this function is called by the SystemC thread // for the task, at the very beginning void os::task_init(){ // REUSE: find this task's pointer "t" os_task *t = NULL; // REUSE: wait for the task to be scheduled by the OS // TODO: find this task's pointer "t" static int count = 0; t = &(task_pool[count++]); // TODO: wait for the task to be scheduled by the OS t->wait_for_activation(); cout << sc_time_stamp() << ": Task " << t->get_name() << " is initialized" << endl; return; } // task termination function // this function is called by the running task // to terminate itself void os::task_terminate(){ // REUSE: update the state of the task os_task *t = CURRENT; t->task_state = TERMINATED; // REUSE: do a rescheduling on remaining tasks schedule(); // REUSE: wait till end of simulation if no tasks remain bool all_terminated = true; for (int i = 0; i < ALL_TASKS.size(); i++) { os_task *temp_t = ALL_TASKS[i]; if (temp_t->get_state() != TERMINATED) { all_terminated = false; break; } } if (all_terminated) { wait(); } } // this function displays the states of // all the tasks in the order of their creation // It is called by the OS schedule method // whenever a rescheduling takes place void os::status(){ cout << endl << sc_time_stamp() << ":" << endl; for (int i = 0; i < ALL_TASKS.size(); i++){ os_task *t = ALL_TASKS[i]; cout << t->get_name() << ": "; if (t->get_state() == RUNNING) cout << "RUNNING" << endl; else if (t->get_state() == READY) cout << "READY" << endl; else if (t->get_state() == SUSPENDED) cout << "SUSPENDED" << endl; else if (t->get_state() == TERMINATED) cout << "TERMINATED" << endl; } } void os::time_wait(sc_time t) { // TODO: use simultaneous wait on time and preemption event // TODO: if preemption event arrives before all the time // TODO: has been consumed, go to ready state, wait for activation // TODO: then consume the remainder time // TODO: repeat until all of "t" has been consumed os_task *temp_task = CURRENT; sc_time start_time = sc_time_stamp(), elapsed_time = SC_ZERO_TIME; do { sc_time remainder_time = t - elapsed_time; wait(remainder_time, preemption); sc_time delta = sc_time_stamp() - start_time; elapsed_time = elapsed_time + delta; if(elapsed_time < t) { temp_task->wait_for_activation(); } } while(elapsed_time < t); return; } // end time_wait ERROR os::schedule() { // REUSE: If there are no tasks or all tasks have terminated // REUSE: Pring the status and return code E_NO_TASKS if (READY_TASKS.empty()) { status(); return E_NO_TASKS; } bool all_terminated = true; for (int i = 0; i < ALL_TASKS.size(); i++) { os_task *t = ALL_TASKS[i]; if (t->get_state() != TERMINATED) { all_terminated = false; break; } } if (all_terminated) { status(); return E_NO_TASKS; } // REUSE: If all tasks are suspended, just display // REUSE: the states and return code E_OK bool not_all_suspended = false; for (int i = 0; i < ALL_TASKS.size(); i++) { os_task *t = ALL_TASKS[i]; if (t->get_state() != SUSPENDED) { not_all_suspended = true; break; } } // otherwise, we have some scheduling to do! // REUSE: find the highest priority ready task // REUSE: remove the highest priority task from the ready list // REUSE: and activate it! if (not_all_suspended) { // TODO: remove the highest priority task from the ready list // TODO: and activate it! unsigned int task_index = 0; unsigned int priority = READY_TASKS[0]->get_priority(); for (int i = 1; i < READY_TASKS.size(); i++) { os_task *t = READY_TASKS[i]; if (t->get_priority() > priority) { task_index = i; priority = t->get_priority(); } } CURRENT = READY_TASKS[task_index]; READY_TASKS.erase(READY_TASKS.begin() + task_index); CURRENT->activate(); } // print out the status of all the tasks status(); return E_OK; } // end schedule void os::run() { // all the initial tasks have been created // kickstart the scheduler cout << "Initializing Scheduler..." <<endl; schedule(); } // os_sem method implementation //------------------------------------------------------------- int os_sem::wait() { int retval; class os_task *temp_t = OS->CURRENT; // TODO: if the semaphore value is 0 // TODO: the accessing task must be blocked if (get_value() == 0) { // TODO: block the caller temp_t->task_state = SUSPENDED; OS->CURRENT = NULL; cout << sc_time_stamp() <<": Task "<< temp_t->get_name() << " blocked on semaphore " << sc_semaphore::name() << "\n"; // TODO: set the blocked_task pointer blocked_task = temp_t; // TODO: find the next active task and run it OS->schedule(); blocked_task->wait_for_activation(); } // proceed by running the base class method retval = sc_semaphore::wait(); return retval; } // end os_sem wait method int os_sem::post() { int retval; class os_task *temp_task = blocked_task; // increment the semaphore value // by calling the base class method retval = sc_semaphore::post(); // TODO: if there is a blocked task, it should be unblocked if (blocked_task) { // TODO: if all tasks are suspended // TODO: run the scheduler here // TODO: after waking up the blocked task bool all_suspended = OS->READY_TASKS.empty(); for (int i = 0; i < OS->ALL_TASKS.size(); i++) { os_task *t = OS->ALL_TASKS[i]; if (t->get_state() == RUNNING) { all_suspended = false; break; } } blocked_task->task_state = READY; OS->READY_TASKS.push_back(blocked_task); blocked_task = 0; if(all_suspended) { OS->schedule(); } else if(OS->CURRENT->get_priority() < temp_task->get_priority() ) { // TODO: if there is a running task with lower priority // TODO: than the newly unblocked task, // TODO: the running task should be preempted OS->CURRENT->task_state = READY; OS->READY_TASKS.push_back(OS->CURRENT); OS->preemption.notify(); // TODO: the message below should be printed only in the case of preemption cout << sc_time_stamp() <<": Task "<< OS->CURRENT->get_name() << " preempted by task " << temp_task->get_name() << "\n"; OS->CURRENT = NULL; OS->schedule(); temp_task->wait_for_activation(); } } return retval; } // end os_sem post method
#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
/******************************************************************************* * 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);
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** forkjoin.cpp -- Demo fork/join and dynamic thread creation Original Author: Stuart Swan, Cadence Design Systems, Inc., 2002-10-22 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Andy Goodrich, Forte Design Systems, 19 Aug 2003 Description of Modification: Modified to use 2.1 dynamic process support. *****************************************************************************/ #include <systemc.h> int test_function(double d) { cout << endl << "Test_function sees " << d << endl; return int(d); } void void_function(double d) { cout << endl << "void_function sees " << d << endl; } int ref_function(const double& d) { cout << endl << "ref_function sees " << d << endl; return int(d); } class top : public sc_module { public: top(sc_module_name name) : sc_module(name) { SC_THREAD(main); } void main() { int r; sc_event e1, e2, e3, e4; cout << endl; e1.notify(100, SC_NS); // Spawn several threads that co-operatively execute in round robin order SC_FORK sc_spawn(&r, sc_bind(&top::round_robin, this, "1", sc_ref(e1), sc_ref(e2), 3), "1") , sc_spawn(&r, sc_bind(&top::round_robin, this, "2", sc_ref(e2), sc_ref(e3), 3), "2") , sc_spawn(&r, sc_bind(&top::round_robin, this, "3", sc_ref(e3), sc_ref(e4), 3), "3") , sc_spawn(&r, sc_bind(&top::round_robin, this, "4", sc_ref(e4), sc_ref(e1), 3), "4") , SC_JOIN cout << "Returned int is " << r << endl; cout << endl << endl; // Test that threads in thread pool are successfully reused ... for (int i = 0 ; i < 10; i++) sc_spawn(&r, sc_bind(&top::wait_and_end, this, i)); wait(20, SC_NS); // Show how to use sc_spawn_options sc_spawn_options o; o.set_stack_size(0); // Demo of a function rather than method call, & use return value ... wait( sc_spawn(&r, sc_bind(&test_function, 3.14159)).terminated_event()); cout << "Returned int is " << r << endl; sc_process_handle handle1 = sc_spawn(sc_bind(&void_function, 1.2345)); wait(handle1.terminated_event()); double d = 9.8765; wait( sc_spawn(&r, sc_bind(&ref_function, sc_cref(d))).terminated_event() ); cout << "Returned int is " << r << endl; cout << endl << "Done." << endl; } int round_robin(const char *str, sc_event& receive, sc_event& send, int cnt) { while (--cnt >= 0) { wait(receive); cout << "Round robin thread " << str << " at time " << sc_time_stamp() << endl; wait(10, SC_NS); send.notify(); } return 0; } int wait_and_end(int i) { wait( i + 1, SC_NS); cout << "Thread " << i << " ending." << endl; return 0; } }; int sc_main (int, char*[]) { top top1("Top1"); sc_start(); return 0; }
#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
/******************************************************************************* * tb_gpio.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Testbench for the GPIO models. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "tb_gpio.h" #include "info.h" void tb_gpio::expect(const char *name, bool a, sc_logic v) { if (a != v) PRINTF_WARN("TEST", "Expected %s to be %c but got %c", name, v.to_char(), (a)?'1':'0') else PRINTF_INFO("TEST", "SUCCESS: got %s to be %c", name, v.to_char()); } void tb_gpio::expect(const char *name, sc_logic a, sc_logic v) { if (a != v) PRINTF_WARN("TEST", "Expected %s to be %c but got %c", name, v.to_char(), a.to_char()) else PRINTF_INFO("TEST", "SUCCESS: got %s to be %c", name, v.to_char()); } void tb_gpio::expect(const char *name, gn_mixed a, sc_logic v) { if (a != v) PRINTF_WARN("TEST", "Expected %s to be %c but got %c", name, v.to_char(), a.to_char()) else PRINTF_INFO("TEST", "SUCCESS: got %s to be %c", name, v.to_char()); } void tb_gpio::expectfunc(const char *name, int a, int v) { if (a != v) PRINTF_WARN("TEST", "Expected %s to be Function %d but got %c",name,v,a) else PRINTF_INFO("TEST", "SUCCESS: got %s to be Function %d", name, v); } void tb_gpio::t0(void) { wait(SC_ZERO_TIME); /* We start off checking the pins. */ expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_Z); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_Z); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_Z); expect(pin3.name(), pin3.read(), SC_LOGIC_Z); expectfunc(i_gpio.name(), i_gpio.get_function(), GPIOMF_GPIO); expectfunc(i_gpio_mix.name(), i_gpio_mix.get_function(), GPIOMF_GPIO); expectfunc(i_gpio_mfmix.name(), i_gpio_mfmix.get_function(), GPIOMF_GPIO); expectfunc(i_gpio_mf.name(), i_gpio_mf.get_function(), GPIOMF_GPIO); /* We now change the GPIOs to be Output and check the outputs. */ wait(10, SC_NS); printf("\n\n**** Changing GPIOs to Output ****\n"); i_gpio.set_dir(GPIODIR_OUTPUT); i_gpio_mix.set_dir(GPIODIR_OUTPUT); i_gpio_mfmix.set_dir(GPIODIR_OUTPUT); i_gpio_mf.set_dir(GPIODIR_OUTPUT); wait(SC_ZERO_TIME); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_0); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_0); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_0); expect(pin3.name(), pin3.read(), SC_LOGIC_0); /* We drive something and check it. */ wait(10, SC_NS); i_gpio.set_val(true); i_gpio_mix.set_val(true); i_gpio_mfmix.set_val(true); i_gpio_mf.set_val(true); wait(SC_ZERO_TIME); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_1); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_1); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_1); expect(pin3.name(), pin3.read(), SC_LOGIC_1); /* We change them to WPU or OD and recheck it. */ printf("\n\n**** Checking weak pull-up/OD ****\n"); i_gpio.set_wpu(); i_gpio_mix.set_od(); i_gpio_mfmix.set_wpu(); i_gpio_mf.set_wpu(); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_Z); /* WPU but looks like Z */ expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_Z); /* OD */ expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_1); /* WPU */ expect(pin3.name(), pin3.read(), SC_LOGIC_Z); /* WPU but looks like Z */ /* And we go low. */ i_gpio.set_val(false); i_gpio_mix.set_val(false); i_gpio_mfmix.set_val(false); i_gpio_mf.set_val(false); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_0); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_0); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_0); expect(pin3.name(), pin3.read(), SC_LOGIC_0); /* Now we switch the OD and WPU pins and try it again. */ printf("\n\n**** Switching weak pull-up and OD ****\n"); i_gpio.set_val(true); i_gpio_mix.set_val(true); i_gpio_mfmix.set_val(true); i_gpio_mf.set_val(true); i_gpio.clr_wpu(); i_gpio.set_od(); i_gpio_mix.clr_od(); i_gpio_mix.set_wpu(); i_gpio_mfmix.clr_wpu(); i_gpio_mfmix.set_od(); i_gpio_mf.clr_wpu(); i_gpio_mf.set_od(); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_Z); /* OD */ expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_1); /* WPU */ expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_Z); /* OD */ expect(pin3.name(), pin3.read(), SC_LOGIC_Z); /* OD */ /* And we go low again. */ i_gpio.set_val(false); i_gpio_mix.set_val(false); i_gpio_mfmix.set_val(false); i_gpio_mf.set_val(false); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_0); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_0); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_0); expect(pin3.name(), pin3.read(), SC_LOGIC_0); /* Now we go with a weak pull-down. */ printf("\n\n**** Checking weak pull-down ****\n"); i_gpio.set_wpd(); i_gpio.clr_od(); i_gpio_mix.set_wpd(); i_gpio_mix.clr_wpu(); i_gpio_mfmix.set_wpd(); i_gpio_mfmix.clr_od(); i_gpio_mf.set_wpd(); i_gpio_mf.clr_od(); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_Z); /* WPD but looks like Z */ expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_0); /* WPD */ expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_0); /* WPD */ expect(pin3.name(), pin3.read(), SC_LOGIC_Z); /* WPD but looks like Z */ /* And we raise the signals. */ i_gpio.set_val(true); i_gpio_mix.set_val(true); i_gpio_mfmix.set_val(true); i_gpio_mf.set_val(true); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_1); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_1); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_1); expect(pin3.name(), pin3.read(), SC_LOGIC_1); /* Now we go with a weak pull-down. */ i_gpio.set_val(false); i_gpio_mix.set_val(false); i_gpio_mfmix.set_val(false); i_gpio_mf.set_val(false); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_Z); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_0); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_0); expect(pin3.name(), pin3.read(), SC_LOGIC_Z); /* And we shut off the pull downs. */ i_gpio.clr_wpd(); i_gpio_mix.clr_wpd(); i_gpio_mfmix.clr_wpd(); i_gpio_mf.clr_wpd(); wait(10, SC_NS); expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); expect(pin1.name(), pin1.read(), SC_LOGIC_0); expect(pin_a1.name(), pin_a1.read(), SC_LOGIC_0); expect(pin_a2.name(), pin_a2.read(), SC_LOGIC_0); expect(pin3.name(), pin3.read(), SC_LOGIC_0); /* Now we go to GPIO In */ printf("\n\n**** Changing GPIOs to Input ****\n"); pin1.write(SC_LOGIC_1); pin_a1.write(SC_LOGIC_0); pin_a2.write(SC_LOGIC_1); pin3.write(SC_LOGIC_0); i_gpio.set_dir(GPIODIR_INPUT); i_gpio_mix.set_dir(GPIODIR_INPUT); i_gpio_mfmix.set_dir(GPIODIR_INPUT); i_gpio_mf.set_dir(GPIODIR_INPUT); wait(10, SC_NS); expect(i_gpio.name(), i_gpio.get_val(), SC_LOGIC_1); expect(i_gpio_mix.name(), i_gpio_mix.get_val(), SC_LOGIC_0); expect(i_gpio_mfmix.name(), i_gpio_mfmix.get_val(), SC_LOGIC_1); expect(i_gpio_mf.name(), i_gpio_mf.get_val(), SC_LOGIC_0); pin1.write(SC_LOGIC_0); pin_a1.write(SC_LOGIC_1); pin_a2.write(SC_LOGIC_0); pin3.write(SC_LOGIC_1); wait(10, SC_NS); expect(pin1.name(), i_gpio.get_val(), SC_LOGIC_0); expect(pin_a1.name(), i_gpio_mix.get_val(), SC_LOGIC_1); expect(pin_a2.name(), i_gpio_mfmix.get_val(), SC_LOGIC_0); expect(pin3.name(), i_gpio_mf.get_val(), SC_LOGIC_1); /* These one should still be low as the function was not selected. */ expect(f1out.name(), f1out.read(), SC_LOGIC_0); expect(f2out.name(), f2out.read(), SC_LOGIC_0); expect(f3out.name(), f3out.read(), SC_LOGIC_0); /* Now we change values. */ printf("\n\n**** Changing GPIOs to I/O ****\n"); pin1.write(SC_LOGIC_1); pin_a1.write(SC_LOGIC_0); pin_a2.write(SC_LOGIC_1); pin3.write(SC_LOGIC_0); i_gpio.set_dir(GPIODIR_INOUT); i_gpio.set_val(true); i_gpio_mix.set_dir(GPIODIR_INOUT); i_gpio_mix.set_val(true); i_gpio_mfmix.set_dir(GPIODIR_INOUT); i_gpio_mfmix.set_val(true); i_gpio_mf.set_dir(GPIODIR_INOUT); i_gpio_mf.set_val(true); wait(10, SC_NS); expect(pin1.name(), pin1, SC_LOGIC_1); expect(pin_a1.name(), pin_a1, SC_LOGIC_X); expect(pin_a2.name(), pin_a2, SC_LOGIC_1); /* It was high. */ expect(pin3.name(), pin3, SC_LOGIC_X); pin1.write(SC_LOGIC_Z); pin_a1.write(SC_LOGIC_Z); pin_a2.write(SC_LOGIC_Z); pin3.write(SC_LOGIC_Z); wait(10, SC_NS); expect(pin1.name(), pin1, sc_logic(i_gpio.get_val())); expect(pin_a1.name(), pin_a1, sc_logic(i_gpio.get_val())); expect(pin_a2.name(), pin_a2, sc_logic(i_gpio.get_val())); expect(pin3.name(), pin3, sc_logic(i_gpio.get_val())); /* Now we change the modes. */ printf("\n\n**** Function ANALOG ****\n"); i_gpio_mix.set_function(GPIOMF_ANALOG); i_gpio_mfmix.set_function(GPIOMF_ANALOG); wait(10, SC_NS); expect(pin1.name(), pin1, sc_logic(i_gpio.get_val())); expect(pin_a1.name(), pin_a1, SC_LOGIC_Z); expect(pin_a2.name(), pin_a2, SC_LOGIC_Z); expect(f1out.name(), f1out, SC_LOGIC_0); expect(f2out.name(), f2out, SC_LOGIC_0); printf("\n\n**** Funtion GPIO ****\n"); /* We drive all functions high and the internal values low and check * that the pins follow signal. */ i_gpio_mfmix.set_function(GPIOMF_GPIO); i_gpio_mfmix.set_dir(GPIODIR_INOUT); i_gpio_mfmix.set_val(false); i_gpio_mf.set_function(GPIOMF_GPIO); i_gpio_mf.set_dir(GPIODIR_INOUT); i_gpio_mf.set_val(false); f1in.write(true); f1en.write(true); f2in.write(true); f2en.write(true); f3in.write(true); f3en.write(true); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_0); expect(f1out.name(), f1out, SC_LOGIC_0); expect(f2out.name(), f2out, SC_LOGIC_0); expect(pin3.name(), pin3, SC_LOGIC_0); expect(f3out.name(), f3out, SC_LOGIC_0); /* We toggle a bit more the pins */ f2in.write(false); f2en.write(true); f3in.write(false); f3en.write(true); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_0); expect(f1out.name(), f1out, SC_LOGIC_0); expect(f2out.name(), f2out, SC_LOGIC_0); expect(pin3.name(), pin3, SC_LOGIC_0); expect(f3out.name(), f3out, SC_LOGIC_0); printf("\n\n**** Funtion 1 ****\n"); /* We now switch to function 1 and check that the functions are passed * through. */ i_gpio_mfmix.set_function(1); i_gpio_mf.set_function(1); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_1); expect(f1out.name(), f1out, SC_LOGIC_1); expect(f2out.name(), f2out, SC_LOGIC_0); expect(pin3.name(), pin3, SC_LOGIC_0); expect(f3out.name(), f3out, SC_LOGIC_0); f2in.write(true); f2en.write(true); f3in.write(true); f3en.write(true); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_1); expect(f1out.name(), f1out, SC_LOGIC_1); expect(f2out.name(), f2out, SC_LOGIC_0); expect(f3out.name(), f3out, SC_LOGIC_1); f2in.write(false); f2en.write(true); f3in.write(true); f3en.write(false); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_1); expect(pin3.name(), pin3, SC_LOGIC_Z); expect(f1out.name(), f1out, SC_LOGIC_1); expect(f2out.name(), f2out, SC_LOGIC_0); expect(f3out.name(), f3out, SC_LOGIC_0); /* Z can't be put on wire f3out.*/ printf("\n\n**** Funtion 2 ****\n"); i_gpio_mfmix.set_function(2); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_0); expect(f1out.name(), f1out, SC_LOGIC_0); expect(f2out.name(), f2out, SC_LOGIC_0); f2in.write(true); f2en.write(false); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_Z); expect(f1out.name(), f1out, SC_LOGIC_0); expect(f2out.name(), f2out, SC_LOGIC_0); f2in.write(true); f2en.write(true); wait(10, SC_NS); expect(pin_a2.name(), pin_a2, SC_LOGIC_1); expect(f1out.name(), f1out, SC_LOGIC_0); expect(f2out.name(), f2out, SC_LOGIC_1); } void tb_gpio::testbench(void) { /* Now we check the test case and run the correct TB. */ PRINTF_INFO("TEST", "Starting Testbench Test%d", tn); if (tn == 0) t0(); else SC_REPORT_FATAL("TEST", "Test number too large."); sc_stop(); } void tb_gpio::trace(sc_trace_file *tf) { sc_trace(tf, pin1, pin1.name()); sc_trace(tf, pin_a1, pin_a1.name()); sc_trace(tf, pin_a2, pin_a2.name()); sc_trace(tf, pin3, pin3.name()); sc_trace(tf, f1in, f1in.name()); sc_trace(tf, f1en, f1en.name()); sc_trace(tf, f1out, f1out.name()); sc_trace(tf, f2in, f2in.name()); sc_trace(tf, f2en, f2en.name()); sc_trace(tf, f2out, f2out.name()); sc_trace(tf, f3in, f3in.name()); sc_trace(tf, f3en, f3en.name()); sc_trace(tf, f3out, f3out.name()); }
/* * @ASCK */ #include <systemc.h> SC_MODULE (IR) { sc_in <sc_uint<14>> addr; sc_out <sc_uint<20>> inst; /* ** module global variables */ sc_uint<20> mem[819]; // 819 rows and 819*20=16380 bits = (16KB - 4bits) ~= 16KB int instNum = 50; sc_uint<20> instruction[50] = { // 0b01234567890123456789 0b00000000000000000000, 0b00100000000000000111, // transfer (r0 <- 7): 7 0b00010010010000000000, // inc (r1++): 1 //stall for achieving the correct register data - sub 0b11110000000000000000, //stall 0b11110000000000000000, //stall 0b11110000000000000000, //stall 0b00000110000010000010, // sub (r3 <-r0 - r1): 6 0b11110000000000000000, //stall 0b11110000000000000000, //stall 0b11110000000000000000, //stall 0b00011000110010000001, // addc (r4 <- r3 + r1 + 1): 8 0b11110000000000000000, //stall 0b11110000000000000000, //stall 0b11110000000000000000, //stall 0b00001001000000101001, // shiftR (r4 >> 2): 2 0b01010000000000000101, // stroe (mem[5] <= r0) : 7 0b01001010000000000101, // load (r5 <= mem[5]) : 7 0b01100000000000000000, // do accelerator 0b01000100000000010100, // load (r2 <= mem[20]) : 17 => 0x11 0b11110000000000000000, //nop 0b11110000000000000000, //nop 0b11110000000000000000, //nop 0b11110000000000000000, //nop 0b11110000000000000000, //nop 0b11110000000000000000 //nop }; SC_CTOR (IR){ SC_METHOD (process); sensitive << addr; for(int i=0; i<instNum; i++){ mem[i] = instruction[i]; } // filling out other rows with a nop opcode for(int i=instNum; i<819; i++){ mem[i] = 0b11110000000000000000; } } void process () { if(addr.read() < 819){ inst.write(mem[addr.read()]); } else{ inst.write(0); } } };
//----------------------------------------------------- // 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
/******************************************************************************* * 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()); }
// Shows the non-blocking transport interface with the generic payload and sockets // Shows nb_transport being called on the forward and backward paths // No support for temporal decoupling // No support for DMI or debug transport interfaces #include <systemc.h> using namespace sc_core; using namespace sc_dt; using namespace std; #include "tlm.h" #include "tlm_utils/simple_initiator_socket.h" #include "tlm_utils/simple_target_socket.h" #include "tlm_utils/peq_with_cb_and_phase.h" // User-defined extension class struct ID_extension: tlm::tlm_extension<ID_extension> { ID_extension() : transaction_id(0) {} virtual tlm_extension_base* clone() const { // Must override pure virtual clone method ID_extension* t = new ID_extension; t->transaction_id = this->transaction_id; return t; } // Must override pure virtual copy_from method virtual void copy_from(tlm_extension_base const &ext) { transaction_id = static_cast<ID_extension const &>(ext).transaction_id; } unsigned int transaction_id; }; // Initiator module generating generic payload transactions struct Initiator: sc_module { // TLM2 socket, defaults to 32-bits wide, generic payload, generic DMI mode sc_core::sc_in<bool> IO_request; tlm_utils::simple_initiator_socket<Initiator> socket; SC_HAS_PROCESS(Initiator); Initiator(sc_module_name initiator) // Construct and name socket { // Register callbacks for incoming interface method calls socket.register_nb_transport_bw(this, &Initiator::nb_transport_bw); SC_THREAD(thread_process); } void thread_process() { while (true) { // TLM2 generic payload transaction tlm::tlm_generic_payload trans; ID_extension* id_extension = new ID_extension; //trans.set_extension( id_extension ); // Add the extension to the transaction trans.set_extension( id_extension ); // Add the extension to the transaction // Generate a random sequence of reads and writes //for (int i = 0; i < 100; i++) //printf("%i",IO_request->read()); cout << "TLM Z value:" <<IO_request->read() << endl; if(IO_request->read() == 1) { int i = rand()%100; tlm::tlm_phase phase = tlm::BEGIN_REQ; sc_time delay = sc_time(10, SC_NS); tlm::tlm_command cmd = static_cast<tlm::tlm_command>(rand() % 2); trans.set_command( cmd ); trans.set_address( rand() % 0xFF ); if (cmd == tlm::TLM_WRITE_COMMAND) data = 0xFF000000 | i; trans.set_data_ptr( reinterpret_cast<unsigned char*>(&data) ); trans.set_data_length( 4 ); // Other fields default: byte enable = 0, streaming width = 0, DMI_hint = false, no extensions //Delay for BEGIN_REQ wait(10, SC_NS); tlm::tlm_sync_enum status; cout << name() << " BEGIN_REQ SENT" << " TRANS ID " << id_extension->transaction_id << " at time " << sc_time_stamp() << endl; status = socket->nb_transport_fw( trans, phase, delay ); // Non-blocking transport call // Check value returned from nb_transport switch (status) { case tlm::TLM_ACCEPTED: //Delay for END_REQ wait(10, SC_NS); cout << name() << " END_REQ SENT" << " TRANS ID " << id_extension->transaction_id << " at time " << sc_time_stamp() << endl; // Expect response on the backward path phase = tlm::END_REQ; status = socket->nb_transport_fw( trans, phase, delay ); // Non-blocking transport call break; case tlm::TLM_UPDATED: case tlm::TLM_COMPLETED: // Initiator obliged to check response status if (trans.is_response_error() ) SC_REPORT_ERROR("TLM2", "Response error from nb_transport_fw"); cout << "trans/fw = { " << (cmd ? 'W' : 'R') << ", " << hex << i << " } , data = " << hex << data << " at time " << sc_time_stamp() << ", delay = " << delay << endl; break; } while(IO_request==1){ wait(10,SC_NS); } id_extension->transaction_id++; } wait(10,SC_NS); } } // ********************************************* // TLM2 backward path non-blocking transport method // ********************************************* virtual tlm::tlm_sync_enum nb_transport_bw( tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_time& delay ) { tlm::tlm_command cmd = trans.get_command(); sc_dt::uint64 adr = trans.get_address(); ID_extension* id_extension = new ID_extension; trans.get_extension( id_extension ); if (phase == tlm::END_RESP) { //Delay for TLM_COMPLETE wait(delay); cout << name() << " END_RESP RECEIVED" << " TRANS ID " << id_extension->transaction_id << " at time " << sc_time_stamp() << endl; return tlm::TLM_COMPLETED; } if (phase == tlm::BEGIN_RESP) { // Initiator obliged to check response status if (trans.is_response_error() ) SC_REPORT_ERROR("TLM2", "Response error from nb_transport"); cout << "trans/bw = { " << (cmd ? 'W' : 'R') << ", " << hex << adr << " } , data = " << hex << data << " at time " << sc_time_stamp() << ", delay = " << delay << endl; //Delay wait(delay); cout << name () << " BEGIN_RESP RECEIVED" << " TRANS ID " << id_extension->transaction_id << " at time " << sc_time_stamp() << endl; return tlm::TLM_ACCEPTED; } } // Internal data buffer used by initiator with generic payload int data; }; // Target module representing a simple memory struct Memory: sc_module { // TLM-2 socket, defaults to 32-bits wide, base protocol tlm_utils::simple_target_socket<Memory> socket; enum { SIZE = 256 }; const sc_time LATENCY; SC_CTOR(Memory) : socket("socket"), LATENCY(10, SC_NS) { // Register callbacks for incoming interface method calls socket.register_nb_transport_fw(this, &Memory::nb_transport_fw); //socket.register_nb_transport_bw(this, &Memory::nb_transport_bw); // Initialize memory with random data for (int i = 0; i < SIZE; i++) mem[i] = 0xAA000000 | (rand() % 256); SC_THREAD(thread_process); } // TLM2 non-blocking transport method virtual tlm::tlm_sync_enum nb_transport_fw( tlm::tlm_generic_payload& trans, tlm::tlm_phase& phase, sc_time& delay ) { sc_dt::uint64 adr = trans.get_address(); unsigned int len = trans.get_data_length(); unsigned char* byt = trans.get_byte_enable_ptr(); unsigned int wid = trans.get_streaming_width(); ID_extension* id_extension = new ID_extension; trans.get_extension( id_extension ); if(phase == tlm::END_REQ){ wait(delay); cout << name() << " END_REQ RECEIVED" << " TRANS ID " << id_extension->transaction_id << " at time " << sc_time_stamp() << endl; return tlm::TLM_COMPLETED; } if(phase == tlm::BEGIN_REQ){ // Obliged to check the transaction attributes for unsupported features // and to generate the appropriate error response if (byt != 0) { trans.set_response_status( tlm::TLM_BYTE_ENABLE_ERROR_RESPONSE ); return tlm::TLM_COMPLETED; } //if (len > 4 || wid < len) { // trans.set_response_status( tlm::TLM_BURST_ERROR_RESPONSE ); // return tlm::TLM_COMPLETED; //} // Now queue the transaction until the annotated time has elapsed trans_pending=&trans; phase_pending=phase; delay_pending=delay; e1.notify(); //Delay wait(delay); cout << name() << " BEGIN_REQ RECEIVED" << " TRANS ID " << id_extension->transaction_id << " at time " << sc_time_stamp() << endl; return tlm::TLM_ACCEPTED; } } // ********************************************* // Thread to call nb_transport on backward path // ********************************************* void thread_process() { while (true) { // Wait for an event to pop out of the back end of the queue wait(e1); //printf("ACCESING MEMORY\n"); //tlm::tlm_generic_payload* trans_ptr; tlm::tlm_phase phase; ID_extension* id_extension = new ID_extension; trans_pending->get_extension( id_extension ); tlm::tlm_command cmd = trans_pending->get_command(); sc_dt::uint64 adr = trans_pending->get_address() / 4; unsigned char* ptr = trans_pending->get_data_ptr(); unsigned int len = trans_pending->get_data_length(); unsigned char* byt = trans_pending->get_byte_enable_ptr(); unsigned int wid = trans_pending->get_streaming_width(); // Obliged to check address range and check for unsupported features, // i.e. byte enables, streaming, and bursts // Can ignore DMI hint and extensions // Using the SystemC report handler is an acceptable way of signalling an error if (adr >= sc_dt::uint64(SIZE) || byt != 0 || wid != 0 || len > 4) SC_REPORT_ERROR("TLM2", "Target does not support given generic payload transaction"); // Obliged to implement read and write commands if ( cmd == tlm::TLM_READ_COMMAND ) memcpy(ptr, &mem[adr], len); else if ( cmd == tlm::TLM_WRITE_COMMAND ) memcpy(&mem[adr], ptr, len); // Obliged to set response status to indicate successful completion trans_pending->set_response_status( tlm::TLM_OK_RESPONSE ); wait(20, SC_NS); delay_pending= (rand() % 4) * sc_time(10, SC_NS); cout << name() << " BEGIN_RESP SENT" << " TRANS ID " << id_extension->transaction_id << " at time " << sc_time_stamp() << endl; // Call on backward path to complete the transaction tlm::tlm_sync_enum status; phase = tlm::BEGIN_RESP; status = socket->nb_transport_bw( *trans_pending, phase, delay_pending ); // The target gets a final chance to read or update the transaction object at this point. // Once this process yields, the target must assume that the transaction object // will be deleted by the initiator // Check value returned from nb_transport switch (status) //case tlm::TLM_REJECTED: case tlm::TLM_ACCEPTED: wait(10, SC_NS); cout << name() << " END_RESP SENT" << " TRANS ID " << id_extension->transaction_id << " at time " << sc_time_stamp() << endl; // Expect response on the backward path phase = tlm::END_RESP; socket->nb_transport_bw( *trans_pending, phase, delay_pending ); // Non-blocking transport call //break; } } int mem[SIZE]; sc_event e1; tlm::tlm_generic_payload* trans_pending; tlm::tlm_phase phase_pending; sc_time delay_pending; }; SC_MODULE(TLM) { Initiator *initiator; Memory *memory; sc_core::sc_in<bool> IO_request; SC_HAS_PROCESS(TLM); TLM(sc_module_name tlm) // Construct and name socket { // Instantiate components initiator = new Initiator("initiator"); initiator->IO_request(IO_request); memory = new Memory ("memory"); // One initiator is bound directly to one target with no intervening bus // Bind initiator socket to target socket initiator->socket.bind(memory->socket); } };
#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. *****************************************************************************/ /***************************************************************************** rsa.cpp -- An implementation of the RSA public-key cipher. The following implementation is based on the one given in Cormen et al., Inroduction to Algorithms, 1991. I'll refer to this book as CLR because of its authors. This implementation shows the usage of arbitrary precision types of SystemC. That is, these types in SystemC can be used to implement algorithmic examples regarding arbitrary precision integers. The algorithms used are not the most efficient ones; however, they are intended for explanatory purposes, so they are simple and perform their job correctly. Below, NBITS shows the maximum number of bits in n, the variable that is a part of both the public and secret keys, P and S, respectively. NBITS can be made larger at the expense of longer running time. For example, CLR mentions that the RSA cipher uses large primes that contain approximately 100 decimal digits. This means that NBITS should be set to approximately 560. Some background knowledge: A prime number p > 1 is an integer that has only two divisiors, 1 and p itself. For example, 2, 3, 5, 7, and 11 are all primes. If p is not a prime number, it is called a composite number. If we are given two primes p and q, it is easy to find their product p * q; however, if we are given a number m which happens to be the product of two primes p and q that we do not know, it is very difficult to find p and q if m is very large, i.e., it is very difficult to factor m. The RSA public-key cryptosystem is based on this fact. Internally, we use the Miller-Rabin randomized primality test to deal with primes. More information can be obtained from pp. 831-836 in CLR, the first edition. Original Author: Ali Dasdan, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include <stdlib.h> #include <sys/types.h> #include <time.h> #include <stdlib.h> // drand48, srand48 #include "systemc.h" #define DEBUG_SYSTEMC // #undef this to disable assertions. // NBITS is the number of bits in n of public and secret keys P and // S. HALF_NBITS is the number of bits in p and q, which are the prime // factors of n. #define NBITS 250 #define HALF_NBITS ( NBITS / 2 ) // +2 is for the format specifier '0b' to make the string binary. #define STR_SIZE ( NBITS + 2 ) #define HALF_STR_SIZE ( HALF_NBITS + 2 ) typedef sc_bigint<NBITS> bigint; // Return the absolute value of x. inline bigint abs_val( const sc_signed& x ) { return ( x < 0 ? -x : x ); } // Initialize the random number generator. If seed == -1, the // generator will be initialized with the system time. If not, it will // be initialized with the given seed. This way, an experiment with // random numbers becomes reproducible. inline long randomize( int seed ) { long in_seed; // time_t is long. in_seed = ( seed <= 0 ? time( 0 ) : seed ); #ifndef WIN32 srand48( in_seed ); #else srand( ( unsigned ) in_seed ); #endif return in_seed; } // Flip a coin with probability p. #ifndef WIN32 inline bool flip( double p ) { return ( drand48() < p ); } #else inline bool flip( double p ) { const int MAX_VAL = ( 1 << 15 ); // rand() produces an integer between 0 and 2^15-1, so rand() / // MAX_VAL is a number between 0 and 1, which is required to compare // with p. return ( rand() < ( int ) ( p * MAX_VAL ) ); } #endif // Randomly generate a bit string with nbits bits. str has a length // of nbits + 1. This function is used to generate random messages to // process. inline void rand_bitstr( char *str, int nbits ) { assert( nbits >= 4 ); str[ 0 ] = '0'; str[ 1 ] = 'b'; str[ 2 ] = '0'; // Sign for positive numbers. for ( int i = 3; i < nbits; ++i ) str[ i ] = ( flip( 0.5 ) == true ? '1' : '0' ); str[ nbits ] = '\0'; } // Generate "111..111" with nbits bits for masking. // str has a length of nbits + 1. inline void max_bitstr( char *str, int nbits ) { assert( nbits >= 4 ); str[ 0 ] = '0'; str[ 1 ] = 'b'; str[ 2 ] = '0'; // Sign for positive numbers. for ( int i = 3; i < nbits; ++i ) str[ i ] = '1'; str[ nbits ] = '\0'; } // Return a positive remainder. inline bigint ret_pos( const bigint& x, const bigint& n ) { if ( x < 0 ) return x + n; return x; } // Compute the greatest common divisor ( gcd ) of a and b. This is // Euclid's algorithm. This algorithm is at least 2,300 years old! The // non-recursive version of this algorithm is not as elegant. bigint gcd( const bigint& a, const bigint& b ) { if ( b == 0 ) return a; return gcd( b, a % b ); } // Compute d, x, and y such that d = gcd( a, b ) = ax + by. x and y can // be zero or negative. This algorithm is also Euclid's algorithm but // it is extended to also find x and y. Recall that the existence of x // and y is guaranteed by Euclid's algorithm. void euclid( const bigint& a, const bigint& b, bigint& d, bigint& x, bigint& y ) { if ( b != 0 ) { euclid( b, a % b, d, x, y ); bigint tmp = x; x = y; y = tmp - ( a / b ) * y; } else { d = a; x = 1; y = 0; } } // Return d = a^b % n, where ^ represents exponentiation. inline bigint modular_exp( const bigint& a, const bigint& b, const bigint& n ) { bigint d = 1; for ( int i = b.length() - 1; i >= 0; --i ) { d = ( d * d ) % n; if ( b[ i ] ) d = ( d * a ) % n; } return ret_pos( d, n ); } // Return the multiplicative inverse of a, modulo n, when a and n are // relatively prime. Recall that x is a multiplicative inverse of a, // modulo n, if a * x = 1 ( mod n ). inline bigint inverse( const bigint& a, const bigint& n ) { bigint d, x, y; euclid( a, n, d, x, y ); assert( d == 1 ); x %= n; return ret_pos( x, n ); } // Find a small odd integer a that is relatively prime to n. I do not // know an efficient algorithm to do that but the loop below seems to // work; it usually iterates a few times. Recall that a is relatively // prime to n if their only common divisor is 1, i.e., gcd( a, n ) == // 1. inline bigint find_rel_prime( const bigint& n ) { bigint a = 3; while ( true ) { if ( gcd( a, n ) == 1 ) break; a += 2; #ifdef DEBUG_SYSTEMC assert( a < n ); #endif } return a; } // Return true if and only if a is a witness to the compositeness of // n, i.e., a can be used to prove that n is composite. inline bool witness( const bigint& a, const bigint& n ) { bigint n_minus1 = n - 1; bigint x; bigint d = 1; // Compute d = a^( n-1 ) % n. for ( int i = n.length() - 1; i >= 0; --i ) { // Sun's SC5 bug when compiling optimized version // makes the wrong assignment if abs_val() is inlined //x = (sc_signed)d<0?-(sc_signed)d:(sc_signed)d;//abs_val( d ); if(d<0) { x = -d; assert(x==-d); } else { x = d; assert(x==d); } d = ( d * d ) % n; // x is a nontrivial square root of 1 modulo n ==> n is composite. if ( ( abs_val( d ) == 1 ) && ( x != 1 ) && ( x != n_minus1 ) ) return true; if ( n_minus1[ i ] ) d = ( d * a ) % n; } // d = a^( n-1 ) % n != 1 ==> n is composite. if ( abs_val( d ) != 1 ) return true; return false; } // Check to see if n has any small divisors. For small numbers, we do // not have to run the Miller-Rabin primality test. We define "small" // to be less than 1023. You can change it if necessary. inline bool div_test( const bigint& n ) { int limit; if ( n < 1023 ) limit = n.to_int() - 2; else limit = 1023; for ( int i = 3; i <= limit; i += 2 ) { if ( n % i == 0 ) return false; // n is composite. } return true; // n may be prime. } // Return true if n is almost surely prime, return false if n is // definitely composite. This test, called the Miller-Rabin primality // test, errs with probaility at most 2^(-s). CLR suggests s = 50 for // any imaginable application, and s = 3 if we are trying to find // large primes by applying miller_rabin to randomly chosen large // integers. Even though we are doing the latter here, we will still // choose s = 50. The probability of failure is at most // 0.00000000000000088817, a pretty small number. inline bool miller_rabin( const bigint& n ) { if ( n <= 2 ) return false; if ( ! div_test( n ) ) return false; char str[ STR_SIZE + 1 ]; int s = 50; for ( int j = 1; j <= s; ++j ) { // Choose a random number. rand_bitstr( str, STR_SIZE ); // Set a to the chosen number. bigint a = str; // Make sure that a is in [ 1, n - 1 ]. a = ( a % ( n - 1 ) ) + 1; // Check to see if a is a witness. if ( witness( a, n ) ) return false; // n is definitely composite. } return true; // n is almost surely prime. } // Return a randomly generated, large prime number using the // Miller-Rabin primality test. inline bigint find_prime( const bigint& r ) { char p_str[ HALF_STR_SIZE + 1 ]; rand_bitstr( p_str, HALF_STR_SIZE ); p_str[ HALF_STR_SIZE - 1 ] = '1'; // Force p to be an odd number. bigint p = p_str; #ifdef DEBUG_SYSTEMC assert( ( p > 0 ) && ( p % 2 == 1 ) ); #endif // p is randomly determined. Now, we'll look for a prime in the // vicinity of p. By the prime number theorem, executing the // following loop approximately ln ( 2^NBITS ) iterations should // find a prime. #ifdef DEBUG_SYSTEMC // A very large counter to check against infinite loops. sc_bigint<NBITS> niter = 0; #endif while ( ! miller_rabin( p ) ) { p = ( p + 2 ) % r; #ifdef DEBUG_SYSTEMC assert( ++niter > 0 ); #endif } return p; } // Encode or cipher the message in msg using the RSA public key P=( e, n ). inline bigint cipher( const bigint& msg, const bigint& e, const bigint& n ) { return modular_exp( msg, e, n ); } // Dencode or decipher the message in msg using the RSA secret key S=( d, n ). inline bigint decipher( const bigint& msg, const bigint& d, const bigint& n ) { return modular_exp( msg, d, n ); } // The RSA cipher. inline void rsa( int seed ) { // Generate all 1's in r. char r_str[ HALF_STR_SIZE + 1 ]; max_bitstr( r_str, HALF_STR_SIZE ); bigint r = r_str; #ifdef DEBUG_SYSTEMC assert( r > 0 ); #endif // Initialize the random number generator. cout << "\nRandom number generator seed = " << randomize( seed ) << endl; cout << endl; // Find two large primes p and q. bigint p = find_prime( r ); bigint q = find_prime( r ); #ifdef DEBUG_SYSTEMC assert( ( p > 0 ) && ( q > 0 ) ); #endif // Compute n and ( p - 1 ) * ( q - 1 ) = m. bigint n = p * q; bigint m = ( p - 1 ) * ( q - 1 ); #ifdef DEBUG_SYSTEMC assert( ( n > 0 ) && ( m > 0 ) ); #endif // Find a small odd integer e that is relatively prime to m. bigint e = find_rel_prime( m ); #ifdef DEBUG_SYSTEMC assert( e > 0 ); #endif // Find the multiplicative inverse d of e, modulo m. bigint d = inverse( e, m ); #ifdef DEBUG_SYSTEMC assert( d > 0 ); #endif // Output public and secret keys. cout << "RSA public key P: P=( e, n )" << endl; cout << "e = " << e << endl; cout << "n = " << n << endl; cout << endl; cout << "RSA secret key S: S=( d, n )" << endl; cout << "d = " << d << endl; cout << "n = " << n << endl; cout << endl; // Cipher and decipher a randomly generated message msg. char msg_str[ STR_SIZE + 1 ]; rand_bitstr( msg_str, STR_SIZE ); bigint msg = msg_str; msg %= n; // Make sure msg is smaller than n. If larger, this part // will be a block of the input message. #ifdef DEBUG_SYSTEMC assert( msg > 0 ); #endif cout << "Message to be ciphered = " << endl; cout << msg << endl; bigint msg2 = cipher( msg, e, n ); cout << "\nCiphered message = " << endl; cout << msg2 << endl; msg2 = decipher( msg2, d, n ); cout << "\nDeciphered message = " << endl; cout << msg2 << endl; // Make sure that the original message is recovered. if ( msg == msg2 ) { cout << "\nNote that the original message == the deciphered message, " << endl; cout << "showing that this algorithm and implementation work correctly.\n" << endl; } else { // This case is unlikely. cout << "\nNote that the original message != the deciphered message, " << endl; cout << "showing that this implementation works incorrectly.\n" << endl; } return; } int sc_main( int argc, char *argv[] ) { if ( argc <= 1 ) rsa( -1 ); else rsa( atoi( argv[ 1 ] ) ); return 0; } // End of file
#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; }
/******************************************************************************* * ledcmod.cpp -- Copyright 2020 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Implements a SystemC module for the ESP32 PWM LEDC module. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #define SC_INCLUDE_DYNAMIC_PROCESSES #include <systemc.h> #include "ledcmod.h" #include "setfield.h" #include "soc/ledc_struct.h" #include "soc/ledc_reg.h" #include "clockpacer.h" #include "info.h" #define LEDC_OVF_TIMER_INTR 0 #define LEDC_DUTYEND_TIMER_INTR 8 void ledcmod::updateth() { int ch; int tim; sc_time base_period; while(true) { wait(); for(ch = 0; ch < (LEDC_CHANNELS/2); ch = ch + 1) { conf0[ch].write(LEDC.channel_group[0].channel[ch].conf0.val); conf1[ch].write(LEDC.channel_group[0].channel[ch].conf1.val); hpoint[ch].write(LEDC.channel_group[0].channel[ch].hpoint.val); duty[ch].write(LEDC.channel_group[0].channel[ch].duty.val); conf0[ch+LEDC_CHANNELS/2].write( LEDC.channel_group[1].channel[ch].conf0.val); conf1[ch+LEDC_CHANNELS/2].write( LEDC.channel_group[1].channel[ch].conf1.val); hpoint[ch+LEDC_CHANNELS/2].write( LEDC.channel_group[1].channel[ch].hpoint.val); duty[ch+LEDC_CHANNELS/2].write( LEDC.channel_group[1].channel[ch].duty.val); } /* we do not actually build the timers, so we need to do some * precalculations for the channels. */ for(tim = 0; tim < (LEDC_TIMERS/2); tim = tim + 1) { /* HSTIMER */ timer_conf[tim].write(LEDC.timer_group[0].timer[tim].conf.val); if (LEDC.timer_group[0].timer[tim].conf.tick_sel == 0) base_period = clockpacer.get_ref_period(); else base_period = clockpacer.get_apb_period(); /* TODO -- do the decimal part */ timerinc[tim].write( sc_time(base_period * (LEDC.timer_group[0].timer[tim].conf.clock_divider>>8))); /* LSTIMER */ timer_conf[tim+LEDC_TIMERS/2].write( LEDC.timer_group[1].timer[tim].conf.val); if (LEDC.timer_group[1].timer[tim].conf.tick_sel == 0) base_period = clockpacer.get_ref_period(); else base_period = clockpacer.get_rtc8m_period(); /* TODO -- do the decimal part */ /* TODO -- do the pause */ if (LEDC.timer_group[1].timer[tim].conf.low_speed_update) { timerinc[tim+LEDC_TIMERS/2].write(sc_time(base_period * (LEDC.timer_group[1].timer[tim].conf.clock_divider>>8))); } } /* int_ena we simply copy. */ int_ena.write(LEDC.int_ena.val); /* If we got a clear command, we trigger the event for the returnth to * handle it. */ if (LEDC.int_clr.val != 0x0) int_clr_ev.notify(); } } void ledcmod::returnth() { int un; /* We wait for one of the responses to get triggered, and then we copy the * R/O register back to the struct. */ while (true) { wait( timer_cnt[0].value_changed_event()| timer_cnt[1].value_changed_event() | timer_cnt[2].value_changed_event()| timer_cnt[3].value_changed_event() | timer_cnt[4].value_changed_event()| timer_cnt[5].value_changed_event() | timer_cnt[6].value_changed_event()| timer_cnt[7].value_changed_event() | duty_r[0].value_changed_event()| duty_r[1].value_changed_event() | duty_r[2].value_changed_event()| duty_r[3].value_changed_event() | duty_r[4].value_changed_event()| duty_r[5].value_changed_event() | duty_r[6].value_changed_event()| duty_r[7].value_changed_event() | duty_r[8].value_changed_event()| duty_r[9].value_changed_event() | duty_r[10].value_changed_event()| duty_r[11].value_changed_event() | duty_r[12].value_changed_event()| duty_r[13].value_changed_event() | duty_r[14].value_changed_event()| duty_r[15].value_changed_event() | int_clr_ev | int_ev[0] | int_ev[1] | int_ev[2] | int_ev[3] | int_ev[4] | int_ev[5] | int_ev[6] | int_ev[7] | int_ev[8] | int_ev[9] | int_ev[10]| int_ev[11]| int_ev[12]| int_ev[13]| int_ev[14]| int_ev[15]| int_ev[16]| int_ev[17]| int_ev[18]| int_ev[19]| int_ev[20]| int_ev[21]| int_ev[22]| int_ev[23]); for (un = 0; un < LEDC_CHANNELS; un = un + 1) { LEDC.int_raw.val = 0x0; /* If we hit the maximum dither times, we have an interrupt and * clear the duty_start. */ if (int_ev[un+LEDC_DUTYEND_TIMER_INTR].triggered()) { LEDC.int_raw.val = LEDC.int_raw.val | (1<<un); if (un < LEDC_CHANNELS/2) LEDC.channel_group[0].channel[un].conf1.duty_start = false; else LEDC.channel_group[1].channel[un-8].conf1.duty_start = false; } /* We copy the duty values */ if (un < LEDC_CHANNELS/2) LEDC.channel_group[0].channel[un].duty_rd.duty_read = duty_r[un].read(); else LEDC.channel_group[1].channel[un-8].duty_rd.duty_read = duty_r[un-8].read(); } /* We also copy over the timer values and interrupts. */ for(un = 0; un < (LEDC_TIMERS/2); un = un + 1) { if (int_ev[un+LEDC_OVF_TIMER_INTR].triggered()) LEDC.int_raw.val = LEDC.int_raw.val | (1<<un); LEDC.timer_group[0].timer[un].value.timer_cnt = timer_cnt[un].read(); if (int_ev[un+LEDC_OVF_TIMER_INTR+LEDC_TIMERS/2].triggered()) LEDC.int_raw.val = LEDC.int_raw.val | (1<<un+LEDC_TIMERS/2); LEDC.timer_group[1].timer[un].value.timer_cnt = timer_cnt[un].read(); } /* If we have a clear event we take it too. */ if (int_clr_ev.triggered()) { LEDC.int_raw.val = LEDC.int_raw.val & ~LEDC.int_clr.val; LEDC.int_clr.val = 0; } /* We update the raw. */ LEDC.int_st.val = LEDC.int_raw.val & int_ena.read(); /* We also drive the interrupt line */ intr_o.write(LEDC.int_st.val != 0); } } void ledcmod::update() { update_ev.notify(); clockpacer.wait_next_apb_clk(); } void ledcmod::initstruct() { memset(&LEDC, 0, sizeof(ledc_dev_t)); /* The reset bits begin all on. */ LEDC.timer_group[0].timer[0].conf.rst = 1; LEDC.timer_group[0].timer[1].conf.rst = 1; LEDC.timer_group[0].timer[2].conf.rst = 1; LEDC.timer_group[0].timer[3].conf.rst = 1; LEDC.timer_group[1].timer[0].conf.rst = 1; LEDC.timer_group[1].timer[1].conf.rst = 1; LEDC.timer_group[1].timer[2].conf.rst = 1; LEDC.timer_group[1].timer[3].conf.rst = 1; } void ledcmod::start_of_simulation() { /* We spawn a thread for each channel and timer. */ int un; for(un = 0; un < LEDC_CHANNELS; un = un + 1) { conf0[un].write(0); conf1[un].write(0); hpoint[un].write(0); duty[un].write(0); } for(un = 0; un < sig_out_hs_o.size(); un = un + 1) { sc_spawn(sc_bind(&ledcmod::channel, this, un)); sig_out_hs_o[un]->write(false); } for(un = LEDC_CHANNELS/2; un < sig_out_ls_o.size(); un = un + 1) { sc_spawn(sc_bind(&ledcmod::channel, this, un)); sig_out_ls_o[un-LEDC_CHANNELS/2]->write(false); } for(un = 0; un < LEDC_TIMERS; un = un + 1) { sc_spawn(sc_bind(&ledcmod::timer, this, un)); /* The RST bit starts off high, the other bits all start off low. */ timer_conf[un].write(LEDC_HSTIMER0_RST_M); timer_cnt[un].write(0); timer_lim[un].write(0); timerinc[un].write(sc_time(0, SC_NS)); } int_ena.write(0); } void ledcmod::calc_points(int un, bool start_dither) { int lp; int lpoint_frac; bool duty_start; int duty_num; int duty_cycle; bool duty_inc; int duty_scale; /* We first take the values into local registers to not have to keep * placing these lines in the middle of the code. */ if (un < LEDC_CHANNELS/2) { duty_start = (RDFIELD(conf1[un],LEDC_DUTY_START_HSCH0_M,LEDC_DUTY_START_HSCH0_S)>0); duty_num = RDFIELD(conf1[un],LEDC_DUTY_NUM_HSCH0_M,LEDC_DUTY_NUM_HSCH0_S); duty_cycle = RDFIELD(conf1[un],LEDC_DUTY_CYCLE_HSCH0_M,LEDC_DUTY_CYCLE_HSCH0_S); duty_inc = (RDFIELD(conf1[un],LEDC_DUTY_CYCLE_HSCH0_M,LEDC_DUTY_INC_HSCH0_S)>0); duty_scale = RDFIELD(conf1[un],LEDC_DUTY_CYCLE_HSCH0_M,LEDC_DUTY_SCALE_HSCH0_S); } else { duty_start = (RDFIELD(conf1[un],LEDC_DUTY_START_LSCH0_M,LEDC_DUTY_START_LSCH0_S)>0); duty_num = RDFIELD(conf1[un],LEDC_DUTY_NUM_LSCH0_M,LEDC_DUTY_NUM_LSCH0_S); duty_cycle = RDFIELD(conf1[un],LEDC_DUTY_CYCLE_LSCH0_M,LEDC_DUTY_CYCLE_LSCH0_S); duty_inc = (RDFIELD(conf1[un],LEDC_DUTY_CYCLE_LSCH0_M,LEDC_DUTY_INC_LSCH0_S)>0); duty_scale = RDFIELD(conf1[un],LEDC_DUTY_CYCLE_LSCH0_M,LEDC_DUTY_SCALE_LSCH0_S); } /* We get the lpoint and frac. */ lp = (duty[un].read() >> 4); lpoint_frac = duty[un].read() & 0x0f; /* We adjust the lpoint according to the fraction */ if (lpoint_frac > thiscyc[un]) lp = lp + 1; /* And we adjust the lpoint according to the dither. */ if (duty_start) { if (start_dither) { /* If this is the first time, dithcycles will be zero. We then * start by loading the settings of the dither and go on. */ dithtimes[un] = duty_num; dithcycles[un] = duty_cycle; } else { /* Other times we count the cycles and process it. */ dithcycles[un] = dithcycles[un] - 1; /* If we hit the target, we are done. */ if (dithcycles == 0 && duty_inc) { lp = lp + duty_scale; dithcycles[un] = duty_cycle; dithtimes[un] = dithtimes[un] - 1; } else if (dithcycles[un] == 0) { lp = lp - duty_scale; dithcycles[un] = duty_cycle; dithtimes[un] = dithtimes[un] - 1; } int_ev[un+LEDC_DUTYEND_TIMER_INTR].notify(); } } /* We put the lp value in the read/only register. */ duty_r[un].write(lp & LEDC_DUTY_HSCH0); thislp[un] = lp & LEDC_DUTY_HSCH0; } void ledcmod::channel(int ch) { bool outen; bool recheckpoints; /* Sel begins with -1 and it then is switched to the correct value. */ int sel = -1; while(1) { /* If there is no selected timer, all we do is wait for a configuration * change. If there is a timer specified, we wait for a timer trigger * or a configuration change. */ if (sel < 0) wait(conf0[ch].value_changed_event()); else wait(conf0[ch].value_changed_event() | conf1[ch].value_changed_event() | hpoint[ch].value_changed_event() | duty[ch].value_changed_event() | timer_cnt[sel].value_changed_event()); /* We go ahead and grab the output enable as we use it quite often. */ if (ch < LEDC_CHANNELS/2) { outen = RDFIELD(conf0[ch], LEDC_SIG_OUT_EN_HSCH0_M, LEDC_SIG_OUT_EN_HSCH0_S); sel= RDFIELD(conf0[ch], LEDC_TIMER_SEL_HSCH0_M, LEDC_TIMER_SEL_HSCH0_S); } else { outen = RDFIELD(conf0[ch], LEDC_SIG_OUT_EN_LSCH0_M, LEDC_SIG_OUT_EN_LSCH0_S); sel= RDFIELD(conf0[ch], LEDC_TIMER_SEL_LSCH0_M, LEDC_TIMER_SEL_LSCH0_S) + LEDC_TIMERS/2; } /* First we process changes in the PWM. These can affect the rest. */ /* If we got a trigger on the output and the channel is stopped, we * update the value. * The timer we ignore as the timer mux is done outside the channel. */ if (conf0[ch].event() && !outen) { if (ch < LEDC_CHANNELS/2) sig_out_hs_o[ch]->write( RDFIELD(conf0[ch], LEDC_IDLE_LV_HSCH0_M, LEDC_IDLE_LV_HSCH0_S)); else sig_out_ls_o[ch-LEDC_CHANNELS/2]->write( RDFIELD(conf0[ch], LEDC_IDLE_LV_LSCH0_M, LEDC_IDLE_LV_LSCH0_S)); } /* If we see a change in the hpoint or the duty we need to recalculate * the lpoint. We also need to do this when the timer is switched or when * we start a new cycle. */ if (duty[ch].event() || conf0[ch].event()) { calc_points(ch, true); /* We restart the cycle calculation. */ thiscyc[ch] = 0; /* And we will need to recheck the hpoint and lpoint. */ recheckpoints = true; } /* Anytime the cycle restarts (timer returns to zero) we need to * increment the cycle counter and adjust the jitter, if any. */ else if (timer_cnt[sel].read() == 0) { /* We start adjusting the cycle number for the dither. */ thiscyc[ch] = thiscyc[ch] + 1; if (thiscyc[ch] == LEDC_CYCLES) thiscyc[ch] = 0; /* We also calculate the lpoint. */ calc_points(ch, false); /* And we will need to recheck the hpoint and lpoint. */ recheckpoints = true; } else recheckpoints = false; /* If it was a timer tick, we need to see if it affects us. */ if (outen && (timer_cnt[sel].event() || recheckpoints)) { /* And we check where we are in the flow. */ bool nv; if (timer_cnt[sel].read() >= thislp[ch] + hpoint[ch].read()) nv = false; else if (timer_cnt[sel].read() >= hpoint[ch]) nv = true; else nv = false; if (ch < LEDC_CHANNELS/2) sig_out_hs_o[ch]->write(nv); else sig_out_ls_o[ch-LEDC_CHANNELS/2]->write(nv); } } } void ledcmod::timer(int tim) { bool rst; bool pause; bool wasstoped = true; while(1) { /* We wait for a timer tick or a change to the configuration register. */ wait(timer_ev[tim] | timer_conf[tim].value_changed_event() | timerinc[tim].value_changed_event()); /* We get the parameters first. */ if (tim < LEDC_TIMERS/2) { rst = RDFIELD(timer_conf[tim], LEDC_HSTIMER0_RST_M, LEDC_HSTIMER0_RST_S)>0; pause = RDFIELD(timer_conf[tim], LEDC_HSTIMER0_PAUSE_M, LEDC_HSTIMER0_PAUSE_S)>0; } else { rst = RDFIELD(timer_conf[tim], LEDC_LSTIMER0_RST_M, LEDC_LSTIMER0_RST_S)>0; pause = RDFIELD(timer_conf[tim], LEDC_LSTIMER0_PAUSE_M, LEDC_LSTIMER0_PAUSE_S)>0; } /* If we are in reset, we clear any future time events and wait. The next * event should be then a configuration change. */ if (rst) { timer_cnt[tim].write(0); timer_ev[tim].cancel(); wasstoped = true; } /* If we are paused, we just cancel any future events, but we do not * touch the counter value. */ else if (pause) { timer_ev[tim].cancel(); wasstoped = true; } /* If the timer increment is zero, we do the same. */ else if (timerinc[tim].read() == sc_time(0, SC_NS)) { timer_ev[tim].cancel(); } /* If we are comming out of reset or pause, we need to get the counter * going. */ else if (wasstoped) { timer_ev[tim].notify(timerinc[tim]); wasstoped = false; } /* We only count on timer event triggers. Configuration events should * not change the timer value. */ else if (timer_ev[tim].triggered()) { /* We calculate the next value, whichever it is. */ if (timer_cnt[tim].read() < timer_lim[tim].read() - 1) timer_cnt[tim].write(timer_cnt[tim].read() + 1); else { /* We hit the end we write a zero and raise the interrupt. */ timer_cnt[tim].write(0); int_ev[tim+LEDC_OVF_TIMER_INTR].notify(); } /* And we sleep until the next event. */ timer_ev[tim].notify(timerinc[tim]); } } } void ledcmod::trace(sc_trace_file *tf) { int un; std::string sigb = name(); std::string sign; for(un = 0; un < LEDC_CHANNELS; un = un + 1) { sign = sigb + std::string(".conf0_") + std::to_string(un); sc_trace(tf, conf0[un], sign.c_str()); } for(un = 0; un < LEDC_CHANNELS; un = un + 1) { sign = sigb + std::string(".conf1_") + std::to_string(un); sc_trace(tf, conf1[un], sign.c_str()); } for(un = 0; un < LEDC_CHANNELS; un = un + 1) { sign = sigb + std::string(".hpoint_") + std::to_string(un); sc_trace(tf, hpoint[un], sign.c_str()); } for(un = 0; un < LEDC_CHANNELS; un = un + 1) { sign = sigb + std::string(".duty_") + std::to_string(un); sc_trace(tf, duty[un], sign.c_str()); } for(un = 0; un < LEDC_CHANNELS; un = un + 1) { sign = sigb + std::string(".duty_r") + std::to_string(un); sc_trace(tf, duty_r[un], sign.c_str()); } for(un = 0; un < LEDC_TIMERS; un = un + 1) { sign = sigb + std::string(".timer_conf_") + std::to_string(un); sc_trace(tf, timer_conf[un], sign.c_str()); } for(un = 0; un < LEDC_TIMERS; un = un + 1) { sign = sigb + std::string(".timer_cnt_") + std::to_string(un); sc_trace(tf, timer_cnt[un], sign.c_str()); } for(un = 0; un < LEDC_TIMERS; un = un + 1) { sign = sigb + std::string(".timer_lim_") + std::to_string(un); sc_trace(tf, timer_lim[un], sign.c_str()); } }
/******************************************************************************* * TestSerial.cpp -- Copyright 2019 Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * Generic Serial Class for communicating with a set of SystemC ports. * This class tries to mimic the behaviour used by the Hardware Serial * and SoftwareSerial classes used by the Arduino IDE. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "info.h" #include "TestSerial.h" #include "clockpacer.h" #include "Arduino.h" TestSerial::TestSerial() { taken = false; waiting = '\0'; uartno = -1; pinmodeset = false; } TestSerial::TestSerial(int _u) { if(_u < 0 || _u > 2) { printf("Invalid UART %d", _u); uartno = 0; } uartno = _u; taken = false; waiting = '\0'; pinmodeset = false; } TestSerial::TestSerial(int _rxpin, int _rxmode, int _txpin, int _txmode) { taken = false; waiting = '\0'; pinmodeset = true; rxpin = _rxpin; rxmode = _rxmode; txpin = _txpin; txmode = _txmode; } TestSerial::~TestSerial() {} void TestSerial::begin(int baudrate, int mode, int pinrx, int pintx) { if (baudrate <= 0) baudrate = 9600; PRINTF_INFO("TSER", "Setting UART %d Baud rate to %0d", uartno, baudrate); /* We set the pin modes. If a value was given in the arguments, we take it. * If not, we check the pinmodeset list. If it was set, we leave it as is. * If not, we go with the UART number. */ if (pinrx >= 0) rxpin = pinrx; else if (!pinmodeset) switch(uartno) { case 0: rxpin = RX; break; case 1: rxpin = 9; break; case 2: rxpin = 16; break; } if (pintx >= 0) txpin = pintx; else if (!pinmodeset) switch(uartno) { case 0: txpin = TX; break; case 1: txpin = 10; break; case 2: txpin = 17; break; } /* For the modes, we do the same. */ if (mode < 0 || !pinmodeset) { rxmode = INPUT; txmode = OUTPUT; } /* We first drive the TX level high. It is now an input, but when we change * the pin to be an output, it will not drive a zero. */ pinMode(rxpin, rxmode); pinMatrixInAttach(rxpin, (uartno == 0)?U0RXD_IN_IDX: (uartno == 1)?U1RXD_IN_IDX: (uartno == 2)?U2RXD_IN_IDX:0, false); pinMode(txpin, txmode); pinMatrixOutAttach(txpin, (uartno == 0)?U0TXD_OUT_IDX: (uartno == 1)?U1TXD_OUT_IDX: (uartno == 2)?U2TXD_OUT_IDX:0, false, false); } void TestSerial::setports(sc_fifo<unsigned char> *_to, sc_fifo<unsigned char> *_from) { to = _to; from = _from; } bool TestSerial::isinit() { if (from == NULL || to == NULL) return false; else return true; } void TestSerial::end() { PRINTF_INFO("TSER", "Ending Serial");} int TestSerial::printf(const char *fmt, ...) { char buff[128], *ptr; int resp; va_list argptr; va_start(argptr, fmt); resp = vsnprintf(buff, 127, fmt, argptr); va_end(argptr); ptr = buff; if (to == NULL) return 0; while(*ptr != '\0') { clockpacer.wait_next_apb_clk(); to->write(*ptr++); } return resp; } size_t TestSerial::write(uint8_t ch) { clockpacer.wait_next_apb_clk(); if (to == NULL) return 0; to->write(ch); return 1; } size_t TestSerial::write(const char* buf) { size_t sent = 0; clockpacer.wait_next_apb_clk(); while(*buf != '\0') { write(*buf); sent = sent + 1; buf = buf + 1; } return sent; } size_t TestSerial::write(const char* buf, size_t len) { size_t sent = 0; clockpacer.wait_next_apb_clk(); while(sent < len) { write(*buf); sent = sent + 1; buf = buf + 1; } return sent; } int TestSerial::availableForWrite() { /* We return if there is space in the buffer. */ if (to == NULL) return 0; return to->num_free(); } int TestSerial::available() { /* If we have something taken due to a peek, we need to inform the * requester that we still have something to return. So we have at * least one. If taken is false, then it depends on the number * available. */ clockpacer.wait_next_apb_clk(); if (from == NULL) return 0; if (taken) return 1 + from->num_available(); else return from->num_available(); } void TestSerial::flush() { /* For flush we get rid of the taken character and then we use the FIFO's * read to dump the rest. */ taken = false; while(from != NULL && from->num_available()>0) from->read(); } int TestSerial::read() { /* Anytime we leave the CPU we need to do a dummy delay. This makes sure * time advances, in case we happen to be in a timeout loop. */ clockpacer.wait_next_apb_clk(); if (from == NULL) return -1; if (taken) { taken = false; return waiting; } else if (!from->num_available()) return -1; return (int)from->read(); } int TestSerial::bl_read() { /* Just like the one above but it does a blocking read. Useful to cut * on polled reads. */ clockpacer.wait_next_apb_clk(); if (from == NULL) return -1; if (taken) { taken = false; return waiting; } return from->read(); } int TestSerial::bl_read(sc_time tmout) { /* And this is a blocking read with a timeout. */ clockpacer.wait_next_apb_clk(); if (from == NULL) return -1; if (taken) { taken = false; return waiting; } /* If there is nothing available, we wait for it to arrive or a timeout. */ if (available() == 0) { wait(tmout, from->data_written_event()); clockpacer.wait_next_apb_clk(); if (available() == 0) return -1; } /* If it was all good, we return it. */ return from->read(); } int TestSerial::peek() { clockpacer.wait_next_apb_clk(); if (from == NULL) return -1; if (taken) return waiting; else if (!from->num_available()) return -1; else { taken = true; waiting = from->read(); return waiting; } } int TestSerial::bl_peek() { clockpacer.wait_next_apb_clk(); if (from == NULL) return -1; if (taken) return waiting; else { taken = true; waiting = from->read(); return waiting; } } int TestSerial::bl_peek(sc_time tmout) { clockpacer.wait_next_apb_clk(); if (from == NULL) return -1; if (taken) return waiting; else { /* If there is nothing available,we wait for it to arrive or a timeout. */ if (available() == 0) { wait(tmout, from->data_written_event()); clockpacer.wait_next_apb_clk(); if (available() == 0) return -1; } taken = true; waiting = from->read(); return waiting; } }
/* * @ASCK */ #include <systemc.h> SC_MODULE (ALU) { sc_in <sc_int<8>> in1; // A sc_in <sc_int<8>> in2; // B sc_in <bool> c; // Carry Out // in this project, this signal is always 1 // ALUOP // has 5 bits by merging: opselect (4bits) and first LSB bit of opcode (1bit) sc_in <sc_uint<5>> aluop; sc_in <sc_uint<3>> sa; // Shift Amount sc_out <sc_int<8>> out; // Output /* ** module global variables */ // SC_CTOR (ALU){ SC_METHOD (process); sensitive << in1 << in2 << aluop; } void process () { sc_int<8> a = in1.read(); sc_int<8> b = in2.read(); bool cin = c.read(); sc_uint<5> op = aluop.read(); sc_uint<3> sh = sa.read(); switch (op){ case 0b00000 : out.write(a); break; case 0b00001 : out.write(++a); break; case 0b00010 : out.write(a+b); break; case 0b00011 : out.write(a+b+cin); break; case 0b00100 : out.write(a-b); break; case 0b00101 : out.write(a-b-cin); break; case 0b00110 : out.write(--a); break; case 0b00111 : out.write(b); break; case 0b01000 : case 0b01001 : out.write(a&b); break; case 0b01010 : case 0b01011 : out.write(a|b); break; case 0b01100 : case 0b01101 : out.write(a^b); break; case 0b01110 : case 0b01111 : out.write(~a); break; case 0b10000 : case 0b10001 : case 0b10010 : case 0b10011 : case 0b10100 : case 0b10101 : case 0b10110 : case 0b10111 : out.write(a>>sh); break; default: out.write(a<<sh); break; } } };
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // 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()); } } } };
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** fir.cpp -- Original Author: Rocco Jonack, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation: Teodor Vasilache and Dragos Dospinescu, AMIQ Consulting s.r.l. ([email protected]) Date: 2018-Feb-20 Description of Modification: Added sampling of the covergroup created in the "fir.h" file. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include <systemc.h> #include "fir.h" void fir::entry() { sc_int<8> sample_tmp; sc_int<17> pro; sc_int<19> acc; sc_int<8> shift[16]; // reset watching /* this would be an unrolled loop */ for (int i=0; i<=15; i++) shift[i] = 0; result.write(0); output_data_ready.write(false); wait(); // main functionality while(1) { output_data_ready.write(false); do { wait(); } while ( !(input_valid == true) ); sample_tmp = sample.read(); acc = sample_tmp*coefs[0]; for(int i=14; i>=0; i--) { /* this would be an unrolled loop */ pro = shift[i]*coefs[i+1]; acc += pro; }; for(int i=14; i>=0; i--) { /* this would be an unrolled loop */ shift[i+1] = shift[i]; }; shift[0] = sample_tmp; // sample the shift value shift_cg.sample(shift[0]); // write output values result.write((int)acc); output_data_ready.write(true); wait(); }; }
/******************************************************************************** * University of L'Aquila - HEPSYCODE Source Code License * * * * * * (c) 2018-2019 Centre of Excellence DEWS All rights reserved * ******************************************************************************** * <one line to give the program's name and a brief idea of what it does.> * * Copyright (C) 2022 Vittoriano Muttillo, Luigi Pomante * * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * ******************************************************************************** * * * Created on: 09/May/2023 * * Authors: Vittoriano Muttillo, Marco Santic, Luigi Pomante * * * * email: [email protected] * * [email protected] * * [email protected] * * * ******************************************************************************** * This code has been developed from an HEPSYCODE model used as demonstrator by * * University of L'Aquila. * *******************************************************************************/ #include <systemc.h> #include "../mainsystem.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <unistd.h> ////////////////////////////// GENANN ////////////////// #ifdef __cplusplus extern "C" { #endif #ifndef ann_02_GENANN_RANDOM /* We use the following for uniform random numbers between 0 and 1. * If you have a better function, redefine this macro. */ #define ann_02_GENANN_RANDOM() (((double)rand())/RAND_MAX) #endif struct ann_02_genann; typedef double (*ann_02_genann_actfun)(const struct ann_02_genann *ann, double a); typedef struct ann_02_genann { /* How many inputs, outputs, and hidden neurons. */ int inputs, hidden_layers, hidden, outputs; /* Which activation function to use for hidden neurons. Default: gennann_act_sigmoid_cached*/ ann_02_genann_actfun activation_hidden; /* Which activation function to use for output. Default: gennann_act_sigmoid_cached*/ ann_02_genann_actfun activation_output; /* Total number of weights, and size of weights buffer. */ int total_weights; /* Total number of neurons + inputs and size of output buffer. */ int total_neurons; /* All weights (total_weights long). */ double *weight; /* Stores input array and output of each neuron (total_neurons long). */ double *output; /* Stores delta of each hidden and output neuron (total_neurons - inputs long). */ double *delta; } ann_02_genann; #ifdef __cplusplus } #endif ///////////////////////////////////// GENANN /////////////////////////// #ifndef ann_02_genann_act #define ann_02_genann_act_hidden ann_02_genann_act_hidden_indirect #define ann_02_genann_act_output ann_02_genann_act_output_indirect #else #define ann_02_genann_act_hidden ann_02_genann_act #define ann_02_genann_act_output ann_02_genann_act #endif #define ann_02_LOOKUP_SIZE 4096 double ann_02_genann_act_hidden_indirect(const struct ann_02_genann *ann, double a) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return ann->activation_hidden(ann, a); } double ann_02_genann_act_output_indirect(const struct ann_02_genann *ann, double a) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return ann->activation_output(ann, a); } const double ann_02_sigmoid_dom_min = -15.0; const double ann_02_sigmoid_dom_max = 15.0; double ann_02_interval; double ann_02_lookup[ann_02_LOOKUP_SIZE]; #ifdef __GNUC__ #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #define unused __attribute__((unused)) #else #define likely(x) x #define unlikely(x) x #define unused #pragma warning(disable : 4996) /* For fscanf */ #endif double ann_02_genann_act_sigmoid(const ann_02_genann *ann unused, double a) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) if (a < -45.0) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return 0; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) if (a > 45.0) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return 1; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return 1.0 / (1 + exp(-a)); } void ann_02_genann_init_sigmoid_lookup(const ann_02_genann *ann) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) const double f = (ann_02_sigmoid_dom_max - ann_02_sigmoid_dom_min) / ann_02_LOOKUP_SIZE; HEPSY_S(ann_02_id) int i; HEPSY_S(ann_02_id) ann_02_interval = ann_02_LOOKUP_SIZE / (ann_02_sigmoid_dom_max - ann_02_sigmoid_dom_min); HEPSY_S(ann_02_id) for (i = 0; i < ann_02_LOOKUP_SIZE; ++i) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) ann_02_lookup[i] = ann_02_genann_act_sigmoid(ann, ann_02_sigmoid_dom_min + f * i); HEPSY_S(ann_02_id) } } double ann_02_genann_act_sigmoid_cached(const ann_02_genann *ann unused, double a) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) assert(!isnan(a)); HEPSY_S(ann_02_id) if (a < ann_02_sigmoid_dom_min) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return ann_02_lookup[0]; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) if (a >= ann_02_sigmoid_dom_max) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return ann_02_lookup[ann_02_LOOKUP_SIZE - 1]; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) size_t j = (size_t)((a-ann_02_sigmoid_dom_min)*ann_02_interval+0.5); /* Because floating point... */ HEPSY_S(ann_02_id) if (unlikely(j >= ann_02_LOOKUP_SIZE)) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return ann_02_lookup[ann_02_LOOKUP_SIZE - 1]; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) return ann_02_lookup[j]; } double ann_02_genann_act_linear(const struct ann_02_genann *ann unused, double a) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return a; } double ann_02_genann_act_threshold(const struct ann_02_genann *ann unused, double a) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return a > 0; } void ann_02_genann_randomize(ann_02_genann *ann) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) int i; HEPSY_S(ann_02_id) for (i = 0; i < ann->total_weights; ++i) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) double r = ann_02_GENANN_RANDOM(); /* Sets weights from -0.5 to 0.5. */ HEPSY_S(ann_02_id) ann->weight[i] = r - 0.5; HEPSY_S(ann_02_id) } } ann_02_genann *ann_02_genann_init(int inputs, int hidden_layers, int hidden, int outputs) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) if (hidden_layers < 0) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return 0; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) if (inputs < 1) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return 0; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) if (outputs < 1) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return 0; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) if (hidden_layers > 0 && hidden < 1) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return 0; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) const int hidden_weights = hidden_layers ? (inputs+1) * hidden + (hidden_layers-1) * (hidden+1) * hidden : 0; HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) const int output_weights = (hidden_layers ? (hidden+1) : (inputs+1)) * outputs; HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) const int total_weights = (hidden_weights + output_weights); HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) const int total_neurons = (inputs + hidden * hidden_layers + outputs); /* Allocate extra size for weights, outputs, and deltas. */ HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) const int size = sizeof(ann_02_genann) + sizeof(double) * (total_weights + total_neurons + (total_neurons - inputs)); HEPSY_S(ann_02_id) ann_02_genann *ret = (ann_02_genann *)malloc(size); HEPSY_S(ann_02_id) if (!ret) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return 0; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) ret->inputs = inputs; HEPSY_S(ann_02_id) ret->hidden_layers = hidden_layers; HEPSY_S(ann_02_id) ret->hidden = hidden; HEPSY_S(ann_02_id) ret->outputs = outputs; HEPSY_S(ann_02_id) ret->total_weights = total_weights; HEPSY_S(ann_02_id) ret->total_neurons = total_neurons; /* Set pointers. */ HEPSY_S(ann_02_id) ret->weight = (double*)((char*)ret + sizeof(ann_02_genann)); HEPSY_S(ann_02_id) ret->output = ret->weight + ret->total_weights; HEPSY_S(ann_02_id) ret->delta = ret->output + ret->total_neurons; HEPSY_S(ann_02_id) ann_02_genann_randomize(ret); HEPSY_S(ann_02_id) ret->activation_hidden = ann_02_genann_act_sigmoid_cached; HEPSY_S(ann_02_id) ret->activation_output = ann_02_genann_act_sigmoid_cached; HEPSY_S(ann_02_id) ann_02_genann_init_sigmoid_lookup(ret); HEPSY_S(ann_02_id) return ret; } void ann_02_genann_free(ann_02_genann *ann) {HEPSY_S(ann_02_id) /* The weight, output, and delta pointers go to the same buffer. */ HEPSY_S(ann_02_id) free(ann); } //genann *genann_read(FILE *in) //genann *genann_copy(genann const *ann) double const *ann_02_genann_run(ann_02_genann const *ann, double const *inputs) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) double const *w = ann->weight; HEPSY_S(ann_02_id) double *o = ann->output + ann->inputs; HEPSY_S(ann_02_id) double const *i = ann->output; /* Copy the inputs to the scratch area, where we also store each neuron's * output, for consistency. This way the first layer isn't a special case. */ HEPSY_S(ann_02_id) memcpy(ann->output, inputs, sizeof(double) * ann->inputs); HEPSY_S(ann_02_id) int h, j, k; HEPSY_S(ann_02_id) if (!ann->hidden_layers) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) double *ret = o; HEPSY_S(ann_02_id) for (j = 0; j < ann->outputs; ++j) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) double sum = *w++ * -1.0; HEPSY_S(ann_02_id) for (k = 0; k < ann->inputs; ++k) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) sum += *w++ * i[k]; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) *o++ = ann_02_genann_act_output(ann, sum); HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) return ret; HEPSY_S(ann_02_id) } /* Figure input layer */ HEPSY_S(ann_02_id) for (j = 0; j < ann->hidden; ++j) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) double sum = *w++ * -1.0; HEPSY_S(ann_02_id) for (k = 0; k < ann->inputs; ++k) { HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) sum += *w++ * i[k]; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) *o++ = ann_02_genann_act_hidden(ann, sum); HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) i += ann->inputs; /* Figure hidden layers, if any. */ HEPSY_S(ann_02_id) for (h = 1; h < ann->hidden_layers; ++h) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) for (j = 0; j < ann->hidden; ++j) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) double sum = *w++ * -1.0; HEPSY_S(ann_02_id) for (k = 0; k < ann->hidden; ++k) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) sum += *w++ * i[k]; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) *o++ = ann_02_genann_act_hidden(ann, sum); HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) i += ann->hidden; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) double const *ret = o; /* Figure output layer. */ HEPSY_S(ann_02_id) for (j = 0; j < ann->outputs; ++j) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) double sum = *w++ * -1.0; HEPSY_S(ann_02_id) for (k = 0; k < ann->hidden; ++k) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) sum += *w++ * i[k]; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) *o++ = ann_02_genann_act_output(ann, sum); HEPSY_S(ann_02_id) } /* Sanity check that we used all weights and wrote all outputs. */ HEPSY_S(ann_02_id) assert(w - ann->weight == ann->total_weights); HEPSY_S(ann_02_id) assert(o - ann->output == ann->total_neurons); HEPSY_S(ann_02_id) return ret; } //void genann_train(genann const *ann, double const *inputs, double const *desired_outputs, double learning_rate) //void genann_write(genann const *ann, FILE *out) /////////////////////// ANN //////////////////////// #define ann_02_NUM_DEV 1 // The equipment is composed of NUM_DEV devices ... //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- #define ann_02_MAX_ANN 100 // Maximum MAX_ANN ANN #define ann_02_ANN_INPUTS 2 // Number of inputs #define ann_02_ANN_HIDDEN_LAYERS 1 // Number of hidden layers #define ann_02_ANN_HIDDEN_NEURONS 2 // Number of neurons of every hidden layer #define ann_02_ANN_OUTPUTS 1 // Number of outputs //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- #define ann_02_ANN_EPOCHS 10000 #define ann_02_ANN_DATASET 6 #define ann_02_ANN_LEARNING_RATE 3 // ... //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- #define ann_02_MAX_ERROR 0.00756 // 0.009 //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- static int ann_02_nANN = -1 ; // Number of ANN that have been created static ann_02_genann * ann_02_ann[ann_02_MAX_ANN] ; // Now up to MAX_ANN ann //static double ann_02_trainingInput[ann_02_ANN_DATASET][ann_02_ANN_INPUTS] = { {0, 0}, {0, 1}, {1, 0}, {1, 1}, {0, 1}, {0, 0} } ; //static double ann_02_trainingExpected[ann_02_ANN_DATASET][ann_02_ANN_OUTPUTS] = { {0}, {1}, {1}, {0}, {1}, {0} } ; static double ann_02_weights[] = { -3.100438, -7.155774, -7.437955, -8.132828, -5.583678, -5.327152, 5.564897, -12.201226, 11.771879 } ; // static double input[4][3] = {{0, 0, 1}, {0, 1, 1}, {1, 0, 1}, {1, 1, 1}}; // static double output[4] = {0, 1, 1, 0}; //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- static int ann_02_annCheck(int index); static int ann_02_annCreate(int n); //----------------------------------------------------------------------------- // Check the correctness of the index of the ANN //----------------------------------------------------------------------------- int ann_02_annCheck(int index) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) if( (index < 0) || (index >= ann_02_nANN) ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return( EXIT_FAILURE ); HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) return( EXIT_SUCCESS ); } //----------------------------------------------------------------------------- // Create n ANN //----------------------------------------------------------------------------- int ann_02_annCreate(int n) {HEPSY_S(ann_02_id) // If already created, or not legal number, or too many ANN, then error HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) if( (ann_02_nANN != -1) || (n <= 0) || (n > ann_02_MAX_ANN) ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return( EXIT_FAILURE ); } // Create the ANN's HEPSY_S(ann_02_id) for ( int i = 0; i < n; i++ ) {HEPSY_S(ann_02_id) // New ANN with ANN_INPUT inputs, ANN_HIDDEN_LAYER hidden layers all with ANN_HIDDEN_NEURON neurons, and ANN_OUTPUT outputs HEPSY_S(ann_02_id) ann_02_ann[i] = ann_02_genann_init(ann_02_ANN_INPUTS, ann_02_ANN_HIDDEN_LAYERS, ann_02_ANN_HIDDEN_NEURONS, ann_02_ANN_OUTPUTS); HEPSY_S(ann_02_id) if ( ann_02_ann[i] == 0 ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) for (int j = 0; j < i; j++) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) ann_02_genann_free(ann_02_ann[j]) ; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) return( EXIT_FAILURE ); HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) ann_02_nANN = n ; HEPSY_S(ann_02_id) return( EXIT_SUCCESS ); } ////----------------------------------------------------------------------------- //// Create and train n identical ANN ////----------------------------------------------------------------------------- //int annCreateAndTrain(int n) //{ // if ( annCreate(n) != EXIT_SUCCESS ) // return( EXIT_FAILURE ); // // // Train the ANN's // for ( int index = 0; index < nANN; index++ ) // for ( int i = 0; i < ANN_EPOCHS; i++ ) // for ( int j = 0; j < ANN_DATASET; j++ ) // genann_train(ann[index], trainingInput[j], trainingExpected[j], ANN_LEARNING_RATE) ; // // return( EXIT_SUCCESS ); //} //----------------------------------------------------------------------------- // Create n identical ANN and set their weight //----------------------------------------------------------------------------- int ann_02_annCreateAndSetWeights(int n) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) if( ann_02_annCreate(n) != EXIT_SUCCESS ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return( EXIT_FAILURE ); HEPSY_S(ann_02_id) } // Set weights HEPSY_S(ann_02_id) for ( int index = 0; index < ann_02_nANN; index++ ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) for( int i = 0; i < ann_02_ann[index]->total_weights; ++i ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) ann_02_ann[index]->weight[i] = ann_02_weights[i] ; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) return( EXIT_SUCCESS ); } //----------------------------------------------------------------------------- // x[2] = x[0] XOR x[1] //----------------------------------------------------------------------------- int ann_02_annRun(int index, double x[ann_02_ANN_INPUTS + ann_02_ANN_OUTPUTS]) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) if( ann_02_annCheck(index) != EXIT_SUCCESS ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return( EXIT_FAILURE ) ; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) x[2] = * ann_02_genann_run(ann_02_ann[index], x) ; HEPSY_S(ann_02_id) return( EXIT_SUCCESS ); } ////----------------------------------------------------------------------------- //// ////----------------------------------------------------------------------------- //int annPrintWeights(int index) //{ // if ( annCheck(index) != EXIT_SUCCESS ) // return( EXIT_FAILURE ) ; // // // printf("\n*** ANN index = %d\n", index) ; // for ( int i = 0; i < ann[index]->total_weights; ++i ) // printf("*** w%d = %f\n", i, ann[index]->weight[i]) ; // // return( EXIT_SUCCESS ); //} ////-------------------------------------------------------
---------------------- //// Run the index-th ANN k time on random input and return the number of error ////----------------------------------------------------------------------------- //int annTest(int index, int k) //{ // int x0; int x1; int y; // double x[2]; // double xor_ex; // int error = 0; // // if ( annCheck(index) != EXIT_SUCCESS ) // return( -1 ); // less than zero errors <==> the ANN isn't correctly created // // for (int i = 0; i < k; i++ ) // { // x0 = rand() % 2; x[0] = (double)x0; // x1 = rand() % 2; x[1] = (double)x1; // y = x0 ^ x1 ; // // xor_ex = * genann_run(ann[index], x); // if ( fabs(xor_ex - (double)y) > MAX_ERROR ) // { // error++ ; // printf("@@@ Error: ANN = %d, step = %d, x0 = %d, x1 = %d, y = %d, xor_ex = %f \n", index, i, x0, x1, y, xor_ex) ; // } // } // // if ( error ) // printf("@@@ ANN = %d: N� of errors = %d\n", index, error) ; // else // printf("*** ANN = %d: Test OK\n",index) ; // return( error ); //} //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void ann_02_annDestroy(void) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) if( ann_02_nANN == -1 ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) return ; } HEPSY_S(ann_02_id) for ( int index = 0; index < ann_02_nANN; index++ ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) ann_02_genann_free(ann_02_ann[index]) ; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) ann_02_nANN = -1 ; } void mainsystem::ann_02_main() { // datatype for channels cleanData_xx_ann_xx_payload cleanData_xx_ann_xx_payload_var; ann_xx_dataCollector_payload ann_xx_dataCollector_payload_var; double x[ann_02_ANN_INPUTS + ann_02_ANN_OUTPUTS] ; //int ann_02_index = 1; HEPSY_S(ann_02_id) if( ann_02_annCreateAndSetWeights(ann_02_NUM_DEV) != EXIT_SUCCESS ) {HEPSY_S(ann_02_id) // Create and init ANN HEPSY_S(ann_02_id) printf("Error Weights \n"); HEPSY_S(ann_02_id) } //implementation HEPSY_S(ann_02_id) while(1) {HEPSY_S(ann_02_id) // content HEPSY_S(ann_02_id)cleanData_xx_ann_xx_payload_var = cleanData_02_ann_02_channel->read(); HEPSY_S(ann_02_id) ann_xx_dataCollector_payload_var.dev = cleanData_xx_ann_xx_payload_var.dev; HEPSY_S(ann_02_id) ann_xx_dataCollector_payload_var.step = cleanData_xx_ann_xx_payload_var.step; HEPSY_S(ann_02_id) ann_xx_dataCollector_payload_var.ex_time = cleanData_xx_ann_xx_payload_var.ex_time; HEPSY_S(ann_02_id) ann_xx_dataCollector_payload_var.device_i = cleanData_xx_ann_xx_payload_var.device_i; HEPSY_S(ann_02_id) ann_xx_dataCollector_payload_var.device_v = cleanData_xx_ann_xx_payload_var.device_v; HEPSY_S(ann_02_id) ann_xx_dataCollector_payload_var.device_t = cleanData_xx_ann_xx_payload_var.device_t; HEPSY_S(ann_02_id) ann_xx_dataCollector_payload_var.device_r = cleanData_xx_ann_xx_payload_var.device_r; HEPSY_S(ann_02_id) x[0] = cleanData_xx_ann_xx_payload_var.x_0; HEPSY_S(ann_02_id) x[1] = cleanData_xx_ann_xx_payload_var.x_1; HEPSY_S(ann_02_id) x[2] = cleanData_xx_ann_xx_payload_var.x_2; //u = cleanData_xx_ann_xx_payload_var.step; HEPSY_S(ann_02_id) ann_xx_dataCollector_payload_var.fault = cleanData_xx_ann_xx_payload_var.fault; //RUN THE ANN... // ### P R E D I C T (simple XOR) // if ( annRun(index, x) != EXIT_SUCCESS ){ // printf("Step = %u Index = %d ANN error.\n", u, index) ; // }else{ // device[index].fault = x[2] <= 0.5 ? 0 : 1 ; // } //u: cycle num HEPSY_S(ann_02_id) if( ann_02_annRun(0, x) != EXIT_SUCCESS ) {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) printf("Step = %d Index = %d ANN error.\n", (int)ann_xx_dataCollector_payload_var.step, (int)ann_xx_dataCollector_payload_var.dev) ; HEPSY_S(ann_02_id) } else {HEPSY_S(ann_02_id) HEPSY_S(ann_02_id) ann_xx_dataCollector_payload_var.fault = x[2] <= 0.5 ? 0 : 1 ; HEPSY_S(ann_02_id) } HEPSY_S(ann_02_id) ann_02_dataCollector_channel->write(ann_xx_dataCollector_payload_var); HEPSY_P(ann_02_id) } } // END
#include <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); }
/***************************************************************************** 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(); } } }
/** * Murac Auxilliary Architecture integration framework * Author: Brandon Hamilton <[email protected]> */ #include <systemc.h> #include <dlfcn.h> #include <fcntl.h> #include <sys/mman.h> #include "muracAA.hpp" typedef int (*murac_init_func)(BusInterface*); typedef int (*murac_exec_func)(unsigned long int); using std::cout; using std::endl; using std::dec; using std::hex; SC_HAS_PROCESS( muracAA ); muracAAInterupt::muracAAInterupt(const char *name, muracAA *aa): m_aa(aa), m_name(name) { } void muracAAInterupt::write(const int &value) { if (value == 1) { m_aa->onBrArch(value); } } /** * Constructor */ muracAA::muracAA( sc_core::sc_module_name name) : sc_module( name ), brarch("brarch", this) { } int muracAA::loadLibrary(const char *library) { cout << "Loading murac library: " << library << endl; void* handle = dlopen(library, RTLD_NOW | RTLD_GLOBAL); if (!handle) { cout << dlerror() << endl; return -1; } dlerror(); cout << "Initializing murac library: " << library << endl; murac_init_func m_init = (murac_init_func) dlsym(handle, "murac_init"); int result = m_init(this); return result; } int muracAA::invokePluginSimulation(const char* path, unsigned long int ptr) { char *error; void* handle = dlopen(path, RTLD_LAZY | RTLD_GLOBAL); if (!handle) { cout << dlerror() << endl; return -1; } dlerror(); murac_exec_func m_exec = (murac_exec_func) dlsym(handle, "murac_execute"); if ((error = dlerror()) != NULL) { fprintf(stderr, "%s\n", error); return -1; } int result = -1; sc_process_handle h = sc_spawn(&result, sc_bind(m_exec, ptr) ); wait(h.terminated_event()); //dlclose(handle); return result; } /** * Handle the BrArch interrupt from the PA */ void muracAA::onBrArch(const int &value) { cout << "@" << sc_time_stamp() << " onBrArch" << endl; int ret = -1; int fd; unsigned long int pc = 0; unsigned int instruction_size = 0; unsigned long int ptr = 0; unsigned char* fmap; char *tmp_file_name = strdup("/tmp/murac_AA_XXXXXX"); if (busRead(MURAC_PC_ADDRESS, (unsigned char*) &pc, 4) < 0) { cout << "@" << sc_time_stamp() << " Memory read error !" << endl; goto trigger_return_interrupt; } cout << "@" << sc_time_stamp() << " PC: 0x" << hex << pc << endl; if (busRead(MURAC_PC_ADDRESS + 4, (unsigned char*) &instruction_size, 4) < 0) { cout << "@" << sc_time_stamp() << " Memory read error !" << endl; goto trigger_return_interrupt; } cout << "@" << sc_time_stamp() << " Instruction size: " << dec << instruction_size << endl; if (busRead(MURAC_PC_ADDRESS + 8, (unsigned char*) &ptr, 4) < 0) { cout << "@" << sc_time_stamp() << " Memory read error !" << endl; goto trigger_return_interrupt; } cout << "@" << sc_time_stamp() << " Ptr : " << hex << ptr << dec << endl; cout << "@" << sc_time_stamp() << " Reading embedded AA simulation file " << endl; fd = mkostemp (tmp_file_name, O_RDWR | O_CREAT | O_TRUNC); if (fd == -1) { cout << "Error: Cannot open temporary file for writing." << endl; goto trigger_return_interrupt; } ret = lseek(fd, instruction_size-1, SEEK_SET); if (ret == -1) { close(fd); cout << "Error: Cannot call lseek() on temporary file." << endl; goto trigger_return_interrupt; } ret = ::write(fd, "", 1); if (ret != 1) { close(fd); cout << "Error: Error writing last byte of the temporary file." << endl; goto trigger_return_interrupt; } fmap = (unsigned char*) mmap(0, instruction_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (fmap == MAP_FAILED) { close(fd); cout << "Error: Error mmapping the temporary file." << endl; goto trigger_return_interrupt; } // Write the file if (busRead(pc, fmap, instruction_size) < 0) { cout << "@" << sc_time_stamp() << " Memory read error !" << endl; munmap(fmap, instruction_size); close(fd); goto trigger_return_interrupt; } if (munmap(fmap, instruction_size) == -1) { close(fd); cout << "Error: Error un-mmapping the temporary file." << endl; goto trigger_return_interrupt; } close(fd); cout << "@" << sc_time_stamp() << " Running murac AA simulation " << endl; ret = invokePluginSimulation(tmp_file_name, ptr); cout << "@" << sc_time_stamp() << " Simulation result = " << ret << endl; remove(tmp_file_name); trigger_return_interrupt: free(tmp_file_name); cout << "@" << sc_time_stamp() << " Returning to PA " << endl; // Trigger interrupt for return to PA intRetArch.write(1); intRetArch.write(0); } /** * Read from the bus */ int muracAA::busRead (unsigned long int addr, unsigned char rdata[], int dataLen) { bus_payload.set_read (); bus_payload.set_address ((sc_dt::uint64) addr); bus_payload.set_byte_enable_length ((const unsigned int) dataLen); bus_payload.set_byte_enable_ptr (0); bus_payload.set_data_length ((const unsigned int) dataLen); bus_payload.set_data_ptr ((unsigned char *) rdata); busTransfer(bus_payload); return bus_payload.is_response_ok () ? 0 : -1; } /** * Write to the bus */ int muracAA::busWrite (unsigned long int addr, unsigned char wdata[], int dataLen) { bus_payload.set_write (); bus_payload.set_address ((sc_dt::uint64) addr); bus_payload.set_byte_enable_length ((const unsigned int) dataLen); bus_payload.set_byte_enable_ptr (0); bus_payload.set_data_length ((const unsigned int) dataLen); bus_payload.set_data_ptr ((unsigned char *) wdata); busTransfer(bus_payload); return bus_payload.is_response_ok () ? 0 : -1; } /** * Initiate bus transfer */ void muracAA::busTransfer( tlm::tlm_generic_payload &trans ) { sc_core::sc_time dummyDelay = sc_core::SC_ZERO_TIME; aa_bus->b_transport( trans, dummyDelay ); } int muracAA::read(unsigned long int addr, unsigned char*data, unsigned int len) { return busRead(addr, data, len); } int muracAA::write(unsigned long int addr, unsigned char*data, unsigned int len) { return busWrite(addr, data, len); }
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2017 Cadence Design Systems, Inc. All rights reserved worldwide. // // The code contained herein is the proprietary and confidential information // of Cadence or its licensors, and is supplied subject to a previously // executed license and maintenance agreement between Cadence and customer. // This code is intended for use with Cadence high-level synthesis tools and // may not be used with other high-level synthesis tools. Permission is only // granted to distribute the code as indicated. Cadence grants permission for // customer to distribute a copy of this code to any partner to aid in designing // or verifying the customer's intellectual property, as long as such // distribution includes a restriction of no additional distributions from the // partner, unless the partner receives permission directly from Cadence. // // ALL CODE FURNISHED BY CADENCE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, AND CADENCE SPECIFICALLY DISCLAIMS ANY WARRANTY OF NONINFRINGEMENT, // FITNESS FOR A PARTICULAR PURPOSE OR MERCHANTABILITY. CADENCE SHALL NOT BE // LIABLE FOR ANY COSTS OF PROCUREMENT OF SUBSTITUTES, LOSS OF PROFITS, // INTERRUPTION OF BUSINESS, OR FOR ANY OTHER SPECIAL, CONSEQUENTIAL OR // INCIDENTAL DAMAGES, HOWEVER CAUSED, WHETHER FOR BREACH OF WARRANTY, // CONTRACT, TORT, NEGLIGENCE, STRICT LIABILITY OR OTHERWISE. // //////////////////////////////////////////////////////////////////////////////// #include <systemc.h> // SystemC definitions #include "system.h" // Top-level System module header file static System * m_system = NULL; // The pointer that holds the top-level System module instance. void esc_elaborate() // This function is required by Stratus to support SystemC-Verilog { // cosimulation. It instances the top-level module. m_system = new System( "system" ); } void esc_cleanup() // This function is called at the end of simulation by the { // Stratus co-simulation hub. It should delete the top-level delete m_system; // module instance. } int sc_main( int argc, char ** argv ) // This function is called by the SystemC kernel for pure SystemC simulations { esc_initialize( argc, argv ); // esc_initialize() passes in the cmd-line args. This initializes the Stratus simulation // environment (such as opening report files for later logging and analysis). esc_elaborate(); // esc_elaborate() (defined above) creates the top-level module instance. In a SystemC-Verilog // co-simulation, this is called during cosim initialization rather than from sc_main. sc_start(); // Starts the simulation. Returns when a module calls esc_stop(), which finishes the simulation. // esc_cleanup() (defined above) is automatically called before sc_start() returns. return 0; // Returns the status of the simulation. Required by most C compilers. }
/* 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; }
#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(); }
/******************************************************************************* * encoder.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This is a testbench module to emulate a rotary quad encoder with a button. * Two pins are provided for the encoder function and a third one handles * the button. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "encoder.h" void encoder::press(bool pb) { if (pb) pinC.write(GN_LOGIC_1); else pinC.write(GN_LOGIC_Z); } void encoder::turnleft(int pulses, bool pressbutton) { /* We start by raising the button, if requested. */ if (pressbutton) press(true); /* If the last was a left turn, we need to do the direction change glitch. * Note that if the button is pressed, we only toggle pin B. */ if (!lastwasright) { wait(speed, SC_MS); pinB.write(GN_LOGIC_1); wait(speed, SC_MS); pinB.write(GN_LOGIC_Z); } /* And we apply the pulses, again, watching for the button. */ wait(phase, SC_MS); while(pulses > 0) { wait(speed-phase, SC_MS); pinA.write(GN_LOGIC_1); wait(phase, SC_MS); pinB.write(GN_LOGIC_1); wait(speed-phase, SC_MS); pinA.write(GN_LOGIC_Z); if (edges == 2) wait(phase, SC_MS); pinB.write(GN_LOGIC_Z); if (edges != 2) wait(phase, SC_MS); pulses = pulses - 1; } /* If the customer requested us to press the button with a turn, we release * it now. */ if (pressbutton) { wait(speed, SC_MS); press(false); } /* And we tag that the last was a right turn as when we shift to the left * we can have some odd behaviour. */ lastwasright = true; } void encoder::turnright(int pulses, bool pressbutton) { /* We start by raising the button, if requested. */ if (pressbutton) press(true); /* If the last was a right turn, we need to do the direction change glitch. * Note that if the button is pressed, we only toggle pin A. */ if (lastwasright) { wait(speed, SC_MS); pinA.write(GN_LOGIC_1); wait(speed, SC_MS); pinB.write(GN_LOGIC_1); wait(speed, SC_MS); pinB.write(GN_LOGIC_Z); wait(speed, SC_MS); pinA.write(GN_LOGIC_Z); } /* And we apply the pulses, again, watching for the button. */ wait(phase, SC_MS); while(pulses > 0) { wait(speed-phase, SC_MS); pinB.write(GN_LOGIC_1); wait(phase, SC_MS); pinA.write(GN_LOGIC_1); wait(speed-phase, SC_MS); pinB.write(GN_LOGIC_Z); if (edges == 2) wait(phase, SC_MS); pinA.write(GN_LOGIC_Z); if (edges != 2) wait(phase, SC_MS); pulses = pulses - 1; } /* If the customer requested us to press the button with a turn, we release * it now. */ if (pressbutton) { wait(speed, SC_MS); press(false); } /* And we tag that the last was a left turn, so we can do the left turn to * right turn glitch. */ lastwasright = false; } void encoder::start_of_simulation() { pinA.write(GN_LOGIC_Z); pinB.write(GN_LOGIC_Z); pinC.write(GN_LOGIC_Z); } void encoder::trace(sc_trace_file *tf) { sc_trace(tf, pinA, pinA.name()); sc_trace(tf, pinB, pinB.name()); sc_trace(tf, pinC, pinC.name()); }
#include <systemc.h> class sc_mutexx : public sc_prim_channel { public: sc_event _free; bool _locked; // blocks until mutex could be locked void lock() { while( _locked ) { wait( _free ); } _locked = true; } // returns false if mutex could not be locked bool trylock() { if( _locked ) return false; else return true; } // unlocks mutex void unlock() { _locked = false; _free.notify(); } // constructor sc_mutexx(){ // _locked = false; } };
/******************************************************************************* * cd4067.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This is a simple model for the CD4067 Analog Mux. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "info.h" #include "cd4067.h" int cd4067::get_selector() { return (((d.read())?1:0) << 3) | (((c.read())?1:0) << 2) | (((b.read())?1:0) << 1) | ((a.read())?1:0); } void cd4067::process_th() { int line; bool channel_is_driver = false; x.write(GN_LOGIC_Z); for(line = 0; line < channel.size(); line = line + 1) channel[line]->write(GN_LOGIC_Z); sel = get_selector(); bool recheck = false; while(true) { /* If the recheck is high, this means the selector changed and we need * to refigure out who is driving. */ if (recheck) { /* We wait a time stamp and redo the driving. */ wait(1, SC_NS); recheck = false; /* In these cases, we just keep everyone at Z. */ if (inh.read() || sel >= channel.size()) continue; /* We check who is the driver and drive the other. If they are both * being driven, we drive X everywhere. */ if (x.read() == GN_LOGIC_Z) { channel_is_driver = true; x.write(channel[sel]->read()); } else if (channel[sel]->read()==GN_LOGIC_Z) { channel_is_driver = false; channel[sel]->write(x.read()); } else { PRINTF_WARN("TEST", "Two drivers on MUX"); channel[sel]->write(GN_LOGIC_X); x.write(GN_LOGIC_X); } continue; } /* We wait for one either a change in the selector or a change in * either side of the mux. If the selector is pointing to an illegal * value, we then just wait for a change in the selector. */ if (sel >= channel.size()) wait(a->default_event() | b->default_event() | c->default_event() | d->default_event() | inh->default_event()); else wait(channel[sel]->default_event() | a->default_event() | b->default_event() | c->default_event() | d->default_event() | inh->default_event() | x->default_event()); bool sel_triggered = a->value_changed_event().triggered() || b->value_changed_event().triggered() || c->value_changed_event().triggered() || d->value_changed_event().triggered(); if (debug) { /* If the sel is illegal, we only can process the selector. */ if (sel >= channel.size()) printf("%s: sel = %d, triggers: sel %c, inh %c, x %c\n", name(), sel, (sel_triggered)?'t':'f', (inh->value_changed_event().triggered())?'t':'f', (x->value_changed_event().triggered())?'t':'f'); else printf( "%s: sel = %d, triggers: channel %c, sel %c, inh %c, x %c\n", name(), sel, (channel[sel]->value_changed_event().triggered())?'t':'f', (sel_triggered)?'t':'f', (inh->value_changed_event().triggered())?'t':'f', (x->value_changed_event().triggered())?'t':'f'); } /* If inh went high we shut it all off, it does not matter who triggered * what. */ if (inh.read() == GN_LOGIC_1) { x.write(GN_LOGIC_Z); if (sel < channel.size()) channel[sel]->write(GN_LOGIC_Z); channel_is_driver = false; } /* If inh came back, we then need to resolve. */ else if (inh.value_changed_event().triggered()) { /* No need to drive Z if it is already. */ recheck = true; channel_is_driver = false; } /* Now we check the selector. If it changed, we need to drive Z and * recheck. This is because it is difficult to check every single * driver in a signal to find out what is going on. */ else if (sel_triggered) { int newsel = get_selector(); /* We now drive Z everywhere. */ if (sel < channel.size()) channel[sel]->write(GN_LOGIC_Z); x.write(GN_LOGIC_Z); channel_is_driver = false; /* And we update the selector variable. */ sel = newsel; /* And if the new selector is valid, we do a recheck. */ if (sel < channel.size()) recheck = true; } /* If the selector is not valid, we just ignore any activity on either * side as there can't be any change. We simply drive Z everywhere. * Note: this path is a safety one, it is probably never called. */ else if (sel >= channel.size()) { channel_is_driver = false; x.write(GN_LOGIC_Z); } /* When we update a output pin, there is always a reflection. If both * sides have the same value, this probably was a reflection, so we * can dump it. */ else if (x.read() == channel[sel]->read()) continue; /* We have an analog mux. In a real mux system, we would do a fight * between the sides and eventually settle to something. This is a * digital simulator though, so we need a simplification. If I get a * driver on one side, we drive that value on the other. */ else if (channel[sel]->value_changed_event().triggered() && (channel_is_driver || x.read() == GN_LOGIC_Z)) { channel_is_driver = true; x.write(channel[sel]->read()); } else if (x.default_event().triggered() && (!channel_is_driver || channel[sel]->read() == GN_LOGIC_Z)) { channel_is_driver = false; channel[sel]->write(x.read()); } /* If there are drivers on both sides, we need to put X on both sides. * Note: the current model will not leave this state unless there is * an inh or sel change. */ else { PRINTF_WARN("TEST", "Two drivers on MUX"); channel[sel]->write(GN_LOGIC_X); x.write(GN_LOGIC_X); } } } void cd4067::trace(sc_trace_file *tf) { sc_trace(tf, x, x.name()); sc_trace(tf, a, a.name()); sc_trace(tf, b, b.name()); sc_trace(tf, c, c.name()); sc_trace(tf, d, d.name()); sc_trace(tf, inh, inh.name()); }
#include <systemc.h> #include "Memory.h" using namespace std; void Memory::execute() { // Initialize memory to some predefined contents. for (int i=0; i<MEM_SIZE; i++) _data[i] = i + 0xff000; port_Stall = true; for (;;) { wait(); int addr = port_Addr % MEM_SIZE; if (port_Read) { // Read word from memory. int data = _data[addr]; port_RData = data; port_Stall = false; // Always ready. #if defined(PRINT_WHILE_RUN) cout << sc_time_stamp() << "\tMemory: Done read request. Addr = " << showbase << hex << addr << ", Data = " << showbase << hex << data << endl; #endif // Hold data until read cleared. do { wait(); } while (port_Read); port_RData = 0; } else if (port_Write) { // Write a word to memory. int data = port_WData; //int be = port_BE; port_Stall = true; #if defined(PRINT_WHILE_RUN) cout << sc_time_stamp() << "\tMemory: Started write request. Addr = " << showbase << hex << addr << ", Data = " << showbase << hex << data << endl; #endif wait(10); port_Stall = false; _data[addr] = data; // TODO: byte enable #if defined(PRINT_WHILE_RUN) cout << sc_time_stamp() << "\tMemory: Finished write request. Addr = " << showbase << hex << addr << endl; #endif // Wait until write cleared. do { wait(); } while (port_Write); } } }
/******************************************************************************* * st7735.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This is a testbench module to emulate the ST7735 display controller. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "info.h" #include "st7735.h" void st7735::collect() { pos = 0; collected = 0; while(1) { wait(); /* We check the reset. */ if (!resx.read().islogic()) { PRINTF_WARN("ST7735", "RESX is non-logic value %c", resx.read().to_char()); continue; } else if (resx.read().islow()) { pos = 0; collected = 0; initialized = true; continue; } // If the CSX is not low, we ignore what came in. if (!csx.read().islogic()) { PRINTF_WARN("ST7735", "CSX is non-logic value %c", csx.read().to_char()); continue; } else if (csx.read().ishigh()) continue; // To use the controller, it needs to have been reset. if (!initialized) { PRINTF_WARN("ST7735", "Module has not been reset"); continue; } // Now we check the mode to see what came in. This depends on the mode // selection. switch(im.read().to_uint()) { // SPI mode -- we only react to a chane in the SCL pin. default: /* We first discard the illegal values. */ if (!scl_dcx.read().islogic()) { PRINTF_WARN("ST7735", "SCL is non-logic value %c", scl_dcx.read().to_char()); continue; } /* If we are in readmode, we return the value. */ if (readmode) { if (scl_dcx.read().ishigh()) sda.write(GN_LOGIC_Z); else if (pos > 0) sda.write(((collected & (1 << (pos-1)))>0)?GN_LOGIC_1:GN_LOGIC_0); continue; } /* If it is not a read it is a write. We sample on the rising edge. */ if (scl_dcx.read() != SC_LOGIC_1) continue; /* We increment the counter. If we are using the 3wire interface, we * need to get the DCX first */ if (!spi4w.read().islogic()) { PRINTF_WARN("ST7735", "Tried to latch while spi4w is non-logic value %c", spi4w.read().to_char()); continue; } else if (wrx.read().ishigh()) collected = collected | 0x100; if (pos <= 0 && spi4w.read().islow()) { collected = 0; pos = 9; } else if (pos <= 0) { collected = 0; pos = 8; } else pos = pos - 1; if (spi4w.read().ishigh()) { if (!wrx.read().islogic()) { PRINTF_WARN("ST7735", "Tried to latch non-logic WRX value %c", wrx.read().to_char()); } else if (wrx.read().ishigh()) collected = collected | 0x100; else collected = collected & 0x0ff; } /* If the pin is non-logic we complain and skip it. */ if(!sda.read().islogic()) { PRINTF_WARN("ST7735", "Tried to latch non-logic SDA value %c", sda.read().to_char()); } /* If the logic is valid, we take in the ones. */ else if (sda.read().ishigh()) collected = collected | (1 << (pos-1)); if (pos == 1) { printf("%s: received %03x\n", sc_time_stamp().to_string().c_str(), collected); } break; } } } void st7735::start_of_simulation() { sda.write(GN_LOGIC_Z); osc.write(GN_LOGIC_0); te.write(GN_LOGIC_0); d0.write(GN_LOGIC_Z); d1.write(GN_LOGIC_Z); d2.write(GN_LOGIC_Z); d3.write(GN_LOGIC_Z); d4.write(GN_LOGIC_Z); d5.write(GN_LOGIC_Z); d6.write(GN_LOGIC_Z); d7.write(GN_LOGIC_Z); d8.write(GN_LOGIC_Z); d9.write(GN_LOGIC_Z); d10.write(GN_LOGIC_Z); d11.write(GN_LOGIC_Z); d12.write(GN_LOGIC_Z); d13.write(GN_LOGIC_Z); d14.write(GN_LOGIC_Z); d15.write(GN_LOGIC_Z); d16.write(GN_LOGIC_Z); d17.write(GN_LOGIC_Z); } void st7735::trace(sc_trace_file *tf) { sc_trace(tf, sda, sda.name()); sc_trace(tf, d0, d0.name()); sc_trace(tf, d1, d1.name()); sc_trace(tf, d2, d2.name()); sc_trace(tf, d3, d3.name()); sc_trace(tf, d4, d4.name()); sc_trace(tf, d5, d5.name()); sc_trace(tf, d6, d6.name()); sc_trace(tf, d7, d7.name()); sc_trace(tf, d8, d8.name()); sc_trace(tf, d9, d9.name()); sc_trace(tf, d10, d10.name()); sc_trace(tf, d11, d11.name()); sc_trace(tf, d12, d12.name()); sc_trace(tf, d13, d13.name()); sc_trace(tf, d14, d14.name()); sc_trace(tf, d15, d15.name()); sc_trace(tf, d16, d16.name()); sc_trace(tf, d17, d17.name()); sc_trace(tf, wrx, wrx.name()); sc_trace(tf, rdx, rdx.name()); sc_trace(tf, csx, csx.name()); sc_trace(tf, scl_dcx, scl_dcx.name()); sc_trace(tf, spi4w, spi4w.name()); sc_trace(tf, im, im.name()); }
//----------------------------------------------------- #include <systemc.h> /** * @brief Enum that represents the main FPU operations * */ typedef enum { SC_FPU_ADD = 1, SC_FPU_SUB = 2, SC_FPU_MULT = 3, SC_FPU_DIV = 4 } sc_fpu_op_t; /** * @brief Class the represent and FPU using PV model * */ SC_MODULE (fpu_unit) { protected: //----------------------------Internal variables---------------------------- // Operation type sc_fpu_op_t op_type; // Events to trigger the operation execution sc_event event_op; //-----------------------------Internal methods----------------------------- /** * @brief Performs the operation between the operands * */ void exec_op() { while (true) { wait(event_op); // Perform the operations switch (this->op_type) { case SC_FPU_ADD: this->op_c.write(this->op_a.read() + this->op_b.read()); break; case SC_FPU_SUB: this->op_c.write(this->op_a.read() - this->op_b.read()); break; case SC_FPU_MULT: this->op_c.write(this->op_a.read() * this->op_b.read()); break; case SC_FPU_DIV: this->op_c.write(this->op_a.read() / this->op_b.read()); break; default: break; } } } public: // First operand sc_in<float> op_a; // Second operand sc_in<float> op_b; // Result sc_out<float> op_c; SC_HAS_PROCESS(fpu_unit); /** * @brief Construct a new fpu unit object * * @param name - name of the module */ fpu_unit(sc_module_name name) : sc_module(name) { SC_THREAD(exec_op); } // End of Constructor //------------------------------Public methods------------------------------ /** * @brief Adds two float numbers * */ void add() { this->op_type = SC_FPU_ADD; this->event_op.notify(1, SC_NS); } /** * @brief Divides two float numbers */ void div() { this->op_type = SC_FPU_DIV; this->event_op.notify(3, SC_NS); } /** * @brief Multiplies two float numbers * */ void mult() { this->op_type = SC_FPU_MULT; this->event_op.notify(3, SC_NS); } /** * @brief Subtracts two float numbers * */ void subs() { this->op_type = SC_FPU_SUB; this->event_op.notify(1, SC_NS); } };
//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 * */
#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 }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // 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" SC_MODULE(scalar_logistic_function) { sc_in_clk clock; sc_in<int> data_in; sc_out<int> data_out; SC_CTOR(scalar_logistic_function) { SC_METHOD(logistic_function); sensitive << clock.pos(); sensitive << data_in; } void logistic_function() { data_out.write(data_in.read()); } };
/******************************************************************************* * 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 "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(); } }
/* * 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: */
#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; }
#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
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ /***************************************************************************** display.cpp -- Original Author: Rocco Jonack, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation: Teodor Vasilache and Dragos Dospinescu, AMIQ Consulting s.r.l. ([email protected]) Date: 2018-Feb-20 Description of Modification: Included the FC4SC library in order to collect functional coverage data and generate a coverage database. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include <systemc.h> #include "display.h" #include "fc4sc.hpp" void display::entry(){ // Reading Data when valid if high tmp1 = result.read(); cout << "Display : " << tmp1 << " " /* << " at time " << sc_time_stamp() << endl; */ << " at time " << sc_time_stamp().to_double() << endl; i++; // sample the data this->out_cg.sample(result, output_data_ready); if(i == 24) { cout << "Simulation of " << i << " items finished" /* << " at time " << sc_time_stamp() << endl; */ << " at time " << sc_time_stamp().to_double() << endl; // generate the coverage database from the collected data fc4sc::global::coverage_save("coverage_results.xml"); sc_stop(); }; } // EOF
/******************************************************************************** * University of L'Aquila - HEPSYCODE Source Code License * * * * * * (c) 2018-2019 Centre of Excellence DEWS All rights reserved * ******************************************************************************** * <one line to give the program's name and a brief idea of what it does.> * * Copyright (C) 2022 Vittoriano Muttillo, Luigi Pomante * * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * ******************************************************************************** * * * Created on: 09/May/2023 * * Authors: Vittoriano Muttillo, Marco Santic, Luigi Pomante * * * * email: [email protected] * * [email protected] * * [email protected] * * * ******************************************************************************** * This code has been developed from an HEPSYCODE model used as demonstrator by * * University of L'Aquila. * *******************************************************************************/ #include <systemc.h> #include "../mainsystem.h" #include <math.h> //----------------------------------------------------------------------------- // 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
// //------------------------------------------------------------// // 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; }
/******************************************************************************* * 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()); }
/******************************************************************************* * 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(); }
/******************************************************************************* * <DIRNAME>test.cpp -- Copyright 2019 (c) Glenn Ramalho - RFIDo Design ******************************************************************************* * Description: * This is the main testbench for the <DIRNAME>.ino test. ******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************* */ #include <systemc.h> #include "<DIRNAME>test.h" #include <string> #include <vector> #include "info.h" <IFESPIDF>#include "main.h" /********************** * Function: trace() * inputs: trace file * outputs: none * return: none * globals: none * * Traces all signals in the design. For a signal to be traced it must be listed * here. This function should also call tracing in any subblocks, if desired. */ void <DIRNAME>test::trace(sc_trace_file *tf) { sc_trace(tf, led, led.name()); sc_trace(tf, rx, rx.name()); sc_trace(tf, tx, tx.name()); i_esp.trace(tf); } /********************** * Task: start_of_simulation(): * inputs: none * outputs: none * return: none * globals: none * * Runs commands at the beginning of the simulation. */ void <DIRNAME>test::start_of_simulation() { /* We add a deadtime to the uart client as the ESP sends a glitch down the * UART0 at power-up. */ i_uartclient.i_uart.set_deadtime(sc_time(5, SC_US)); } /********************** * Task: serflush(): * inputs: none * outputs: none * return: none * globals: none * * Dumps everything comming from the serial interface. */ void <DIRNAME>test::serflush() { //i_uartclient.i_uart.set_debug(true); i_uartclient.dump(); } /******************************************************************************* ** Testbenches ***************************************************************** *******************************************************************************/ void <DIRNAME>test::t0(void) { SC_REPORT_INFO("TEST", "Running Test T0."); wait(1, SC_MS); sc_stop(); PRINTF_INFO("TEST", "Waiting for power-up"); wait(500, SC_MS); } void <DIRNAME>test::testbench(void) { /* Now we check the test case and run the correct TB. */ printf("Starting Testbench Test%d @%s\n", tn, sc_time_stamp().to_string().c_str()); if (tn == 0) t0(); else SC_REPORT_ERROR("TEST", "Test number too large."); sc_stop(); }
// //------------------------------------------------------------// // Copyright 2009-2012 Mentor Graphics Corporation // // All Rights Reserved Worldwid // // // // Licensed under the Apache License, Version 2.0 (the // // "License"); you may not use this file except in // // compliance with the License. You may obtain a copy of // // the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in // // writing, software distributed under the License is // // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // // CONDITIONS OF ANY KIND, either express or implied. See // // the License for the specific language governing // // permissions and limitations under the License. // //------------------------------------------------------------// #include "systemc.h" #include "tlm.h" #include <vector> #include <iomanip> #include <uvmc.h> using std::vector; using namespace sc_core; using namespace tlm; //------------------------------------------------------------------------------ // Title: UVMC Converter Example - SC In-Transaction // // This example's packet class defines ~do_pack~ and ~do_unpack~ methods that // are compatible with the default converter in SC. The default converter merely // delegates conversion to these two methods in the transaction class. // // (see UVMC_Converters_SC_InTrans.png) // // This approach is not very common in practice, as it couples your transaction // types to the UVMC library. // // Instead of defining member functions of the transaction type to do conversion, // you should instead implement a template specialization of uvmc_convert<T>. // This leaves conversion knowledge outside your transaction proper, and allows // you to define different conversion algorithms without requiring inheritance. // This example demonstrates use of a transaction class that defines the // conversion functionality in compliant ~do_pack~ and ~do_unpack~ methods. // Thus, an custom converter specialization will not be needed--the default // converter, which delegates to ~do_pack~ and ~do_unpack~ methods in the // transaction, is sufficient. // // Because most SC transactions do not implement the pack and unpack member // functions required by the default converter, a template specialization // definition is normally required. // // The default converter, uvmc_converter<T>, or any template specialization // of that converter for a given packet type, e.g. uvmc_converter<packet>, // is implicitly chosen by the C+ compiler. This means you will seldom need to // explicitly specify the converter type when connecting via <uvmc_connect>. // //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Group: User Library // // This section defines a transaction class and generic consumer model. The // transaction implements the ~do_pack~ and ~do_unpack~ methods required by the // default converter. // // Packing and unpacking involves streaming the contents of your transaction // fields into and out of the ~packer~ object provided as an argument to ~do_pack~ // and ~do_unpack~. The packer needs to have defined ~operator<<~ for each type // of field you stream. See <UVMC Type Support> for a list of supported // transaction field types. //------------------------------------------------------------------------------ // (begin inline source) namespace user_lib { using namespace uvmc; class packet_base { public: enum cmd_t { WRITE=0, READ, NOOP }; cmd_t cmd; unsigned int addr; vector<unsigned char> data; virtual void do_pack(uvmc_packer &packer) const { packer << cmd << addr << data; } virtual void do_unpack(uvmc_packer &packer) { packer >> cmd >> addr >> data; } }; class packet : public packet_base { public: unsigned int extra_int; virtual void do_pack(uvmc_packer &packer) const { packet_base::do_pack(packer); packer << extra_int; } virtual void do_unpack(uvmc_packer &packer) { packet_base::do_unpack(packer); packer >> extra_int; } }; // a generic target with a TLM2 b_transport export #include "consumer.cpp" } // (end inline source) //------------------------------------------------------------------------------ // Group: Conversion code // // We do not need to define an external conversion class because it conversion // is built into the transaction proper. The default converter will delegate to // our transaction's ~do_pack~ and ~do_unpack~ methods. // // We do, however, define ~operator<< (ostream&)~ for our transaction type using // <UVMC_PRINT> macros. With this, we can print the transaction contents to any // output stream. // // For example // //| packet p; //| ...initialize p... //| cout << p; // // This produces output similar to // //| '{cmd:2 addr:1fa34f22 data:'{4a, 27, de, a2, 6b, 62, 8d, 1d, 6} } // // You can invoke the macros in any namepace in which the uvmc namespace // was imported and the macros #included. // //------------------------------------------------------------------------------ // (begin inline source) using namespace user_lib; UVMC_PRINT_3(packet_base,cmd,addr,data) UVMC_PRINT_EXT_1(packet,packet_base,extra_int) // (end inline source) //------------------------------------------------------------------------------ // Group: Testbench code // // This section defines our testbench environment. In the top-level module, we // instantiate the generic consumer model. We also register the consumer's ~in~ // export to have a UVMC connection with a lookup string, ~stimulus~. The // SV-side will register its producer's ~out~ port with the same lookup string. // UVMC will match these two strings to complete the cross-language connection, // i.e. the SV producer's ~out~ port will be bound to the SC consumer's // ~in~ export. //------------------------------------------------------------------------------ // (begin inline source) class sc_env : public sc_module { public: consumer<packet> cons; sc_env(sc_module_name nm) : cons("cons") { uvmc_connect(cons.in,"stimulus"); } }; // Define sc_main, the vendor-independent means of starting a // SystemC simulation. int sc_main(int argc, char* argv[]) { sc_env env("env"); sc_start(); return 0; } // (end inline source)
#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
//**************************************************************************************** // 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; }
/* 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; }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // 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_state_vector_state_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; }
/******************************************************************************** * University of L'Aquila - HEPSYCODE Source Code License * * * * * * (c) 2018-2019 Centre of Excellence DEWS All rights reserved * ******************************************************************************** * <one line to give the program's name and a brief idea of what it does.> * * Copyright (C) 2022 Vittoriano Muttillo, Luigi Pomante * * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * ******************************************************************************** * * * Created on: 09/May/2023 * * Authors: Vittoriano Muttillo, Marco Santic, Luigi Pomante * * * * email: [email protected] * * [email protected] * * [email protected] * * * ******************************************************************************** * This code has been developed from an HEPSYCODE model used as demonstrator by * * University of L'Aquila. * *******************************************************************************/ #include "display.h" #include <systemc.h> void display::main() { int i = 1; system_display_payload system_display_payload_var; /* //implementation while(1) { system_display_payload_var = system_display_port_in->read(); cout << "Display-" << i << "\t at time \t" << sc_time_stamp().to_seconds() << endl; i++; } */ //implementation while(i <= 100) { system_display_payload_var = system_display_port_in->read(); cout << "Display-" << i <<": \t" << "\t at time \t" << sc_time_stamp().to_seconds() << endl; i++; } sc_stop(); }
/////////////////////////////////////////////////////////////////////////////////// // __ _ _ _ // // / _(_) | | | | // // __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | // // / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | // // | (_| | |_| | __/ __/ | | | | | | __/ | (_| | // // \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| // // | | // // |_| // // // // // // 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_multiplier_design.cpp" #include "systemc.h" int sc_main(int argc, char *argv[]) { vector_multiplier vector_multiplier("VECTOR_MULTIPLIER"); 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_multiplier.clock(clock); for (int i = 0; i < SIZE_I_IN; i++) { vector_multiplier.data_a_in[i](data_a_in[i]); vector_multiplier.data_b_in[i](data_b_in[i]); vector_multiplier.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; }
/***************************************************************************** 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