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