scheduler.cc revision 13188:7af408b60cac
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/scheduler.hh"
31
32#include "base/fiber.hh"
33#include "base/logging.hh"
34#include "sim/eventq.hh"
35#include "systemc/core/kernel.hh"
36#include "systemc/ext/core/sc_main.hh"
37#include "systemc/ext/utils/sc_report.hh"
38#include "systemc/ext/utils/sc_report_handler.hh"
39
40namespace sc_gem5
41{
42
43Scheduler::Scheduler() :
44    eq(nullptr), readyEvent(this, false, ReadyPriority),
45    pauseEvent(this, false, PausePriority),
46    stopEvent(this, false, StopPriority),
47    scMain(nullptr), _throwToScMain(nullptr),
48    starvationEvent(this, false, StarvationPriority),
49    _started(false), _stopNow(false), _status(StatusOther),
50    maxTickEvent(this, false, MaxTickPriority),
51    _numCycles(0), _changeStamp(0), _current(nullptr), initDone(false),
52    runOnce(false), readyList(nullptr)
53{}
54
55Scheduler::~Scheduler()
56{
57    // Clear out everything that belongs to us to make sure nobody tries to
58    // clear themselves out after the scheduler goes away.
59    clear();
60}
61
62void
63Scheduler::clear()
64{
65    // Delta notifications.
66    while (!deltas.empty())
67        deltas.front()->deschedule();
68
69    // Timed notifications.
70    for (auto &tsp: timeSlots) {
71        TimeSlot *&ts = tsp.second;
72        while (!ts->events.empty())
73            ts->events.front()->deschedule();
74        deschedule(ts);
75    }
76    timeSlots.clear();
77
78    // gem5 events.
79    if (readyEvent.scheduled())
80        deschedule(&readyEvent);
81    if (pauseEvent.scheduled())
82        deschedule(&pauseEvent);
83    if (stopEvent.scheduled())
84        deschedule(&stopEvent);
85    if (starvationEvent.scheduled())
86        deschedule(&starvationEvent);
87    if (maxTickEvent.scheduled())
88        deschedule(&maxTickEvent);
89
90    Process *p;
91    while ((p = toFinalize.getNext()))
92        p->popListNode();
93    while ((p = initList.getNext()))
94        p->popListNode();
95    while ((p = readyListMethods.getNext()))
96        p->popListNode();
97    while ((p = readyListThreads.getNext()))
98        p->popListNode();
99
100    Channel *c;
101    while ((c = updateList.getNext()))
102        c->popListNode();
103}
104
105void
106Scheduler::initPhase()
107{
108    for (Process *p = toFinalize.getNext(); p; p = toFinalize.getNext()) {
109        p->finalize();
110        p->popListNode();
111
112        if (!p->hasStaticSensitivities() && !p->internal()) {
113            SC_REPORT_WARNING(
114                    "(W558) disable() or dont_initialize() called on process "
115                    "with no static sensitivity, it will be orphaned",
116                    p->name());
117        }
118    }
119
120    for (Process *p = initList.getNext(); p; p = initList.getNext()) {
121        p->finalize();
122        p->popListNode();
123        p->ready();
124    }
125
126    runUpdate();
127    runDelta();
128
129    for (auto ets: eventsToSchedule)
130        eq->schedule(ets.first, ets.second);
131    eventsToSchedule.clear();
132
133    if (_started) {
134        if (!runToTime && starved())
135            scheduleStarvationEvent();
136        kernel->status(::sc_core::SC_RUNNING);
137    }
138
139    initDone = true;
140
141    status(StatusOther);
142}
143
144void
145Scheduler::reg(Process *p)
146{
147    if (initDone) {
148        // If we're past initialization, finalize static sensitivity.
149        p->finalize();
150        // Mark the process as ready.
151        p->ready();
152    } else {
153        // Otherwise, record that this process should be initialized once we
154        // get there.
155        initList.pushLast(p);
156    }
157}
158
159void
160Scheduler::dontInitialize(Process *p)
161{
162    if (initDone) {
163        // Pop this process off of the ready list.
164        p->popListNode();
165    } else {
166        // Push this process onto the list of processes which still need
167        // their static sensitivity to be finalized. That implicitly pops it
168        // off the list of processes to be initialized/marked ready.
169        toFinalize.pushLast(p);
170    }
171}
172
173void
174Scheduler::yield()
175{
176    // Pull a process from the active list.
177    _current = readyList->getNext();
178    if (!_current) {
179        // There are no more processes, so return control to evaluate.
180        Fiber::primaryFiber()->run();
181    } else {
182        _current->popListNode();
183        // Switch to whatever Fiber is supposed to run this process. All
184        // Fibers which aren't running should be parked at this line.
185        _current->fiber()->run();
186        // If the current process needs to be manually started, start it.
187        if (_current && _current->needsStart()) {
188            _current->needsStart(false);
189            try {
190                _current->run();
191            } catch (...) {
192                throwToScMain();
193            }
194        }
195    }
196    if (_current && _current->excWrapper) {
197        // Make sure this isn't a method process.
198        assert(!_current->needsStart());
199        auto ew = _current->excWrapper;
200        _current->excWrapper = nullptr;
201        ew->throw_it();
202    }
203}
204
205void
206Scheduler::ready(Process *p)
207{
208    if (_stopNow)
209        return;
210
211    if (p->procKind() == ::sc_core::SC_METHOD_PROC_)
212        readyListMethods.pushLast(p);
213    else
214        readyListThreads.pushLast(p);
215
216    scheduleReadyEvent();
217}
218
219void
220Scheduler::resume(Process *p)
221{
222    if (initDone)
223        ready(p);
224    else
225        initList.pushLast(p);
226}
227
228bool
229listContains(ListNode *list, ListNode *target)
230{
231    ListNode *n = list->nextListNode;
232    while (n != list)
233        if (n == target)
234            return true;
235    return false;
236}
237
238bool
239Scheduler::suspend(Process *p)
240{
241    bool was_ready;
242    if (initDone) {
243        // After initialization, the only list we can be on is the ready list.
244        was_ready = (p->nextListNode != nullptr);
245        p->popListNode();
246    } else {
247        // Check the ready lists to see if we find this process.
248        was_ready = listContains(&readyListMethods, p) ||
249            listContains(&readyListThreads, p);
250        if (was_ready)
251            toFinalize.pushLast(p);
252    }
253    return was_ready;
254}
255
256void
257Scheduler::requestUpdate(Channel *c)
258{
259    updateList.pushLast(c);
260    scheduleReadyEvent();
261}
262
263void
264Scheduler::scheduleReadyEvent()
265{
266    // Schedule the evaluate and update phases.
267    if (!readyEvent.scheduled()) {
268        schedule(&readyEvent);
269        if (starvationEvent.scheduled())
270            deschedule(&starvationEvent);
271    }
272}
273
274void
275Scheduler::scheduleStarvationEvent()
276{
277    if (!starvationEvent.scheduled()) {
278        schedule(&starvationEvent);
279        if (readyEvent.scheduled())
280            deschedule(&readyEvent);
281    }
282}
283
284void
285Scheduler::runReady()
286{
287    bool empty = readyListMethods.empty() && readyListThreads.empty();
288    lastReadyTick = getCurTick();
289
290    // The evaluation phase.
291    do {
292        // We run methods and threads in two seperate passes to emulate how
293        // Accellera orders things, but without having to scan through a
294        // unified list to find the next process of the correct type.
295        readyList = &readyListMethods;
296        while (!readyListMethods.empty())
297            yield();
298
299        readyList = &readyListThreads;
300        while (!readyListThreads.empty())
301            yield();
302
303        // We already know that readyListThreads is empty at this point.
304    } while (!readyListMethods.empty());
305
306    if (!empty) {
307        _numCycles++;
308        _changeStamp++;
309    }
310
311    if (_stopNow)
312        return;
313
314    runUpdate();
315    runDelta();
316
317    if (!runToTime && starved())
318        scheduleStarvationEvent();
319
320    if (runOnce)
321        schedulePause();
322
323    status(StatusOther);
324}
325
326void
327Scheduler::runUpdate()
328{
329    status(StatusUpdate);
330
331    try {
332        Channel *channel = updateList.getNext();
333        while (channel) {
334            channel->popListNode();
335            channel->update();
336            channel = updateList.getNext();
337        }
338    } catch (...) {
339        throwToScMain();
340    }
341}
342
343void
344Scheduler::runDelta()
345{
346    status(StatusDelta);
347
348    try {
349        while (!deltas.empty())
350            deltas.front()->run();
351    } catch (...) {
352        throwToScMain();
353    }
354}
355
356void
357Scheduler::pause()
358{
359    status(StatusPaused);
360    kernel->status(::sc_core::SC_PAUSED);
361    runOnce = false;
362    if (scMain && !scMain->finished())
363        scMain->run();
364}
365
366void
367Scheduler::stop()
368{
369    status(StatusStopped);
370    kernel->stop();
371
372    clear();
373
374    runOnce = false;
375    if (scMain && !scMain->finished())
376        scMain->run();
377}
378
379void
380Scheduler::start(Tick max_tick, bool run_to_time)
381{
382    // We should be running from sc_main. Keep track of that Fiber to return
383    // to later.
384    scMain = Fiber::currentFiber();
385
386    _started = true;
387    status(StatusOther);
388    runToTime = run_to_time;
389
390    maxTick = max_tick;
391    lastReadyTick = getCurTick();
392
393    if (initDone) {
394        if (!runToTime && starved())
395            scheduleStarvationEvent();
396        kernel->status(::sc_core::SC_RUNNING);
397    }
398
399    schedule(&maxTickEvent, maxTick);
400
401    // Return to gem5 to let it run events, etc.
402    Fiber::primaryFiber()->run();
403
404    if (pauseEvent.scheduled())
405        deschedule(&pauseEvent);
406    if (stopEvent.scheduled())
407        deschedule(&stopEvent);
408    if (maxTickEvent.scheduled())
409        deschedule(&maxTickEvent);
410    if (starvationEvent.scheduled())
411        deschedule(&starvationEvent);
412
413    if (_throwToScMain) {
414        const ::sc_core::sc_report *to_throw = _throwToScMain;
415        _throwToScMain = nullptr;
416        throw *to_throw;
417    }
418}
419
420void
421Scheduler::oneCycle()
422{
423    runOnce = true;
424    scheduleReadyEvent();
425    start(::MaxTick, false);
426}
427
428void
429Scheduler::schedulePause()
430{
431    if (pauseEvent.scheduled())
432        return;
433
434    schedule(&pauseEvent);
435}
436
437void
438Scheduler::throwToScMain(const ::sc_core::sc_report *r)
439{
440    if (!r)
441        r = reportifyException();
442    _throwToScMain = r;
443    status(StatusOther);
444    scMain->run();
445}
446
447void
448Scheduler::scheduleStop(bool finish_delta)
449{
450    if (stopEvent.scheduled())
451        return;
452
453    if (!finish_delta) {
454        _stopNow = true;
455        // If we're not supposed to finish the delta cycle, flush all
456        // pending activity.
457        clear();
458    }
459    schedule(&stopEvent);
460}
461
462Scheduler scheduler;
463
464namespace {
465
466void
467throwingReportHandler(const ::sc_core::sc_report &r,
468                      const ::sc_core::sc_actions &)
469{
470    throw r;
471}
472
473} // anonymous namespace
474
475const ::sc_core::sc_report *
476reportifyException()
477{
478    ::sc_core::sc_report_handler_proc old_handler =
479        ::sc_core::sc_report_handler::get_handler();
480    ::sc_core::sc_report_handler::set_handler(&throwingReportHandler);
481
482    try {
483        try {
484            // Rethrow the current exception so we can catch it and throw an
485            // sc_report instead if it's not a type we recognize/can handle.
486            throw;
487        } catch (const ::sc_core::sc_report &) {
488            // It's already a sc_report, so nothing to do.
489            throw;
490        } catch (const ::sc_core::sc_unwind_exception &) {
491            panic("Kill/reset exception escaped a Process::run()");
492        } catch (const std::exception &e) {
493            SC_REPORT_ERROR("uncaught exception", e.what());
494        } catch (const char *msg) {
495            SC_REPORT_ERROR("uncaught exception", msg);
496        } catch (...) {
497            SC_REPORT_ERROR("uncaught exception", "UNKNOWN EXCEPTION");
498        }
499    } catch (const ::sc_core::sc_report &r) {
500        ::sc_core::sc_report_handler::set_handler(old_handler);
501        return &r;
502    }
503    panic("No exception thrown in reportifyException.");
504}
505
506} // namespace sc_gem5
507