eventq.cc revision 9356
1/*
2 * Copyright (c) 2000-2005 The Regents of The University of Michigan
3 * Copyright (c) 2008 The Hewlett-Packard Development Company
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are
8 * met: redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer;
10 * redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution;
13 * neither the name of the copyright holders nor the names of its
14 * contributors may be used to endorse or promote products derived from
15 * this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 *
29 * Authors: Steve Reinhardt
30 *          Nathan Binkert
31 *          Steve Raasch
32 */
33
34#include <cassert>
35#include <iostream>
36#include <string>
37#include <vector>
38
39#include "base/hashmap.hh"
40#include "base/misc.hh"
41#include "base/trace.hh"
42#include "cpu/smt.hh"
43#include "debug/Config.hh"
44#include "sim/core.hh"
45#include "sim/eventq_impl.hh"
46
47using namespace std;
48
49//
50// Main Event Queue
51//
52// Events on this queue are processed at the *beginning* of each
53// cycle, before the pipeline simulation is performed.
54//
55EventQueue mainEventQueue("Main Event Queue");
56
57#ifndef NDEBUG
58Counter Event::instanceCounter = 0;
59#endif
60
61Event::~Event()
62{
63    assert(!scheduled());
64    flags = 0;
65}
66
67const std::string
68Event::name() const
69{
70#ifndef NDEBUG
71    return csprintf("Event_%d", instance);
72#else
73    return csprintf("Event_%x", (uintptr_t)this);
74#endif
75}
76
77
78Event *
79Event::insertBefore(Event *event, Event *curr)
80{
81    // Either way, event will be the top element in the 'in bin' list
82    // which is the pointer we need in order to look into the list, so
83    // we need to insert that into the bin list.
84    if (!curr || *event < *curr) {
85        // Insert the event before the current list since it is in the future.
86        event->nextBin = curr;
87        event->nextInBin = NULL;
88    } else {
89        // Since we're on the correct list, we need to point to the next list
90        event->nextBin = curr->nextBin;  // curr->nextBin can now become stale
91
92        // Insert event at the top of the stack
93        event->nextInBin = curr;
94    }
95
96    return event;
97}
98
99void
100EventQueue::insert(Event *event)
101{
102    // Deal with the head case
103    if (!head || *event <= *head) {
104        head = Event::insertBefore(event, head);
105        return;
106    }
107
108    // Figure out either which 'in bin' list we are on, or where a new list
109    // needs to be inserted
110    Event *prev = head;
111    Event *curr = head->nextBin;
112    while (curr && *curr < *event) {
113        prev = curr;
114        curr = curr->nextBin;
115    }
116
117    // Note: this operation may render all nextBin pointers on the
118    // prev 'in bin' list stale (except for the top one)
119    prev->nextBin = Event::insertBefore(event, curr);
120}
121
122Event *
123Event::removeItem(Event *event, Event *top)
124{
125    Event *curr = top;
126    Event *next = top->nextInBin;
127
128    // if we removed the top item, we need to handle things specially
129    // and just remove the top item, fixing up the next bin pointer of
130    // the new top item
131    if (event == top) {
132        if (!next)
133            return top->nextBin;
134        next->nextBin = top->nextBin;
135        return next;
136    }
137
138    // Since we already checked the current element, we're going to
139    // keep checking event against the next element.
140    while (event != next) {
141        if (!next)
142            panic("event not found!");
143
144        curr = next;
145        next = next->nextInBin;
146    }
147
148    // remove next from the 'in bin' list since it's what we're looking for
149    curr->nextInBin = next->nextInBin;
150    return top;
151}
152
153void
154EventQueue::remove(Event *event)
155{
156    if (head == NULL)
157        panic("event not found!");
158
159    // deal with an event on the head's 'in bin' list (event has the same
160    // time as the head)
161    if (*head == *event) {
162        head = Event::removeItem(event, head);
163        return;
164    }
165
166    // Find the 'in bin' list that this event belongs on
167    Event *prev = head;
168    Event *curr = head->nextBin;
169    while (curr && *curr < *event) {
170        prev = curr;
171        curr = curr->nextBin;
172    }
173
174    if (!curr || *curr != *event)
175        panic("event not found!");
176
177    // curr points to the top item of the the correct 'in bin' list, when
178    // we remove an item, it returns the new top item (which may be
179    // unchanged)
180    prev->nextBin = Event::removeItem(event, curr);
181}
182
183Event *
184EventQueue::serviceOne()
185{
186    Event *event = head;
187    Event *next = head->nextInBin;
188    event->flags.clear(Event::Scheduled);
189
190    if (next) {
191        // update the next bin pointer since it could be stale
192        next->nextBin = head->nextBin;
193
194        // pop the stack
195        head = next;
196    } else {
197        // this was the only element on the 'in bin' list, so get rid of
198        // the 'in bin' list and point to the next bin list
199        head = head->nextBin;
200    }
201
202    // handle action
203    if (!event->squashed()) {
204        // forward current cycle to the time when this event occurs.
205        setCurTick(event->when());
206
207        event->process();
208        if (event->isExitEvent()) {
209            assert(!event->flags.isSet(Event::AutoDelete) ||
210                   !event->flags.isSet(Event::IsMainQueue)); // would be silly
211            return event;
212        }
213    } else {
214        event->flags.clear(Event::Squashed);
215    }
216
217    if (event->flags.isSet(Event::AutoDelete) && !event->scheduled())
218        delete event;
219
220    return NULL;
221}
222
223void
224Event::serialize(std::ostream &os)
225{
226    SERIALIZE_SCALAR(_when);
227    SERIALIZE_SCALAR(_priority);
228    short _flags = flags;
229    SERIALIZE_SCALAR(_flags);
230}
231
232void
233Event::unserialize(Checkpoint *cp, const string &section)
234{
235    if (scheduled())
236        mainEventQueue.deschedule(this);
237
238    UNSERIALIZE_SCALAR(_when);
239    UNSERIALIZE_SCALAR(_priority);
240
241    short _flags;
242    UNSERIALIZE_SCALAR(_flags);
243
244    // Old checkpoints had no concept of the Initialized flag
245    // so restoring from old checkpoints always fail.
246    // Events are initialized on construction but original code
247    // "flags = _flags" would just overwrite the initialization.
248    // So, read in the checkpoint flags, but then set the Initialized
249    // flag on top of it in order to avoid failures.
250    assert(initialized());
251    flags = _flags;
252    flags.set(Initialized);
253
254    // need to see if original event was in a scheduled, unsquashed
255    // state, but don't want to restore those flags in the current
256    // object itself (since they aren't immediately true)
257    bool wasScheduled = flags.isSet(Scheduled) && !flags.isSet(Squashed);
258    flags.clear(Squashed | Scheduled);
259
260    if (wasScheduled) {
261        DPRINTF(Config, "rescheduling at %d\n", _when);
262        mainEventQueue.schedule(this, _when);
263    }
264}
265
266void
267EventQueue::serialize(ostream &os)
268{
269    std::list<Event *> eventPtrs;
270
271    int numEvents = 0;
272    Event *nextBin = head;
273    while (nextBin) {
274        Event *nextInBin = nextBin;
275
276        while (nextInBin) {
277            if (nextInBin->flags.isSet(Event::AutoSerialize)) {
278                eventPtrs.push_back(nextInBin);
279                paramOut(os, csprintf("event%d", numEvents++),
280                         nextInBin->name());
281            }
282            nextInBin = nextInBin->nextInBin;
283        }
284
285        nextBin = nextBin->nextBin;
286    }
287
288    SERIALIZE_SCALAR(numEvents);
289
290    for (std::list<Event *>::iterator it = eventPtrs.begin();
291         it != eventPtrs.end(); ++it) {
292        (*it)->nameOut(os);
293        (*it)->serialize(os);
294    }
295}
296
297void
298EventQueue::unserialize(Checkpoint *cp, const std::string &section)
299{
300    int numEvents;
301    UNSERIALIZE_SCALAR(numEvents);
302
303    std::string eventName;
304    for (int i = 0; i < numEvents; i++) {
305        // get the pointer value associated with the event
306        paramIn(cp, section, csprintf("event%d", i), eventName);
307
308        // create the event based on its pointer value
309        Serializable::create(cp, eventName);
310    }
311}
312
313void
314EventQueue::dump() const
315{
316    cprintf("============================================================\n");
317    cprintf("EventQueue Dump  (cycle %d)\n", curTick());
318    cprintf("------------------------------------------------------------\n");
319
320    if (empty())
321        cprintf("<No Events>\n");
322    else {
323        Event *nextBin = head;
324        while (nextBin) {
325            Event *nextInBin = nextBin;
326            while (nextInBin) {
327                nextInBin->dump();
328                nextInBin = nextInBin->nextInBin;
329            }
330
331            nextBin = nextBin->nextBin;
332        }
333    }
334
335    cprintf("============================================================\n");
336}
337
338bool
339EventQueue::debugVerify() const
340{
341    m5::hash_map<long, bool> map;
342
343    Tick time = 0;
344    short priority = 0;
345
346    Event *nextBin = head;
347    while (nextBin) {
348        Event *nextInBin = nextBin;
349        while (nextInBin) {
350            if (nextInBin->when() < time) {
351                cprintf("time goes backwards!");
352                nextInBin->dump();
353                return false;
354            } else if (nextInBin->when() == time &&
355                       nextInBin->priority() < priority) {
356                cprintf("priority inverted!");
357                nextInBin->dump();
358                return false;
359            }
360
361            if (map[reinterpret_cast<long>(nextInBin)]) {
362                cprintf("Node already seen");
363                nextInBin->dump();
364                return false;
365            }
366            map[reinterpret_cast<long>(nextInBin)] = true;
367
368            time = nextInBin->when();
369            priority = nextInBin->priority();
370
371            nextInBin = nextInBin->nextInBin;
372        }
373
374        nextBin = nextBin->nextBin;
375    }
376
377    return true;
378}
379
380Event*
381EventQueue::replaceHead(Event* s)
382{
383    Event* t = head;
384    head = s;
385    return t;
386}
387
388void
389dumpMainQueue()
390{
391    mainEventQueue.dump();
392}
393
394
395const char *
396Event::description() const
397{
398    return "generic";
399}
400
401void
402Event::trace(const char *action)
403{
404    // This DPRINTF is unconditional because calls to this function
405    // are protected by an 'if (DTRACE(Event))' in the inlined Event
406    // methods.
407    //
408    // This is just a default implementation for derived classes where
409    // it's not worth doing anything special.  If you want to put a
410    // more informative message in the trace, override this method on
411    // the particular subclass where you have the information that
412    // needs to be printed.
413    DPRINTFN("%s event %s @ %d\n", description(), action, when());
414}
415
416void
417Event::dump() const
418{
419    cprintf("Event %s (%s)\n", name(), description());
420    cprintf("Flags: %#x\n", flags);
421#ifdef EVENTQ_DEBUG
422    cprintf("Created: %d\n", whenCreated);
423#endif
424    if (scheduled()) {
425#ifdef EVENTQ_DEBUG
426        cprintf("Scheduled at  %d\n", whenScheduled);
427#endif
428        cprintf("Scheduled for %d, priority %d\n", when(), _priority);
429    } else {
430        cprintf("Not Scheduled\n");
431    }
432}
433
434EventQueue::EventQueue(const string &n)
435    : objName(n), head(NULL), _curTick(0)
436{}
437