eventq.cc revision 10906
1/*
2 * Copyright (c) 2000-2005 The Regents of The University of Michigan
3 * Copyright (c) 2008 The Hewlett-Packard Development Company
4 * Copyright (c) 2013 Advanced Micro Devices, Inc.
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 * Authors: Steve Reinhardt
31 *          Nathan Binkert
32 *          Steve Raasch
33 */
34
35#include <cassert>
36#include <iostream>
37#include <string>
38#include <vector>
39
40#include "base/hashmap.hh"
41#include "base/misc.hh"
42#include "base/trace.hh"
43#include "cpu/smt.hh"
44#include "debug/Checkpoint.hh"
45#include "sim/core.hh"
46#include "sim/eventq_impl.hh"
47
48using namespace std;
49
50Tick simQuantum = 0;
51
52//
53// Main Event Queues
54//
55// Events on these queues are processed at the *beginning* of each
56// cycle, before the pipeline simulation is performed.
57//
58uint32_t numMainEventQueues = 0;
59vector<EventQueue *> mainEventQueue;
60__thread EventQueue *_curEventQueue = NULL;
61bool inParallelMode = false;
62
63EventQueue *
64getEventQueue(uint32_t index)
65{
66    while (numMainEventQueues <= index) {
67        numMainEventQueues++;
68        mainEventQueue.push_back(
69            new EventQueue(csprintf("MainEventQueue-%d", index)));
70    }
71
72    return mainEventQueue[index];
73}
74
75#ifndef NDEBUG
76Counter Event::instanceCounter = 0;
77#endif
78
79Event::~Event()
80{
81    assert(!scheduled());
82    flags = 0;
83}
84
85const std::string
86Event::name() const
87{
88#ifndef NDEBUG
89    return csprintf("Event_%d", instance);
90#else
91    return csprintf("Event_%x", (uintptr_t)this);
92#endif
93}
94
95
96Event *
97Event::insertBefore(Event *event, Event *curr)
98{
99    // Either way, event will be the top element in the 'in bin' list
100    // which is the pointer we need in order to look into the list, so
101    // we need to insert that into the bin list.
102    if (!curr || *event < *curr) {
103        // Insert the event before the current list since it is in the future.
104        event->nextBin = curr;
105        event->nextInBin = NULL;
106    } else {
107        // Since we're on the correct list, we need to point to the next list
108        event->nextBin = curr->nextBin;  // curr->nextBin can now become stale
109
110        // Insert event at the top of the stack
111        event->nextInBin = curr;
112    }
113
114    return event;
115}
116
117void
118EventQueue::insert(Event *event)
119{
120    // Deal with the head case
121    if (!head || *event <= *head) {
122        head = Event::insertBefore(event, head);
123        return;
124    }
125
126    // Figure out either which 'in bin' list we are on, or where a new list
127    // needs to be inserted
128    Event *prev = head;
129    Event *curr = head->nextBin;
130    while (curr && *curr < *event) {
131        prev = curr;
132        curr = curr->nextBin;
133    }
134
135    // Note: this operation may render all nextBin pointers on the
136    // prev 'in bin' list stale (except for the top one)
137    prev->nextBin = Event::insertBefore(event, curr);
138}
139
140Event *
141Event::removeItem(Event *event, Event *top)
142{
143    Event *curr = top;
144    Event *next = top->nextInBin;
145
146    // if we removed the top item, we need to handle things specially
147    // and just remove the top item, fixing up the next bin pointer of
148    // the new top item
149    if (event == top) {
150        if (!next)
151            return top->nextBin;
152        next->nextBin = top->nextBin;
153        return next;
154    }
155
156    // Since we already checked the current element, we're going to
157    // keep checking event against the next element.
158    while (event != next) {
159        if (!next)
160            panic("event not found!");
161
162        curr = next;
163        next = next->nextInBin;
164    }
165
166    // remove next from the 'in bin' list since it's what we're looking for
167    curr->nextInBin = next->nextInBin;
168    return top;
169}
170
171void
172EventQueue::remove(Event *event)
173{
174    if (head == NULL)
175        panic("event not found!");
176
177    assert(event->queue == this);
178
179    // deal with an event on the head's 'in bin' list (event has the same
180    // time as the head)
181    if (*head == *event) {
182        head = Event::removeItem(event, head);
183        return;
184    }
185
186    // Find the 'in bin' list that this event belongs on
187    Event *prev = head;
188    Event *curr = head->nextBin;
189    while (curr && *curr < *event) {
190        prev = curr;
191        curr = curr->nextBin;
192    }
193
194    if (!curr || *curr != *event)
195        panic("event not found!");
196
197    // curr points to the top item of the the correct 'in bin' list, when
198    // we remove an item, it returns the new top item (which may be
199    // unchanged)
200    prev->nextBin = Event::removeItem(event, curr);
201}
202
203Event *
204EventQueue::serviceOne()
205{
206    std::lock_guard<EventQueue> lock(*this);
207    Event *event = head;
208    Event *next = head->nextInBin;
209    event->flags.clear(Event::Scheduled);
210
211    if (next) {
212        // update the next bin pointer since it could be stale
213        next->nextBin = head->nextBin;
214
215        // pop the stack
216        head = next;
217    } else {
218        // this was the only element on the 'in bin' list, so get rid of
219        // the 'in bin' list and point to the next bin list
220        head = head->nextBin;
221    }
222
223    // handle action
224    if (!event->squashed()) {
225        // forward current cycle to the time when this event occurs.
226        setCurTick(event->when());
227
228        event->process();
229        if (event->isExitEvent()) {
230            assert(!event->flags.isSet(Event::AutoDelete) ||
231                   !event->flags.isSet(Event::IsMainQueue)); // would be silly
232            return event;
233        }
234    } else {
235        event->flags.clear(Event::Squashed);
236    }
237
238    if (event->flags.isSet(Event::AutoDelete) && !event->scheduled())
239        delete event;
240
241    return NULL;
242}
243
244void
245Event::serialize(CheckpointOut &cp) const
246{
247    SERIALIZE_SCALAR(_when);
248    SERIALIZE_SCALAR(_priority);
249    short _flags = flags;
250    SERIALIZE_SCALAR(_flags);
251}
252
253void
254Event::unserialize(CheckpointIn &cp)
255{
256    assert(!scheduled());
257
258    UNSERIALIZE_SCALAR(_when);
259    UNSERIALIZE_SCALAR(_priority);
260
261    FlagsType _flags;
262    UNSERIALIZE_SCALAR(_flags);
263
264    // Old checkpoints had no concept of the Initialized flag
265    // so restoring from old checkpoints always fail.
266    // Events are initialized on construction but original code
267    // "flags = _flags" would just overwrite the initialization.
268    // So, read in the checkpoint flags, but then set the Initialized
269    // flag on top of it in order to avoid failures.
270    assert(initialized());
271    flags = _flags;
272    flags.set(Initialized);
273
274    // need to see if original event was in a scheduled, unsquashed
275    // state, but don't want to restore those flags in the current
276    // object itself (since they aren't immediately true)
277    if (flags.isSet(Scheduled) && !flags.isSet(Squashed)) {
278        flags.clear(Squashed | Scheduled);
279    } else {
280        DPRINTF(Checkpoint, "Event '%s' need to be scheduled @%d\n",
281                name(), _when);
282    }
283}
284
285void
286EventQueue::serialize(CheckpointOut &cp) const
287{
288    std::list<Event *> eventPtrs;
289
290    int numEvents = 0;
291    Event *nextBin = head;
292    while (nextBin) {
293        Event *nextInBin = nextBin;
294
295        while (nextInBin) {
296            if (nextInBin->flags.isSet(Event::AutoSerialize)) {
297                eventPtrs.push_back(nextInBin);
298                paramOut(cp, csprintf("event%d", numEvents++),
299                         nextInBin->name());
300            }
301            nextInBin = nextInBin->nextInBin;
302        }
303
304        nextBin = nextBin->nextBin;
305    }
306
307    SERIALIZE_SCALAR(numEvents);
308
309    for (Event *ev : eventPtrs)
310        ev->serializeSection(cp, ev->name());
311}
312
313void
314EventQueue::unserialize(CheckpointIn &cp)
315{
316    int numEvents;
317    UNSERIALIZE_SCALAR(numEvents);
318
319    std::string eventName;
320    for (int i = 0; i < numEvents; i++) {
321        // get the pointer value associated with the event
322        paramIn(cp, csprintf("event%d", i), eventName);
323
324        // create the event based on its pointer value
325        Serializable *obj(Serializable::create(cp, eventName));
326        Event *event(dynamic_cast<Event *>(obj));
327        fatal_if(!event,
328                 "Event queue unserialized something that wasn't an event.\n");
329
330        checkpointReschedule(event);
331    }
332}
333
334void
335EventQueue::checkpointReschedule(Event *event)
336{
337    // It's safe to call insert() directly here since this method
338    // should only be called when restoring from a checkpoint (which
339    // happens before thread creation).
340    if (event->flags.isSet(Event::Scheduled))
341        insert(event);
342}
343void
344EventQueue::dump() const
345{
346    cprintf("============================================================\n");
347    cprintf("EventQueue Dump  (cycle %d)\n", curTick());
348    cprintf("------------------------------------------------------------\n");
349
350    if (empty())
351        cprintf("<No Events>\n");
352    else {
353        Event *nextBin = head;
354        while (nextBin) {
355            Event *nextInBin = nextBin;
356            while (nextInBin) {
357                nextInBin->dump();
358                nextInBin = nextInBin->nextInBin;
359            }
360
361            nextBin = nextBin->nextBin;
362        }
363    }
364
365    cprintf("============================================================\n");
366}
367
368bool
369EventQueue::debugVerify() const
370{
371    m5::hash_map<long, bool> map;
372
373    Tick time = 0;
374    short priority = 0;
375
376    Event *nextBin = head;
377    while (nextBin) {
378        Event *nextInBin = nextBin;
379        while (nextInBin) {
380            if (nextInBin->when() < time) {
381                cprintf("time goes backwards!");
382                nextInBin->dump();
383                return false;
384            } else if (nextInBin->when() == time &&
385                       nextInBin->priority() < priority) {
386                cprintf("priority inverted!");
387                nextInBin->dump();
388                return false;
389            }
390
391            if (map[reinterpret_cast<long>(nextInBin)]) {
392                cprintf("Node already seen");
393                nextInBin->dump();
394                return false;
395            }
396            map[reinterpret_cast<long>(nextInBin)] = true;
397
398            time = nextInBin->when();
399            priority = nextInBin->priority();
400
401            nextInBin = nextInBin->nextInBin;
402        }
403
404        nextBin = nextBin->nextBin;
405    }
406
407    return true;
408}
409
410Event*
411EventQueue::replaceHead(Event* s)
412{
413    Event* t = head;
414    head = s;
415    return t;
416}
417
418void
419dumpMainQueue()
420{
421    for (uint32_t i = 0; i < numMainEventQueues; ++i) {
422        mainEventQueue[i]->dump();
423    }
424}
425
426
427const char *
428Event::description() const
429{
430    return "generic";
431}
432
433void
434Event::trace(const char *action)
435{
436    // This DPRINTF is unconditional because calls to this function
437    // are protected by an 'if (DTRACE(Event))' in the inlined Event
438    // methods.
439    //
440    // This is just a default implementation for derived classes where
441    // it's not worth doing anything special.  If you want to put a
442    // more informative message in the trace, override this method on
443    // the particular subclass where you have the information that
444    // needs to be printed.
445    DPRINTFN("%s event %s @ %d\n", description(), action, when());
446}
447
448void
449Event::dump() const
450{
451    cprintf("Event %s (%s)\n", name(), description());
452    cprintf("Flags: %#x\n", flags);
453#ifdef EVENTQ_DEBUG
454    cprintf("Created: %d\n", whenCreated);
455#endif
456    if (scheduled()) {
457#ifdef EVENTQ_DEBUG
458        cprintf("Scheduled at  %d\n", whenScheduled);
459#endif
460        cprintf("Scheduled for %d, priority %d\n", when(), _priority);
461    } else {
462        cprintf("Not Scheduled\n");
463    }
464}
465
466EventQueue::EventQueue(const string &n)
467    : objName(n), head(NULL), _curTick(0)
468{
469}
470
471void
472EventQueue::asyncInsert(Event *event)
473{
474    async_queue_mutex.lock();
475    async_queue.push_back(event);
476    async_queue_mutex.unlock();
477}
478
479void
480EventQueue::handleAsyncInsertions()
481{
482    assert(this == curEventQueue());
483    async_queue_mutex.lock();
484
485    while (!async_queue.empty()) {
486        insert(async_queue.front());
487        async_queue.pop_front();
488    }
489
490    async_queue_mutex.unlock();
491}
492