1/*
2 * Copyright (c) 2017, 2019 ARM Limited
3 * All rights reserved
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder.  You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Copyright (c) 2010 Advanced Micro Devices, Inc.
15 * Copyright (c) 2006 The Regents of The University of Michigan
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met: redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer;
22 * redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution;
25 * neither the name of the copyright holders nor the names of its
26 * contributors may be used to endorse or promote products derived from
27 * this software without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 *
41 * Authors: Nathan Binkert
42 *          Steve Reinhardt
43 *          Gabe Black
44 *          Andreas Sandberg
45 */
46
47#include "pybind11/pybind11.h"
48#include "pybind11/stl.h"
49
50#include "python/pybind11/core.hh"
51
52#include <ctime>
53
54#include "base/addr_range.hh"
55#include "base/inet.hh"
56#include "base/logging.hh"
57#include "base/random.hh"
58#include "base/socket.hh"
59#include "base/types.hh"
60#include "sim/core.hh"
61#include "sim/drain.hh"
62#include "sim/serialize.hh"
63#include "sim/sim_object.hh"
64
65namespace py = pybind11;
66
67/** Resolve a SimObject name using the Pybind configuration */
68class PybindSimObjectResolver : public SimObjectResolver
69{
70    SimObject *resolveSimObject(const std::string &name);
71};
72
73PybindSimObjectResolver pybindSimObjectResolver;
74
75SimObject *
76PybindSimObjectResolver::resolveSimObject(const std::string &name)
77{
78    // TODO
79    py::module m = py::module::import("m5.SimObject");
80    auto f = m.attr("resolveSimObject");
81
82    return f(name).cast<SimObject *>();
83}
84
85extern const char *compileDate;
86
87#ifdef DEBUG
88const bool flag_DEBUG = true;
89#else
90const bool flag_DEBUG = false;
91#endif
92#ifdef NDEBUG
93const bool flag_NDEBUG = true;
94#else
95const bool flag_NDEBUG = false;
96#endif
97const bool flag_TRACING_ON = TRACING_ON;
98
99static void
100init_drain(py::module &m_native)
101{
102    py::module m = m_native.def_submodule("drain");
103
104    py::enum_<DrainState>(m, "DrainState")
105        .value("Running", DrainState::Running)
106        .value("Draining", DrainState::Draining)
107        .value("Drained", DrainState::Drained)
108        ;
109
110    py::class_<Drainable, std::unique_ptr<Drainable, py::nodelete>>(
111        m, "Drainable")
112        .def("drainState", &Drainable::drainState)
113        .def("notifyFork", &Drainable::notifyFork)
114        ;
115
116    // The drain manager is a singleton with a private
117    // destructor. Disable deallocation from the Python binding.
118    py::class_<DrainManager, std::unique_ptr<DrainManager, py::nodelete>>(
119        m, "DrainManager")
120        .def("tryDrain", &DrainManager::tryDrain)
121        .def("resume", &DrainManager::resume)
122        .def("preCheckpointRestore", &DrainManager::preCheckpointRestore)
123        .def("isDrained", &DrainManager::isDrained)
124        .def("state", &DrainManager::state)
125        .def("signalDrainDone", &DrainManager::signalDrainDone)
126        .def_static("instance", &DrainManager::instance,
127                    py::return_value_policy::reference)
128        ;
129}
130
131static void
132init_serialize(py::module &m_native)
133{
134    py::module m = m_native.def_submodule("serialize");
135
136    py::class_<Serializable, std::unique_ptr<Serializable, py::nodelete>>(
137        m, "Serializable")
138        ;
139
140    py::class_<CheckpointIn>(m, "CheckpointIn")
141        ;
142}
143
144static void
145init_range(py::module &m_native)
146{
147    py::module m = m_native.def_submodule("range");
148
149    py::class_<AddrRange>(m, "AddrRange")
150        .def(py::init<>())
151        .def(py::init<Addr &, Addr &>())
152        .def(py::init<Addr, Addr, const std::vector<Addr> &, uint8_t>())
153        .def(py::init<const std::vector<AddrRange> &>())
154        .def(py::init<Addr, Addr, uint8_t, uint8_t, uint8_t, uint8_t>())
155
156        .def("__str__", &AddrRange::to_string)
157
158        .def("interleaved", &AddrRange::interleaved)
159        .def("granularity", &AddrRange::granularity)
160        .def("stripes", &AddrRange::stripes)
161        .def("size", &AddrRange::size)
162        .def("valid", &AddrRange::valid)
163        .def("start", &AddrRange::start)
164        .def("end", &AddrRange::end)
165        .def("mergesWith", &AddrRange::mergesWith)
166        .def("intersects", &AddrRange::intersects)
167        .def("isSubset", &AddrRange::isSubset)
168        ;
169
170    // We need to make vectors of AddrRange opaque to avoid weird
171    // memory allocation issues in PyBind's STL wrappers.
172    py::bind_vector<std::vector<AddrRange>>(m, "AddrRangeVector");
173
174    m.def("RangeEx", &RangeEx);
175    m.def("RangeIn", &RangeIn);
176    m.def("RangeSize", &RangeSize);
177}
178
179static void
180init_net(py::module &m_native)
181{
182    py::module m = m_native.def_submodule("net");
183
184    py::class_<Net::EthAddr>(m, "EthAddr")
185        .def(py::init<>())
186        .def(py::init<const std::string &>())
187        ;
188
189    py::class_<Net::IpAddress>(m, "IpAddress")
190        .def(py::init<>())
191        .def(py::init<uint32_t>())
192        ;
193
194    py::class_<Net::IpNetmask, Net::IpAddress>(m, "IpNetmask")
195        .def(py::init<>())
196        .def(py::init<uint32_t, uint8_t>())
197        ;
198
199    py::class_<Net::IpWithPort, Net::IpAddress>(m, "IpWithPort")
200        .def(py::init<>())
201        .def(py::init<uint32_t, uint16_t>())
202        ;
203}
204
205void
206pybind_init_core(py::module &m_native)
207{
208    py::module m_core = m_native.def_submodule("core");
209
210    py::class_<Cycles>(m_core, "Cycles")
211        .def(py::init<>())
212        .def(py::init<uint64_t>())
213        .def("__int__", &Cycles::operator uint64_t)
214        .def("__add__", &Cycles::operator+)
215        .def("__sub__", &Cycles::operator-)
216        ;
217
218    py::class_<tm>(m_core, "tm")
219        .def_static("gmtime", [](std::time_t t) { return *std::gmtime(&t); })
220        .def_readwrite("tm_sec", &tm::tm_sec)
221        .def_readwrite("tm_min", &tm::tm_min)
222        .def_readwrite("tm_hour", &tm::tm_hour)
223        .def_readwrite("tm_mday", &tm::tm_mday)
224        .def_readwrite("tm_mon", &tm::tm_mon)
225        .def_readwrite("tm_wday", &tm::tm_wday)
226        .def_readwrite("tm_yday", &tm::tm_yday)
227        .def_readwrite("tm_isdst", &tm::tm_isdst)
228        ;
229
230    py::enum_<Logger::LogLevel>(m_core, "LogLevel")
231        .value("PANIC", Logger::PANIC)
232        .value("FATAL", Logger::FATAL)
233        .value("WARN", Logger::WARN)
234        .value("INFO", Logger::INFO)
235        .value("HACK", Logger::HACK)
236        ;
237
238    m_core
239        .def("setLogLevel", &Logger::setLevel)
240        .def("setOutputDir", &setOutputDir)
241        .def("doExitCleanup", &doExitCleanup)
242
243        .def("disableAllListeners", &ListenSocket::disableAll)
244        .def("listenersDisabled", &ListenSocket::allDisabled)
245        .def("listenersLoopbackOnly", &ListenSocket::loopbackOnly)
246        .def("seedRandom", [](uint64_t seed) { random_mt.init(seed); })
247
248
249        .def("fixClockFrequency", &fixClockFrequency)
250        .def("clockFrequencyFixed", &clockFrequencyFixed)
251
252        .def("setClockFrequency", &setClockFrequency)
253        .def("getClockFrequency", &getClockFrequency)
254        .def("curTick", curTick)
255        ;
256
257    /* TODO: These should be read-only */
258    m_core.attr("compileDate") = py::cast(compileDate);
259
260    m_core.attr("flag_DEBUG") = py::cast(flag_DEBUG);
261    m_core.attr("flag_DEBUG") = py::cast(flag_DEBUG);
262    m_core.attr("flag_NDEBUG") = py::cast(flag_NDEBUG);
263    m_core.attr("flag_TRACING_ON") = py::cast(flag_TRACING_ON);
264
265    m_core.attr("MaxTick") = py::cast(MaxTick);
266
267    /*
268     * Serialization helpers
269     */
270    m_core
271        .def("serializeAll", &Serializable::serializeAll)
272        .def("unserializeGlobals", &Serializable::unserializeGlobals)
273        .def("getCheckpoint", [](const std::string &cpt_dir) {
274            return new CheckpointIn(cpt_dir, pybindSimObjectResolver);
275        })
276
277        ;
278
279
280    init_drain(m_native);
281    init_serialize(m_native);
282    init_range(m_native);
283    init_net(m_native);
284}
285
286