noncoherent_xbar.cc revision 8948
1/*
2 * Copyright (c) 2011-2012 ARM Limited
3 * All rights reserved
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder.  You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Copyright (c) 2006 The Regents of The University of Michigan
15 * All rights reserved.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions are
19 * met: redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer;
21 * redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution;
24 * neither the name of the copyright holders nor the names of its
25 * contributors may be used to endorse or promote products derived from
26 * this software without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 *
40 * Authors: Ali Saidi
41 *          Andreas Hansson
42 *          William Wang
43 */
44
45/**
46 * @file
47 * Definition of a bus object.
48 */
49
50#include "base/misc.hh"
51#include "base/trace.hh"
52#include "debug/Bus.hh"
53#include "debug/BusAddrRanges.hh"
54#include "mem/bus.hh"
55
56Bus::Bus(const BusParams *p)
57    : MemObject(p), clock(p->clock),
58      headerCycles(p->header_cycles), width(p->width), tickNextIdle(0),
59      drainEvent(NULL), busIdleEvent(this), inRetry(false),
60      defaultPortId(INVALID_PORT_ID), useDefaultRange(p->use_default_range),
61      defaultBlockSize(p->block_size),
62      cachedBlockSize(0), cachedBlockSizeValid(false)
63{
64    //width, clock period, and header cycles must be positive
65    if (width <= 0)
66        fatal("Bus width must be positive\n");
67    if (clock <= 0)
68        fatal("Bus clock period must be positive\n");
69    if (headerCycles <= 0)
70        fatal("Number of header cycles must be positive\n");
71
72    // create the ports based on the size of the master and slave
73    // vector ports, and the presence of the default port, the ports
74    // are enumerated starting from zero
75    for (int i = 0; i < p->port_master_connection_count; ++i) {
76        std::string portName = csprintf("%s-p%d", name(), i);
77        BusMasterPort* bp = new BusMasterPort(portName, this, i);
78        masterPorts.push_back(bp);
79    }
80
81    // see if we have a default slave device connected and if so add
82    // our corresponding master port
83    if (p->port_default_connection_count) {
84        defaultPortId = masterPorts.size();
85        std::string portName = csprintf("%s-default", name());
86        BusMasterPort* bp = new BusMasterPort(portName, this, defaultPortId);
87        masterPorts.push_back(bp);
88    }
89
90    // create the slave ports, once again starting at zero
91    for (int i = 0; i < p->port_slave_connection_count; ++i) {
92        std::string portName = csprintf("%s-p%d", name(), i);
93        BusSlavePort* bp = new BusSlavePort(portName, this, i);
94        slavePorts.push_back(bp);
95    }
96
97    clearPortCache();
98}
99
100MasterPort &
101Bus::getMasterPort(const std::string &if_name, int idx)
102{
103    if (if_name == "master" && idx < masterPorts.size()) {
104        // the master port index translates directly to the vector position
105        return *masterPorts[idx];
106    } else  if (if_name == "default") {
107        return *masterPorts[defaultPortId];
108    } else {
109        return MemObject::getMasterPort(if_name, idx);
110    }
111}
112
113SlavePort &
114Bus::getSlavePort(const std::string &if_name, int idx)
115{
116    if (if_name == "slave" && idx < slavePorts.size()) {
117        // the slave port index translates directly to the vector position
118        return *slavePorts[idx];
119    } else {
120        return MemObject::getSlavePort(if_name, idx);
121    }
122}
123
124void
125Bus::init()
126{
127    std::vector<BusSlavePort*>::iterator p;
128
129    // iterate over our slave ports and determine which of our
130    // neighbouring master ports are snooping and add them as snoopers
131    for (p = slavePorts.begin(); p != slavePorts.end(); ++p) {
132        if ((*p)->getMasterPort().isSnooping()) {
133            DPRINTF(BusAddrRanges, "Adding snooping neighbour %s\n",
134                    (*p)->getMasterPort().name());
135            snoopPorts.push_back(*p);
136        }
137    }
138}
139
140Tick
141Bus::calcPacketTiming(PacketPtr pkt)
142{
143    // determine the current time rounded to the closest following
144    // clock edge
145    Tick now = curTick();
146    if (now % clock != 0) {
147        now = ((now / clock) + 1) * clock;
148    }
149
150    Tick headerTime = now + headerCycles * clock;
151
152    // The packet will be sent. Figure out how long it occupies the bus, and
153    // how much of that time is for the first "word", aka bus width.
154    int numCycles = 0;
155    if (pkt->hasData()) {
156        // If a packet has data, it needs ceil(size/width) cycles to send it
157        int dataSize = pkt->getSize();
158        numCycles += dataSize/width;
159        if (dataSize % width)
160            numCycles++;
161    }
162
163    // The first word will be delivered after the current tick, the delivery
164    // of the address if any, and one bus cycle to deliver the data
165    pkt->firstWordTime = headerTime + clock;
166
167    pkt->finishTime = headerTime + numCycles * clock;
168
169    return headerTime;
170}
171
172void Bus::occupyBus(Tick until)
173{
174    if (until == 0) {
175        // shortcut for express snoop packets
176        return;
177    }
178
179    tickNextIdle = until;
180    reschedule(busIdleEvent, tickNextIdle, true);
181
182    DPRINTF(Bus, "The bus is now occupied from tick %d to %d\n",
183            curTick(), tickNextIdle);
184}
185
186bool
187Bus::isOccupied(PacketPtr pkt, Port* port)
188{
189    // first we see if the next idle tick is in the future, next the
190    // bus is considered occupied if there are ports on the retry list
191    // and we are not in a retry with the current port
192    if (tickNextIdle > curTick() ||
193        (!retryList.empty() && !(inRetry && port == retryList.front()))) {
194        addToRetryList(port);
195        return true;
196    }
197    return false;
198}
199
200bool
201Bus::recvTiming(PacketPtr pkt)
202{
203    // get the source id
204    Packet::NodeID src_id = pkt->getSrc();
205
206    // determine the source port based on the id and direction
207    Port *src_port = NULL;
208    if (pkt->isRequest())
209        src_port = slavePorts[src_id];
210    else
211        src_port = masterPorts[src_id];
212
213    // test if the bus should be considered occupied for the current
214    // packet, and exclude express snoops from the check
215    if (!pkt->isExpressSnoop() && isOccupied(pkt, src_port)) {
216        DPRINTF(Bus, "recvTiming: src %d dst %d %s 0x%x BUSY\n",
217                src_id, pkt->getDest(), pkt->cmdString(), pkt->getAddr());
218        return false;
219    }
220
221    DPRINTF(Bus, "recvTiming: src %d dst %d %s 0x%x\n",
222            src_id, pkt->getDest(), pkt->cmdString(), pkt->getAddr());
223
224    Tick headerFinishTime = pkt->isExpressSnoop() ? 0 : calcPacketTiming(pkt);
225    Tick packetFinishTime = pkt->isExpressSnoop() ? 0 : pkt->finishTime;
226
227    // decide what to do based on the direction
228    if (pkt->isRequest()) {
229        // the packet is a memory-mapped request and should be broadcasted to
230        // our snoopers
231        assert(pkt->getDest() == Packet::Broadcast);
232
233        // forward to all snoopers but the source
234        forwardTiming(pkt, src_id);
235
236        // remember if we add an outstanding req so we can undo it if
237        // necessary, if the packet needs a response, we should add it
238        // as outstanding and express snoops never fail so there is
239        // not need to worry about them
240        bool add_outstanding = !pkt->isExpressSnoop() && pkt->needsResponse();
241
242        // keep track that we have an outstanding request packet
243        // matching this request, this is used by the coherency
244        // mechanism in determining what to do with snoop responses
245        // (in recvTimingSnoop)
246        if (add_outstanding) {
247            // we should never have an exsiting request outstanding
248            assert(outstandingReq.find(pkt->req) == outstandingReq.end());
249            outstandingReq.insert(pkt->req);
250        }
251
252        // since it is a normal request, determine the destination
253        // based on the address and attempt to send the packet
254        bool success = masterPorts[findPort(pkt->getAddr())]->sendTiming(pkt);
255
256        if (!success)  {
257            // inhibited packets should never be forced to retry
258            assert(!pkt->memInhibitAsserted());
259
260            // if it was added as outstanding and the send failed, then
261            // erase it again
262            if (add_outstanding)
263                outstandingReq.erase(pkt->req);
264
265            DPRINTF(Bus, "recvTiming: src %d dst %d %s 0x%x RETRY\n",
266                    src_id, pkt->getDest(), pkt->cmdString(), pkt->getAddr());
267
268            addToRetryList(src_port);
269            occupyBus(headerFinishTime);
270
271            return false;
272        }
273    } else {
274        // the packet is a normal response to a request that we should
275        // have seen passing through the bus
276        assert(outstandingReq.find(pkt->req) != outstandingReq.end());
277
278        // remove it as outstanding
279        outstandingReq.erase(pkt->req);
280
281        // send the packet to the destination through one of our slave
282        // ports, as determined by the destination field
283        bool success M5_VAR_USED = slavePorts[pkt->getDest()]->sendTiming(pkt);
284
285        // currently it is illegal to block responses... can lead to
286        // deadlock
287        assert(success);
288    }
289
290    succeededTiming(packetFinishTime);
291
292    return true;
293}
294
295bool
296Bus::recvTimingSnoop(PacketPtr pkt)
297{
298    // get the source id
299    Packet::NodeID src_id = pkt->getSrc();
300
301    if (pkt->isRequest()) {
302        DPRINTF(Bus, "recvTimingSnoop: src %d dst %d %s 0x%x\n",
303                src_id, pkt->getDest(), pkt->cmdString(), pkt->getAddr());
304
305        // the packet is an express snoop request and should be
306        // broadcasted to our snoopers
307        assert(pkt->getDest() == Packet::Broadcast);
308        assert(pkt->isExpressSnoop());
309
310        // forward to all snoopers
311        forwardTiming(pkt, INVALID_PORT_ID);
312
313        // a snoop request came from a connected slave device (one of
314        // our master ports), and if it is not coming from the slave
315        // device responsible for the address range something is
316        // wrong, hence there is nothing further to do as the packet
317        // would be going back to where it came from
318        assert(src_id == findPort(pkt->getAddr()));
319
320        // this is an express snoop and is never forced to retry
321        assert(!inRetry);
322
323        return true;
324    } else {
325        // determine the source port based on the id
326        SlavePort* src_port = slavePorts[src_id];
327
328        if (isOccupied(pkt, src_port)) {
329            DPRINTF(Bus, "recvTimingSnoop: src %d dst %d %s 0x%x BUSY\n",
330                    src_id, pkt->getDest(), pkt->cmdString(), pkt->getAddr());
331            return false;
332        }
333
334        DPRINTF(Bus, "recvTimingSnoop: src %d dst %d %s 0x%x\n",
335                src_id, pkt->getDest(), pkt->cmdString(), pkt->getAddr());
336
337        // get the destination from the packet
338        Packet::NodeID dest = pkt->getDest();
339
340        // responses are never express snoops
341        assert(!pkt->isExpressSnoop());
342
343        calcPacketTiming(pkt);
344        Tick packetFinishTime = pkt->finishTime;
345
346        // determine if the response is from a snoop request we
347        // created as the result of a normal request (in which case it
348        // should be in the outstandingReq), or if we merely forwarded
349        // someone else's snoop request
350        if (outstandingReq.find(pkt->req) == outstandingReq.end()) {
351            // this is a snoop response to a snoop request we
352            // forwarded, e.g. coming from the L1 and going to the L2
353            // this should be forwarded as a snoop response
354            bool success M5_VAR_USED = masterPorts[dest]->sendTimingSnoop(pkt);
355            assert(success);
356        } else {
357            // we got a snoop response on one of our slave ports,
358            // i.e. from a coherent master connected to the bus, and
359            // since we created the snoop request as part of
360            // recvTiming, this should now be a normal response again
361            outstandingReq.erase(pkt->req);
362
363            // this is a snoop response from a coherent master, with a
364            // destination field set on its way through the bus as
365            // request, hence it should never go back to where the
366            // snoop response came from, but instead to where the
367            // original request came from
368            assert(src_id != dest);
369
370            // as a normal response, it should go back to a master
371            // through one of our slave ports
372            bool success M5_VAR_USED = slavePorts[dest]->sendTiming(pkt);
373
374            // currently it is illegal to block responses... can lead
375            // to deadlock
376            assert(success);
377        }
378
379        succeededTiming(packetFinishTime);
380
381        return true;
382    }
383}
384
385void
386Bus::succeededTiming(Tick busy_time)
387{
388    // occupy the bus accordingly
389    occupyBus(busy_time);
390
391    // if a retrying port succeeded, also take it off the retry list
392    if (inRetry) {
393        DPRINTF(Bus, "Remove retry from list %s\n",
394                retryList.front()->name());
395        retryList.pop_front();
396        inRetry = false;
397    }
398}
399
400void
401Bus::forwardTiming(PacketPtr pkt, int exclude_slave_port_id)
402{
403    SnoopIter s_end = snoopPorts.end();
404    for (SnoopIter s_iter = snoopPorts.begin(); s_iter != s_end; s_iter++) {
405        BusSlavePort *p = *s_iter;
406        // we could have gotten this request from a snooping master
407        // (corresponding to our own slave port that is also in
408        // snoopPorts) and should not send it back to where it came
409        // from
410        if (exclude_slave_port_id == INVALID_PORT_ID ||
411            p->getId() != exclude_slave_port_id) {
412            // cache is not allowed to refuse snoop
413            bool success M5_VAR_USED = p->sendTimingSnoop(pkt);
414            assert(success);
415        }
416    }
417}
418
419void
420Bus::releaseBus()
421{
422    // releasing the bus means we should now be idle
423    assert(curTick() >= tickNextIdle);
424
425    // bus is now idle, so if someone is waiting we can retry
426    if (!retryList.empty()) {
427        // note that we block (return false on recvTiming) both
428        // because the bus is busy and because the destination is
429        // busy, and in the latter case the bus may be released before
430        // we see a retry from the destination
431        retryWaiting();
432    }
433
434    //If we weren't able to drain before, we might be able to now.
435    if (drainEvent && retryList.empty() && curTick() >= tickNextIdle) {
436        drainEvent->process();
437        // Clear the drain event once we're done with it.
438        drainEvent = NULL;
439    }
440}
441
442void
443Bus::retryWaiting()
444{
445    // this should never be called with an empty retry list
446    assert(!retryList.empty());
447
448    // send a retry to the port at the head of the retry list
449    inRetry = true;
450
451    // note that we might have blocked on the receiving port being
452    // busy (rather than the bus itself) and now call retry before the
453    // destination called retry on the bus
454    retryList.front()->sendRetry();
455
456    // If inRetry is still true, sendTiming wasn't called in zero time
457    // (e.g. the cache does this)
458    if (inRetry) {
459        retryList.pop_front();
460        inRetry = false;
461
462        //Bring tickNextIdle up to the present
463        while (tickNextIdle < curTick())
464            tickNextIdle += clock;
465
466        //Burn a cycle for the missed grant.
467        tickNextIdle += clock;
468
469        reschedule(busIdleEvent, tickNextIdle, true);
470    }
471}
472
473void
474Bus::recvRetry(int id)
475{
476    // we got a retry from a peer that we tried to send something to
477    // and failed, but we sent it on the account of someone else, and
478    // that source port should be on our retry list, however if the
479    // bus is released before this happens and the retry (from the bus
480    // point of view) is successful then this no longer holds and we
481    // could in fact have an empty retry list
482    if (retryList.empty())
483        return;
484
485    // if the bus isn't busy
486    if (curTick() >= tickNextIdle) {
487        // note that we do not care who told us to retry at the moment, we
488        // merely let the first one on the retry list go
489        retryWaiting();
490    }
491}
492
493int
494Bus::findPort(Addr addr)
495{
496    /* An interval tree would be a better way to do this. --ali. */
497    int dest_id;
498
499    dest_id = checkPortCache(addr);
500    if (dest_id != INVALID_PORT_ID)
501        return dest_id;
502
503    // Check normal port ranges
504    PortIter i = portMap.find(RangeSize(addr,1));
505    if (i != portMap.end()) {
506        dest_id = i->second;
507        updatePortCache(dest_id, i->first.start, i->first.end);
508        return dest_id;
509    }
510
511    // Check if this matches the default range
512    if (useDefaultRange) {
513        AddrRangeIter a_end = defaultRange.end();
514        for (AddrRangeIter i = defaultRange.begin(); i != a_end; i++) {
515            if (*i == addr) {
516                DPRINTF(Bus, "  found addr %#llx on default\n", addr);
517                return defaultPortId;
518            }
519        }
520    } else if (defaultPortId != INVALID_PORT_ID) {
521        DPRINTF(Bus, "Unable to find destination for addr %#llx, "
522                "will use default port\n", addr);
523        return defaultPortId;
524    }
525
526    // we should use the range for the default port and it did not
527    // match, or the default port is not set
528    fatal("Unable to find destination for addr %#llx on bus %s\n", addr,
529          name());
530}
531
532Tick
533Bus::recvAtomic(PacketPtr pkt)
534{
535    DPRINTF(Bus, "recvAtomic: packet src %d dest %d addr 0x%x cmd %s\n",
536            pkt->getSrc(), pkt->getDest(), pkt->getAddr(), pkt->cmdString());
537
538    // we should always see a request routed based on the address
539    assert(pkt->getDest() == Packet::Broadcast);
540    assert(pkt->isRequest());
541
542    // forward to all snoopers but the source
543    std::pair<MemCmd, Tick> snoop_result = forwardAtomic(pkt, pkt->getSrc());
544    MemCmd snoop_response_cmd = snoop_result.first;
545    Tick snoop_response_latency = snoop_result.second;
546
547    // even if we had a snoop response, we must continue and also
548    // perform the actual request at the destination
549    int dest_id = findPort(pkt->getAddr());
550
551    // forward the request to the appropriate destination
552    Tick response_latency = masterPorts[dest_id]->sendAtomic(pkt);
553
554    // if we got a response from a snooper, restore it here
555    if (snoop_response_cmd != MemCmd::InvalidCmd) {
556        // no one else should have responded
557        assert(!pkt->isResponse());
558        pkt->cmd = snoop_response_cmd;
559        response_latency = snoop_response_latency;
560    }
561
562    pkt->finishTime = curTick() + response_latency;
563    return response_latency;
564}
565
566Tick
567Bus::recvAtomicSnoop(PacketPtr pkt)
568{
569    DPRINTF(Bus, "recvAtomicSnoop: packet src %d dest %d addr 0x%x cmd %s\n",
570            pkt->getSrc(), pkt->getDest(), pkt->getAddr(), pkt->cmdString());
571
572    // we should always see a request routed based on the address
573    assert(pkt->getDest() == Packet::Broadcast);
574    assert(pkt->isRequest());
575
576    // forward to all snoopers
577    std::pair<MemCmd, Tick> snoop_result = forwardAtomic(pkt, INVALID_PORT_ID);
578    MemCmd snoop_response_cmd = snoop_result.first;
579    Tick snoop_response_latency = snoop_result.second;
580
581    if (snoop_response_cmd != MemCmd::InvalidCmd)
582        pkt->cmd = snoop_response_cmd;
583
584    pkt->finishTime = curTick() + snoop_response_latency;
585    return snoop_response_latency;
586}
587
588std::pair<MemCmd, Tick>
589Bus::forwardAtomic(PacketPtr pkt, int exclude_slave_port_id)
590{
591    // the packet may be changed on snoops, record the original source
592    // and command to enable us to restore it between snoops so that
593    // additional snoops can take place properly
594    Packet::NodeID orig_src_id = pkt->getSrc();
595    MemCmd orig_cmd = pkt->cmd;
596    MemCmd snoop_response_cmd = MemCmd::InvalidCmd;
597    Tick snoop_response_latency = 0;
598
599    SnoopIter s_end = snoopPorts.end();
600    for (SnoopIter s_iter = snoopPorts.begin(); s_iter != s_end; s_iter++) {
601        BusSlavePort *p = *s_iter;
602        // we could have gotten this request from a snooping master
603        // (corresponding to our own slave port that is also in
604        // snoopPorts) and should not send it back to where it came
605        // from
606        if (exclude_slave_port_id == INVALID_PORT_ID ||
607            p->getId() != exclude_slave_port_id) {
608            Tick latency = p->sendAtomicSnoop(pkt);
609            // in contrast to a functional access, we have to keep on
610            // going as all snoopers must be updated even if we get a
611            // response
612            if (pkt->isResponse()) {
613                // response from snoop agent
614                assert(pkt->cmd != orig_cmd);
615                assert(pkt->memInhibitAsserted());
616                // should only happen once
617                assert(snoop_response_cmd == MemCmd::InvalidCmd);
618                // save response state
619                snoop_response_cmd = pkt->cmd;
620                snoop_response_latency = latency;
621                // restore original packet state for remaining snoopers
622                pkt->cmd = orig_cmd;
623                pkt->setSrc(orig_src_id);
624                pkt->setDest(Packet::Broadcast);
625            }
626        }
627    }
628
629    // the packet is restored as part of the loop and any potential
630    // snoop response is part of the returned pair
631    return std::make_pair(snoop_response_cmd, snoop_response_latency);
632}
633
634void
635Bus::recvFunctional(PacketPtr pkt)
636{
637    if (!pkt->isPrint()) {
638        // don't do DPRINTFs on PrintReq as it clutters up the output
639        DPRINTF(Bus,
640                "recvFunctional: packet src %d dest %d addr 0x%x cmd %s\n",
641                pkt->getSrc(), pkt->getDest(), pkt->getAddr(),
642                pkt->cmdString());
643    }
644
645    // we should always see a request routed based on the address
646    assert(pkt->getDest() == Packet::Broadcast);
647    assert(pkt->isRequest());
648
649    // forward to all snoopers but the source
650    forwardFunctional(pkt, pkt->getSrc());
651
652    // there is no need to continue if the snooping has found what we
653    // were looking for and the packet is already a response
654    if (!pkt->isResponse()) {
655        int dest_id = findPort(pkt->getAddr());
656
657        masterPorts[dest_id]->sendFunctional(pkt);
658    }
659}
660
661void
662Bus::recvFunctionalSnoop(PacketPtr pkt)
663{
664    if (!pkt->isPrint()) {
665        // don't do DPRINTFs on PrintReq as it clutters up the output
666        DPRINTF(Bus,
667                "recvFunctionalSnoop: packet src %d dest %d addr 0x%x cmd %s\n",
668                pkt->getSrc(), pkt->getDest(), pkt->getAddr(),
669                pkt->cmdString());
670    }
671
672    // we should always see a request routed based on the address
673    assert(pkt->getDest() == Packet::Broadcast);
674    assert(pkt->isRequest());
675
676    // forward to all snoopers
677    forwardFunctional(pkt, INVALID_PORT_ID);
678}
679
680void
681Bus::forwardFunctional(PacketPtr pkt, int exclude_slave_port_id)
682{
683    SnoopIter s_end = snoopPorts.end();
684    for (SnoopIter s_iter = snoopPorts.begin(); s_iter != s_end; s_iter++) {
685        BusSlavePort *p = *s_iter;
686        // we could have gotten this request from a snooping master
687        // (corresponding to our own slave port that is also in
688        // snoopPorts) and should not send it back to where it came
689        // from
690        if (exclude_slave_port_id == INVALID_PORT_ID ||
691            p->getId() != exclude_slave_port_id)
692            p->sendFunctionalSnoop(pkt);
693
694        // if we get a response we are done
695        if (pkt->isResponse()) {
696            break;
697        }
698    }
699}
700
701/** Function called by the port when the bus is receiving a range change.*/
702void
703Bus::recvRangeChange(int id)
704{
705    AddrRangeList ranges;
706    AddrRangeIter iter;
707
708    if (inRecvRangeChange.count(id))
709        return;
710    inRecvRangeChange.insert(id);
711
712    DPRINTF(BusAddrRanges, "received RangeChange from device id %d\n", id);
713
714    clearPortCache();
715    if (id == defaultPortId) {
716        defaultRange.clear();
717        // Only try to update these ranges if the user set a default responder.
718        if (useDefaultRange) {
719            AddrRangeList ranges =
720                masterPorts[id]->getSlavePort().getAddrRanges();
721            for(iter = ranges.begin(); iter != ranges.end(); iter++) {
722                defaultRange.push_back(*iter);
723                DPRINTF(BusAddrRanges, "Adding range %#llx - %#llx for default range\n",
724                        iter->start, iter->end);
725            }
726        }
727    } else {
728
729        assert(id < masterPorts.size() && id >= 0);
730        BusMasterPort *port = masterPorts[id];
731
732        // Clean out any previously existent ids
733        for (PortIter portIter = portMap.begin();
734             portIter != portMap.end(); ) {
735            if (portIter->second == id)
736                portMap.erase(portIter++);
737            else
738                portIter++;
739        }
740
741        ranges = port->getSlavePort().getAddrRanges();
742
743        for (iter = ranges.begin(); iter != ranges.end(); iter++) {
744            DPRINTF(BusAddrRanges, "Adding range %#llx - %#llx for id %d\n",
745                    iter->start, iter->end, id);
746            if (portMap.insert(*iter, id) == portMap.end()) {
747                int conflict_id = portMap.find(*iter)->second;
748                fatal("%s has two ports with same range:\n\t%s\n\t%s\n",
749                      name(), masterPorts[id]->getSlavePort().name(),
750                      masterPorts[conflict_id]->getSlavePort().name());
751            }
752        }
753    }
754    DPRINTF(BusAddrRanges, "port list has %d entries\n", portMap.size());
755
756    // tell all our peers that our address range has changed.
757    // Don't tell the device that caused this change, it already knows
758    std::vector<BusSlavePort*>::const_iterator intIter;
759
760    for (intIter = slavePorts.begin(); intIter != slavePorts.end(); intIter++)
761        (*intIter)->sendRangeChange();
762
763    inRecvRangeChange.erase(id);
764}
765
766AddrRangeList
767Bus::getAddrRanges(int id)
768{
769    AddrRangeList ranges;
770
771    DPRINTF(BusAddrRanges, "received address range request, returning:\n");
772
773    for (AddrRangeIter dflt_iter = defaultRange.begin();
774         dflt_iter != defaultRange.end(); dflt_iter++) {
775        ranges.push_back(*dflt_iter);
776        DPRINTF(BusAddrRanges, "  -- Dflt: %#llx : %#llx\n",dflt_iter->start,
777                dflt_iter->end);
778    }
779    for (PortIter portIter = portMap.begin();
780         portIter != portMap.end(); portIter++) {
781        bool subset = false;
782        for (AddrRangeIter dflt_iter = defaultRange.begin();
783             dflt_iter != defaultRange.end(); dflt_iter++) {
784            if ((portIter->first.start < dflt_iter->start &&
785                portIter->first.end >= dflt_iter->start) ||
786               (portIter->first.start < dflt_iter->end &&
787                portIter->first.end >= dflt_iter->end))
788                fatal("Devices can not set ranges that itersect the default set\
789                        but are not a subset of the default set.\n");
790            if (portIter->first.start >= dflt_iter->start &&
791                portIter->first.end <= dflt_iter->end) {
792                subset = true;
793                DPRINTF(BusAddrRanges, "  -- %#llx : %#llx is a SUBSET\n",
794                    portIter->first.start, portIter->first.end);
795            }
796        }
797        if (portIter->second != id && !subset) {
798            ranges.push_back(portIter->first);
799            DPRINTF(BusAddrRanges, "  -- %#llx : %#llx\n",
800                    portIter->first.start, portIter->first.end);
801        }
802    }
803
804    return ranges;
805}
806
807bool
808Bus::isSnooping(int id) const
809{
810    // in essence, answer the question if there are snooping ports
811    return !snoopPorts.empty();
812}
813
814unsigned
815Bus::findBlockSize(int id)
816{
817    if (cachedBlockSizeValid)
818        return cachedBlockSize;
819
820    unsigned max_bs = 0;
821
822    PortIter p_end = portMap.end();
823    for (PortIter p_iter = portMap.begin(); p_iter != p_end; p_iter++) {
824        unsigned tmp_bs = masterPorts[p_iter->second]->peerBlockSize();
825        if (tmp_bs > max_bs)
826            max_bs = tmp_bs;
827    }
828    SnoopIter s_end = snoopPorts.end();
829    for (SnoopIter s_iter = snoopPorts.begin(); s_iter != s_end; s_iter++) {
830        unsigned tmp_bs = (*s_iter)->peerBlockSize();
831        if (tmp_bs > max_bs)
832            max_bs = tmp_bs;
833    }
834    if (max_bs == 0)
835        max_bs = defaultBlockSize;
836
837    if (max_bs != 64)
838        warn_once("Blocksize found to not be 64... hmm... probably not.\n");
839    cachedBlockSize = max_bs;
840    cachedBlockSizeValid = true;
841    return max_bs;
842}
843
844
845unsigned int
846Bus::drain(Event * de)
847{
848    //We should check that we're not "doing" anything, and that noone is
849    //waiting. We might be idle but have someone waiting if the device we
850    //contacted for a retry didn't actually retry.
851    if (!retryList.empty() || (curTick() < tickNextIdle &&
852                               busIdleEvent.scheduled())) {
853        drainEvent = de;
854        return 1;
855    }
856    return 0;
857}
858
859void
860Bus::startup()
861{
862    if (tickNextIdle < curTick())
863        tickNextIdle = (curTick() / clock) * clock + clock;
864}
865
866Bus *
867BusParams::create()
868{
869    return new Bus(this);
870}
871