xbar.cc revision 9091
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/intmath.hh"
51#include "base/misc.hh"
52#include "base/trace.hh"
53#include "debug/Bus.hh"
54#include "debug/BusAddrRanges.hh"
55#include "mem/bus.hh"
56
57BaseBus::BaseBus(const BaseBusParams *p)
58    : MemObject(p), state(IDLE), clock(p->clock),
59      headerCycles(p->header_cycles), width(p->width),
60      drainEvent(NULL), busIdleEvent(this),
61      defaultPortID(InvalidPortID),
62      useDefaultRange(p->use_default_range),
63      defaultBlockSize(p->block_size),
64      cachedBlockSize(0), cachedBlockSizeValid(false)
65{
66    //width, clock period, and header cycles must be positive
67    if (width <= 0)
68        fatal("Bus width must be positive\n");
69    if (clock <= 0)
70        fatal("Bus clock period must be positive\n");
71    if (headerCycles <= 0)
72        fatal("Number of header cycles must be positive\n");
73}
74
75BaseBus::~BaseBus()
76{
77    for (MasterPortIter m = masterPorts.begin(); m != masterPorts.end();
78         ++m) {
79        delete *m;
80    }
81
82    for (SlavePortIter s = slavePorts.begin(); s != slavePorts.end();
83         ++s) {
84        delete *s;
85    }
86}
87
88MasterPort &
89BaseBus::getMasterPort(const std::string &if_name, int idx)
90{
91    if (if_name == "master" && idx < masterPorts.size()) {
92        // the master port index translates directly to the vector position
93        return *masterPorts[idx];
94    } else  if (if_name == "default") {
95        return *masterPorts[defaultPortID];
96    } else {
97        return MemObject::getMasterPort(if_name, idx);
98    }
99}
100
101SlavePort &
102BaseBus::getSlavePort(const std::string &if_name, int idx)
103{
104    if (if_name == "slave" && idx < slavePorts.size()) {
105        // the slave port index translates directly to the vector position
106        return *slavePorts[idx];
107    } else {
108        return MemObject::getSlavePort(if_name, idx);
109    }
110}
111
112Tick
113BaseBus::calcPacketTiming(PacketPtr pkt)
114{
115    // determine the current time rounded to the closest following
116    // clock edge
117    Tick now = divCeil(curTick(), clock) * clock;
118
119    Tick headerTime = now + headerCycles * clock;
120
121    // The packet will be sent. Figure out how long it occupies the bus, and
122    // how much of that time is for the first "word", aka bus width.
123    int numCycles = 0;
124    if (pkt->hasData()) {
125        // If a packet has data, it needs ceil(size/width) cycles to send it
126        int dataSize = pkt->getSize();
127        numCycles += dataSize/width;
128        if (dataSize % width)
129            numCycles++;
130    }
131
132    // The first word will be delivered after the current tick, the delivery
133    // of the address if any, and one bus cycle to deliver the data
134    pkt->firstWordTime = headerTime + clock;
135
136    pkt->finishTime = headerTime + numCycles * clock;
137
138    return headerTime;
139}
140
141void BaseBus::occupyBus(Tick until)
142{
143    // ensure the state is busy or in retry and never idle at this
144    // point, as the bus should transition from idle as soon as it has
145    // decided to forward the packet to prevent any follow-on calls to
146    // sendTiming seeing an unoccupied bus
147    assert(state != IDLE);
148
149    // note that we do not change the bus state here, if we are going
150    // from idle to busy it is handled by tryTiming, and if we
151    // are in retry we should remain in retry such that
152    // succeededTiming still sees the accurate state
153
154    // until should never be 0 as express snoops never occupy the bus
155    assert(until != 0);
156    schedule(busIdleEvent, until);
157
158    DPRINTF(BaseBus, "The bus is now busy from tick %d to %d\n",
159            curTick(), until);
160}
161
162bool
163BaseBus::tryTiming(Port* port)
164{
165    // first we see if the bus is busy, next we check if we are in a
166    // retry with a port other than the current one
167    if (state == BUSY || (state == RETRY && port != retryList.front())) {
168        // put the port at the end of the retry list
169        retryList.push_back(port);
170        return false;
171    }
172
173    // update the state which is shared for request, response and
174    // snoop responses, if we were idle we are now busy, if we are in
175    // a retry, then do not change
176    if (state == IDLE)
177        state = BUSY;
178
179    return true;
180}
181
182void
183BaseBus::succeededTiming(Tick busy_time)
184{
185    // if a retrying port succeeded, also take it off the retry list
186    if (state == RETRY) {
187        DPRINTF(BaseBus, "Remove retry from list %s\n",
188                retryList.front()->name());
189        retryList.pop_front();
190        state = BUSY;
191    }
192
193    // we should either have gone from idle to busy in the
194    // tryTiming test, or just gone from a retry to busy
195    assert(state == BUSY);
196
197    // occupy the bus accordingly
198    occupyBus(busy_time);
199}
200
201void
202BaseBus::failedTiming(SlavePort* port, Tick busy_time)
203{
204    // if we are not in a retry, i.e. busy (but never idle), or we are
205    // in a retry but not for the current port, then add the port at
206    // the end of the retry list
207    if (state != RETRY || port != retryList.front()) {
208        retryList.push_back(port);
209    }
210
211    // even if we retried the current one and did not succeed,
212    // we are no longer retrying but instead busy
213    state = BUSY;
214
215    // occupy the bus accordingly
216    occupyBus(busy_time);
217}
218
219void
220BaseBus::releaseBus()
221{
222    // releasing the bus means we should now be idle
223    assert(state == BUSY);
224    assert(!busIdleEvent.scheduled());
225
226    // update the state
227    state = IDLE;
228
229    // bus is now idle, so if someone is waiting we can retry
230    if (!retryList.empty()) {
231        // note that we block (return false on recvTiming) both
232        // because the bus is busy and because the destination is
233        // busy, and in the latter case the bus may be released before
234        // we see a retry from the destination
235        retryWaiting();
236    } else if (drainEvent) {
237        //If we weren't able to drain before, do it now.
238        drainEvent->process();
239        // Clear the drain event once we're done with it.
240        drainEvent = NULL;
241    }
242}
243
244void
245BaseBus::retryWaiting()
246{
247    // this should never be called with an empty retry list
248    assert(!retryList.empty());
249
250    // we always go to retrying from idle
251    assert(state == IDLE);
252
253    // update the state which is shared for request, response and
254    // snoop responses
255    state = RETRY;
256
257    // note that we might have blocked on the receiving port being
258    // busy (rather than the bus itself) and now call retry before the
259    // destination called retry on the bus
260    if (dynamic_cast<SlavePort*>(retryList.front()) != NULL)
261        (dynamic_cast<SlavePort*>(retryList.front()))->sendRetry();
262    else
263        (dynamic_cast<MasterPort*>(retryList.front()))->sendRetry();
264
265    // If the bus is still in the retry state, sendTiming wasn't
266    // called in zero time (e.g. the cache does this)
267    if (state == RETRY) {
268        retryList.pop_front();
269
270        //Burn a cycle for the missed grant.
271
272        // update the state which is shared for request, response and
273        // snoop responses
274        state = BUSY;
275
276        // determine the current time rounded to the closest following
277        // clock edge
278        Tick now = divCeil(curTick(), clock) * clock;
279
280        occupyBus(now + clock);
281    }
282}
283
284void
285BaseBus::recvRetry()
286{
287    // we got a retry from a peer that we tried to send something to
288    // and failed, but we sent it on the account of someone else, and
289    // that source port should be on our retry list, however if the
290    // bus is released before this happens and the retry (from the bus
291    // point of view) is successful then this no longer holds and we
292    // could in fact have an empty retry list
293    if (retryList.empty())
294        return;
295
296    // if the bus is idle
297    if (state == IDLE) {
298        // note that we do not care who told us to retry at the moment, we
299        // merely let the first one on the retry list go
300        retryWaiting();
301    }
302}
303
304PortID
305BaseBus::findPort(Addr addr)
306{
307    /* An interval tree would be a better way to do this. --ali. */
308    PortID dest_id = checkPortCache(addr);
309    if (dest_id != InvalidPortID)
310        return dest_id;
311
312    // Check normal port ranges
313    PortMapConstIter i = portMap.find(RangeSize(addr,1));
314    if (i != portMap.end()) {
315        dest_id = i->second;
316        updatePortCache(dest_id, i->first.start, i->first.end);
317        return dest_id;
318    }
319
320    // Check if this matches the default range
321    if (useDefaultRange) {
322        AddrRangeConstIter a_end = defaultRange.end();
323        for (AddrRangeConstIter i = defaultRange.begin(); i != a_end; i++) {
324            if (*i == addr) {
325                DPRINTF(BusAddrRanges, "  found addr %#llx on default\n",
326                        addr);
327                return defaultPortID;
328            }
329        }
330    } else if (defaultPortID != InvalidPortID) {
331        DPRINTF(BusAddrRanges, "Unable to find destination for addr %#llx, "
332                "will use default port\n", addr);
333        return defaultPortID;
334    }
335
336    // we should use the range for the default port and it did not
337    // match, or the default port is not set
338    fatal("Unable to find destination for addr %#llx on bus %s\n", addr,
339          name());
340}
341
342/** Function called by the port when the bus is receiving a range change.*/
343void
344BaseBus::recvRangeChange(PortID master_port_id)
345{
346    AddrRangeList ranges;
347    AddrRangeIter iter;
348
349    if (inRecvRangeChange.count(master_port_id))
350        return;
351    inRecvRangeChange.insert(master_port_id);
352
353    DPRINTF(BusAddrRanges, "received RangeChange from device id %d\n",
354            master_port_id);
355
356    clearPortCache();
357    if (master_port_id == defaultPortID) {
358        defaultRange.clear();
359        // Only try to update these ranges if the user set a default responder.
360        if (useDefaultRange) {
361            // get the address ranges of the connected slave port
362            AddrRangeList ranges =
363                masterPorts[master_port_id]->getAddrRanges();
364            for(iter = ranges.begin(); iter != ranges.end(); iter++) {
365                defaultRange.push_back(*iter);
366                DPRINTF(BusAddrRanges, "Adding range %#llx - %#llx for default range\n",
367                        iter->start, iter->end);
368            }
369        }
370    } else {
371
372        assert(master_port_id < masterPorts.size() && master_port_id >= 0);
373        MasterPort *port = masterPorts[master_port_id];
374
375        // Clean out any previously existent ids
376        for (PortMapIter portIter = portMap.begin();
377             portIter != portMap.end(); ) {
378            if (portIter->second == master_port_id)
379                portMap.erase(portIter++);
380            else
381                portIter++;
382        }
383
384        // get the address ranges of the connected slave port
385        ranges = port->getAddrRanges();
386
387        for (iter = ranges.begin(); iter != ranges.end(); iter++) {
388            DPRINTF(BusAddrRanges, "Adding range %#llx - %#llx for id %d\n",
389                    iter->start, iter->end, master_port_id);
390            if (portMap.insert(*iter, master_port_id) == portMap.end()) {
391                PortID conflict_id = portMap.find(*iter)->second;
392                fatal("%s has two ports with same range:\n\t%s\n\t%s\n",
393                      name(),
394                      masterPorts[master_port_id]->getSlavePort().name(),
395                      masterPorts[conflict_id]->getSlavePort().name());
396            }
397        }
398    }
399    DPRINTF(BusAddrRanges, "port list has %d entries\n", portMap.size());
400
401    // tell all our neighbouring master ports that our address range
402    // has changed
403    for (SlavePortConstIter p = slavePorts.begin(); p != slavePorts.end();
404         ++p)
405        (*p)->sendRangeChange();
406
407    inRecvRangeChange.erase(master_port_id);
408}
409
410AddrRangeList
411BaseBus::getAddrRanges() const
412{
413    AddrRangeList ranges;
414
415    DPRINTF(BusAddrRanges, "received address range request, returning:\n");
416
417    for (AddrRangeConstIter dflt_iter = defaultRange.begin();
418         dflt_iter != defaultRange.end(); dflt_iter++) {
419        ranges.push_back(*dflt_iter);
420        DPRINTF(BusAddrRanges, "  -- Dflt: %#llx : %#llx\n",dflt_iter->start,
421                dflt_iter->end);
422    }
423    for (PortMapConstIter portIter = portMap.begin();
424         portIter != portMap.end(); portIter++) {
425        bool subset = false;
426        for (AddrRangeConstIter dflt_iter = defaultRange.begin();
427             dflt_iter != defaultRange.end(); dflt_iter++) {
428            if ((portIter->first.start < dflt_iter->start &&
429                portIter->first.end >= dflt_iter->start) ||
430               (portIter->first.start < dflt_iter->end &&
431                portIter->first.end >= dflt_iter->end))
432                fatal("Devices can not set ranges that itersect the default set\
433                        but are not a subset of the default set.\n");
434            if (portIter->first.start >= dflt_iter->start &&
435                portIter->first.end <= dflt_iter->end) {
436                subset = true;
437                DPRINTF(BusAddrRanges, "  -- %#llx : %#llx is a SUBSET\n",
438                    portIter->first.start, portIter->first.end);
439            }
440        }
441        if (!subset) {
442            ranges.push_back(portIter->first);
443            DPRINTF(BusAddrRanges, "  -- %#llx : %#llx\n",
444                    portIter->first.start, portIter->first.end);
445        }
446    }
447
448    return ranges;
449}
450
451unsigned
452BaseBus::findBlockSize()
453{
454    if (cachedBlockSizeValid)
455        return cachedBlockSize;
456
457    unsigned max_bs = 0;
458
459    for (MasterPortConstIter m = masterPorts.begin(); m != masterPorts.end();
460         ++m) {
461        unsigned tmp_bs = (*m)->peerBlockSize();
462        if (tmp_bs > max_bs)
463            max_bs = tmp_bs;
464    }
465
466    for (SlavePortConstIter s = slavePorts.begin(); s != slavePorts.end();
467         ++s) {
468        unsigned tmp_bs = (*s)->peerBlockSize();
469        if (tmp_bs > max_bs)
470            max_bs = tmp_bs;
471    }
472    if (max_bs == 0)
473        max_bs = defaultBlockSize;
474
475    if (max_bs != 64)
476        warn_once("Blocksize found to not be 64... hmm... probably not.\n");
477    cachedBlockSize = max_bs;
478    cachedBlockSizeValid = true;
479    return max_bs;
480}
481
482
483unsigned int
484BaseBus::drain(Event * de)
485{
486    //We should check that we're not "doing" anything, and that noone is
487    //waiting. We might be idle but have someone waiting if the device we
488    //contacted for a retry didn't actually retry.
489    if (!retryList.empty() || state != IDLE) {
490        drainEvent = de;
491        return 1;
492    }
493    return 0;
494}
495