xbar.cc revision 9648
1/*
2 * Copyright (c) 2011-2013 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 "debug/Drain.hh"
55#include "mem/bus.hh"
56
57BaseBus::BaseBus(const BaseBusParams *p)
58    : MemObject(p),
59      headerCycles(p->header_cycles), width(p->width),
60      gotAddrRanges(p->port_default_connection_count +
61                          p->port_master_connection_count, false),
62      gotAllAddrRanges(false), defaultPortID(InvalidPortID),
63      useDefaultRange(p->use_default_range),
64      blockSize(p->block_size)
65{}
66
67BaseBus::~BaseBus()
68{
69    for (MasterPortIter m = masterPorts.begin(); m != masterPorts.end();
70         ++m) {
71        delete *m;
72    }
73
74    for (SlavePortIter s = slavePorts.begin(); s != slavePorts.end();
75         ++s) {
76        delete *s;
77    }
78}
79
80void
81BaseBus::init()
82{
83    // determine the maximum peer block size, look at both the
84    // connected master and slave modules
85    uint32_t peer_block_size = 0;
86
87    for (MasterPortConstIter m = masterPorts.begin(); m != masterPorts.end();
88         ++m) {
89        peer_block_size = std::max((*m)->peerBlockSize(), peer_block_size);
90    }
91
92    for (SlavePortConstIter s = slavePorts.begin(); s != slavePorts.end();
93         ++s) {
94        peer_block_size = std::max((*s)->peerBlockSize(), peer_block_size);
95    }
96
97    // if the peers do not have a block size, use the default value
98    // set through the bus parameters
99    if (peer_block_size != 0)
100        blockSize = peer_block_size;
101
102    // check if the block size is a value known to work
103    if (!(blockSize == 16 || blockSize == 32 || blockSize == 64 ||
104          blockSize == 128))
105        warn_once("Block size is neither 16, 32, 64 or 128 bytes.\n");
106}
107
108BaseMasterPort &
109BaseBus::getMasterPort(const std::string &if_name, PortID idx)
110{
111    if (if_name == "master" && idx < masterPorts.size()) {
112        // the master port index translates directly to the vector position
113        return *masterPorts[idx];
114    } else  if (if_name == "default") {
115        return *masterPorts[defaultPortID];
116    } else {
117        return MemObject::getMasterPort(if_name, idx);
118    }
119}
120
121BaseSlavePort &
122BaseBus::getSlavePort(const std::string &if_name, PortID idx)
123{
124    if (if_name == "slave" && idx < slavePorts.size()) {
125        // the slave port index translates directly to the vector position
126        return *slavePorts[idx];
127    } else {
128        return MemObject::getSlavePort(if_name, idx);
129    }
130}
131
132void
133BaseBus::calcPacketTiming(PacketPtr pkt)
134{
135    // the bus will be called at a time that is not necessarily
136    // coinciding with its own clock, so start by determining how long
137    // until the next clock edge (could be zero)
138    Tick offset = clockEdge() - curTick();
139
140    // determine how many cycles are needed to send the data
141    unsigned dataCycles = pkt->hasData() ? divCeil(pkt->getSize(), width) : 0;
142
143    // before setting the bus delay fields of the packet, ensure that
144    // the delay from any previous bus has been accounted for
145    if (pkt->busFirstWordDelay != 0 || pkt->busLastWordDelay != 0)
146        panic("Packet %s already has bus delay (%d, %d) that should be "
147              "accounted for.\n", pkt->cmdString(), pkt->busFirstWordDelay,
148              pkt->busLastWordDelay);
149
150    // The first word will be delivered on the cycle after the header.
151    pkt->busFirstWordDelay = (headerCycles + 1) * clockPeriod() + offset;
152
153    // Note that currently busLastWordDelay can be smaller than
154    // busFirstWordDelay if the packet has no data
155    pkt->busLastWordDelay = (headerCycles + dataCycles) * clockPeriod() +
156        offset;
157}
158
159template <typename PortClass>
160BaseBus::Layer<PortClass>::Layer(BaseBus& _bus, const std::string& _name,
161                                 uint16_t num_dest_ports) :
162    Drainable(),
163    bus(_bus), _name(_name), state(IDLE), drainManager(NULL),
164    retryingPort(NULL), waitingForPeer(num_dest_ports, NULL),
165    releaseEvent(this)
166{
167}
168
169template <typename PortClass>
170void BaseBus::Layer<PortClass>::occupyLayer(Tick until)
171{
172    // ensure the state is busy at this point, as the bus should
173    // transition from idle as soon as it has decided to forward the
174    // packet to prevent any follow-on calls to sendTiming seeing an
175    // unoccupied bus
176    assert(state == BUSY);
177
178    // until should never be 0 as express snoops never occupy the bus
179    assert(until != 0);
180    bus.schedule(releaseEvent, until);
181
182    DPRINTF(BaseBus, "The bus is now busy from tick %d to %d\n",
183            curTick(), until);
184}
185
186template <typename PortClass>
187bool
188BaseBus::Layer<PortClass>::tryTiming(PortClass* port, PortID dest_port_id)
189{
190    // first we see if the bus is busy, next we check if we are in a
191    // retry with a port other than the current one, lastly we check
192    // if the destination port is already engaged in a transaction
193    // waiting for a retry from the peer
194    if (state == BUSY || (state == RETRY && port != retryingPort) ||
195        (dest_port_id != InvalidPortID &&
196         waitingForPeer[dest_port_id] != NULL)) {
197        // put the port at the end of the retry list waiting for the
198        // layer to be freed up (and in the case of a busy peer, for
199        // that transaction to go through, and then the bus to free
200        // up)
201        waitingForLayer.push_back(port);
202        return false;
203    }
204
205    // update the state to busy
206    state = BUSY;
207
208    // reset the retrying port
209    retryingPort = NULL;
210
211    return true;
212}
213
214template <typename PortClass>
215void
216BaseBus::Layer<PortClass>::succeededTiming(Tick busy_time)
217{
218    // we should have gone from idle or retry to busy in the tryTiming
219    // test
220    assert(state == BUSY);
221
222    // occupy the bus accordingly
223    occupyLayer(busy_time);
224}
225
226template <typename PortClass>
227void
228BaseBus::Layer<PortClass>::failedTiming(PortClass* src_port,
229                                        PortID dest_port_id, Tick busy_time)
230{
231    // ensure no one got in between and tried to send something to
232    // this port
233    assert(waitingForPeer[dest_port_id] == NULL);
234
235    // if the source port is the current retrying one or not, we have
236    // failed in forwarding and should track that we are now waiting
237    // for the peer to send a retry
238    waitingForPeer[dest_port_id] = src_port;
239
240    // we should have gone from idle or retry to busy in the tryTiming
241    // test
242    assert(state == BUSY);
243
244    // occupy the bus accordingly
245    occupyLayer(busy_time);
246}
247
248template <typename PortClass>
249void
250BaseBus::Layer<PortClass>::releaseLayer()
251{
252    // releasing the bus means we should now be idle
253    assert(state == BUSY);
254    assert(!releaseEvent.scheduled());
255
256    // update the state
257    state = IDLE;
258
259    // bus layer is now idle, so if someone is waiting we can retry
260    if (!waitingForLayer.empty()) {
261        retryWaiting();
262    } else if (drainManager) {
263        DPRINTF(Drain, "Bus done draining, signaling drain manager\n");
264        //If we weren't able to drain before, do it now.
265        drainManager->signalDrainDone();
266        // Clear the drain event once we're done with it.
267        drainManager = NULL;
268    }
269}
270
271template <typename PortClass>
272void
273BaseBus::Layer<PortClass>::retryWaiting()
274{
275    // this should never be called with no one waiting
276    assert(!waitingForLayer.empty());
277
278    // we always go to retrying from idle
279    assert(state == IDLE);
280
281    // update the state
282    state = RETRY;
283
284    // set the retrying port to the front of the retry list and pop it
285    // off the list
286    assert(retryingPort == NULL);
287    retryingPort = waitingForLayer.front();
288    waitingForLayer.pop_front();
289
290    // tell the port to retry, which in some cases ends up calling the
291    // bus
292    retryingPort->sendRetry();
293
294    // If the bus is still in the retry state, sendTiming wasn't
295    // called in zero time (e.g. the cache does this), burn a cycle
296    if (state == RETRY) {
297        // update the state to busy and reset the retrying port, we
298        // have done our bit and sent the retry
299        state = BUSY;
300        retryingPort = NULL;
301
302        // occupy the bus layer until the next cycle ends
303        occupyLayer(bus.clockEdge(Cycles(1)));
304    }
305}
306
307template <typename PortClass>
308void
309BaseBus::Layer<PortClass>::recvRetry(PortID port_id)
310{
311    // we should never get a retry without having failed to forward
312    // something to this port
313    assert(waitingForPeer[port_id] != NULL);
314
315    // find the port where the failed packet originated and remove the
316    // item from the waiting list
317    PortClass* retry_port = waitingForPeer[port_id];
318    waitingForPeer[port_id] = NULL;
319
320    // add this port at the front of the waiting ports for the layer,
321    // this allows us to call retry on the port immediately if the bus
322    // layer is idle
323    waitingForLayer.push_front(retry_port);
324
325    // if the bus layer is idle, retry this port straight away, if we
326    // are busy, then simply let the port wait for its turn
327    if (state == IDLE) {
328        retryWaiting();
329    } else {
330        assert(state == BUSY);
331    }
332}
333
334PortID
335BaseBus::findPort(Addr addr)
336{
337    // we should never see any address lookups before we've got the
338    // ranges of all connected slave modules
339    assert(gotAllAddrRanges);
340
341    // Check the cache
342    PortID dest_id = checkPortCache(addr);
343    if (dest_id != InvalidPortID)
344        return dest_id;
345
346    // Check the address map interval tree
347    PortMapConstIter i = portMap.find(addr);
348    if (i != portMap.end()) {
349        dest_id = i->second;
350        updatePortCache(dest_id, i->first);
351        return dest_id;
352    }
353
354    // Check if this matches the default range
355    if (useDefaultRange) {
356        if (defaultRange.contains(addr)) {
357            DPRINTF(BusAddrRanges, "  found addr %#llx on default\n",
358                    addr);
359            return defaultPortID;
360        }
361    } else if (defaultPortID != InvalidPortID) {
362        DPRINTF(BusAddrRanges, "Unable to find destination for addr %#llx, "
363                "will use default port\n", addr);
364        return defaultPortID;
365    }
366
367    // we should use the range for the default port and it did not
368    // match, or the default port is not set
369    fatal("Unable to find destination for addr %#llx on bus %s\n", addr,
370          name());
371}
372
373/** Function called by the port when the bus is receiving a range change.*/
374void
375BaseBus::recvRangeChange(PortID master_port_id)
376{
377    DPRINTF(BusAddrRanges, "Received range change from slave port %s\n",
378            masterPorts[master_port_id]->getSlavePort().name());
379
380    // remember that we got a range from this master port and thus the
381    // connected slave module
382    gotAddrRanges[master_port_id] = true;
383
384    // update the global flag
385    if (!gotAllAddrRanges) {
386        // take a logical AND of all the ports and see if we got
387        // ranges from everyone
388        gotAllAddrRanges = true;
389        std::vector<bool>::const_iterator r = gotAddrRanges.begin();
390        while (gotAllAddrRanges &&  r != gotAddrRanges.end()) {
391            gotAllAddrRanges &= *r++;
392        }
393        if (gotAllAddrRanges)
394            DPRINTF(BusAddrRanges, "Got address ranges from all slaves\n");
395    }
396
397    // note that we could get the range from the default port at any
398    // point in time, and we cannot assume that the default range is
399    // set before the other ones are, so we do additional checks once
400    // all ranges are provided
401    if (master_port_id == defaultPortID) {
402        // only update if we are indeed checking ranges for the
403        // default port since the port might not have a valid range
404        // otherwise
405        if (useDefaultRange) {
406            AddrRangeList ranges = masterPorts[master_port_id]->getAddrRanges();
407
408            if (ranges.size() != 1)
409                fatal("Bus %s may only have a single default range",
410                      name());
411
412            defaultRange = ranges.front();
413        }
414    } else {
415        // the ports are allowed to update their address ranges
416        // dynamically, so remove any existing entries
417        if (gotAddrRanges[master_port_id]) {
418            for (PortMapIter p = portMap.begin(); p != portMap.end(); ) {
419                if (p->second == master_port_id)
420                    // erasing invalidates the iterator, so advance it
421                    // before the deletion takes place
422                    portMap.erase(p++);
423                else
424                    p++;
425            }
426        }
427
428        AddrRangeList ranges = masterPorts[master_port_id]->getAddrRanges();
429
430        for (AddrRangeConstIter r = ranges.begin(); r != ranges.end(); ++r) {
431            DPRINTF(BusAddrRanges, "Adding range %s for id %d\n",
432                    r->to_string(), master_port_id);
433            if (portMap.insert(*r, master_port_id) == portMap.end()) {
434                PortID conflict_id = portMap.find(*r)->second;
435                fatal("%s has two ports with same range:\n\t%s\n\t%s\n",
436                      name(),
437                      masterPorts[master_port_id]->getSlavePort().name(),
438                      masterPorts[conflict_id]->getSlavePort().name());
439            }
440        }
441    }
442
443    // if we have received ranges from all our neighbouring slave
444    // modules, go ahead and tell our connected master modules in
445    // turn, this effectively assumes a tree structure of the system
446    if (gotAllAddrRanges) {
447        DPRINTF(BusAddrRanges, "Aggregating bus ranges\n");
448        busRanges.clear();
449
450        // start out with the default range
451        if (useDefaultRange) {
452            if (!gotAddrRanges[defaultPortID])
453                fatal("Bus %s uses default range, but none provided",
454                      name());
455
456            busRanges.push_back(defaultRange);
457            DPRINTF(BusAddrRanges, "-- Adding default %s\n",
458                    defaultRange.to_string());
459        }
460
461        // merge all interleaved ranges and add any range that is not
462        // a subset of the default range
463        std::vector<AddrRange> intlv_ranges;
464        for (AddrRangeMap<PortID>::const_iterator r = portMap.begin();
465             r != portMap.end(); ++r) {
466            // if the range is interleaved then save it for now
467            if (r->first.interleaved()) {
468                // if we already got interleaved ranges that are not
469                // part of the same range, then first do a merge
470                // before we add the new one
471                if (!intlv_ranges.empty() &&
472                    !intlv_ranges.back().mergesWith(r->first)) {
473                    DPRINTF(BusAddrRanges, "-- Merging range from %d ranges\n",
474                            intlv_ranges.size());
475                    AddrRange merged_range(intlv_ranges);
476                    // next decide if we keep the merged range or not
477                    if (!(useDefaultRange &&
478                          merged_range.isSubset(defaultRange))) {
479                        busRanges.push_back(merged_range);
480                        DPRINTF(BusAddrRanges, "-- Adding merged range %s\n",
481                                merged_range.to_string());
482                    }
483                    intlv_ranges.clear();
484                }
485                intlv_ranges.push_back(r->first);
486            } else {
487                // keep the current range if not a subset of the default
488                if (!(useDefaultRange &&
489                      r->first.isSubset(defaultRange))) {
490                    busRanges.push_back(r->first);
491                    DPRINTF(BusAddrRanges, "-- Adding range %s\n",
492                            r->first.to_string());
493                }
494            }
495        }
496
497        // if there is still interleaved ranges waiting to be merged,
498        // go ahead and do it
499        if (!intlv_ranges.empty()) {
500            DPRINTF(BusAddrRanges, "-- Merging range from %d ranges\n",
501                    intlv_ranges.size());
502            AddrRange merged_range(intlv_ranges);
503            if (!(useDefaultRange && merged_range.isSubset(defaultRange))) {
504                busRanges.push_back(merged_range);
505                DPRINTF(BusAddrRanges, "-- Adding merged range %s\n",
506                        merged_range.to_string());
507            }
508        }
509
510        // also check that no range partially overlaps with the
511        // default range, this has to be done after all ranges are set
512        // as there are no guarantees for when the default range is
513        // update with respect to the other ones
514        if (useDefaultRange) {
515            for (AddrRangeConstIter r = busRanges.begin();
516                 r != busRanges.end(); ++r) {
517                // see if the new range is partially
518                // overlapping the default range
519                if (r->intersects(defaultRange) &&
520                    !r->isSubset(defaultRange))
521                    fatal("Range %s intersects the "                    \
522                          "default range of %s but is not a "           \
523                          "subset\n", r->to_string(), name());
524            }
525        }
526
527        // tell all our neighbouring master ports that our address
528        // ranges have changed
529        for (SlavePortConstIter s = slavePorts.begin(); s != slavePorts.end();
530             ++s)
531            (*s)->sendRangeChange();
532    }
533
534    clearPortCache();
535}
536
537AddrRangeList
538BaseBus::getAddrRanges() const
539{
540    // we should never be asked without first having sent a range
541    // change, and the latter is only done once we have all the ranges
542    // of the connected devices
543    assert(gotAllAddrRanges);
544
545    // at the moment, this never happens, as there are no cycles in
546    // the range queries and no devices on the master side of a bus
547    // (CPU, cache, bridge etc) actually care about the ranges of the
548    // ports they are connected to
549
550    DPRINTF(BusAddrRanges, "Received address range request\n");
551
552    return busRanges;
553}
554
555unsigned
556BaseBus::deviceBlockSize() const
557{
558    return blockSize;
559}
560
561template <typename PortClass>
562unsigned int
563BaseBus::Layer<PortClass>::drain(DrainManager *dm)
564{
565    //We should check that we're not "doing" anything, and that noone is
566    //waiting. We might be idle but have someone waiting if the device we
567    //contacted for a retry didn't actually retry.
568    if (state != IDLE) {
569        DPRINTF(Drain, "Bus not drained\n");
570        drainManager = dm;
571        return 1;
572    }
573    return 0;
574}
575
576/**
577 * Bus layer template instantiations. Could be removed with _impl.hh
578 * file, but since there are only two given options (MasterPort and
579 * SlavePort) it seems a bit excessive at this point.
580 */
581template class BaseBus::Layer<SlavePort>;
582template class BaseBus::Layer<MasterPort>;
583