xbar.cc revision 9716
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 SrcType, typename DstType>
160BaseBus::Layer<SrcType,DstType>::Layer(DstType& _port, BaseBus& _bus,
161                                       const std::string& _name) :
162    port(_port), bus(_bus), _name(_name), state(IDLE), drainManager(NULL),
163    retryingPort(NULL), waitingForPeer(NULL),
164    releaseEvent(this)
165{
166}
167
168template <typename SrcType, typename DstType>
169void BaseBus::Layer<SrcType,DstType>::occupyLayer(Tick until)
170{
171    // ensure the state is busy at this point, as the bus should
172    // transition from idle as soon as it has decided to forward the
173    // packet to prevent any follow-on calls to sendTiming seeing an
174    // unoccupied bus
175    assert(state == BUSY);
176
177    // until should never be 0 as express snoops never occupy the bus
178    assert(until != 0);
179    bus.schedule(releaseEvent, until);
180
181    // account for the occupied ticks
182    occupancy += until - curTick();
183
184    DPRINTF(BaseBus, "The bus is now busy from tick %d to %d\n",
185            curTick(), until);
186}
187
188template <typename SrcType, typename DstType>
189bool
190BaseBus::Layer<SrcType,DstType>::tryTiming(SrcType* src_port)
191{
192    // if we are in the retry state, we will not see anything but the
193    // retrying port (or in the case of the snoop ports the snoop
194    // response port that mirrors the actual slave port) as we leave
195    // this state again in zero time if the peer does not immediately
196    // call the bus when receiving the retry
197
198    // first we see if the layer is busy, next we check if the
199    // destination port is already engaged in a transaction waiting
200    // for a retry from the peer
201    if (state == BUSY || waitingForPeer != NULL) {
202        // the port should not be waiting already
203        assert(std::find(waitingForLayer.begin(), waitingForLayer.end(),
204                         src_port) == waitingForLayer.end());
205
206        // put the port at the end of the retry list waiting for the
207        // layer to be freed up (and in the case of a busy peer, for
208        // that transaction to go through, and then the bus to free
209        // up)
210        waitingForLayer.push_back(src_port);
211        return false;
212    }
213
214    // update the state to busy
215    state = BUSY;
216
217    // reset the retrying port
218    retryingPort = NULL;
219
220    return true;
221}
222
223template <typename SrcType, typename DstType>
224void
225BaseBus::Layer<SrcType,DstType>::succeededTiming(Tick busy_time)
226{
227    // we should have gone from idle or retry to busy in the tryTiming
228    // test
229    assert(state == BUSY);
230
231    // occupy the bus accordingly
232    occupyLayer(busy_time);
233}
234
235template <typename SrcType, typename DstType>
236void
237BaseBus::Layer<SrcType,DstType>::failedTiming(SrcType* src_port,
238                                              Tick busy_time)
239{
240    // ensure no one got in between and tried to send something to
241    // this port
242    assert(waitingForPeer == NULL);
243
244    // if the source port is the current retrying one or not, we have
245    // failed in forwarding and should track that we are now waiting
246    // for the peer to send a retry
247    waitingForPeer = src_port;
248
249    // we should have gone from idle or retry to busy in the tryTiming
250    // test
251    assert(state == BUSY);
252
253    // occupy the bus accordingly
254    occupyLayer(busy_time);
255}
256
257template <typename SrcType, typename DstType>
258void
259BaseBus::Layer<SrcType,DstType>::releaseLayer()
260{
261    // releasing the bus means we should now be idle
262    assert(state == BUSY);
263    assert(!releaseEvent.scheduled());
264
265    // update the state
266    state = IDLE;
267
268    // bus layer is now idle, so if someone is waiting we can retry
269    if (!waitingForLayer.empty()) {
270        retryWaiting();
271    } else if (waitingForPeer == NULL && drainManager) {
272        DPRINTF(Drain, "Bus done draining, signaling drain manager\n");
273        //If we weren't able to drain before, do it now.
274        drainManager->signalDrainDone();
275        // Clear the drain event once we're done with it.
276        drainManager = NULL;
277    }
278}
279
280template <typename SrcType, typename DstType>
281void
282BaseBus::Layer<SrcType,DstType>::retryWaiting()
283{
284    // this should never be called with no one waiting
285    assert(!waitingForLayer.empty());
286
287    // we always go to retrying from idle
288    assert(state == IDLE);
289
290    // update the state
291    state = RETRY;
292
293    // set the retrying port to the front of the retry list and pop it
294    // off the list
295    assert(retryingPort == NULL);
296    retryingPort = waitingForLayer.front();
297    waitingForLayer.pop_front();
298
299    // tell the port to retry, which in some cases ends up calling the
300    // bus
301    retryingPort->sendRetry();
302
303    // If the bus is still in the retry state, sendTiming wasn't
304    // called in zero time (e.g. the cache does this), burn a cycle
305    if (state == RETRY) {
306        // update the state to busy and reset the retrying port, we
307        // have done our bit and sent the retry
308        state = BUSY;
309        retryingPort = NULL;
310
311        // occupy the bus layer until the next cycle ends
312        occupyLayer(bus.clockEdge(Cycles(1)));
313    }
314}
315
316template <typename SrcType, typename DstType>
317void
318BaseBus::Layer<SrcType,DstType>::recvRetry()
319{
320    // we should never get a retry without having failed to forward
321    // something to this port
322    assert(waitingForPeer != NULL);
323
324    // add the port where the failed packet originated to the front of
325    // the waiting ports for the layer, this allows us to call retry
326    // on the port immediately if the bus layer is idle
327    waitingForLayer.push_front(waitingForPeer);
328
329    // we are no longer waiting for the peer
330    waitingForPeer = NULL;
331
332    // if the bus layer is idle, retry this port straight away, if we
333    // are busy, then simply let the port wait for its turn
334    if (state == IDLE) {
335        retryWaiting();
336    } else {
337        assert(state == BUSY);
338    }
339}
340
341PortID
342BaseBus::findPort(Addr addr)
343{
344    // we should never see any address lookups before we've got the
345    // ranges of all connected slave modules
346    assert(gotAllAddrRanges);
347
348    // Check the cache
349    PortID dest_id = checkPortCache(addr);
350    if (dest_id != InvalidPortID)
351        return dest_id;
352
353    // Check the address map interval tree
354    PortMapConstIter i = portMap.find(addr);
355    if (i != portMap.end()) {
356        dest_id = i->second;
357        updatePortCache(dest_id, i->first);
358        return dest_id;
359    }
360
361    // Check if this matches the default range
362    if (useDefaultRange) {
363        if (defaultRange.contains(addr)) {
364            DPRINTF(BusAddrRanges, "  found addr %#llx on default\n",
365                    addr);
366            return defaultPortID;
367        }
368    } else if (defaultPortID != InvalidPortID) {
369        DPRINTF(BusAddrRanges, "Unable to find destination for addr %#llx, "
370                "will use default port\n", addr);
371        return defaultPortID;
372    }
373
374    // we should use the range for the default port and it did not
375    // match, or the default port is not set
376    fatal("Unable to find destination for addr %#llx on bus %s\n", addr,
377          name());
378}
379
380/** Function called by the port when the bus is receiving a range change.*/
381void
382BaseBus::recvRangeChange(PortID master_port_id)
383{
384    DPRINTF(BusAddrRanges, "Received range change from slave port %s\n",
385            masterPorts[master_port_id]->getSlavePort().name());
386
387    // remember that we got a range from this master port and thus the
388    // connected slave module
389    gotAddrRanges[master_port_id] = true;
390
391    // update the global flag
392    if (!gotAllAddrRanges) {
393        // take a logical AND of all the ports and see if we got
394        // ranges from everyone
395        gotAllAddrRanges = true;
396        std::vector<bool>::const_iterator r = gotAddrRanges.begin();
397        while (gotAllAddrRanges &&  r != gotAddrRanges.end()) {
398            gotAllAddrRanges &= *r++;
399        }
400        if (gotAllAddrRanges)
401            DPRINTF(BusAddrRanges, "Got address ranges from all slaves\n");
402    }
403
404    // note that we could get the range from the default port at any
405    // point in time, and we cannot assume that the default range is
406    // set before the other ones are, so we do additional checks once
407    // all ranges are provided
408    if (master_port_id == defaultPortID) {
409        // only update if we are indeed checking ranges for the
410        // default port since the port might not have a valid range
411        // otherwise
412        if (useDefaultRange) {
413            AddrRangeList ranges = masterPorts[master_port_id]->getAddrRanges();
414
415            if (ranges.size() != 1)
416                fatal("Bus %s may only have a single default range",
417                      name());
418
419            defaultRange = ranges.front();
420        }
421    } else {
422        // the ports are allowed to update their address ranges
423        // dynamically, so remove any existing entries
424        if (gotAddrRanges[master_port_id]) {
425            for (PortMapIter p = portMap.begin(); p != portMap.end(); ) {
426                if (p->second == master_port_id)
427                    // erasing invalidates the iterator, so advance it
428                    // before the deletion takes place
429                    portMap.erase(p++);
430                else
431                    p++;
432            }
433        }
434
435        AddrRangeList ranges = masterPorts[master_port_id]->getAddrRanges();
436
437        for (AddrRangeConstIter r = ranges.begin(); r != ranges.end(); ++r) {
438            DPRINTF(BusAddrRanges, "Adding range %s for id %d\n",
439                    r->to_string(), master_port_id);
440            if (portMap.insert(*r, master_port_id) == portMap.end()) {
441                PortID conflict_id = portMap.find(*r)->second;
442                fatal("%s has two ports with same range:\n\t%s\n\t%s\n",
443                      name(),
444                      masterPorts[master_port_id]->getSlavePort().name(),
445                      masterPorts[conflict_id]->getSlavePort().name());
446            }
447        }
448    }
449
450    // if we have received ranges from all our neighbouring slave
451    // modules, go ahead and tell our connected master modules in
452    // turn, this effectively assumes a tree structure of the system
453    if (gotAllAddrRanges) {
454        DPRINTF(BusAddrRanges, "Aggregating bus ranges\n");
455        busRanges.clear();
456
457        // start out with the default range
458        if (useDefaultRange) {
459            if (!gotAddrRanges[defaultPortID])
460                fatal("Bus %s uses default range, but none provided",
461                      name());
462
463            busRanges.push_back(defaultRange);
464            DPRINTF(BusAddrRanges, "-- Adding default %s\n",
465                    defaultRange.to_string());
466        }
467
468        // merge all interleaved ranges and add any range that is not
469        // a subset of the default range
470        std::vector<AddrRange> intlv_ranges;
471        for (AddrRangeMap<PortID>::const_iterator r = portMap.begin();
472             r != portMap.end(); ++r) {
473            // if the range is interleaved then save it for now
474            if (r->first.interleaved()) {
475                // if we already got interleaved ranges that are not
476                // part of the same range, then first do a merge
477                // before we add the new one
478                if (!intlv_ranges.empty() &&
479                    !intlv_ranges.back().mergesWith(r->first)) {
480                    DPRINTF(BusAddrRanges, "-- Merging range from %d ranges\n",
481                            intlv_ranges.size());
482                    AddrRange merged_range(intlv_ranges);
483                    // next decide if we keep the merged range or not
484                    if (!(useDefaultRange &&
485                          merged_range.isSubset(defaultRange))) {
486                        busRanges.push_back(merged_range);
487                        DPRINTF(BusAddrRanges, "-- Adding merged range %s\n",
488                                merged_range.to_string());
489                    }
490                    intlv_ranges.clear();
491                }
492                intlv_ranges.push_back(r->first);
493            } else {
494                // keep the current range if not a subset of the default
495                if (!(useDefaultRange &&
496                      r->first.isSubset(defaultRange))) {
497                    busRanges.push_back(r->first);
498                    DPRINTF(BusAddrRanges, "-- Adding range %s\n",
499                            r->first.to_string());
500                }
501            }
502        }
503
504        // if there is still interleaved ranges waiting to be merged,
505        // go ahead and do it
506        if (!intlv_ranges.empty()) {
507            DPRINTF(BusAddrRanges, "-- Merging range from %d ranges\n",
508                    intlv_ranges.size());
509            AddrRange merged_range(intlv_ranges);
510            if (!(useDefaultRange && merged_range.isSubset(defaultRange))) {
511                busRanges.push_back(merged_range);
512                DPRINTF(BusAddrRanges, "-- Adding merged range %s\n",
513                        merged_range.to_string());
514            }
515        }
516
517        // also check that no range partially overlaps with the
518        // default range, this has to be done after all ranges are set
519        // as there are no guarantees for when the default range is
520        // update with respect to the other ones
521        if (useDefaultRange) {
522            for (AddrRangeConstIter r = busRanges.begin();
523                 r != busRanges.end(); ++r) {
524                // see if the new range is partially
525                // overlapping the default range
526                if (r->intersects(defaultRange) &&
527                    !r->isSubset(defaultRange))
528                    fatal("Range %s intersects the "                    \
529                          "default range of %s but is not a "           \
530                          "subset\n", r->to_string(), name());
531            }
532        }
533
534        // tell all our neighbouring master ports that our address
535        // ranges have changed
536        for (SlavePortConstIter s = slavePorts.begin(); s != slavePorts.end();
537             ++s)
538            (*s)->sendRangeChange();
539    }
540
541    clearPortCache();
542}
543
544AddrRangeList
545BaseBus::getAddrRanges() const
546{
547    // we should never be asked without first having sent a range
548    // change, and the latter is only done once we have all the ranges
549    // of the connected devices
550    assert(gotAllAddrRanges);
551
552    // at the moment, this never happens, as there are no cycles in
553    // the range queries and no devices on the master side of a bus
554    // (CPU, cache, bridge etc) actually care about the ranges of the
555    // ports they are connected to
556
557    DPRINTF(BusAddrRanges, "Received address range request\n");
558
559    return busRanges;
560}
561
562unsigned
563BaseBus::deviceBlockSize() const
564{
565    return blockSize;
566}
567
568void
569BaseBus::regStats()
570{
571    using namespace Stats;
572
573    transDist
574        .init(MemCmd::NUM_MEM_CMDS)
575        .name(name() + ".trans_dist")
576        .desc("Transaction distribution")
577        .flags(nozero);
578
579    // get the string representation of the commands
580    for (int i = 0; i < MemCmd::NUM_MEM_CMDS; i++) {
581        MemCmd cmd(i);
582        const std::string &cstr = cmd.toString();
583        transDist.subname(i, cstr);
584    }
585
586    pktCount
587        .init(slavePorts.size(), masterPorts.size())
588        .name(name() + ".pkt_count")
589        .desc("Packet count per connected master and slave (bytes)")
590        .flags(total | nozero | nonan);
591
592    totPktSize
593        .init(slavePorts.size(), masterPorts.size())
594        .name(name() + ".tot_pkt_size")
595        .desc("Cumulative packet size per connected master and slave (bytes)")
596        .flags(total | nozero | nonan);
597
598    // both the packet count and total size are two-dimensional
599    // vectors, indexed by slave port id and master port id, thus the
600    // neighbouring master and slave, they do not differentiate what
601    // came from the master and was forwarded to the slave (requests
602    // and snoop responses) and what came from the slave and was
603    // forwarded to the master (responses and snoop requests)
604    for (int i = 0; i < slavePorts.size(); i++) {
605        pktCount.subname(i, slavePorts[i]->getMasterPort().name());
606        totPktSize.subname(i, slavePorts[i]->getMasterPort().name());
607        for (int j = 0; j < masterPorts.size(); j++) {
608            pktCount.ysubname(j, masterPorts[j]->getSlavePort().name());
609            totPktSize.ysubname(j, masterPorts[j]->getSlavePort().name());
610        }
611    }
612}
613
614template <typename SrcType, typename DstType>
615unsigned int
616BaseBus::Layer<SrcType,DstType>::drain(DrainManager *dm)
617{
618    //We should check that we're not "doing" anything, and that noone is
619    //waiting. We might be idle but have someone waiting if the device we
620    //contacted for a retry didn't actually retry.
621    if (state != IDLE) {
622        DPRINTF(Drain, "Bus not drained\n");
623        drainManager = dm;
624        return 1;
625    }
626    return 0;
627}
628
629template <typename SrcType, typename DstType>
630void
631BaseBus::Layer<SrcType,DstType>::regStats()
632{
633    using namespace Stats;
634
635    occupancy
636        .name(name() + ".occupancy")
637        .desc("Layer occupancy (ticks)")
638        .flags(nozero);
639
640    utilization
641        .name(name() + ".utilization")
642        .desc("Layer utilization (%)")
643        .precision(1)
644        .flags(nozero);
645
646    utilization = 100 * occupancy / simTicks;
647}
648
649/**
650 * Bus layer template instantiations. Could be removed with _impl.hh
651 * file, but since there are only two given options (MasterPort and
652 * SlavePort) it seems a bit excessive at this point.
653 */
654template class BaseBus::Layer<SlavePort,MasterPort>;
655template class BaseBus::Layer<MasterPort,SlavePort>;
656