xbar.cc revision 9405
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 "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
132Tick
133BaseBus::calcPacketTiming(PacketPtr pkt)
134{
135    // determine the current time rounded to the closest following
136    // clock edge
137    Tick now = nextCycle();
138
139    Tick headerTime = now + headerCycles * clock;
140
141    // The packet will be sent. Figure out how long it occupies the bus, and
142    // how much of that time is for the first "word", aka bus width.
143    int numCycles = 0;
144    if (pkt->hasData()) {
145        // If a packet has data, it needs ceil(size/width) cycles to send it
146        int dataSize = pkt->getSize();
147        numCycles += dataSize/width;
148        if (dataSize % width)
149            numCycles++;
150    }
151
152    // The first word will be delivered after the current tick, the delivery
153    // of the address if any, and one bus cycle to deliver the data
154    pkt->firstWordTime = headerTime + clock;
155
156    pkt->finishTime = headerTime + numCycles * clock;
157
158    return headerTime;
159}
160
161template <typename PortClass>
162BaseBus::Layer<PortClass>::Layer(BaseBus& _bus, const std::string& _name,
163                                 Tick _clock) :
164    Drainable(),
165    bus(_bus), _name(_name), state(IDLE), clock(_clock), drainManager(NULL),
166    releaseEvent(this)
167{
168}
169
170template <typename PortClass>
171void BaseBus::Layer<PortClass>::occupyLayer(Tick until)
172{
173    // ensure the state is busy or in retry and never idle at this
174    // point, as the bus should transition from idle as soon as it has
175    // decided to forward the packet to prevent any follow-on calls to
176    // sendTiming seeing an unoccupied bus
177    assert(state != IDLE);
178
179    // note that we do not change the bus state here, if we are going
180    // from idle to busy it is handled by tryTiming, and if we
181    // are in retry we should remain in retry such that
182    // succeededTiming still sees the accurate state
183
184    // until should never be 0 as express snoops never occupy the bus
185    assert(until != 0);
186    bus.schedule(releaseEvent, until);
187
188    DPRINTF(BaseBus, "The bus is now busy from tick %d to %d\n",
189            curTick(), until);
190}
191
192template <typename PortClass>
193bool
194BaseBus::Layer<PortClass>::tryTiming(PortClass* port)
195{
196    // first we see if the bus is busy, next we check if we are in a
197    // retry with a port other than the current one
198    if (state == BUSY || (state == RETRY && port != retryList.front())) {
199        // put the port at the end of the retry list
200        retryList.push_back(port);
201        return false;
202    }
203
204    // update the state which is shared for request, response and
205    // snoop responses, if we were idle we are now busy, if we are in
206    // a retry, then do not change
207    if (state == IDLE)
208        state = BUSY;
209
210    return true;
211}
212
213template <typename PortClass>
214void
215BaseBus::Layer<PortClass>::succeededTiming(Tick busy_time)
216{
217    // if a retrying port succeeded, also take it off the retry list
218    if (state == RETRY) {
219        DPRINTF(BaseBus, "Remove retry from list %s\n",
220                retryList.front()->name());
221        retryList.pop_front();
222        state = BUSY;
223    }
224
225    // we should either have gone from idle to busy in the
226    // tryTiming test, or just gone from a retry to busy
227    assert(state == BUSY);
228
229    // occupy the bus accordingly
230    occupyLayer(busy_time);
231}
232
233template <typename PortClass>
234void
235BaseBus::Layer<PortClass>::failedTiming(PortClass* port, Tick busy_time)
236{
237    // if we are not in a retry, i.e. busy (but never idle), or we are
238    // in a retry but not for the current port, then add the port at
239    // the end of the retry list
240    if (state != RETRY || port != retryList.front()) {
241        retryList.push_back(port);
242    }
243
244    // even if we retried the current one and did not succeed,
245    // we are no longer retrying but instead busy
246    state = BUSY;
247
248    // occupy the bus accordingly
249    occupyLayer(busy_time);
250}
251
252template <typename PortClass>
253void
254BaseBus::Layer<PortClass>::releaseLayer()
255{
256    // releasing the bus means we should now be idle
257    assert(state == BUSY);
258    assert(!releaseEvent.scheduled());
259
260    // update the state
261    state = IDLE;
262
263    // bus is now idle, so if someone is waiting we can retry
264    if (!retryList.empty()) {
265        // note that we block (return false on recvTiming) both
266        // because the bus is busy and because the destination is
267        // busy, and in the latter case the bus may be released before
268        // we see a retry from the destination
269        retryWaiting();
270    } else if (drainManager) {
271        DPRINTF(Drain, "Bus done draining, signaling drain manager\n");
272        //If we weren't able to drain before, do it now.
273        drainManager->signalDrainDone();
274        // Clear the drain event once we're done with it.
275        drainManager = NULL;
276    }
277}
278
279template <typename PortClass>
280void
281BaseBus::Layer<PortClass>::retryWaiting()
282{
283    // this should never be called with an empty retry list
284    assert(!retryList.empty());
285
286    // we always go to retrying from idle
287    assert(state == IDLE);
288
289    // update the state which is shared for request, response and
290    // snoop responses
291    state = RETRY;
292
293    // note that we might have blocked on the receiving port being
294    // busy (rather than the bus itself) and now call retry before the
295    // destination called retry on the bus
296    retryList.front()->sendRetry();
297
298    // If the bus is still in the retry state, sendTiming wasn't
299    // called in zero time (e.g. the cache does this)
300    if (state == RETRY) {
301        retryList.pop_front();
302
303        //Burn a cycle for the missed grant.
304
305        // update the state which is shared for request, response and
306        // snoop responses
307        state = BUSY;
308
309        // determine the current time rounded to the closest following
310        // clock edge
311        Tick now = bus.nextCycle();
312
313        occupyLayer(now + clock);
314    }
315}
316
317template <typename PortClass>
318void
319BaseBus::Layer<PortClass>::recvRetry()
320{
321    // we got a retry from a peer that we tried to send something to
322    // and failed, but we sent it on the account of someone else, and
323    // that source port should be on our retry list, however if the
324    // bus layer is released before this happens and the retry (from
325    // the bus point of view) is successful then this no longer holds
326    // and we could in fact have an empty retry list
327    if (retryList.empty())
328        return;
329
330    // if the bus layer is idle
331    if (state == IDLE) {
332        // note that we do not care who told us to retry at the moment, we
333        // merely let the first one on the retry list go
334        retryWaiting();
335    }
336}
337
338PortID
339BaseBus::findPort(Addr addr)
340{
341    // we should never see any address lookups before we've got the
342    // ranges of all connected slave modules
343    assert(gotAllAddrRanges);
344
345    // Check the cache
346    PortID dest_id = checkPortCache(addr);
347    if (dest_id != InvalidPortID)
348        return dest_id;
349
350    // Check the address map interval tree
351    PortMapConstIter i = portMap.find(addr);
352    if (i != portMap.end()) {
353        dest_id = i->second;
354        updatePortCache(dest_id, i->first);
355        return dest_id;
356    }
357
358    // Check if this matches the default range
359    if (useDefaultRange) {
360        if (defaultRange.contains(addr)) {
361            DPRINTF(BusAddrRanges, "  found addr %#llx on default\n",
362                    addr);
363            return defaultPortID;
364        }
365    } else if (defaultPortID != InvalidPortID) {
366        DPRINTF(BusAddrRanges, "Unable to find destination for addr %#llx, "
367                "will use default port\n", addr);
368        return defaultPortID;
369    }
370
371    // we should use the range for the default port and it did not
372    // match, or the default port is not set
373    fatal("Unable to find destination for addr %#llx on bus %s\n", addr,
374          name());
375}
376
377/** Function called by the port when the bus is receiving a range change.*/
378void
379BaseBus::recvRangeChange(PortID master_port_id)
380{
381    // remember that we got a range from this master port and thus the
382    // connected slave module
383    gotAddrRanges[master_port_id] = true;
384
385    // update the global flag
386    if (!gotAllAddrRanges) {
387        // take a logical AND of all the ports and see if we got
388        // ranges from everyone
389        gotAllAddrRanges = true;
390        std::vector<bool>::const_iterator r = gotAddrRanges.begin();
391        while (gotAllAddrRanges &&  r != gotAddrRanges.end()) {
392            gotAllAddrRanges &= *r++;
393        }
394    }
395
396    // note that we could get the range from the default port at any
397    // point in time, and we cannot assume that the default range is
398    // set before the other ones are, so we do additional checks once
399    // all ranges are provided
400    DPRINTF(BusAddrRanges, "received RangeChange from slave port %s\n",
401            masterPorts[master_port_id]->getSlavePort().name());
402
403    if (master_port_id == defaultPortID) {
404        // only update if we are indeed checking ranges for the
405        // default port since the port might not have a valid range
406        // otherwise
407        if (useDefaultRange) {
408            AddrRangeList ranges = masterPorts[master_port_id]->getAddrRanges();
409
410            if (ranges.size() != 1)
411                fatal("Bus %s may only have a single default range",
412                      name());
413
414            defaultRange = ranges.front();
415        }
416    } else {
417        // the ports are allowed to update their address ranges
418        // dynamically, so remove any existing entries
419        if (gotAddrRanges[master_port_id]) {
420            for (PortMapIter p = portMap.begin(); p != portMap.end(); ) {
421                if (p->second == master_port_id)
422                    // erasing invalidates the iterator, so advance it
423                    // before the deletion takes place
424                    portMap.erase(p++);
425                else
426                    p++;
427            }
428        }
429
430        AddrRangeList ranges = masterPorts[master_port_id]->getAddrRanges();
431
432        for (AddrRangeConstIter r = ranges.begin(); r != ranges.end(); ++r) {
433            DPRINTF(BusAddrRanges, "Adding range %s for id %d\n",
434                    r->to_string(), master_port_id);
435            if (portMap.insert(*r, master_port_id) == portMap.end()) {
436                PortID conflict_id = portMap.find(*r)->second;
437                fatal("%s has two ports with same range:\n\t%s\n\t%s\n",
438                      name(),
439                      masterPorts[master_port_id]->getSlavePort().name(),
440                      masterPorts[conflict_id]->getSlavePort().name());
441            }
442        }
443    }
444
445    // if we have received ranges from all our neighbouring slave
446    // modules, go ahead and tell our connected master modules in
447    // turn, this effectively assumes a tree structure of the system
448    if (gotAllAddrRanges) {
449        // also check that no range partially overlaps with the
450        // default range, this has to be done after all ranges are set
451        // as there are no guarantees for when the default range is
452        // update with respect to the other ones
453        if (useDefaultRange) {
454            for (PortID port_id = 0; port_id < masterPorts.size(); ++port_id) {
455                if (port_id == defaultPortID) {
456                    if (!gotAddrRanges[port_id])
457                        fatal("Bus %s uses default range, but none provided",
458                              name());
459                } else {
460                    AddrRangeList ranges =
461                        masterPorts[port_id]->getAddrRanges();
462
463                    for (AddrRangeConstIter r = ranges.begin();
464                         r != ranges.end(); ++r) {
465                        // see if the new range is partially
466                        // overlapping the default range
467                        if (r->intersects(defaultRange) &&
468                            !r->isSubset(defaultRange))
469                            fatal("Range %s intersects the " \
470                                  "default range of %s but is not a " \
471                                  "subset\n", r->to_string(), name());
472                    }
473                }
474            }
475        }
476
477        // tell all our neighbouring master ports that our address
478        // ranges have changed
479        for (SlavePortConstIter s = slavePorts.begin(); s != slavePorts.end();
480             ++s)
481            (*s)->sendRangeChange();
482    }
483
484    clearPortCache();
485}
486
487AddrRangeList
488BaseBus::getAddrRanges() const
489{
490    // we should never be asked without first having sent a range
491    // change, and the latter is only done once we have all the ranges
492    // of the connected devices
493    assert(gotAllAddrRanges);
494
495    DPRINTF(BusAddrRanges, "received address range request, returning:\n");
496
497    // start out with the default range
498    AddrRangeList ranges;
499    ranges.push_back(defaultRange);
500    DPRINTF(BusAddrRanges, "  -- %s DEFAULT\n", defaultRange.to_string());
501
502    // add any range that is not a subset of the default range
503    for (PortMapConstIter p = portMap.begin(); p != portMap.end(); ++p) {
504        if (useDefaultRange && p->first.isSubset(defaultRange)) {
505            DPRINTF(BusAddrRanges, "  -- %s is a SUBSET\n",
506                    p->first.to_string());
507        } else {
508            ranges.push_back(p->first);
509            DPRINTF(BusAddrRanges, "  -- %s\n", p->first.to_string());
510        }
511    }
512
513    return ranges;
514}
515
516unsigned
517BaseBus::deviceBlockSize() const
518{
519    return blockSize;
520}
521
522template <typename PortClass>
523unsigned int
524BaseBus::Layer<PortClass>::drain(DrainManager *dm)
525{
526    //We should check that we're not "doing" anything, and that noone is
527    //waiting. We might be idle but have someone waiting if the device we
528    //contacted for a retry didn't actually retry.
529    if (!retryList.empty() || state != IDLE) {
530        DPRINTF(Drain, "Bus not drained\n");
531        drainManager = dm;
532        return 1;
533    }
534    return 0;
535}
536
537/**
538 * Bus layer template instantiations. Could be removed with _impl.hh
539 * file, but since there are only two given options (MasterPort and
540 * SlavePort) it seems a bit excessive at this point.
541 */
542template class BaseBus::Layer<SlavePort>;
543template class BaseBus::Layer<MasterPort>;
544