scheduler.hh revision 13061
14486Sbinkertn@umich.edu/*
24486Sbinkertn@umich.edu * Copyright 2018 Google, Inc.
34486Sbinkertn@umich.edu *
44486Sbinkertn@umich.edu * Redistribution and use in source and binary forms, with or without
54486Sbinkertn@umich.edu * modification, are permitted provided that the following conditions are
64486Sbinkertn@umich.edu * met: redistributions of source code must retain the above copyright
74486Sbinkertn@umich.edu * notice, this list of conditions and the following disclaimer;
84486Sbinkertn@umich.edu * redistributions in binary form must reproduce the above copyright
94486Sbinkertn@umich.edu * notice, this list of conditions and the following disclaimer in the
104486Sbinkertn@umich.edu * documentation and/or other materials provided with the distribution;
114486Sbinkertn@umich.edu * neither the name of the copyright holders nor the names of its
124486Sbinkertn@umich.edu * contributors may be used to endorse or promote products derived from
134486Sbinkertn@umich.edu * this software without specific prior written permission.
144486Sbinkertn@umich.edu *
154486Sbinkertn@umich.edu * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
164486Sbinkertn@umich.edu * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
174486Sbinkertn@umich.edu * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
184486Sbinkertn@umich.edu * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
194486Sbinkertn@umich.edu * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
204486Sbinkertn@umich.edu * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
214486Sbinkertn@umich.edu * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
224486Sbinkertn@umich.edu * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
234486Sbinkertn@umich.edu * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
244486Sbinkertn@umich.edu * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
254486Sbinkertn@umich.edu * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
264486Sbinkertn@umich.edu *
274486Sbinkertn@umich.edu * Authors: Gabe Black
284486Sbinkertn@umich.edu */
293102SN/A
303102SN/A#ifndef __SYSTEMC_CORE_SCHEDULER_HH__
315480Snate@binkert.org#define __SYSTEMC_CORE_SCHEDULER_HH__
325480Snate@binkert.org
333812SN/A#include <vector>
345480Snate@binkert.org
351310SN/A#include "base/logging.hh"
362916SN/A#include "sim/eventq.hh"
371310SN/A#include "systemc/core/channel.hh"
382542SN/A#include "systemc/core/list.hh"
391366SN/A#include "systemc/core/process.hh"
409338SAndreas.Sandberg@arm.com
411692SN/Aclass Fiber;
421310SN/A
432542SN/Anamespace sc_gem5
441366SN/A{
459338SAndreas.Sandberg@arm.com
463934SN/Atypedef NodeList<Process> ProcessList;
473885SN/Atypedef NodeList<Channel> ChannelList;
483932SN/A
493932SN/A/*
501692SN/A * The scheduler supports three different mechanisms, the initialization phase,
511634SN/A * delta cycles, and timed notifications.
521310SN/A *
532542SN/A * INITIALIZATION PHASE
541366SN/A *
559338SAndreas.Sandberg@arm.com * The initialization phase has three parts:
561692SN/A * 1. Run requested channel updates.
572916SN/A * 2. Make processes which need to initialize runnable (methods and threads
582916SN/A *    which didn't have dont_initialize called on them).
592916SN/A * 3. Process delta notifications.
609338SAndreas.Sandberg@arm.com *
612916SN/A * First, the Kernel SimObject calls the update() method during its startup()
622916SN/A * callback which handles the requested channel updates. The Kernel also
632916SN/A * schedules an event to be run at time 0 with a slightly elevated priority
642916SN/A * so that it happens before any "normal" event.
652916SN/A *
662916SN/A * When that t0 event happens, it calls the schedulers prepareForInit method
672916SN/A * which performs step 2 above. That indirectly causes the scheduler's
682916SN/A * readyEvent to be scheduled with slightly lowered priority, ensuring it
692916SN/A * happens after any "normal" event.
702916SN/A *
712916SN/A * Because delta notifications are scheduled at the standard priority, all
722916SN/A * of those events will happen next, performing step 3 above. Once they finish,
733847SN/A * if the readyEvent was scheduled above, there shouldn't be any higher
742916SN/A * priority events in front of it. When it runs, it will start the first
752916SN/A * evaluate phase of the first delta cycle.
762916SN/A *
772916SN/A * DELTA CYCLE
782916SN/A *
792916SN/A * A delta cycle has three phases within it.
802916SN/A * 1. The evaluate phase where runnable processes are allowed to run.
812916SN/A * 2. The update phase where requested channel updates hapen.
822916SN/A * 3. The delta notification phase where delta notifications happen.
832916SN/A *
842916SN/A * The readyEvent runs the first two steps of the delta cycle. It first goes
852916SN/A * through the list of runnable processes and executes them until the set is
862916SN/A * empty, and then immediately runs the update phase. Since these are all part
872916SN/A * of the same event, there's no chance for other events to intervene and
882916SN/A * break the required order above.
892916SN/A *
902916SN/A * During the update phase above, the spec forbids any action which would make
912916SN/A * a process runnable. That means that once the update phase finishes, the set
922916SN/A * of runnable processes will be empty. There may, however, have been some
932916SN/A * delta notifications/timeouts which will have been scheduled during either
945480Snate@binkert.org * the evaluate or update phase above. Because those are scheduled at the
952916SN/A * normal priority, they will now happen together until there aren't any
962916SN/A * delta events left.
972916SN/A *
982916SN/A * If any processes became runnable during the delta notification phase, the
992916SN/A * readyEvent will have been scheduled and will have been waiting patiently
1008839Sandreas.hansson@arm.com * behind the delta notification events. That will now run, effectively
1018839Sandreas.hansson@arm.com * starting the next delta cycle.
1022916SN/A *
1037523Ssteve.reinhardt@amd.com * TIMED NOTIFICATION PHASE
1048839Sandreas.hansson@arm.com *
1058839Sandreas.hansson@arm.com * If no processes became runnable, the event queue will continue to process
1068839Sandreas.hansson@arm.com * events until it comes across a timed notification, aka a notification
1078839Sandreas.hansson@arm.com * scheduled to happen in the future. Like delta notification events, those
1088839Sandreas.hansson@arm.com * will all happen together since the readyEvent priority is lower,
1098839Sandreas.hansson@arm.com * potentially marking new processes as ready. Once these events finish, the
1108839Sandreas.hansson@arm.com * readyEvent may run, starting the next delta cycle.
1118839Sandreas.hansson@arm.com *
1128839Sandreas.hansson@arm.com * PAUSE/STOP
1138839Sandreas.hansson@arm.com *
1148839Sandreas.hansson@arm.com * To inject a pause from sc_pause which should happen after the current delta
1158839Sandreas.hansson@arm.com * cycle's delta notification phase, an event is scheduled with a lower than
1168839Sandreas.hansson@arm.com * normal priority, but higher than the readyEvent. That ensures that any
1178839Sandreas.hansson@arm.com * delta notifications which are scheduled with normal priority will happen
1188839Sandreas.hansson@arm.com * first, since those are part of the current delta cycle. Then the pause
1198839Sandreas.hansson@arm.com * event will happen before the next readyEvent which would start the next
1208839Sandreas.hansson@arm.com * delta cycle. All of these events are scheduled for the current time, and so
1218839Sandreas.hansson@arm.com * would happen before any timed notifications went off.
1228839Sandreas.hansson@arm.com *
1238839Sandreas.hansson@arm.com * To inject a stop from sc_stop, the delta cycles should stop before even the
1248839Sandreas.hansson@arm.com * delta notifications have happened, but after the evaluate and update phases.
1258839Sandreas.hansson@arm.com * For that, a stop event with slightly higher than normal priority will be
1268839Sandreas.hansson@arm.com * scheduled so that it happens before any of the delta notification events
127 * which are at normal priority.
128 *
129 * MAX RUN TIME
130 *
131 * When sc_start is called, it's possible to pass in a maximum time the
132 * simulation should run to, at which point sc_pause is implicitly called. The
133 * simulation is supposed to run up to the latest timed notification phase
134 * which is less than or equal to the maximum time. In other words it should
135 * run timed notifications at the maximum time, but not the subsequent evaluate
136 * phase. That's implemented by scheduling an event at the max time with a
137 * priority which is lower than all the others except the ready event. Timed
138 * notifications will happen before it fires, but it will override any ready
139 * event and prevent the evaluate phase from starting.
140 */
141
142class Scheduler
143{
144  public:
145    Scheduler();
146
147    const std::string name() const { return "systemc_scheduler"; }
148
149    uint64_t numCycles() { return _numCycles; }
150    Process *current() { return _current; }
151
152    // Prepare for initialization.
153    void prepareForInit();
154
155    // Register a process with the scheduler.
156    void reg(Process *p);
157
158    // Tell the scheduler not to initialize a process.
159    void dontInitialize(Process *p);
160
161    // Run the next process, if there is one.
162    void yield();
163
164    // Put a process on the ready list.
165    void ready(Process *p);
166
167    // Schedule an update for a given channel.
168    void requestUpdate(Channel *c);
169
170    // Run the given process immediately, preempting whatever may be running.
171    void
172    runNow(Process *p)
173    {
174        // If a process is running, schedule it/us to run again.
175        if (_current)
176            readyList.pushFirst(_current);
177        // Schedule p to run first.
178        readyList.pushFirst(p);
179        yield();
180    }
181
182    // Set an event queue for scheduling events.
183    void setEventQueue(EventQueue *_eq) { eq = _eq; }
184
185    // Get the current time according to gem5.
186    Tick getCurTick() { return eq ? eq->getCurTick() : 0; }
187
188    // For scheduling delayed/timed notifications/timeouts.
189    void
190    schedule(::Event *event, Tick tick)
191    {
192        pendingTicks[tick]++;
193
194        if (initReady)
195            eq->schedule(event, tick);
196        else
197            eventsToSchedule[event] = tick;
198    }
199
200    // For descheduling delayed/timed notifications/timeouts.
201    void
202    deschedule(::Event *event)
203    {
204        auto it = pendingTicks.find(event->when());
205        if (--it->second == 0)
206            pendingTicks.erase(it);
207
208        if (initReady)
209            eq->deschedule(event);
210        else
211            eventsToSchedule.erase(event);
212    }
213
214    // Tell the scheduler than an event fired for bookkeeping purposes.
215    void
216    eventHappened()
217    {
218        auto it = pendingTicks.begin();
219        if (--it->second == 0)
220            pendingTicks.erase(it);
221
222        if (starved() && !runToTime)
223            scheduleStarvationEvent();
224    }
225
226    // Pending activity ignores gem5 activity, much like how a systemc
227    // simulation wouldn't know about asynchronous external events (socket IO
228    // for instance) that might happen before time advances in a pure
229    // systemc simulation. Also the spec lists what specific types of pending
230    // activity needs to be counted, which obviously doesn't include gem5
231    // events.
232
233    // Return whether there's pending systemc activity at this time.
234    bool
235    pendingCurr()
236    {
237        if (!readyList.empty() || !updateList.empty())
238            return true;
239        return pendingTicks.size() &&
240            pendingTicks.begin()->first == getCurTick();
241    }
242
243    // Return whether there are pending timed notifications or timeouts.
244    bool
245    pendingFuture()
246    {
247        switch (pendingTicks.size()) {
248          case 0: return false;
249          case 1: return pendingTicks.begin()->first > getCurTick();
250          default: return true;
251        }
252    }
253
254    // Return how many ticks there are until the first pending event, if any.
255    Tick
256    timeToPending()
257    {
258        if (!readyList.empty() || !updateList.empty())
259            return 0;
260        else if (pendingTicks.size())
261            return pendingTicks.begin()->first - getCurTick();
262        else
263            return MaxTick - getCurTick();
264    }
265
266    // Run scheduled channel updates.
267    void update();
268
269    void setScMainFiber(Fiber *sc_main) { scMain = sc_main; }
270
271    void start(Tick max_tick, bool run_to_time);
272    void oneCycle();
273
274    void schedulePause();
275    void scheduleStop(bool finish_delta);
276
277    bool paused() { return _paused; }
278    bool stopped() { return _stopped; }
279
280  private:
281    typedef const EventBase::Priority Priority;
282    static Priority DefaultPriority = EventBase::Default_Pri;
283
284    static Priority StopPriority = DefaultPriority - 1;
285    static Priority PausePriority = DefaultPriority + 1;
286    static Priority MaxTickPriority = DefaultPriority + 2;
287    static Priority ReadyPriority = DefaultPriority + 3;
288    static Priority StarvationPriority = ReadyPriority;
289
290    EventQueue *eq;
291    std::map<Tick, int> pendingTicks;
292
293    void runReady();
294    EventWrapper<Scheduler, &Scheduler::runReady> readyEvent;
295    void scheduleReadyEvent();
296
297    void pause();
298    void stop();
299    EventWrapper<Scheduler, &Scheduler::pause> pauseEvent;
300    EventWrapper<Scheduler, &Scheduler::stop> stopEvent;
301    Fiber *scMain;
302
303    bool
304    starved()
305    {
306        return (readyList.empty() && updateList.empty() &&
307                (pendingTicks.empty() ||
308                 pendingTicks.begin()->first > maxTick) &&
309                initList.empty());
310    }
311    EventWrapper<Scheduler, &Scheduler::pause> starvationEvent;
312    void scheduleStarvationEvent();
313
314    bool _started;
315    bool _paused;
316    bool _stopped;
317
318    Tick maxTick;
319    EventWrapper<Scheduler, &Scheduler::pause> maxTickEvent;
320
321    uint64_t _numCycles;
322
323    Process *_current;
324
325    bool initReady;
326    bool runToTime;
327    bool runOnce;
328
329    ProcessList initList;
330    ProcessList toFinalize;
331    ProcessList readyList;
332
333    ChannelList updateList;
334
335    std::map<::Event *, Tick> eventsToSchedule;
336};
337
338extern Scheduler scheduler;
339
340} // namespace sc_gem5
341
342#endif // __SYSTEMC_CORE_SCHEDULER_H__
343