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