process.cc revision 13207:034ca389a810
1/*
2 * Copyright 2018 Google, Inc.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met: redistributions of source code must retain the above copyright
7 * notice, this list of conditions and the following disclaimer;
8 * redistributions in binary form must reproduce the above copyright
9 * notice, this list of conditions and the following disclaimer in the
10 * documentation and/or other materials provided with the distribution;
11 * neither the name of the copyright holders nor the names of its
12 * contributors may be used to endorse or promote products derived from
13 * this software without specific prior written permission.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 *
27 * Authors: Gabe Black
28 */
29
30#include "systemc/core/process.hh"
31
32#include "base/logging.hh"
33#include "systemc/core/event.hh"
34#include "systemc/core/scheduler.hh"
35#include "systemc/ext/core/sc_join.hh"
36#include "systemc/ext/core/sc_main.hh"
37#include "systemc/ext/core/sc_process_handle.hh"
38#include "systemc/ext/utils/sc_report_handler.hh"
39
40namespace sc_gem5
41{
42
43class UnwindExceptionReset : public ::sc_core::sc_unwind_exception
44{
45  public:
46    UnwindExceptionReset() { _isReset = true; }
47};
48
49class UnwindExceptionKill : public ::sc_core::sc_unwind_exception
50{
51  public:
52    UnwindExceptionKill() {}
53};
54
55template <typename T>
56struct BuiltinExceptionWrapper : public ExceptionWrapperBase
57{
58  public:
59    T t;
60    void throw_it() override { throw t; }
61};
62
63BuiltinExceptionWrapper<UnwindExceptionReset> resetException;
64BuiltinExceptionWrapper<UnwindExceptionKill> killException;
65
66
67void
68Process::forEachKid(const std::function<void(Process *)> &work)
69{
70    for (auto &kid: get_child_objects()) {
71        Process *p_kid = dynamic_cast<Process *>(kid);
72        if (p_kid)
73            work(p_kid);
74    }
75}
76
77void
78Process::suspend(bool inc_kids)
79{
80    if (inc_kids)
81        forEachKid([](Process *p) { p->suspend(true); });
82
83    if (!_suspended) {
84        _suspended = true;
85        _suspendedReady = scheduler.suspend(this);
86
87        if (procKind() != ::sc_core::SC_METHOD_PROC_ &&
88                scheduler.current() == this) {
89            // This isn't in the spec, but Accellera says that a thread that
90            // self suspends should be marked ready immediately when it's
91            // resumed.
92            _suspendedReady = true;
93            scheduler.yield();
94        }
95    }
96}
97
98void
99Process::resume(bool inc_kids)
100{
101    if (inc_kids)
102        forEachKid([](Process *p) { p->resume(true); });
103
104    if (_suspended) {
105        _suspended = false;
106        if (_suspendedReady)
107            scheduler.resume(this);
108        _suspendedReady = false;
109    }
110}
111
112void
113Process::disable(bool inc_kids)
114{
115    if (inc_kids)
116        forEachKid([](Process *p) { p->disable(true); });
117
118    if (!::sc_core::sc_allow_process_control_corners &&
119            timeoutEvent.scheduled()) {
120        std::string message("attempt to disable a thread with timeout wait: ");
121        message += name();
122        SC_REPORT_ERROR("Undefined process control interaction",
123                message.c_str());
124    }
125
126    _disabled = true;
127}
128
129void
130Process::enable(bool inc_kids)
131{
132
133    if (inc_kids)
134        forEachKid([](Process *p) { p->enable(true); });
135
136    _disabled = false;
137}
138
139void
140Process::kill(bool inc_kids)
141{
142    if (::sc_core::sc_get_status() != ::sc_core::SC_RUNNING) {
143        SC_REPORT_ERROR(
144                "(E572) a process may not be killed before it is initialized",
145                name());
146    }
147
148    // Propogate the kill to our children no matter what happens to us.
149    if (inc_kids)
150        forEachKid([](Process *p) { p->kill(true); });
151
152    // If we're in the middle of unwinding, ignore the kill request.
153    if (_isUnwinding)
154        return;
155
156    // Update our state.
157    terminate();
158    _isUnwinding = true;
159
160    // Make sure this process isn't marked ready
161    popListNode();
162
163    // Inject the kill exception into this process if it's started.
164    if (!_needsStart)
165        injectException(killException);
166}
167
168void
169Process::reset(bool inc_kids)
170{
171    if (::sc_core::sc_get_status() != ::sc_core::SC_RUNNING) {
172        SC_REPORT_ERROR(
173                "(E573) a process may not be asynchronously reset while"
174                "the simulation is not running", name());
175    }
176
177    // Propogate the reset to our children no matter what happens to us.
178    if (inc_kids)
179        forEachKid([](Process *p) { p->reset(true); });
180
181    // If we're in the middle of unwinding, ignore the reset request.
182    if (_isUnwinding)
183        return;
184
185
186    if (_needsStart) {
187        scheduler.runNow(this);
188    } else {
189        _isUnwinding = true;
190        injectException(resetException);
191    }
192
193    _resetEvent.notify();
194}
195
196void
197Process::throw_it(ExceptionWrapperBase &exc, bool inc_kids)
198{
199    if (::sc_core::sc_get_status() != ::sc_core::SC_RUNNING) {
200        SC_REPORT_ERROR(
201                "(E574) throw_it not allowed unless simulation is running ",
202                name());
203    }
204
205    if (inc_kids)
206        forEachKid([&exc](Process *p) { p->throw_it(exc, true); });
207
208    // Only inject an exception into threads that have started.
209    if (!_needsStart)
210        injectException(exc);
211}
212
213void
214Process::injectException(ExceptionWrapperBase &exc)
215{
216    excWrapper = &exc;
217    scheduler.runNow(this);
218};
219
220void
221Process::syncResetOn(bool inc_kids)
222{
223    if (inc_kids)
224        forEachKid([](Process *p) { p->syncResetOn(true); });
225
226    _syncReset = true;
227}
228
229void
230Process::syncResetOff(bool inc_kids)
231{
232    if (inc_kids)
233        forEachKid([](Process *p) { p->syncResetOff(true); });
234
235    _syncReset = false;
236}
237
238void
239Process::run()
240{
241    bool reset;
242    do {
243        reset = false;
244        try {
245            func->call();
246        } catch(ScHalt) {
247            std::cout << "Terminating process " << name() << std::endl;
248        } catch(const ::sc_core::sc_unwind_exception &exc) {
249            reset = exc.is_reset();
250            _isUnwinding = false;
251        } catch (...) {
252            throw;
253        }
254    } while (reset);
255    needsStart(true);
256}
257
258void
259Process::addStatic(StaticSensitivity *s)
260{
261    staticSensitivities.push_back(s);
262}
263
264void
265Process::setDynamic(DynamicSensitivity *s)
266{
267    if (dynamicSensitivity) {
268        dynamicSensitivity->clear();
269        delete dynamicSensitivity;
270    }
271    dynamicSensitivity = s;
272}
273
274void
275Process::cancelTimeout()
276{
277    if (timeoutEvent.scheduled())
278        scheduler.deschedule(&timeoutEvent);
279}
280
281void
282Process::setTimeout(::sc_core::sc_time t)
283{
284    cancelTimeout();
285    scheduler.schedule(&timeoutEvent, t);
286}
287
288void
289Process::timeout()
290{
291    // A process is considered timed_out only if it was also waiting for an
292    // event but got a timeout instead.
293    _timedOut = (dynamicSensitivity != nullptr);
294
295    setDynamic(nullptr);
296    if (disabled())
297        return;
298
299    ready();
300}
301
302void
303Process::satisfySensitivity(Sensitivity *s)
304{
305    // If there's a dynamic sensitivity and this wasn't it, ignore.
306    if ((dynamicSensitivity || timeoutEvent.scheduled()) &&
307            dynamicSensitivity != s) {
308        return;
309    }
310
311    _timedOut = false;
312    // This sensitivity should already be cleared by this point, or the event
313    // which triggered it will take care of it.
314    delete dynamicSensitivity;
315    dynamicSensitivity = nullptr;
316    cancelTimeout();
317    ready();
318}
319
320void
321Process::ready()
322{
323    if (disabled())
324        return;
325    if (suspended())
326        _suspendedReady = true;
327    else
328        scheduler.ready(this);
329}
330
331void
332Process::lastReport(::sc_core::sc_report *report)
333{
334    if (report) {
335        _lastReport = std::unique_ptr<::sc_core::sc_report>(
336                new ::sc_core::sc_report(*report));
337    } else {
338        _lastReport = nullptr;
339    }
340}
341
342::sc_core::sc_report *Process::lastReport() const { return _lastReport.get(); }
343
344Process::Process(const char *name, ProcessFuncWrapper *func, bool internal) :
345    ::sc_core::sc_process_b(name), excWrapper(nullptr),
346    timeoutEvent([this]() { this->timeout(); }),
347    func(func), _internal(internal), _timedOut(false), _dontInitialize(false),
348    _needsStart(true), _isUnwinding(false), _terminated(false),
349    _suspended(false), _disabled(false), _syncReset(false), refCount(0),
350    stackSize(::Fiber::DefaultStackSize), dynamicSensitivity(nullptr)
351{
352    _dynamic =
353            (::sc_core::sc_get_status() >
354             ::sc_core::SC_BEFORE_END_OF_ELABORATION);
355    _newest = this;
356}
357
358void
359Process::terminate()
360{
361    _terminated = true;
362    _suspendedReady = false;
363    _suspended = false;
364    _syncReset = false;
365    clearDynamic();
366    cancelTimeout();
367    for (auto s: staticSensitivities) {
368        s->clear();
369        delete s;
370    }
371    staticSensitivities.clear();
372
373    _terminatedEvent.notify();
374
375    for (auto jw: joinWaiters)
376        jw->signal();
377    joinWaiters.clear();
378}
379
380Process *Process::_newest;
381
382void
383throw_it_wrapper(Process *p, ExceptionWrapperBase &exc, bool inc_kids)
384{
385    p->throw_it(exc, inc_kids);
386}
387
388} // namespace sc_gem5
389