sim: Expose the system's byte order as a param
[gem5.git] / src / sim / eventq.hh
1 /*
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
5 * All rights reserved.
6 *
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.
17 *
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.
29 */
30
31 /* @file
32 * EventQueue interfaces
33 */
34
35 #ifndef __SIM_EVENTQ_HH__
36 #define __SIM_EVENTQ_HH__
37
38 #include <algorithm>
39 #include <cassert>
40 #include <climits>
41 #include <functional>
42 #include <iosfwd>
43 #include <memory>
44 #include <mutex>
45 #include <string>
46
47 #include "base/debug.hh"
48 #include "base/flags.hh"
49 #include "base/types.hh"
50 #include "debug/Event.hh"
51 #include "sim/serialize.hh"
52
53 class EventQueue; // forward declaration
54 class BaseGlobalEvent;
55
56 //! Simulation Quantum for multiple eventq simulation.
57 //! The quantum value is the period length after which the queues
58 //! synchronize themselves with each other. This means that any
59 //! event to scheduled on Queue A which is generated by an event on
60 //! Queue B should be at least simQuantum ticks away in future.
61 extern Tick simQuantum;
62
63 //! Current number of allocated main event queues.
64 extern uint32_t numMainEventQueues;
65
66 //! Array for main event queues.
67 extern std::vector<EventQueue *> mainEventQueue;
68
69 //! The current event queue for the running thread. Access to this queue
70 //! does not require any locking from the thread.
71
72 extern __thread EventQueue *_curEventQueue;
73
74 //! Current mode of execution: parallel / serial
75 extern bool inParallelMode;
76
77 //! Function for returning eventq queue for the provided
78 //! index. The function allocates a new queue in case one
79 //! does not exist for the index, provided that the index
80 //! is with in bounds.
81 EventQueue *getEventQueue(uint32_t index);
82
83 inline EventQueue *curEventQueue() { return _curEventQueue; }
84 inline void curEventQueue(EventQueue *q) { _curEventQueue = q; }
85
86 /**
87 * Common base class for Event and GlobalEvent, so they can share flag
88 * and priority definitions and accessor functions. This class should
89 * not be used directly.
90 */
91 class EventBase
92 {
93 protected:
94 typedef unsigned short FlagsType;
95 typedef ::Flags<FlagsType> Flags;
96
97 static const FlagsType PublicRead = 0x003f; // public readable flags
98 static const FlagsType PublicWrite = 0x001d; // public writable flags
99 static const FlagsType Squashed = 0x0001; // has been squashed
100 static const FlagsType Scheduled = 0x0002; // has been scheduled
101 static const FlagsType Managed = 0x0004; // Use life cycle manager
102 static const FlagsType AutoDelete = Managed; // delete after dispatch
103 /**
104 * This used to be AutoSerialize. This value can't be reused
105 * without changing the checkpoint version since the flag field
106 * gets serialized.
107 */
108 static const FlagsType Reserved0 = 0x0008;
109 static const FlagsType IsExitEvent = 0x0010; // special exit event
110 static const FlagsType IsMainQueue = 0x0020; // on main event queue
111 static const FlagsType Initialized = 0x7a40; // somewhat random bits
112 static const FlagsType InitMask = 0xffc0; // mask for init bits
113
114 public:
115 /**
116 * @ingroup api_eventq
117 */
118 typedef int8_t Priority;
119
120 /// Event priorities, to provide tie-breakers for events scheduled
121 /// at the same cycle. Most events are scheduled at the default
122 /// priority; these values are used to control events that need to
123 /// be ordered within a cycle.
124
125 /**
126 * Minimum priority
127 *
128 * @ingroup api_eventq
129 */
130 static const Priority Minimum_Pri = SCHAR_MIN;
131
132 /**
133 * If we enable tracing on a particular cycle, do that as the
134 * very first thing so we don't miss any of the events on
135 * that cycle (even if we enter the debugger).
136 *
137 * @ingroup api_eventq
138 */
139 static const Priority Debug_Enable_Pri = -101;
140
141 /**
142 * Breakpoints should happen before anything else (except
143 * enabling trace output), so we don't miss any action when
144 * debugging.
145 *
146 * @ingroup api_eventq
147 */
148 static const Priority Debug_Break_Pri = -100;
149
150 /**
151 * CPU switches schedule the new CPU's tick event for the
152 * same cycle (after unscheduling the old CPU's tick event).
153 * The switch needs to come before any tick events to make
154 * sure we don't tick both CPUs in the same cycle.
155 *
156 * @ingroup api_eventq
157 */
158 static const Priority CPU_Switch_Pri = -31;
159
160 /**
161 * For some reason "delayed" inter-cluster writebacks are
162 * scheduled before regular writebacks (which have default
163 * priority). Steve?
164 *
165 * @ingroup api_eventq
166 */
167 static const Priority Delayed_Writeback_Pri = -1;
168
169 /**
170 * Default is zero for historical reasons.
171 *
172 * @ingroup api_eventq
173 */
174 static const Priority Default_Pri = 0;
175
176 /**
177 * DVFS update event leads to stats dump therefore given a lower priority
178 * to ensure all relevant states have been updated
179 *
180 * @ingroup api_eventq
181 */
182 static const Priority DVFS_Update_Pri = 31;
183
184 /**
185 * Serailization needs to occur before tick events also, so
186 * that a serialize/unserialize is identical to an on-line
187 * CPU switch.
188 *
189 * @ingroup api_eventq
190 */
191 static const Priority Serialize_Pri = 32;
192
193 /**
194 * CPU ticks must come after other associated CPU events
195 * (such as writebacks).
196 *
197 * @ingroup api_eventq
198 */
199 static const Priority CPU_Tick_Pri = 50;
200
201 /**
202 * If we want to exit a thread in a CPU, it comes after CPU_Tick_Pri
203 *
204 * @ingroup api_eventq
205 */
206 static const Priority CPU_Exit_Pri = 64;
207
208 /**
209 * Statistics events (dump, reset, etc.) come after
210 * everything else, but before exit.
211 *
212 * @ingroup api_eventq
213 */
214 static const Priority Stat_Event_Pri = 90;
215
216 /**
217 * Progress events come at the end.
218 *
219 * @ingroup api_eventq
220 */
221 static const Priority Progress_Event_Pri = 95;
222
223 /**
224 * If we want to exit on this cycle, it's the very last thing
225 * we do.
226 *
227 * @ingroup api_eventq
228 */
229 static const Priority Sim_Exit_Pri = 100;
230
231 /**
232 * Maximum priority
233 *
234 * @ingroup api_eventq
235 */
236 static const Priority Maximum_Pri = SCHAR_MAX;
237 };
238
239 /*
240 * An item on an event queue. The action caused by a given
241 * event is specified by deriving a subclass and overriding the
242 * process() member function.
243 *
244 * Caution, the order of members is chosen to maximize data packing.
245 */
246 class Event : public EventBase, public Serializable
247 {
248 friend class EventQueue;
249
250 private:
251 // The event queue is now a linked list of linked lists. The
252 // 'nextBin' pointer is to find the bin, where a bin is defined as
253 // when+priority. All events in the same bin will be stored in a
254 // second linked list (a stack) maintained by the 'nextInBin'
255 // pointer. The list will be accessed in LIFO order. The end
256 // result is that the insert/removal in 'nextBin' is
257 // linear/constant, and the lookup/removal in 'nextInBin' is
258 // constant/constant. Hopefully this is a significant improvement
259 // over the current fully linear insertion.
260 Event *nextBin;
261 Event *nextInBin;
262
263 static Event *insertBefore(Event *event, Event *curr);
264 static Event *removeItem(Event *event, Event *last);
265
266 Tick _when; //!< timestamp when event should be processed
267 Priority _priority; //!< event priority
268 Flags flags;
269
270 #ifndef NDEBUG
271 /// Global counter to generate unique IDs for Event instances
272 static Counter instanceCounter;
273
274 /// This event's unique ID. We can also use pointer values for
275 /// this but they're not consistent across runs making debugging
276 /// more difficult. Thus we use a global counter value when
277 /// debugging.
278 Counter instance;
279
280 /// queue to which this event belongs (though it may or may not be
281 /// scheduled on this queue yet)
282 EventQueue *queue;
283 #endif
284
285 #ifdef EVENTQ_DEBUG
286 Tick whenCreated; //!< time created
287 Tick whenScheduled; //!< time scheduled
288 #endif
289
290 void
291 setWhen(Tick when, EventQueue *q)
292 {
293 _when = when;
294 #ifndef NDEBUG
295 queue = q;
296 #endif
297 #ifdef EVENTQ_DEBUG
298 whenScheduled = curTick();
299 #endif
300 }
301
302 bool
303 initialized() const
304 {
305 return (flags & InitMask) == Initialized;
306 }
307
308 protected:
309 Flags
310 getFlags() const
311 {
312 return flags & PublicRead;
313 }
314
315 bool
316 isFlagSet(Flags _flags) const
317 {
318 assert(_flags.noneSet(~PublicRead));
319 return flags.isSet(_flags);
320 }
321
322 void
323 setFlags(Flags _flags)
324 {
325 assert(_flags.noneSet(~PublicWrite));
326 flags.set(_flags);
327 }
328
329 void
330 clearFlags(Flags _flags)
331 {
332 assert(_flags.noneSet(~PublicWrite));
333 flags.clear(_flags);
334 }
335
336 void
337 clearFlags()
338 {
339 flags.clear(PublicWrite);
340 }
341
342 /**
343 * This function isn't really useful if TRACING_ON is not defined
344 *
345 * @ingroup api_eventq
346 */
347 virtual void trace(const char *action); //!< trace event activity
348
349 /// Return the instance number as a string.
350 const std::string instanceString() const;
351
352 protected: /* Memory management */
353 /**
354 * @{
355 * Memory management hooks for events that have the Managed flag set
356 *
357 * Events can use automatic memory management by setting the
358 * Managed flag. The default implementation automatically deletes
359 * events once they have been removed from the event queue. This
360 * typically happens when events are descheduled or have been
361 * triggered and not rescheduled.
362 *
363 * The methods below may be overridden by events that need custom
364 * memory management. For example, events exported to Python need
365 * to impement reference counting to ensure that the Python
366 * implementation of the event is kept alive while it lives in the
367 * event queue.
368 *
369 * @note Memory managers are responsible for implementing
370 * reference counting (by overriding both acquireImpl() and
371 * releaseImpl()) or checking if an event is no longer scheduled
372 * in releaseImpl() before deallocating it.
373 */
374
375 /**
376 * Managed event scheduled and being held in the event queue.
377 */
378 void acquire()
379 {
380 if (flags.isSet(Event::Managed))
381 acquireImpl();
382 }
383
384 /**
385 * Managed event removed from the event queue.
386 */
387 void release() {
388 if (flags.isSet(Event::Managed))
389 releaseImpl();
390 }
391
392 virtual void acquireImpl() {}
393
394 virtual void releaseImpl() {
395 if (!scheduled())
396 delete this;
397 }
398
399 /** @} */
400
401 public:
402
403 /*
404 * Event constructor
405 * @param queue that the event gets scheduled on
406 *
407 * @ingroup api_eventq
408 */
409 Event(Priority p = Default_Pri, Flags f = 0)
410 : nextBin(nullptr), nextInBin(nullptr), _when(0), _priority(p),
411 flags(Initialized | f)
412 {
413 assert(f.noneSet(~PublicWrite));
414 #ifndef NDEBUG
415 instance = ++instanceCounter;
416 queue = NULL;
417 #endif
418 #ifdef EVENTQ_DEBUG
419 whenCreated = curTick();
420 whenScheduled = 0;
421 #endif
422 }
423
424 /**
425 * @ingroup api_eventq
426 * @{
427 */
428 virtual ~Event();
429 virtual const std::string name() const;
430
431 /// Return a C string describing the event. This string should
432 /// *not* be dynamically allocated; just a const char array
433 /// describing the event class.
434 virtual const char *description() const;
435
436 /// Dump the current event data
437 void dump() const;
438 /** @}*/ //end of api group
439
440 public:
441 /*
442 * This member function is invoked when the event is processed
443 * (occurs). There is no default implementation; each subclass
444 * must provide its own implementation. The event is not
445 * automatically deleted after it is processed (to allow for
446 * statically allocated event objects).
447 *
448 * If the AutoDestroy flag is set, the object is deleted once it
449 * is processed.
450 *
451 * @ingroup api_eventq
452 */
453 virtual void process() = 0;
454
455 /**
456 * Determine if the current event is scheduled
457 *
458 * @ingroup api_eventq
459 */
460 bool scheduled() const { return flags.isSet(Scheduled); }
461
462 /**
463 * Squash the current event
464 *
465 * @ingroup api_eventq
466 */
467 void squash() { flags.set(Squashed); }
468
469 /**
470 * Check whether the event is squashed
471 *
472 * @ingroup api_eventq
473 */
474 bool squashed() const { return flags.isSet(Squashed); }
475
476 /**
477 * See if this is a SimExitEvent (without resorting to RTTI)
478 *
479 * @ingroup api_eventq
480 */
481 bool isExitEvent() const { return flags.isSet(IsExitEvent); }
482
483 /**
484 * Check whether this event will auto-delete
485 *
486 * @ingroup api_eventq
487 */
488 bool isManaged() const { return flags.isSet(Managed); }
489
490 /**
491 * @ingroup api_eventq
492 */
493 bool isAutoDelete() const { return isManaged(); }
494
495 /**
496 * Get the time that the event is scheduled
497 *
498 * @ingroup api_eventq
499 */
500 Tick when() const { return _when; }
501
502 /**
503 * Get the event priority
504 *
505 * @ingroup api_eventq
506 */
507 Priority priority() const { return _priority; }
508
509 //! If this is part of a GlobalEvent, return the pointer to the
510 //! Global Event. By default, there is no GlobalEvent, so return
511 //! NULL. (Overridden in GlobalEvent::BarrierEvent.)
512 virtual BaseGlobalEvent *globalEvent() { return NULL; }
513
514 void serialize(CheckpointOut &cp) const override;
515 void unserialize(CheckpointIn &cp) override;
516 };
517
518 /**
519 * @ingroup api_eventq
520 */
521 inline bool
522 operator<(const Event &l, const Event &r)
523 {
524 return l.when() < r.when() ||
525 (l.when() == r.when() && l.priority() < r.priority());
526 }
527
528 /**
529 * @ingroup api_eventq
530 */
531 inline bool
532 operator>(const Event &l, const Event &r)
533 {
534 return l.when() > r.when() ||
535 (l.when() == r.when() && l.priority() > r.priority());
536 }
537
538 /**
539 * @ingroup api_eventq
540 */
541 inline bool
542 operator<=(const Event &l, const Event &r)
543 {
544 return l.when() < r.when() ||
545 (l.when() == r.when() && l.priority() <= r.priority());
546 }
547
548 /**
549 * @ingroup api_eventq
550 */
551 inline bool
552 operator>=(const Event &l, const Event &r)
553 {
554 return l.when() > r.when() ||
555 (l.when() == r.when() && l.priority() >= r.priority());
556 }
557
558 /**
559 * @ingroup api_eventq
560 */
561 inline bool
562 operator==(const Event &l, const Event &r)
563 {
564 return l.when() == r.when() && l.priority() == r.priority();
565 }
566
567 /**
568 * @ingroup api_eventq
569 */
570 inline bool
571 operator!=(const Event &l, const Event &r)
572 {
573 return l.when() != r.when() || l.priority() != r.priority();
574 }
575
576 /**
577 * Queue of events sorted in time order
578 *
579 * Events are scheduled (inserted into the event queue) using the
580 * schedule() method. This method either inserts a <i>synchronous</i>
581 * or <i>asynchronous</i> event.
582 *
583 * Synchronous events are scheduled using schedule() method with the
584 * argument 'global' set to false (default). This should only be done
585 * from a thread holding the event queue lock
586 * (EventQueue::service_mutex). The lock is always held when an event
587 * handler is called, it can therefore always insert events into its
588 * own event queue unless it voluntarily releases the lock.
589 *
590 * Events can be scheduled across thread (and event queue borders) by
591 * either scheduling asynchronous events or taking the target event
592 * queue's lock. However, the lock should <i>never</i> be taken
593 * directly since this is likely to cause deadlocks. Instead, code
594 * that needs to schedule events in other event queues should
595 * temporarily release its own queue and lock the new queue. This
596 * prevents deadlocks since a single thread never owns more than one
597 * event queue lock. This functionality is provided by the
598 * ScopedMigration helper class. Note that temporarily migrating
599 * between event queues can make the simulation non-deterministic, it
600 * should therefore be limited to cases where that can be tolerated
601 * (e.g., handling asynchronous IO or fast-forwarding in KVM).
602 *
603 * Asynchronous events can also be scheduled using the normal
604 * schedule() method with the 'global' parameter set to true. Unlike
605 * the previous queue migration strategy, this strategy is fully
606 * deterministic. This causes the event to be inserted in a separate
607 * queue of asynchronous events (async_queue), which is merged main
608 * event queue at the end of each simulation quantum (by calling the
609 * handleAsyncInsertions() method). Note that this implies that such
610 * events must happen at least one simulation quantum into the future,
611 * otherwise they risk being scheduled in the past by
612 * handleAsyncInsertions().
613 */
614 class EventQueue
615 {
616 private:
617 std::string objName;
618 Event *head;
619 Tick _curTick;
620
621 //! Mutex to protect async queue.
622 std::mutex async_queue_mutex;
623
624 //! List of events added by other threads to this event queue.
625 std::list<Event*> async_queue;
626
627 /**
628 * Lock protecting event handling.
629 *
630 * This lock is always taken when servicing events. It is assumed
631 * that the thread scheduling new events (not asynchronous events
632 * though) have taken this lock. This is normally done by
633 * serviceOne() since new events are typically scheduled as a
634 * response to an earlier event.
635 *
636 * This lock is intended to be used to temporarily steal an event
637 * queue to support inter-thread communication when some
638 * deterministic timing can be sacrificed for speed. For example,
639 * the KVM CPU can use this support to access devices running in a
640 * different thread.
641 *
642 * @see EventQueue::ScopedMigration.
643 * @see EventQueue::ScopedRelease
644 * @see EventQueue::lock()
645 * @see EventQueue::unlock()
646 */
647 std::mutex service_mutex;
648
649 //! Insert / remove event from the queue. Should only be called
650 //! by thread operating this queue.
651 void insert(Event *event);
652 void remove(Event *event);
653
654 //! Function for adding events to the async queue. The added events
655 //! are added to main event queue later. Threads, other than the
656 //! owning thread, should call this function instead of insert().
657 void asyncInsert(Event *event);
658
659 EventQueue(const EventQueue &);
660
661 public:
662 /**
663 * Temporarily migrate execution to a different event queue.
664 *
665 * An instance of this class temporarily migrates execution to a
666 * different event queue by releasing the current queue, locking
667 * the new queue, and updating curEventQueue(). This can, for
668 * example, be useful when performing IO across thread event
669 * queues when timing is not crucial (e.g., during fast
670 * forwarding).
671 *
672 * ScopedMigration does nothing if both eqs are the same
673 */
674 class ScopedMigration
675 {
676 public:
677 /**
678 * @ingroup api_eventq
679 */
680 ScopedMigration(EventQueue *_new_eq, bool _doMigrate = true)
681 :new_eq(*_new_eq), old_eq(*curEventQueue()),
682 doMigrate((&new_eq != &old_eq)&&_doMigrate)
683 {
684 if (doMigrate){
685 old_eq.unlock();
686 new_eq.lock();
687 curEventQueue(&new_eq);
688 }
689 }
690
691 ~ScopedMigration()
692 {
693 if (doMigrate){
694 new_eq.unlock();
695 old_eq.lock();
696 curEventQueue(&old_eq);
697 }
698 }
699
700 private:
701 EventQueue &new_eq;
702 EventQueue &old_eq;
703 bool doMigrate;
704 };
705
706 /**
707 * Temporarily release the event queue service lock.
708 *
709 * There are cases where it is desirable to temporarily release
710 * the event queue lock to prevent deadlocks. For example, when
711 * waiting on the global barrier, we need to release the lock to
712 * prevent deadlocks from happening when another thread tries to
713 * temporarily take over the event queue waiting on the barrier.
714 */
715 class ScopedRelease
716 {
717 public:
718 /**
719 * @group api_eventq
720 */
721 ScopedRelease(EventQueue *_eq)
722 : eq(*_eq)
723 {
724 eq.unlock();
725 }
726
727 ~ScopedRelease()
728 {
729 eq.lock();
730 }
731
732 private:
733 EventQueue &eq;
734 };
735
736 /**
737 * @ingroup api_eventq
738 */
739 EventQueue(const std::string &n);
740
741 /**
742 * @ingroup api_eventq
743 * @{
744 */
745 virtual const std::string name() const { return objName; }
746 void name(const std::string &st) { objName = st; }
747 /** @}*/ //end of api_eventq group
748
749 /**
750 * Schedule the given event on this queue. Safe to call from any thread.
751 *
752 * @ingroup api_eventq
753 */
754 void
755 schedule(Event *event, Tick when, bool global=false)
756 {
757 assert(when >= getCurTick());
758 assert(!event->scheduled());
759 assert(event->initialized());
760
761 event->setWhen(when, this);
762
763 // The check below is to make sure of two things
764 // a. A thread schedules local events on other queues through the
765 // asyncq.
766 // b. A thread schedules global events on the asyncq, whether or not
767 // this event belongs to this eventq. This is required to maintain
768 // a total order amongst the global events. See global_event.{cc,hh}
769 // for more explanation.
770 if (inParallelMode && (this != curEventQueue() || global)) {
771 asyncInsert(event);
772 } else {
773 insert(event);
774 }
775 event->flags.set(Event::Scheduled);
776 event->acquire();
777
778 if (DTRACE(Event))
779 event->trace("scheduled");
780 }
781
782 /**
783 * Deschedule the specified event. Should be called only from the owning
784 * thread.
785 * @ingroup api_eventq
786 */
787 void
788 deschedule(Event *event)
789 {
790 assert(event->scheduled());
791 assert(event->initialized());
792 assert(!inParallelMode || this == curEventQueue());
793
794 remove(event);
795
796 event->flags.clear(Event::Squashed);
797 event->flags.clear(Event::Scheduled);
798
799 if (DTRACE(Event))
800 event->trace("descheduled");
801
802 event->release();
803 }
804
805 /**
806 * Reschedule the specified event. Should be called only from the owning
807 * thread.
808 *
809 * @ingroup api_eventq
810 */
811 void
812 reschedule(Event *event, Tick when, bool always=false)
813 {
814 assert(when >= getCurTick());
815 assert(always || event->scheduled());
816 assert(event->initialized());
817 assert(!inParallelMode || this == curEventQueue());
818
819 if (event->scheduled()) {
820 remove(event);
821 } else {
822 event->acquire();
823 }
824
825 event->setWhen(when, this);
826 insert(event);
827 event->flags.clear(Event::Squashed);
828 event->flags.set(Event::Scheduled);
829
830 if (DTRACE(Event))
831 event->trace("rescheduled");
832 }
833
834 Tick nextTick() const { return head->when(); }
835 void setCurTick(Tick newVal) { _curTick = newVal; }
836
837 /**
838 * While curTick() is useful for any object assigned to this event queue,
839 * if an object that is assigned to another event queue (or a non-event
840 * object) need to access the current tick of this event queue, this
841 * function is used.
842 *
843 * @return Tick The current tick of this event queue.
844 * @ingroup api_eventq
845 */
846 Tick getCurTick() const { return _curTick; }
847 Event *getHead() const { return head; }
848
849 Event *serviceOne();
850
851 /**
852 * process all events up to the given timestamp. we inline a quick test
853 * to see if there are any events to process; if so, call the internal
854 * out-of-line version to process them all.
855 *
856 * Notes:
857 * - This is only used for "instruction" event queues. Instead of counting
858 * ticks, this is actually counting instructions.
859 * - This updates the current tick value to the value of the entry at the
860 * head of the queue.
861 *
862 * @ingroup api_eventq
863 */
864 void
865 serviceEvents(Tick when)
866 {
867 while (!empty()) {
868 if (nextTick() > when)
869 break;
870
871 /**
872 * @todo this assert is a good bug catcher. I need to
873 * make it true again.
874 */
875 //assert(head->when() >= when && "event scheduled in the past");
876 serviceOne();
877 }
878
879 setCurTick(when);
880 }
881
882 /**
883 * Returns true if no events are queued
884 *
885 * @ingroup api_eventq
886 */
887 bool empty() const { return head == NULL; }
888
889 /**
890 * This is a debugging function which will print everything on the event
891 * queue.
892 *
893 * @ingroup api_eventq
894 */
895 void dump() const;
896
897 bool debugVerify() const;
898
899 /**
900 * Function for moving events from the async_queue to the main queue.
901 */
902 void handleAsyncInsertions();
903
904 /**
905 * Function to signal that the event loop should be woken up because
906 * an event has been scheduled by an agent outside the gem5 event
907 * loop(s) whose event insertion may not have been noticed by gem5.
908 * This function isn't needed by the usual gem5 event loop but may
909 * be necessary in derived EventQueues which host gem5 onto other
910 * schedulers.
911 *
912 * @param when Time of a delayed wakeup (if known). This parameter
913 * can be used by an implementation to schedule a wakeup in the
914 * future if it is sure it will remain active until then.
915 * Or it can be ignored and the event queue can be woken up now.
916 *
917 * @ingroup api_eventq
918 */
919 virtual void wakeup(Tick when = (Tick)-1) { }
920
921 /**
922 * function for replacing the head of the event queue, so that a
923 * different set of events can run without disturbing events that have
924 * already been scheduled. Already scheduled events can be processed
925 * by replacing the original head back.
926 * USING THIS FUNCTION CAN BE DANGEROUS TO THE HEALTH OF THE SIMULATOR.
927 * NOT RECOMMENDED FOR USE.
928 */
929 Event* replaceHead(Event* s);
930
931 /**@{*/
932 /**
933 * Provide an interface for locking/unlocking the event queue.
934 *
935 * @warn Do NOT use these methods directly unless you really know
936 * what you are doing. Incorrect use can easily lead to simulator
937 * deadlocks.
938 *
939 * @see EventQueue::ScopedMigration.
940 * @see EventQueue::ScopedRelease
941 * @see EventQueue
942 */
943 void lock() { service_mutex.lock(); }
944 void unlock() { service_mutex.unlock(); }
945 /**@}*/
946
947 /**
948 * Reschedule an event after a checkpoint.
949 *
950 * Since events don't know which event queue they belong to,
951 * parent objects need to reschedule events themselves. This
952 * method conditionally schedules an event that has the Scheduled
953 * flag set. It should be called by parent objects after
954 * unserializing an object.
955 *
956 * @warn Only use this method after unserializing an Event.
957 */
958 void checkpointReschedule(Event *event);
959
960 virtual ~EventQueue()
961 {
962 while (!empty())
963 deschedule(getHead());
964 }
965 };
966
967 void dumpMainQueue();
968
969 class EventManager
970 {
971 protected:
972 /** A pointer to this object's event queue */
973 EventQueue *eventq;
974
975 public:
976 /**
977 * @ingroup api_eventq
978 * @{
979 */
980 EventManager(EventManager &em) : eventq(em.eventq) {}
981 EventManager(EventManager *em) : eventq(em->eventq) {}
982 EventManager(EventQueue *eq) : eventq(eq) {}
983 /** @}*/ //end of api_eventq group
984
985 /**
986 * @ingroup api_eventq
987 */
988 EventQueue *
989 eventQueue() const
990 {
991 return eventq;
992 }
993
994 /**
995 * @ingroup api_eventq
996 */
997 void
998 schedule(Event &event, Tick when)
999 {
1000 eventq->schedule(&event, when);
1001 }
1002
1003 /**
1004 * @ingroup api_eventq
1005 */
1006 void
1007 deschedule(Event &event)
1008 {
1009 eventq->deschedule(&event);
1010 }
1011
1012 /**
1013 * @ingroup api_eventq
1014 */
1015 void
1016 reschedule(Event &event, Tick when, bool always = false)
1017 {
1018 eventq->reschedule(&event, when, always);
1019 }
1020
1021 /**
1022 * @ingroup api_eventq
1023 */
1024 void
1025 schedule(Event *event, Tick when)
1026 {
1027 eventq->schedule(event, when);
1028 }
1029
1030 /**
1031 * @ingroup api_eventq
1032 */
1033 void
1034 deschedule(Event *event)
1035 {
1036 eventq->deschedule(event);
1037 }
1038
1039 /**
1040 * @ingroup api_eventq
1041 */
1042 void
1043 reschedule(Event *event, Tick when, bool always = false)
1044 {
1045 eventq->reschedule(event, when, always);
1046 }
1047
1048 /**
1049 * @ingroup api_eventq
1050 */
1051 void wakeupEventQueue(Tick when = (Tick)-1)
1052 {
1053 eventq->wakeup(when);
1054 }
1055
1056 void setCurTick(Tick newVal) { eventq->setCurTick(newVal); }
1057 };
1058
1059 template <class T, void (T::* F)()>
1060 class EventWrapper : public Event
1061 {
1062 private:
1063 T *object;
1064
1065 public:
1066 EventWrapper(T *obj, bool del = false, Priority p = Default_Pri)
1067 : Event(p), object(obj)
1068 {
1069 if (del)
1070 setFlags(AutoDelete);
1071 }
1072
1073 EventWrapper(T &obj, bool del = false, Priority p = Default_Pri)
1074 : Event(p), object(&obj)
1075 {
1076 if (del)
1077 setFlags(AutoDelete);
1078 }
1079
1080 void process() { (object->*F)(); }
1081
1082 const std::string
1083 name() const
1084 {
1085 return object->name() + ".wrapped_event";
1086 }
1087
1088 const char *description() const { return "EventWrapped"; }
1089 };
1090
1091 class EventFunctionWrapper : public Event
1092 {
1093 private:
1094 std::function<void(void)> callback;
1095 std::string _name;
1096
1097 public:
1098 /**
1099 * @ingroup api_eventq
1100 */
1101 EventFunctionWrapper(const std::function<void(void)> &callback,
1102 const std::string &name,
1103 bool del = false,
1104 Priority p = Default_Pri)
1105 : Event(p), callback(callback), _name(name)
1106 {
1107 if (del)
1108 setFlags(AutoDelete);
1109 }
1110
1111 /**
1112 * @ingroup api_eventq
1113 */
1114 void process() { callback(); }
1115
1116 /**
1117 * @ingroup api_eventq
1118 */
1119 const std::string
1120 name() const
1121 {
1122 return _name + ".wrapped_function_event";
1123 }
1124
1125 /**
1126 * @ingroup api_eventq
1127 */
1128 const char *description() const { return "EventFunctionWrapped"; }
1129 };
1130
1131 #endif // __SIM_EVENTQ_HH__