2 * Copyright (c) 2000-2005 The Regents of The University of Michigan
3 * Copyright (c) 2013 Advanced Micro Devices, Inc.
4 * Copyright (c) 2013 Mark D. Hill and David A. Wood
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions are
9 * met: redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer;
11 * redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution;
14 * neither the name of the copyright holders nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 * Authors: Steve Reinhardt
35 * EventQueue interfaces
38 #ifndef __SIM_EVENTQ_HH__
39 #define __SIM_EVENTQ_HH__
49 #include "base/flags.hh"
50 #include "base/types.hh"
51 #include "debug/Event.hh"
52 #include "sim/serialize.hh"
54 class EventQueue; // forward declaration
55 class BaseGlobalEvent;
57 //! Simulation Quantum for multiple eventq simulation.
58 //! The quantum value is the period length after which the queues
59 //! synchronize themselves with each other. This means that any
60 //! event to scheduled on Queue A which is generated by an event on
61 //! Queue B should be at least simQuantum ticks away in future.
62 extern Tick simQuantum;
64 //! Current number of allocated main event queues.
65 extern uint32_t numMainEventQueues;
67 //! Array for main event queues.
68 extern std::vector<EventQueue *> mainEventQueue;
70 //! The current event queue for the running thread. Access to this queue
71 //! does not require any locking from the thread.
73 extern __thread EventQueue *_curEventQueue;
75 //! Current mode of execution: parallel / serial
76 extern bool inParallelMode;
78 //! Function for returning eventq queue for the provided
79 //! index. The function allocates a new queue in case one
80 //! does not exist for the index, provided that the index
81 //! is with in bounds.
82 EventQueue *getEventQueue(uint32_t index);
84 inline EventQueue *curEventQueue() { return _curEventQueue; }
85 inline void curEventQueue(EventQueue *q) { _curEventQueue = q; }
88 * Common base class for Event and GlobalEvent, so they can share flag
89 * and priority definitions and accessor functions. This class should
90 * not be used directly.
95 typedef unsigned short FlagsType;
96 typedef ::Flags<FlagsType> Flags;
98 static const FlagsType PublicRead = 0x003f; // public readable flags
99 static const FlagsType PublicWrite = 0x001d; // public writable flags
100 static const FlagsType Squashed = 0x0001; // has been squashed
101 static const FlagsType Scheduled = 0x0002; // has been scheduled
102 static const FlagsType Managed = 0x0004; // Use life cycle manager
103 static const FlagsType AutoDelete = Managed; // delete after dispatch
105 * This used to be AutoSerialize. This value can't be reused
106 * without changing the checkpoint version since the flag field
109 static const FlagsType Reserved0 = 0x0008;
110 static const FlagsType IsExitEvent = 0x0010; // special exit event
111 static const FlagsType IsMainQueue = 0x0020; // on main event queue
112 static const FlagsType Initialized = 0x7a40; // somewhat random bits
113 static const FlagsType InitMask = 0xffc0; // mask for init bits
116 typedef int8_t Priority;
118 /// Event priorities, to provide tie-breakers for events scheduled
119 /// at the same cycle. Most events are scheduled at the default
120 /// priority; these values are used to control events that need to
121 /// be ordered within a cycle.
124 static const Priority Minimum_Pri = SCHAR_MIN;
126 /// If we enable tracing on a particular cycle, do that as the
127 /// very first thing so we don't miss any of the events on
128 /// that cycle (even if we enter the debugger).
129 static const Priority Debug_Enable_Pri = -101;
131 /// Breakpoints should happen before anything else (except
132 /// enabling trace output), so we don't miss any action when
134 static const Priority Debug_Break_Pri = -100;
136 /// CPU switches schedule the new CPU's tick event for the
137 /// same cycle (after unscheduling the old CPU's tick event).
138 /// The switch needs to come before any tick events to make
139 /// sure we don't tick both CPUs in the same cycle.
140 static const Priority CPU_Switch_Pri = -31;
142 /// For some reason "delayed" inter-cluster writebacks are
143 /// scheduled before regular writebacks (which have default
144 /// priority). Steve?
145 static const Priority Delayed_Writeback_Pri = -1;
147 /// Default is zero for historical reasons.
148 static const Priority Default_Pri = 0;
150 /// DVFS update event leads to stats dump therefore given a lower priority
151 /// to ensure all relevant states have been updated
152 static const Priority DVFS_Update_Pri = 31;
154 /// Serailization needs to occur before tick events also, so
155 /// that a serialize/unserialize is identical to an on-line
157 static const Priority Serialize_Pri = 32;
159 /// CPU ticks must come after other associated CPU events
160 /// (such as writebacks).
161 static const Priority CPU_Tick_Pri = 50;
163 /// Statistics events (dump, reset, etc.) come after
164 /// everything else, but before exit.
165 static const Priority Stat_Event_Pri = 90;
167 /// Progress events come at the end.
168 static const Priority Progress_Event_Pri = 95;
170 /// If we want to exit on this cycle, it's the very last thing
172 static const Priority Sim_Exit_Pri = 100;
175 static const Priority Maximum_Pri = SCHAR_MAX;
179 * An item on an event queue. The action caused by a given
180 * event is specified by deriving a subclass and overriding the
181 * process() member function.
183 * Caution, the order of members is chosen to maximize data packing.
185 class Event : public EventBase, public Serializable
187 friend class EventQueue;
190 // The event queue is now a linked list of linked lists. The
191 // 'nextBin' pointer is to find the bin, where a bin is defined as
192 // when+priority. All events in the same bin will be stored in a
193 // second linked list (a stack) maintained by the 'nextInBin'
194 // pointer. The list will be accessed in LIFO order. The end
195 // result is that the insert/removal in 'nextBin' is
196 // linear/constant, and the lookup/removal in 'nextInBin' is
197 // constant/constant. Hopefully this is a significant improvement
198 // over the current fully linear insertion.
202 static Event *insertBefore(Event *event, Event *curr);
203 static Event *removeItem(Event *event, Event *last);
205 Tick _when; //!< timestamp when event should be processed
206 Priority _priority; //!< event priority
210 /// Global counter to generate unique IDs for Event instances
211 static Counter instanceCounter;
213 /// This event's unique ID. We can also use pointer values for
214 /// this but they're not consistent across runs making debugging
215 /// more difficult. Thus we use a global counter value when
219 /// queue to which this event belongs (though it may or may not be
220 /// scheduled on this queue yet)
225 Tick whenCreated; //!< time created
226 Tick whenScheduled; //!< time scheduled
230 setWhen(Tick when, EventQueue *q)
237 whenScheduled = curTick();
244 return (flags & InitMask) == Initialized;
248 /// Accessor for flags.
252 return flags & PublicRead;
256 isFlagSet(Flags _flags) const
258 assert(_flags.noneSet(~PublicRead));
259 return flags.isSet(_flags);
262 /// Accessor for flags.
264 setFlags(Flags _flags)
266 assert(_flags.noneSet(~PublicWrite));
271 clearFlags(Flags _flags)
273 assert(_flags.noneSet(~PublicWrite));
280 flags.clear(PublicWrite);
283 // This function isn't really useful if TRACING_ON is not defined
284 virtual void trace(const char *action); //!< trace event activity
286 protected: /* Memory management */
289 * Memory management hooks for events that have the Managed flag set
291 * Events can use automatic memory management by setting the
292 * Managed flag. The default implementation automatically deletes
293 * events once they have been removed from the event queue. This
294 * typically happens when events are descheduled or have been
295 * triggered and not rescheduled.
297 * The methods below may be overridden by events that need custom
298 * memory management. For example, events exported to Python need
299 * to impement reference counting to ensure that the Python
300 * implementation of the event is kept alive while it lives in the
303 * @note Memory managers are responsible for implementing
304 * reference counting (by overriding both acquireImpl() and
305 * releaseImpl()) or checking if an event is no longer scheduled
306 * in releaseImpl() before deallocating it.
310 * Managed event scheduled and being held in the event queue.
314 if (flags.isSet(Event::Managed))
319 * Managed event removed from the event queue.
322 if (flags.isSet(Event::Managed))
326 virtual void acquireImpl() {}
328 virtual void releaseImpl() {
339 * @param queue that the event gets scheduled on
341 Event(Priority p = Default_Pri, Flags f = 0)
342 : nextBin(nullptr), nextInBin(nullptr), _when(0), _priority(p),
343 flags(Initialized | f)
345 assert(f.noneSet(~PublicWrite));
347 instance = ++instanceCounter;
351 whenCreated = curTick();
357 virtual const std::string name() const;
359 /// Return a C string describing the event. This string should
360 /// *not* be dynamically allocated; just a const char array
361 /// describing the event class.
362 virtual const char *description() const;
364 /// Dump the current event data
369 * This member function is invoked when the event is processed
370 * (occurs). There is no default implementation; each subclass
371 * must provide its own implementation. The event is not
372 * automatically deleted after it is processed (to allow for
373 * statically allocated event objects).
375 * If the AutoDestroy flag is set, the object is deleted once it
378 virtual void process() = 0;
380 /// Determine if the current event is scheduled
381 bool scheduled() const { return flags.isSet(Scheduled); }
383 /// Squash the current event
384 void squash() { flags.set(Squashed); }
386 /// Check whether the event is squashed
387 bool squashed() const { return flags.isSet(Squashed); }
389 /// See if this is a SimExitEvent (without resorting to RTTI)
390 bool isExitEvent() const { return flags.isSet(IsExitEvent); }
392 /// Check whether this event will auto-delete
393 bool isManaged() const { return flags.isSet(Managed); }
394 bool isAutoDelete() const { return isManaged(); }
396 /// Get the time that the event is scheduled
397 Tick when() const { return _when; }
399 /// Get the event priority
400 Priority priority() const { return _priority; }
402 //! If this is part of a GlobalEvent, return the pointer to the
403 //! Global Event. By default, there is no GlobalEvent, so return
404 //! NULL. (Overridden in GlobalEvent::BarrierEvent.)
405 virtual BaseGlobalEvent *globalEvent() { return NULL; }
407 void serialize(CheckpointOut &cp) const override;
408 void unserialize(CheckpointIn &cp) override;
412 operator<(const Event &l, const Event &r)
414 return l.when() < r.when() ||
415 (l.when() == r.when() && l.priority() < r.priority());
419 operator>(const Event &l, const Event &r)
421 return l.when() > r.when() ||
422 (l.when() == r.when() && l.priority() > r.priority());
426 operator<=(const Event &l, const Event &r)
428 return l.when() < r.when() ||
429 (l.when() == r.when() && l.priority() <= r.priority());
432 operator>=(const Event &l, const Event &r)
434 return l.when() > r.when() ||
435 (l.when() == r.when() && l.priority() >= r.priority());
439 operator==(const Event &l, const Event &r)
441 return l.when() == r.when() && l.priority() == r.priority();
445 operator!=(const Event &l, const Event &r)
447 return l.when() != r.when() || l.priority() != r.priority();
451 * Queue of events sorted in time order
453 * Events are scheduled (inserted into the event queue) using the
454 * schedule() method. This method either inserts a <i>synchronous</i>
455 * or <i>asynchronous</i> event.
457 * Synchronous events are scheduled using schedule() method with the
458 * argument 'global' set to false (default). This should only be done
459 * from a thread holding the event queue lock
460 * (EventQueue::service_mutex). The lock is always held when an event
461 * handler is called, it can therefore always insert events into its
462 * own event queue unless it voluntarily releases the lock.
464 * Events can be scheduled across thread (and event queue borders) by
465 * either scheduling asynchronous events or taking the target event
466 * queue's lock. However, the lock should <i>never</i> be taken
467 * directly since this is likely to cause deadlocks. Instead, code
468 * that needs to schedule events in other event queues should
469 * temporarily release its own queue and lock the new queue. This
470 * prevents deadlocks since a single thread never owns more than one
471 * event queue lock. This functionality is provided by the
472 * ScopedMigration helper class. Note that temporarily migrating
473 * between event queues can make the simulation non-deterministic, it
474 * should therefore be limited to cases where that can be tolerated
475 * (e.g., handling asynchronous IO or fast-forwarding in KVM).
477 * Asynchronous events can also be scheduled using the normal
478 * schedule() method with the 'global' parameter set to true. Unlike
479 * the previous queue migration strategy, this strategy is fully
480 * deterministic. This causes the event to be inserted in a separate
481 * queue of asynchronous events (async_queue), which is merged main
482 * event queue at the end of each simulation quantum (by calling the
483 * handleAsyncInsertions() method). Note that this implies that such
484 * events must happen at least one simulation quantum into the future,
485 * otherwise they risk being scheduled in the past by
486 * handleAsyncInsertions().
495 //! Mutex to protect async queue.
496 std::mutex async_queue_mutex;
498 //! List of events added by other threads to this event queue.
499 std::list<Event*> async_queue;
502 * Lock protecting event handling.
504 * This lock is always taken when servicing events. It is assumed
505 * that the thread scheduling new events (not asynchronous events
506 * though) have taken this lock. This is normally done by
507 * serviceOne() since new events are typically scheduled as a
508 * response to an earlier event.
510 * This lock is intended to be used to temporarily steal an event
511 * queue to support inter-thread communication when some
512 * deterministic timing can be sacrificed for speed. For example,
513 * the KVM CPU can use this support to access devices running in a
516 * @see EventQueue::ScopedMigration.
517 * @see EventQueue::ScopedRelease
518 * @see EventQueue::lock()
519 * @see EventQueue::unlock()
521 std::mutex service_mutex;
523 //! Insert / remove event from the queue. Should only be called
524 //! by thread operating this queue.
525 void insert(Event *event);
526 void remove(Event *event);
528 //! Function for adding events to the async queue. The added events
529 //! are added to main event queue later. Threads, other than the
530 //! owning thread, should call this function instead of insert().
531 void asyncInsert(Event *event);
533 EventQueue(const EventQueue &);
537 * Temporarily migrate execution to a different event queue.
539 * An instance of this class temporarily migrates execution to a
540 * different event queue by releasing the current queue, locking
541 * the new queue, and updating curEventQueue(). This can, for
542 * example, be useful when performing IO across thread event
543 * queues when timing is not crucial (e.g., during fast
546 * ScopedMigration does nothing if both eqs are the same
548 class ScopedMigration
551 ScopedMigration(EventQueue *_new_eq, bool _doMigrate = true)
552 :new_eq(*_new_eq), old_eq(*curEventQueue()),
553 doMigrate((&new_eq != &old_eq)&&_doMigrate)
558 curEventQueue(&new_eq);
567 curEventQueue(&old_eq);
578 * Temporarily release the event queue service lock.
580 * There are cases where it is desirable to temporarily release
581 * the event queue lock to prevent deadlocks. For example, when
582 * waiting on the global barrier, we need to release the lock to
583 * prevent deadlocks from happening when another thread tries to
584 * temporarily take over the event queue waiting on the barrier.
589 ScopedRelease(EventQueue *_eq)
604 EventQueue(const std::string &n);
606 virtual const std::string name() const { return objName; }
607 void name(const std::string &st) { objName = st; }
609 //! Schedule the given event on this queue. Safe to call from any
611 void schedule(Event *event, Tick when, bool global = false);
613 //! Deschedule the specified event. Should be called only from the
615 void deschedule(Event *event);
617 //! Reschedule the specified event. Should be called only from
618 //! the owning thread.
619 void reschedule(Event *event, Tick when, bool always = false);
621 Tick nextTick() const { return head->when(); }
622 void setCurTick(Tick newVal) { _curTick = newVal; }
623 Tick getCurTick() const { return _curTick; }
624 Event *getHead() const { return head; }
628 // process all events up to the given timestamp. we inline a
629 // quick test to see if there are any events to process; if so,
630 // call the internal out-of-line version to process them all.
632 serviceEvents(Tick when)
635 if (nextTick() > when)
639 * @todo this assert is a good bug catcher. I need to
640 * make it true again.
642 //assert(head->when() >= when && "event scheduled in the past");
649 // return true if no events are queued
650 bool empty() const { return head == NULL; }
654 bool debugVerify() const;
656 //! Function for moving events from the async_queue to the main queue.
657 void handleAsyncInsertions();
660 * Function to signal that the event loop should be woken up because
661 * an event has been scheduled by an agent outside the gem5 event
662 * loop(s) whose event insertion may not have been noticed by gem5.
663 * This function isn't needed by the usual gem5 event loop but may
664 * be necessary in derived EventQueues which host gem5 onto other
667 * @param when Time of a delayed wakeup (if known). This parameter
668 * can be used by an implementation to schedule a wakeup in the
669 * future if it is sure it will remain active until then.
670 * Or it can be ignored and the event queue can be woken up now.
672 virtual void wakeup(Tick when = (Tick)-1) { }
675 * function for replacing the head of the event queue, so that a
676 * different set of events can run without disturbing events that have
677 * already been scheduled. Already scheduled events can be processed
678 * by replacing the original head back.
679 * USING THIS FUNCTION CAN BE DANGEROUS TO THE HEALTH OF THE SIMULATOR.
680 * NOT RECOMMENDED FOR USE.
682 Event* replaceHead(Event* s);
686 * Provide an interface for locking/unlocking the event queue.
688 * @warn Do NOT use these methods directly unless you really know
689 * what you are doing. Incorrect use can easily lead to simulator
692 * @see EventQueue::ScopedMigration.
693 * @see EventQueue::ScopedRelease
696 void lock() { service_mutex.lock(); }
697 void unlock() { service_mutex.unlock(); }
701 * Reschedule an event after a checkpoint.
703 * Since events don't know which event queue they belong to,
704 * parent objects need to reschedule events themselves. This
705 * method conditionally schedules an event that has the Scheduled
706 * flag set. It should be called by parent objects after
707 * unserializing an object.
709 * @warn Only use this method after unserializing an Event.
711 void checkpointReschedule(Event *event);
713 virtual ~EventQueue() { }
716 void dumpMainQueue();
721 /** A pointer to this object's event queue */
725 EventManager(EventManager &em) : eventq(em.eventq) {}
726 EventManager(EventManager *em) : eventq(em->eventq) {}
727 EventManager(EventQueue *eq) : eventq(eq) {}
736 schedule(Event &event, Tick when)
738 eventq->schedule(&event, when);
742 deschedule(Event &event)
744 eventq->deschedule(&event);
748 reschedule(Event &event, Tick when, bool always = false)
750 eventq->reschedule(&event, when, always);
754 schedule(Event *event, Tick when)
756 eventq->schedule(event, when);
760 deschedule(Event *event)
762 eventq->deschedule(event);
766 reschedule(Event *event, Tick when, bool always = false)
768 eventq->reschedule(event, when, always);
771 void wakeupEventQueue(Tick when = (Tick)-1)
773 eventq->wakeup(when);
776 void setCurTick(Tick newVal) { eventq->setCurTick(newVal); }
779 template <class T, void (T::* F)()>
780 class EventWrapper : public Event
786 EventWrapper(T *obj, bool del = false, Priority p = Default_Pri)
787 : Event(p), object(obj)
790 setFlags(AutoDelete);
793 EventWrapper(T &obj, bool del = false, Priority p = Default_Pri)
794 : Event(p), object(&obj)
797 setFlags(AutoDelete);
800 void process() { (object->*F)(); }
805 return object->name() + ".wrapped_event";
808 const char *description() const { return "EventWrapped"; }
811 class EventFunctionWrapper : public Event
814 std::function<void(void)> callback;
818 EventFunctionWrapper(const std::function<void(void)> &callback,
819 const std::string &name,
821 Priority p = Default_Pri)
822 : Event(p), callback(callback), _name(name)
825 setFlags(AutoDelete);
828 void process() { callback(); }
833 return _name + ".wrapped_function_event";
836 const char *description() const { return "EventFunctionWrapped"; }
839 #endif // __SIM_EVENTQ_HH__