coherent_xbar.cc revision 9033
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(InvalidPortID),
61      useDefaultRange(p->use_default_range),
62      defaultBlockSize(p->block_size),
63      cachedBlockSize(0), cachedBlockSizeValid(false)
64{
65    //width, clock period, and header cycles must be positive
66    if (width <= 0)
67        fatal("Bus width must be positive\n");
68    if (clock <= 0)
69        fatal("Bus clock period must be positive\n");
70    if (headerCycles <= 0)
71        fatal("Number of header cycles must be positive\n");
72
73    // create the ports based on the size of the master and slave
74    // vector ports, and the presence of the default port, the ports
75    // are enumerated starting from zero
76    for (int i = 0; i < p->port_master_connection_count; ++i) {
77        std::string portName = csprintf("%s-p%d", name(), i);
78        MasterPort* bp = new BusMasterPort(portName, this, i);
79        masterPorts.push_back(bp);
80    }
81
82    // see if we have a default slave device connected and if so add
83    // our corresponding master port
84    if (p->port_default_connection_count) {
85        defaultPortID = masterPorts.size();
86        std::string portName = csprintf("%s-default", name());
87        MasterPort* bp = new BusMasterPort(portName, this, defaultPortID);
88        masterPorts.push_back(bp);
89    }
90
91    // create the slave ports, once again starting at zero
92    for (int i = 0; i < p->port_slave_connection_count; ++i) {
93        std::string portName = csprintf("%s-p%d", name(), i);
94        SlavePort* bp = new BusSlavePort(portName, this, i);
95        slavePorts.push_back(bp);
96    }
97
98    clearPortCache();
99}
100
101MasterPort &
102Bus::getMasterPort(const std::string &if_name, int idx)
103{
104    if (if_name == "master" && idx < masterPorts.size()) {
105        // the master port index translates directly to the vector position
106        return *masterPorts[idx];
107    } else  if (if_name == "default") {
108        return *masterPorts[defaultPortID];
109    } else {
110        return MemObject::getMasterPort(if_name, idx);
111    }
112}
113
114SlavePort &
115Bus::getSlavePort(const std::string &if_name, int idx)
116{
117    if (if_name == "slave" && idx < slavePorts.size()) {
118        // the slave port index translates directly to the vector position
119        return *slavePorts[idx];
120    } else {
121        return MemObject::getSlavePort(if_name, idx);
122    }
123}
124
125void
126Bus::init()
127{
128    // iterate over our slave ports and determine which of our
129    // neighbouring master ports are snooping and add them as snoopers
130    for (SlavePortConstIter p = slavePorts.begin(); p != slavePorts.end();
131         ++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(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::recvTimingReq(PacketPtr pkt, PortID slave_port_id)
202{
203    // determine the source port based on the id
204    SlavePort *src_port = slavePorts[slave_port_id];
205
206    // test if the bus should be considered occupied for the current
207    // port, and exclude express snoops from the check
208    if (!pkt->isExpressSnoop() && isOccupied(src_port)) {
209        DPRINTF(Bus, "recvTimingReq: src %s %s 0x%x BUSY\n",
210                src_port->name(), pkt->cmdString(), pkt->getAddr());
211        return false;
212    }
213
214    DPRINTF(Bus, "recvTimingReq: src %s %s 0x%x\n",
215            src_port->name(), pkt->cmdString(), pkt->getAddr());
216
217    // set the source port for routing of the response
218    pkt->setSrc(slave_port_id);
219
220    Tick headerFinishTime = pkt->isExpressSnoop() ? 0 : calcPacketTiming(pkt);
221    Tick packetFinishTime = pkt->isExpressSnoop() ? 0 : pkt->finishTime;
222
223    // uncacheable requests need never be snooped
224    if (!pkt->req->isUncacheable()) {
225        // the packet is a memory-mapped request and should be
226        // broadcasted to our snoopers but the source
227        forwardTiming(pkt, slave_port_id);
228    }
229
230    // remember if we add an outstanding req so we can undo it if
231    // necessary, if the packet needs a response, we should add it
232    // as outstanding and express snoops never fail so there is
233    // not need to worry about them
234    bool add_outstanding = !pkt->isExpressSnoop() && pkt->needsResponse();
235
236    // keep track that we have an outstanding request packet
237    // matching this request, this is used by the coherency
238    // mechanism in determining what to do with snoop responses
239    // (in recvTimingSnoop)
240    if (add_outstanding) {
241        // we should never have an exsiting request outstanding
242        assert(outstandingReq.find(pkt->req) == outstandingReq.end());
243        outstandingReq.insert(pkt->req);
244    }
245
246    // since it is a normal request, determine the destination
247    // based on the address and attempt to send the packet
248    bool success = masterPorts[findPort(pkt->getAddr())]->sendTimingReq(pkt);
249
250    if (!success)  {
251        // inhibited packets should never be forced to retry
252        assert(!pkt->memInhibitAsserted());
253
254        // if it was added as outstanding and the send failed, then
255        // erase it again
256        if (add_outstanding)
257            outstandingReq.erase(pkt->req);
258
259        DPRINTF(Bus, "recvTimingReq: src %s %s 0x%x RETRY\n",
260                src_port->name(), pkt->cmdString(), pkt->getAddr());
261
262        addToRetryList(src_port);
263        occupyBus(headerFinishTime);
264
265        return false;
266    }
267
268    succeededTiming(packetFinishTime);
269
270    return true;
271}
272
273bool
274Bus::recvTimingResp(PacketPtr pkt, PortID master_port_id)
275{
276    // determine the source port based on the id
277    MasterPort *src_port = masterPorts[master_port_id];
278
279    // test if the bus should be considered occupied for the current
280    // port
281    if (isOccupied(src_port)) {
282        DPRINTF(Bus, "recvTimingResp: src %s %s 0x%x BUSY\n",
283                src_port->name(), pkt->cmdString(), pkt->getAddr());
284        return false;
285    }
286
287    DPRINTF(Bus, "recvTimingResp: src %s %s 0x%x\n",
288            src_port->name(), pkt->cmdString(), pkt->getAddr());
289
290    calcPacketTiming(pkt);
291    Tick packetFinishTime = pkt->finishTime;
292
293    // the packet is a normal response to a request that we should
294    // have seen passing through the bus
295    assert(outstandingReq.find(pkt->req) != outstandingReq.end());
296
297    // remove it as outstanding
298    outstandingReq.erase(pkt->req);
299
300    // send the packet to the destination through one of our slave
301    // ports, as determined by the destination field
302    bool success M5_VAR_USED = slavePorts[pkt->getDest()]->sendTimingResp(pkt);
303
304    // currently it is illegal to block responses... can lead to
305    // deadlock
306    assert(success);
307
308    succeededTiming(packetFinishTime);
309
310    return true;
311}
312
313void
314Bus::recvTimingSnoopReq(PacketPtr pkt, PortID master_port_id)
315{
316    DPRINTF(Bus, "recvTimingSnoopReq: src %s %s 0x%x\n",
317            masterPorts[master_port_id]->name(), pkt->cmdString(),
318            pkt->getAddr());
319
320    // we should only see express snoops from caches
321    assert(pkt->isExpressSnoop());
322
323    // set the source port for routing of the response
324    pkt->setSrc(master_port_id);
325
326    // forward to all snoopers
327    forwardTiming(pkt, InvalidPortID);
328
329    // a snoop request came from a connected slave device (one of
330    // our master ports), and if it is not coming from the slave
331    // device responsible for the address range something is
332    // wrong, hence there is nothing further to do as the packet
333    // would be going back to where it came from
334    assert(master_port_id == findPort(pkt->getAddr()));
335
336    // this is an express snoop and is never forced to retry
337    assert(!inRetry);
338}
339
340bool
341Bus::recvTimingSnoopResp(PacketPtr pkt, PortID slave_port_id)
342{
343    // determine the source port based on the id
344    SlavePort* src_port = slavePorts[slave_port_id];
345
346    // test if the bus should be considered occupied for the current
347    // port
348    if (isOccupied(src_port)) {
349        DPRINTF(Bus, "recvTimingSnoopResp: src %s %s 0x%x BUSY\n",
350                src_port->name(), pkt->cmdString(), pkt->getAddr());
351        return false;
352    }
353
354    DPRINTF(Bus, "recvTimingSnoop: src %s %s 0x%x\n",
355            src_port->name(), pkt->cmdString(), pkt->getAddr());
356
357    // get the destination from the packet
358    PortID dest = pkt->getDest();
359
360    // responses are never express snoops
361    assert(!pkt->isExpressSnoop());
362
363    calcPacketTiming(pkt);
364    Tick packetFinishTime = pkt->finishTime;
365
366    // determine if the response is from a snoop request we
367    // created as the result of a normal request (in which case it
368    // should be in the outstandingReq), or if we merely forwarded
369    // someone else's snoop request
370    if (outstandingReq.find(pkt->req) == outstandingReq.end()) {
371        // this is a snoop response to a snoop request we
372        // forwarded, e.g. coming from the L1 and going to the L2
373        // this should be forwarded as a snoop response
374        bool success M5_VAR_USED = masterPorts[dest]->sendTimingSnoopResp(pkt);
375        assert(success);
376    } else {
377        // we got a snoop response on one of our slave ports,
378        // i.e. from a coherent master connected to the bus, and
379        // since we created the snoop request as part of
380        // recvTiming, this should now be a normal response again
381        outstandingReq.erase(pkt->req);
382
383        // this is a snoop response from a coherent master, with a
384        // destination field set on its way through the bus as
385        // request, hence it should never go back to where the
386        // snoop response came from, but instead to where the
387        // original request came from
388        assert(slave_port_id != dest);
389
390        // as a normal response, it should go back to a master
391        // through one of our slave ports
392        bool success M5_VAR_USED = slavePorts[dest]->sendTimingResp(pkt);
393
394        // currently it is illegal to block responses... can lead
395        // to deadlock
396        assert(success);
397    }
398
399    succeededTiming(packetFinishTime);
400
401    return true;
402}
403
404
405void
406Bus::succeededTiming(Tick busy_time)
407{
408    // occupy the bus accordingly
409    occupyBus(busy_time);
410
411    // if a retrying port succeeded, also take it off the retry list
412    if (inRetry) {
413        DPRINTF(Bus, "Remove retry from list %s\n",
414                retryList.front()->name());
415        retryList.pop_front();
416        inRetry = false;
417    }
418}
419
420void
421Bus::forwardTiming(PacketPtr pkt, PortID exclude_slave_port_id)
422{
423    for (SlavePortIter s = snoopPorts.begin(); s != snoopPorts.end(); ++s) {
424        SlavePort *p = *s;
425        // we could have gotten this request from a snooping master
426        // (corresponding to our own slave port that is also in
427        // snoopPorts) and should not send it back to where it came
428        // from
429        if (exclude_slave_port_id == InvalidPortID ||
430            p->getId() != exclude_slave_port_id) {
431            // cache is not allowed to refuse snoop
432            p->sendTimingSnoopReq(pkt);
433        }
434    }
435}
436
437void
438Bus::releaseBus()
439{
440    // releasing the bus means we should now be idle
441    assert(curTick() >= tickNextIdle);
442
443    // bus is now idle, so if someone is waiting we can retry
444    if (!retryList.empty()) {
445        // note that we block (return false on recvTiming) both
446        // because the bus is busy and because the destination is
447        // busy, and in the latter case the bus may be released before
448        // we see a retry from the destination
449        retryWaiting();
450    }
451
452    //If we weren't able to drain before, we might be able to now.
453    if (drainEvent && retryList.empty() && curTick() >= tickNextIdle) {
454        drainEvent->process();
455        // Clear the drain event once we're done with it.
456        drainEvent = NULL;
457    }
458}
459
460void
461Bus::retryWaiting()
462{
463    // this should never be called with an empty retry list
464    assert(!retryList.empty());
465
466    // send a retry to the port at the head of the retry list
467    inRetry = true;
468
469    // note that we might have blocked on the receiving port being
470    // busy (rather than the bus itself) and now call retry before the
471    // destination called retry on the bus
472    retryList.front()->sendRetry();
473
474    // If inRetry is still true, sendTiming wasn't called in zero time
475    // (e.g. the cache does this)
476    if (inRetry) {
477        retryList.pop_front();
478        inRetry = false;
479
480        //Bring tickNextIdle up to the present
481        while (tickNextIdle < curTick())
482            tickNextIdle += clock;
483
484        //Burn a cycle for the missed grant.
485        tickNextIdle += clock;
486
487        reschedule(busIdleEvent, tickNextIdle, true);
488    }
489}
490
491void
492Bus::recvRetry()
493{
494    // we got a retry from a peer that we tried to send something to
495    // and failed, but we sent it on the account of someone else, and
496    // that source port should be on our retry list, however if the
497    // bus is released before this happens and the retry (from the bus
498    // point of view) is successful then this no longer holds and we
499    // could in fact have an empty retry list
500    if (retryList.empty())
501        return;
502
503    // if the bus isn't busy
504    if (curTick() >= tickNextIdle) {
505        // note that we do not care who told us to retry at the moment, we
506        // merely let the first one on the retry list go
507        retryWaiting();
508    }
509}
510
511PortID
512Bus::findPort(Addr addr)
513{
514    /* An interval tree would be a better way to do this. --ali. */
515    PortID dest_id = checkPortCache(addr);
516    if (dest_id != InvalidPortID)
517        return dest_id;
518
519    // Check normal port ranges
520    PortIter i = portMap.find(RangeSize(addr,1));
521    if (i != portMap.end()) {
522        dest_id = i->second;
523        updatePortCache(dest_id, i->first.start, i->first.end);
524        return dest_id;
525    }
526
527    // Check if this matches the default range
528    if (useDefaultRange) {
529        AddrRangeIter a_end = defaultRange.end();
530        for (AddrRangeIter i = defaultRange.begin(); i != a_end; i++) {
531            if (*i == addr) {
532                DPRINTF(Bus, "  found addr %#llx on default\n", addr);
533                return defaultPortID;
534            }
535        }
536    } else if (defaultPortID != InvalidPortID) {
537        DPRINTF(Bus, "Unable to find destination for addr %#llx, "
538                "will use default port\n", addr);
539        return defaultPortID;
540    }
541
542    // we should use the range for the default port and it did not
543    // match, or the default port is not set
544    fatal("Unable to find destination for addr %#llx on bus %s\n", addr,
545          name());
546}
547
548Tick
549Bus::recvAtomic(PacketPtr pkt, PortID slave_port_id)
550{
551    DPRINTF(Bus, "recvAtomic: packet src %s addr 0x%x cmd %s\n",
552            slavePorts[slave_port_id]->name(), pkt->getAddr(),
553            pkt->cmdString());
554
555    MemCmd snoop_response_cmd = MemCmd::InvalidCmd;
556    Tick snoop_response_latency = 0;
557
558    // uncacheable requests need never be snooped
559    if (!pkt->req->isUncacheable()) {
560        // forward to all snoopers but the source
561        std::pair<MemCmd, Tick> snoop_result =
562            forwardAtomic(pkt, slave_port_id);
563        snoop_response_cmd = snoop_result.first;
564        snoop_response_latency = snoop_result.second;
565    }
566
567    // even if we had a snoop response, we must continue and also
568    // perform the actual request at the destination
569    PortID dest_id = findPort(pkt->getAddr());
570
571    // forward the request to the appropriate destination
572    Tick response_latency = masterPorts[dest_id]->sendAtomic(pkt);
573
574    // if we got a response from a snooper, restore it here
575    if (snoop_response_cmd != MemCmd::InvalidCmd) {
576        // no one else should have responded
577        assert(!pkt->isResponse());
578        pkt->cmd = snoop_response_cmd;
579        response_latency = snoop_response_latency;
580    }
581
582    pkt->finishTime = curTick() + response_latency;
583    return response_latency;
584}
585
586Tick
587Bus::recvAtomicSnoop(PacketPtr pkt, PortID master_port_id)
588{
589    DPRINTF(Bus, "recvAtomicSnoop: packet src %s addr 0x%x cmd %s\n",
590            masterPorts[master_port_id]->name(), pkt->getAddr(),
591            pkt->cmdString());
592
593    // forward to all snoopers
594    std::pair<MemCmd, Tick> snoop_result =
595        forwardAtomic(pkt, InvalidPortID);
596    MemCmd snoop_response_cmd = snoop_result.first;
597    Tick snoop_response_latency = snoop_result.second;
598
599    if (snoop_response_cmd != MemCmd::InvalidCmd)
600        pkt->cmd = snoop_response_cmd;
601
602    pkt->finishTime = curTick() + snoop_response_latency;
603    return snoop_response_latency;
604}
605
606std::pair<MemCmd, Tick>
607Bus::forwardAtomic(PacketPtr pkt, PortID exclude_slave_port_id)
608{
609    // the packet may be changed on snoops, record the original
610    // command to enable us to restore it between snoops so that
611    // additional snoops can take place properly
612    MemCmd orig_cmd = pkt->cmd;
613    MemCmd snoop_response_cmd = MemCmd::InvalidCmd;
614    Tick snoop_response_latency = 0;
615
616    for (SlavePortIter s = snoopPorts.begin(); s != snoopPorts.end(); ++s) {
617        SlavePort *p = *s;
618        // we could have gotten this request from a snooping master
619        // (corresponding to our own slave port that is also in
620        // snoopPorts) and should not send it back to where it came
621        // from
622        if (exclude_slave_port_id == InvalidPortID ||
623            p->getId() != exclude_slave_port_id) {
624            Tick latency = p->sendAtomicSnoop(pkt);
625            // in contrast to a functional access, we have to keep on
626            // going as all snoopers must be updated even if we get a
627            // response
628            if (pkt->isResponse()) {
629                // response from snoop agent
630                assert(pkt->cmd != orig_cmd);
631                assert(pkt->memInhibitAsserted());
632                // should only happen once
633                assert(snoop_response_cmd == MemCmd::InvalidCmd);
634                // save response state
635                snoop_response_cmd = pkt->cmd;
636                snoop_response_latency = latency;
637                // restore original packet state for remaining snoopers
638                pkt->cmd = orig_cmd;
639            }
640        }
641    }
642
643    // the packet is restored as part of the loop and any potential
644    // snoop response is part of the returned pair
645    return std::make_pair(snoop_response_cmd, snoop_response_latency);
646}
647
648void
649Bus::recvFunctional(PacketPtr pkt, PortID slave_port_id)
650{
651    if (!pkt->isPrint()) {
652        // don't do DPRINTFs on PrintReq as it clutters up the output
653        DPRINTF(Bus,
654                "recvFunctional: packet src %s addr 0x%x cmd %s\n",
655                slavePorts[slave_port_id]->name(), pkt->getAddr(),
656                pkt->cmdString());
657    }
658
659    // uncacheable requests need never be snooped
660    if (!pkt->req->isUncacheable()) {
661        // forward to all snoopers but the source
662        forwardFunctional(pkt, slave_port_id);
663    }
664
665    // there is no need to continue if the snooping has found what we
666    // were looking for and the packet is already a response
667    if (!pkt->isResponse()) {
668        PortID dest_id = findPort(pkt->getAddr());
669
670        masterPorts[dest_id]->sendFunctional(pkt);
671    }
672}
673
674void
675Bus::recvFunctionalSnoop(PacketPtr pkt, PortID master_port_id)
676{
677    if (!pkt->isPrint()) {
678        // don't do DPRINTFs on PrintReq as it clutters up the output
679        DPRINTF(Bus,
680                "recvFunctionalSnoop: packet src %s addr 0x%x cmd %s\n",
681                masterPorts[master_port_id]->name(), pkt->getAddr(),
682                pkt->cmdString());
683    }
684
685    // forward to all snoopers
686    forwardFunctional(pkt, InvalidPortID);
687}
688
689void
690Bus::forwardFunctional(PacketPtr pkt, PortID exclude_slave_port_id)
691{
692    for (SlavePortIter s = snoopPorts.begin(); s != snoopPorts.end(); ++s) {
693        SlavePort *p = *s;
694        // we could have gotten this request from a snooping master
695        // (corresponding to our own slave port that is also in
696        // snoopPorts) and should not send it back to where it came
697        // from
698        if (exclude_slave_port_id == InvalidPortID ||
699            p->getId() != exclude_slave_port_id)
700            p->sendFunctionalSnoop(pkt);
701
702        // if we get a response we are done
703        if (pkt->isResponse()) {
704            break;
705        }
706    }
707}
708
709/** Function called by the port when the bus is receiving a range change.*/
710void
711Bus::recvRangeChange(PortID master_port_id)
712{
713    AddrRangeList ranges;
714    AddrRangeIter iter;
715
716    if (inRecvRangeChange.count(master_port_id))
717        return;
718    inRecvRangeChange.insert(master_port_id);
719
720    DPRINTF(BusAddrRanges, "received RangeChange from device id %d\n",
721            master_port_id);
722
723    clearPortCache();
724    if (master_port_id == defaultPortID) {
725        defaultRange.clear();
726        // Only try to update these ranges if the user set a default responder.
727        if (useDefaultRange) {
728            AddrRangeList ranges =
729                masterPorts[master_port_id]->getSlavePort().getAddrRanges();
730            for(iter = ranges.begin(); iter != ranges.end(); iter++) {
731                defaultRange.push_back(*iter);
732                DPRINTF(BusAddrRanges, "Adding range %#llx - %#llx for default range\n",
733                        iter->start, iter->end);
734            }
735        }
736    } else {
737
738        assert(master_port_id < masterPorts.size() && master_port_id >= 0);
739        MasterPort *port = masterPorts[master_port_id];
740
741        // Clean out any previously existent ids
742        for (PortIter portIter = portMap.begin();
743             portIter != portMap.end(); ) {
744            if (portIter->second == master_port_id)
745                portMap.erase(portIter++);
746            else
747                portIter++;
748        }
749
750        ranges = port->getSlavePort().getAddrRanges();
751
752        for (iter = ranges.begin(); iter != ranges.end(); iter++) {
753            DPRINTF(BusAddrRanges, "Adding range %#llx - %#llx for id %d\n",
754                    iter->start, iter->end, master_port_id);
755            if (portMap.insert(*iter, master_port_id) == portMap.end()) {
756                PortID conflict_id = portMap.find(*iter)->second;
757                fatal("%s has two ports with same range:\n\t%s\n\t%s\n",
758                      name(),
759                      masterPorts[master_port_id]->getSlavePort().name(),
760                      masterPorts[conflict_id]->getSlavePort().name());
761            }
762        }
763    }
764    DPRINTF(BusAddrRanges, "port list has %d entries\n", portMap.size());
765
766    // tell all our neighbouring master ports that our address range
767    // has changed
768    for (SlavePortConstIter p = slavePorts.begin(); p != slavePorts.end();
769         ++p)
770        (*p)->sendRangeChange();
771
772    inRecvRangeChange.erase(master_port_id);
773}
774
775AddrRangeList
776Bus::getAddrRanges()
777{
778    AddrRangeList ranges;
779
780    DPRINTF(BusAddrRanges, "received address range request, returning:\n");
781
782    for (AddrRangeIter dflt_iter = defaultRange.begin();
783         dflt_iter != defaultRange.end(); dflt_iter++) {
784        ranges.push_back(*dflt_iter);
785        DPRINTF(BusAddrRanges, "  -- Dflt: %#llx : %#llx\n",dflt_iter->start,
786                dflt_iter->end);
787    }
788    for (PortIter portIter = portMap.begin();
789         portIter != portMap.end(); portIter++) {
790        bool subset = false;
791        for (AddrRangeIter dflt_iter = defaultRange.begin();
792             dflt_iter != defaultRange.end(); dflt_iter++) {
793            if ((portIter->first.start < dflt_iter->start &&
794                portIter->first.end >= dflt_iter->start) ||
795               (portIter->first.start < dflt_iter->end &&
796                portIter->first.end >= dflt_iter->end))
797                fatal("Devices can not set ranges that itersect the default set\
798                        but are not a subset of the default set.\n");
799            if (portIter->first.start >= dflt_iter->start &&
800                portIter->first.end <= dflt_iter->end) {
801                subset = true;
802                DPRINTF(BusAddrRanges, "  -- %#llx : %#llx is a SUBSET\n",
803                    portIter->first.start, portIter->first.end);
804            }
805        }
806        if (!subset) {
807            ranges.push_back(portIter->first);
808            DPRINTF(BusAddrRanges, "  -- %#llx : %#llx\n",
809                    portIter->first.start, portIter->first.end);
810        }
811    }
812
813    return ranges;
814}
815
816bool
817Bus::isSnooping() const
818{
819    // in essence, answer the question if there are snooping ports
820    return !snoopPorts.empty();
821}
822
823unsigned
824Bus::findBlockSize()
825{
826    if (cachedBlockSizeValid)
827        return cachedBlockSize;
828
829    unsigned max_bs = 0;
830
831    PortIter p_end = portMap.end();
832    for (PortIter p_iter = portMap.begin(); p_iter != p_end; p_iter++) {
833        unsigned tmp_bs = masterPorts[p_iter->second]->peerBlockSize();
834        if (tmp_bs > max_bs)
835            max_bs = tmp_bs;
836    }
837
838    for (SlavePortConstIter s = snoopPorts.begin(); s != snoopPorts.end();
839         ++s) {
840        unsigned tmp_bs = (*s)->peerBlockSize();
841        if (tmp_bs > max_bs)
842            max_bs = tmp_bs;
843    }
844    if (max_bs == 0)
845        max_bs = defaultBlockSize;
846
847    if (max_bs != 64)
848        warn_once("Blocksize found to not be 64... hmm... probably not.\n");
849    cachedBlockSize = max_bs;
850    cachedBlockSizeValid = true;
851    return max_bs;
852}
853
854
855unsigned int
856Bus::drain(Event * de)
857{
858    //We should check that we're not "doing" anything, and that noone is
859    //waiting. We might be idle but have someone waiting if the device we
860    //contacted for a retry didn't actually retry.
861    if (!retryList.empty() || (curTick() < tickNextIdle &&
862                               busIdleEvent.scheduled())) {
863        drainEvent = de;
864        return 1;
865    }
866    return 0;
867}
868
869void
870Bus::startup()
871{
872    if (tickNextIdle < curTick())
873        tickNextIdle = (curTick() / clock) * clock + clock;
874}
875
876Bus *
877BusParams::create()
878{
879    return new Bus(this);
880}
881