scheduler.hh revision 13257
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#ifndef __SYSTEMC_CORE_SCHEDULER_HH__
31#define __SYSTEMC_CORE_SCHEDULER_HH__
32
33#include <functional>
34#include <map>
35#include <set>
36#include <vector>
37
38#include "base/logging.hh"
39#include "sim/core.hh"
40#include "sim/eventq.hh"
41#include "systemc/core/channel.hh"
42#include "systemc/core/list.hh"
43#include "systemc/core/process.hh"
44#include "systemc/core/sched_event.hh"
45
46class Fiber;
47
48namespace sc_gem5
49{
50
51class TraceFile;
52
53typedef NodeList<Process> ProcessList;
54typedef NodeList<Channel> ChannelList;
55
56/*
57 * The scheduler supports three different mechanisms, the initialization phase,
58 * delta cycles, and timed notifications.
59 *
60 * INITIALIZATION PHASE
61 *
62 * The initialization phase has three parts:
63 * 1. Run requested channel updates.
64 * 2. Make processes which need to initialize runnable (methods and threads
65 *    which didn't have dont_initialize called on them).
66 * 3. Process delta notifications.
67 *
68 * First, the Kernel SimObject calls the update() method during its startup()
69 * callback which handles the requested channel updates. The Kernel also
70 * schedules an event to be run at time 0 with a slightly elevated priority
71 * so that it happens before any "normal" event.
72 *
73 * When that t0 event happens, it calls the schedulers prepareForInit method
74 * which performs step 2 above. That indirectly causes the scheduler's
75 * readyEvent to be scheduled with slightly lowered priority, ensuring it
76 * happens after any "normal" event.
77 *
78 * Because delta notifications are scheduled at the standard priority, all
79 * of those events will happen next, performing step 3 above. Once they finish,
80 * if the readyEvent was scheduled above, there shouldn't be any higher
81 * priority events in front of it. When it runs, it will start the first
82 * evaluate phase of the first delta cycle.
83 *
84 * DELTA CYCLE
85 *
86 * A delta cycle has three phases within it.
87 * 1. The evaluate phase where runnable processes are allowed to run.
88 * 2. The update phase where requested channel updates hapen.
89 * 3. The delta notification phase where delta notifications happen.
90 *
91 * The readyEvent runs all three steps of the delta cycle. It first goes
92 * through the list of runnable processes and executes them until the set is
93 * empty, and then immediately runs the update phase. Since these are all part
94 * of the same event, there's no chance for other events to intervene and
95 * break the required order above.
96 *
97 * During the update phase above, the spec forbids any action which would make
98 * a process runnable. That means that once the update phase finishes, the set
99 * of runnable processes will be empty. There may, however, have been some
100 * delta notifications/timeouts which will have been scheduled during either
101 * the evaluate or update phase above. Those will have been accumulated in the
102 * scheduler, and are now all executed.
103 *
104 * If any processes became runnable during the delta notification phase, the
105 * readyEvent will have been scheduled and will be waiting and ready to run
106 * again, effectively starting the next delta cycle.
107 *
108 * TIMED NOTIFICATION PHASE
109 *
110 * If no processes became runnable, the event queue will continue to process
111 * events until it comes across an event which represents all the timed
112 * notifications which are supposed to happen at a particular time. The object
113 * which tracks them will execute all those notifications, and then destroy
114 * itself. If the readyEvent is now ready to run, the next delta cycle will
115 * start.
116 *
117 * PAUSE/STOP
118 *
119 * To inject a pause from sc_pause which should happen after the current delta
120 * cycle's delta notification phase, an event is scheduled with a lower than
121 * normal priority, but higher than the readyEvent. That ensures that any
122 * delta notifications which are scheduled with normal priority will happen
123 * first, since those are part of the current delta cycle. Then the pause
124 * event will happen before the next readyEvent which would start the next
125 * delta cycle. All of these events are scheduled for the current time, and so
126 * would happen before any timed notifications went off.
127 *
128 * To inject a stop from sc_stop, the delta cycles should stop before even the
129 * delta notifications have happened, but after the evaluate and update phases.
130 * For that, a stop event with slightly higher than normal priority will be
131 * scheduled so that it happens before any of the delta notification events
132 * which are at normal priority.
133 *
134 * MAX RUN TIME
135 *
136 * When sc_start is called, it's possible to pass in a maximum time the
137 * simulation should run to, at which point sc_pause is implicitly called. The
138 * simulation is supposed to run up to the latest timed notification phase
139 * which is less than or equal to the maximum time. In other words it should
140 * run timed notifications at the maximum time, but not the subsequent evaluate
141 * phase. That's implemented by scheduling an event at the max time with a
142 * priority which is lower than all the others except the ready event. Timed
143 * notifications will happen before it fires, but it will override any ready
144 * event and prevent the evaluate phase from starting.
145 */
146
147class Scheduler
148{
149  public:
150    typedef std::list<ScEvent *> ScEvents;
151
152    class TimeSlot : public ::Event
153    {
154      public:
155        TimeSlot() : ::Event(Default_Pri, AutoDelete) {}
156
157        ScEvents events;
158        void process();
159    };
160
161    typedef std::map<Tick, TimeSlot *> TimeSlots;
162
163    Scheduler();
164    ~Scheduler();
165
166    void clear();
167
168    const std::string name() const { return "systemc_scheduler"; }
169
170    uint64_t numCycles() { return _numCycles; }
171    Process *current() { return _current; }
172
173    void initPhase();
174
175    // Register a process with the scheduler.
176    void reg(Process *p);
177
178    // Run the next process, if there is one.
179    void yield();
180
181    // Put a process on the ready list.
182    void ready(Process *p);
183
184    // Mark a process as ready if init is finished, or put it on the list of
185    // processes to be initialized.
186    void resume(Process *p);
187
188    // Remove a process from the ready/init list if it was on one of them, and
189    // return if it was.
190    bool suspend(Process *p);
191
192    // Schedule an update for a given channel.
193    void requestUpdate(Channel *c);
194
195    // Run the given process immediately, preempting whatever may be running.
196    void
197    runNow(Process *p)
198    {
199        // This function may put a process on the wrong list, ie a thread
200        // the method list. That's fine since that's just a performance
201        // optimization, and the important thing here is how the processes are
202        // ordered.
203
204        // If a process is running, schedule it/us to run again.
205        if (_current)
206            readyListMethods.pushFirst(_current);
207        // Schedule p to run first.
208        readyListMethods.pushFirst(p);
209        yield();
210    }
211
212    // Set an event queue for scheduling events.
213    void setEventQueue(EventQueue *_eq) { eq = _eq; }
214
215    // Get the current time according to gem5.
216    Tick getCurTick() { return eq ? eq->getCurTick() : 0; }
217
218    Tick
219    delayed(const ::sc_core::sc_time &delay)
220    {
221        return getCurTick() + delay.value();
222    }
223
224    // For scheduling delayed/timed notifications/timeouts.
225    void
226    schedule(ScEvent *event, const ::sc_core::sc_time &delay)
227    {
228        Tick tick = delayed(delay);
229        if (tick < getCurTick())
230            tick = getCurTick();
231
232        // Delta notification/timeout.
233        if (delay.value() == 0) {
234            event->schedule(deltas, tick);
235            if (!inEvaluate() && !inUpdate())
236                scheduleReadyEvent();
237            return;
238        }
239
240        // Timed notification/timeout.
241        TimeSlot *&ts = timeSlots[tick];
242        if (!ts) {
243            ts = new TimeSlot;
244            schedule(ts, tick);
245        }
246        event->schedule(ts->events, tick);
247    }
248
249    // For descheduling delayed/timed notifications/timeouts.
250    void
251    deschedule(ScEvent *event)
252    {
253        ScEvents *on = event->scheduledOn();
254
255        if (on == &deltas) {
256            event->deschedule();
257            return;
258        }
259
260        // Timed notification/timeout.
261        auto tsit = timeSlots.find(event->when());
262        panic_if(tsit == timeSlots.end(),
263                "Descheduling event at time with no events.");
264        TimeSlot *ts = tsit->second;
265        ScEvents &events = ts->events;
266        assert(on == &events);
267        event->deschedule();
268
269        // If no more events are happening at this time slot, get rid of it.
270        if (events.empty()) {
271            deschedule(ts);
272            timeSlots.erase(tsit);
273        }
274    }
275
276    void
277    completeTimeSlot(TimeSlot *ts)
278    {
279        _changeStamp++;
280        assert(ts == timeSlots.begin()->second);
281        timeSlots.erase(timeSlots.begin());
282        if (!runToTime && starved())
283            scheduleStarvationEvent();
284        scheduleTimeAdvancesEvent();
285    }
286
287    // Pending activity ignores gem5 activity, much like how a systemc
288    // simulation wouldn't know about asynchronous external events (socket IO
289    // for instance) that might happen before time advances in a pure
290    // systemc simulation. Also the spec lists what specific types of pending
291    // activity needs to be counted, which obviously doesn't include gem5
292    // events.
293
294    // Return whether there's pending systemc activity at this time.
295    bool
296    pendingCurr()
297    {
298        return !readyListMethods.empty() || !readyListThreads.empty() ||
299            !updateList.empty() || !deltas.empty();
300    }
301
302    // Return whether there are pending timed notifications or timeouts.
303    bool
304    pendingFuture()
305    {
306        return !timeSlots.empty();
307    }
308
309    // Return how many ticks there are until the first pending event, if any.
310    Tick
311    timeToPending()
312    {
313        if (pendingCurr())
314            return 0;
315        if (pendingFuture())
316            return timeSlots.begin()->first - getCurTick();
317        return MaxTick - getCurTick();
318    }
319
320    // Run scheduled channel updates.
321    void runUpdate();
322
323    // Run delta events.
324    void runDelta();
325
326    void setScMainFiber(Fiber *sc_main) { scMain = sc_main; }
327
328    void start(Tick max_tick, bool run_to_time);
329    void oneCycle();
330
331    void schedulePause();
332    void scheduleStop(bool finish_delta);
333
334    enum Status
335    {
336        StatusOther = 0,
337        StatusEvaluate,
338        StatusUpdate,
339        StatusDelta,
340        StatusTiming,
341        StatusPaused,
342        StatusStopped
343    };
344
345    bool elaborationDone() { return _elaborationDone; }
346    void elaborationDone(bool b) { _elaborationDone = b; }
347
348    bool paused() { return status() == StatusPaused; }
349    bool stopped() { return status() == StatusStopped; }
350    bool inEvaluate() { return status() == StatusEvaluate; }
351    bool inUpdate() { return status() == StatusUpdate; }
352    bool inDelta() { return status() == StatusDelta; }
353    bool inTiming() { return status() == StatusTiming; }
354
355    uint64_t changeStamp() { return _changeStamp; }
356
357    void throwToScMain(const ::sc_core::sc_report *r=nullptr);
358
359    Status status() { return _status; }
360    void status(Status s) { _status = s; }
361
362    void registerTraceFile(TraceFile *tf) { traceFiles.insert(tf); }
363    void unregisterTraceFile(TraceFile *tf) { traceFiles.erase(tf); }
364
365  private:
366    typedef const EventBase::Priority Priority;
367    static Priority DefaultPriority = EventBase::Default_Pri;
368
369    static Priority StopPriority = DefaultPriority - 1;
370    static Priority PausePriority = DefaultPriority + 1;
371    static Priority MaxTickPriority = DefaultPriority + 2;
372    static Priority ReadyPriority = DefaultPriority + 3;
373    static Priority StarvationPriority = ReadyPriority;
374    static Priority TimeAdvancesPriority = EventBase::Maximum_Pri;
375
376    EventQueue *eq;
377
378    // For gem5 style events.
379    void
380    schedule(::Event *event, Tick tick)
381    {
382        if (initDone)
383            eq->schedule(event, tick);
384        else
385            eventsToSchedule[event] = tick;
386    }
387
388    void schedule(::Event *event) { schedule(event, getCurTick()); }
389
390    void
391    deschedule(::Event *event)
392    {
393        if (initDone)
394            eq->deschedule(event);
395        else
396            eventsToSchedule.erase(event);
397    }
398
399    ScEvents deltas;
400    TimeSlots timeSlots;
401
402    Process *
403    getNextReady()
404    {
405        Process *p = readyListMethods.getNext();
406        return p ? p : readyListThreads.getNext();
407    }
408
409    void runReady();
410    EventWrapper<Scheduler, &Scheduler::runReady> readyEvent;
411    void scheduleReadyEvent();
412
413    void pause();
414    void stop();
415    EventWrapper<Scheduler, &Scheduler::pause> pauseEvent;
416    EventWrapper<Scheduler, &Scheduler::stop> stopEvent;
417
418    Fiber *scMain;
419    const ::sc_core::sc_report *_throwToScMain;
420
421    bool
422    starved()
423    {
424        return (readyListMethods.empty() && readyListThreads.empty() &&
425                updateList.empty() && deltas.empty() &&
426                (timeSlots.empty() || timeSlots.begin()->first > maxTick) &&
427                initList.empty());
428    }
429    EventWrapper<Scheduler, &Scheduler::pause> starvationEvent;
430    void scheduleStarvationEvent();
431
432    bool _elaborationDone;
433    bool _started;
434    bool _stopNow;
435
436    Status _status;
437
438    Tick maxTick;
439    Tick lastReadyTick;
440    void
441    maxTickFunc()
442    {
443        if (lastReadyTick != getCurTick())
444            _changeStamp++;
445        pause();
446    }
447    EventWrapper<Scheduler, &Scheduler::maxTickFunc> maxTickEvent;
448
449    void timeAdvances() { trace(false); }
450    EventWrapper<Scheduler, &Scheduler::timeAdvances> timeAdvancesEvent;
451    void
452    scheduleTimeAdvancesEvent()
453    {
454        if (!traceFiles.empty() && !timeAdvancesEvent.scheduled())
455            schedule(&timeAdvancesEvent);
456    }
457
458    uint64_t _numCycles;
459    uint64_t _changeStamp;
460
461    Process *_current;
462
463    bool initDone;
464    bool runToTime;
465    bool runOnce;
466
467    ProcessList initList;
468
469    ProcessList readyListMethods;
470    ProcessList readyListThreads;
471
472    ChannelList updateList;
473
474    std::map<::Event *, Tick> eventsToSchedule;
475
476    std::set<TraceFile *> traceFiles;
477
478    void trace(bool delta);
479};
480
481extern Scheduler scheduler;
482
483inline void
484Scheduler::TimeSlot::process()
485{
486    scheduler.status(StatusTiming);
487
488    try {
489        while (!events.empty())
490            events.front()->run();
491    } catch (...) {
492        if (events.empty())
493            scheduler.completeTimeSlot(this);
494        else
495            scheduler.schedule(this);
496        scheduler.throwToScMain();
497    }
498
499    scheduler.status(StatusOther);
500    scheduler.completeTimeSlot(this);
501}
502
503const ::sc_core::sc_report *reportifyException();
504
505} // namespace sc_gem5
506
507#endif // __SYSTEMC_CORE_SCHEDULER_H__
508