process.cc revision 13288
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/port.hh"
35#include "systemc/core/scheduler.hh"
36#include "systemc/ext/core/sc_join.hh"
37#include "systemc/ext/core/sc_main.hh"
38#include "systemc/ext/core/sc_process_handle.hh"
39#include "systemc/ext/utils/sc_report_handler.hh"
40
41namespace sc_gem5
42{
43
44class UnwindExceptionReset : public ::sc_core::sc_unwind_exception
45{
46  public:
47    UnwindExceptionReset() { _isReset = true; }
48};
49
50class UnwindExceptionKill : public ::sc_core::sc_unwind_exception
51{
52  public:
53    UnwindExceptionKill() {}
54};
55
56template <typename T>
57struct BuiltinExceptionWrapper : public ExceptionWrapperBase
58{
59  public:
60    T t;
61    void throw_it() override { throw t; }
62};
63
64BuiltinExceptionWrapper<UnwindExceptionReset> resetException;
65BuiltinExceptionWrapper<UnwindExceptionKill> killException;
66
67
68void
69Process::forEachKid(const std::function<void(Process *)> &work)
70{
71    for (auto &kid: get_child_objects()) {
72        Process *p_kid = dynamic_cast<Process *>(kid);
73        if (p_kid)
74            work(p_kid);
75    }
76}
77
78void
79Process::suspend(bool inc_kids)
80{
81    if (inc_kids)
82        forEachKid([](Process *p) { p->suspend(true); });
83
84    if (!_suspended) {
85        _suspended = true;
86        _suspendedReady = scheduler.suspend(this);
87
88        if (procKind() != ::sc_core::SC_METHOD_PROC_ &&
89                scheduler.current() == this) {
90            // This isn't in the spec, but Accellera says that a thread that
91            // self suspends should be marked ready immediately when it's
92            // resumed.
93            _suspendedReady = true;
94            scheduler.yield();
95        }
96    }
97}
98
99void
100Process::resume(bool inc_kids)
101{
102    if (inc_kids)
103        forEachKid([](Process *p) { p->resume(true); });
104
105    if (_suspended) {
106        _suspended = false;
107        if (_suspendedReady)
108            scheduler.resume(this);
109        _suspendedReady = false;
110    }
111}
112
113void
114Process::disable(bool inc_kids)
115{
116    if (inc_kids)
117        forEachKid([](Process *p) { p->disable(true); });
118
119    if (!::sc_core::sc_allow_process_control_corners &&
120            timeoutEvent.scheduled()) {
121        std::string message("attempt to disable a thread with timeout wait: ");
122        message += name();
123        SC_REPORT_ERROR("Undefined process control interaction",
124                message.c_str());
125    }
126
127    _disabled = true;
128}
129
130void
131Process::enable(bool inc_kids)
132{
133
134    if (inc_kids)
135        forEachKid([](Process *p) { p->enable(true); });
136
137    _disabled = false;
138}
139
140void
141Process::kill(bool inc_kids)
142{
143    if (::sc_core::sc_get_status() != ::sc_core::SC_RUNNING) {
144        SC_REPORT_ERROR(
145                "(E572) a process may not be killed before it is initialized",
146                name());
147    }
148
149    // Propogate the kill to our children no matter what happens to us.
150    if (inc_kids)
151        forEachKid([](Process *p) { p->kill(true); });
152
153    // If we're in the middle of unwinding, ignore the kill request.
154    if (_isUnwinding)
155        return;
156
157    // Update our state.
158    terminate();
159    _isUnwinding = true;
160
161    // Make sure this process isn't marked ready
162    popListNode();
163
164    // Inject the kill exception into this process if it's started.
165    if (!_needsStart)
166        injectException(killException);
167}
168
169void
170Process::reset(bool inc_kids)
171{
172    if (::sc_core::sc_get_status() != ::sc_core::SC_RUNNING) {
173        SC_REPORT_ERROR(
174                "(E573) a process may not be asynchronously reset while"
175                "the simulation is not running", name());
176    }
177
178    // Propogate the reset to our children no matter what happens to us.
179    if (inc_kids)
180        forEachKid([](Process *p) { p->reset(true); });
181
182    // If we're in the middle of unwinding, ignore the reset request.
183    if (_isUnwinding)
184        return;
185
186
187    _resetEvent.notify();
188
189    if (_needsStart) {
190        scheduler.runNow(this);
191    } else {
192        _isUnwinding = true;
193        injectException(resetException);
194    }
195}
196
197void
198Process::throw_it(ExceptionWrapperBase &exc, bool inc_kids)
199{
200    if (::sc_core::sc_get_status() != ::sc_core::SC_RUNNING) {
201        SC_REPORT_ERROR(
202                "(E574) throw_it not allowed unless simulation is running ",
203                name());
204    }
205
206    if (inc_kids)
207        forEachKid([&exc](Process *p) { p->throw_it(exc, true); });
208
209    // Only inject an exception into threads that have started.
210    if (!_needsStart)
211        injectException(exc);
212}
213
214void
215Process::injectException(ExceptionWrapperBase &exc)
216{
217    excWrapper = &exc;
218    scheduler.runNow(this);
219};
220
221void
222Process::syncResetOn(bool inc_kids)
223{
224    if (inc_kids)
225        forEachKid([](Process *p) { p->syncResetOn(true); });
226
227    _syncReset = true;
228}
229
230void
231Process::syncResetOff(bool inc_kids)
232{
233    if (inc_kids)
234        forEachKid([](Process *p) { p->syncResetOff(true); });
235
236    _syncReset = false;
237}
238
239void
240Process::signalReset(bool set, bool sync)
241{
242    if (set) {
243        waitCount(0);
244        if (sync) {
245            syncResetCount++;
246        } else {
247            asyncResetCount++;
248            cancelTimeout();
249            clearDynamic();
250            scheduler.runNext(this);
251        }
252    } else {
253        if (sync)
254            syncResetCount--;
255        else
256            asyncResetCount--;
257    }
258}
259
260void
261Process::run()
262{
263    bool reset;
264    do {
265        reset = false;
266        try {
267            func->call();
268        } catch(ScHalt) {
269            std::cout << "Terminating process " << name() << std::endl;
270        } catch(const ::sc_core::sc_unwind_exception &exc) {
271            reset = exc.is_reset();
272            _isUnwinding = false;
273        } catch (...) {
274            throw;
275        }
276    } while (reset);
277    needsStart(true);
278}
279
280void
281Process::addStatic(StaticSensitivity *s)
282{
283    staticSensitivities.push_back(s);
284}
285
286void
287Process::setDynamic(DynamicSensitivity *s)
288{
289    if (dynamicSensitivity) {
290        dynamicSensitivity->clear();
291        delete dynamicSensitivity;
292    }
293    dynamicSensitivity = s;
294}
295
296void
297Process::addReset(Reset *reset)
298{
299    resets.push_back(reset);
300}
301
302void
303Process::cancelTimeout()
304{
305    if (timeoutEvent.scheduled())
306        scheduler.deschedule(&timeoutEvent);
307}
308
309void
310Process::setTimeout(::sc_core::sc_time t)
311{
312    cancelTimeout();
313    scheduler.schedule(&timeoutEvent, t);
314}
315
316void
317Process::timeout()
318{
319    // A process is considered timed_out only if it was also waiting for an
320    // event but got a timeout instead.
321    _timedOut = (dynamicSensitivity != nullptr);
322
323    setDynamic(nullptr);
324    if (disabled())
325        return;
326
327    ready();
328}
329
330void
331Process::satisfySensitivity(Sensitivity *s)
332{
333    if (_waitCount) {
334        _waitCount--;
335        return;
336    }
337
338    // If there's a dynamic sensitivity and this wasn't it, ignore.
339    if ((dynamicSensitivity || timeoutEvent.scheduled()) &&
340            dynamicSensitivity != s) {
341        return;
342    }
343
344    _timedOut = false;
345    // This sensitivity should already be cleared by this point, or the event
346    // which triggered it will take care of it.
347    delete dynamicSensitivity;
348    dynamicSensitivity = nullptr;
349    cancelTimeout();
350    ready();
351}
352
353void
354Process::ready()
355{
356    if (disabled())
357        return;
358    if (suspended())
359        _suspendedReady = true;
360    else
361        scheduler.ready(this);
362}
363
364void
365Process::lastReport(::sc_core::sc_report *report)
366{
367    if (report) {
368        _lastReport = std::unique_ptr<::sc_core::sc_report>(
369                new ::sc_core::sc_report(*report));
370    } else {
371        _lastReport = nullptr;
372    }
373}
374
375::sc_core::sc_report *Process::lastReport() const { return _lastReport.get(); }
376
377Process::Process(const char *name, ProcessFuncWrapper *func, bool internal) :
378    ::sc_core::sc_process_b(name), excWrapper(nullptr),
379    timeoutEvent([this]() { this->timeout(); }),
380    func(func), _internal(internal), _timedOut(false), _dontInitialize(false),
381    _needsStart(true), _isUnwinding(false), _terminated(false),
382    _suspended(false), _disabled(false), _syncReset(false), syncResetCount(0),
383    asyncResetCount(0), _waitCount(0), refCount(0),
384    stackSize(::Fiber::DefaultStackSize), dynamicSensitivity(nullptr)
385{
386    _dynamic =
387            (::sc_core::sc_get_status() >
388             ::sc_core::SC_BEFORE_END_OF_ELABORATION);
389    _newest = this;
390}
391
392void
393Process::terminate()
394{
395    _terminated = true;
396    _suspendedReady = false;
397    _suspended = false;
398    _syncReset = false;
399    clearDynamic();
400    cancelTimeout();
401    for (auto s: staticSensitivities) {
402        s->clear();
403        delete s;
404    }
405    staticSensitivities.clear();
406
407    _terminatedEvent.notify();
408
409    for (auto jw: joinWaiters)
410        jw->signal();
411    joinWaiters.clear();
412}
413
414Process *Process::_newest;
415
416void
417throw_it_wrapper(Process *p, ExceptionWrapperBase &exc, bool inc_kids)
418{
419    p->throw_it(exc, inc_kids);
420}
421
422void
423newReset(const sc_core::sc_port_base *pb, Process *p, bool s, bool v)
424{
425    Port *port = Port::fromPort(pb);
426    port->addReset(new Reset(p, s, v));
427}
428
429void
430newReset(const sc_core::sc_signal_in_if<bool> *sig, Process *p, bool s, bool v)
431{
432    Reset *reset = new Reset(p, s, v);
433    if (!reset->install(sig))
434        delete reset;
435}
436
437} // namespace sc_gem5
438