MESI: Add queues for stalled requests
[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 */
43
44 /**
45 * @file
46 * Definition of a bus object.
47 */
48
49 #include "base/misc.hh"
50 #include "base/trace.hh"
51 #include "debug/Bus.hh"
52 #include "debug/BusAddrRanges.hh"
53 #include "debug/MMU.hh"
54 #include "mem/bus.hh"
55
56 Bus::Bus(const BusParams *p)
57 : MemObject(p), busId(p->bus_id), clock(p->clock),
58 headerCycles(p->header_cycles), width(p->width), tickNextIdle(0),
59 drainEvent(NULL), busIdle(this), inRetry(false), defaultPortId(-1),
60 useDefaultRange(p->use_default_range), defaultBlockSize(p->block_size),
61 cachedBlockSize(0), cachedBlockSizeValid(false)
62 {
63 //width, clock period, and header cycles must be positive
64 if (width <= 0)
65 fatal("Bus width must be positive\n");
66 if (clock <= 0)
67 fatal("Bus clock period must be positive\n");
68 if (headerCycles <= 0)
69 fatal("Number of header cycles must be positive\n");
70 clearPortCache();
71 }
72
73 Port *
74 Bus::getPort(const std::string &if_name, int idx)
75 {
76 std::string portName;
77 int id = interfaces.size();
78 if (if_name == "default") {
79 if (defaultPortId == -1) {
80 defaultPortId = id;
81 portName = csprintf("%s-default", name());
82 } else
83 fatal("Default port already set on %s\n", name());
84 } else {
85 portName = csprintf("%s-p%d", name(), id);
86 }
87 BusPort *bp = new BusPort(portName, this, id);
88 interfaces.push_back(bp);
89 cachedBlockSizeValid = false;
90 return bp;
91 }
92
93 void
94 Bus::init()
95 {
96 std::vector<BusPort*>::iterator intIter;
97
98 // iterate over our interfaces and determine which of our neighbours
99 // are snooping and add them as snoopers
100 for (intIter = interfaces.begin(); intIter != interfaces.end();
101 intIter++) {
102 if ((*intIter)->getPeer()->isSnooping()) {
103 DPRINTF(BusAddrRanges, "Adding snooping neighbour %s\n",
104 (*intIter)->getPeer()->name());
105 snoopPorts.push_back(*intIter);
106 }
107 }
108 }
109
110 Bus::BusFreeEvent::BusFreeEvent(Bus *_bus)
111 : bus(_bus)
112 {}
113
114 void
115 Bus::BusFreeEvent::process()
116 {
117 bus->recvRetry(-1);
118 }
119
120 const char *
121 Bus::BusFreeEvent::description() const
122 {
123 return "bus became available";
124 }
125
126 Tick
127 Bus::calcPacketTiming(PacketPtr pkt)
128 {
129 // Bring tickNextIdle up to the present tick.
130 // There is some potential ambiguity where a cycle starts, which
131 // might make a difference when devices are acting right around a
132 // cycle boundary. Using a < allows things which happen exactly on
133 // a cycle boundary to take up only the following cycle. Anything
134 // that happens later will have to "wait" for the end of that
135 // cycle, and then start using the bus after that.
136 if (tickNextIdle < curTick()) {
137 tickNextIdle = curTick();
138 if (tickNextIdle % clock != 0)
139 tickNextIdle = curTick() - (curTick() % clock) + clock;
140 }
141
142 Tick headerTime = tickNextIdle + headerCycles * clock;
143
144 // The packet will be sent. Figure out how long it occupies the bus, and
145 // how much of that time is for the first "word", aka bus width.
146 int numCycles = 0;
147 if (pkt->hasData()) {
148 // If a packet has data, it needs ceil(size/width) cycles to send it
149 int dataSize = pkt->getSize();
150 numCycles += dataSize/width;
151 if (dataSize % width)
152 numCycles++;
153 }
154
155 // The first word will be delivered after the current tick, the delivery
156 // of the address if any, and one bus cycle to deliver the data
157 pkt->firstWordTime = headerTime + clock;
158
159 pkt->finishTime = headerTime + numCycles * clock;
160
161 return headerTime;
162 }
163
164 void Bus::occupyBus(Tick until)
165 {
166 if (until == 0) {
167 // shortcut for express snoop packets
168 return;
169 }
170
171 tickNextIdle = until;
172 reschedule(busIdle, tickNextIdle, true);
173
174 DPRINTF(Bus, "The bus is now occupied from tick %d to %d\n",
175 curTick(), tickNextIdle);
176 }
177
178 /** Function called by the port when the bus is receiving a Timing
179 * transaction.*/
180 bool
181 Bus::recvTiming(PacketPtr pkt)
182 {
183 short src = pkt->getSrc();
184
185 BusPort *src_port = interfaces[src];
186
187 // If the bus is busy, or other devices are in line ahead of the current
188 // one, put this device on the retry list.
189 if (!pkt->isExpressSnoop() &&
190 (tickNextIdle > curTick() ||
191 (retryList.size() && (!inRetry || src_port != retryList.front()))))
192 {
193 addToRetryList(src_port);
194 DPRINTF(Bus, "recvTiming: src %d dst %d %s 0x%x BUSY\n",
195 src, pkt->getDest(), pkt->cmdString(), pkt->getAddr());
196 return false;
197 }
198
199 DPRINTF(Bus, "recvTiming: src %d dst %d %s 0x%x\n",
200 src, pkt->getDest(), pkt->cmdString(), pkt->getAddr());
201
202 Tick headerFinishTime = pkt->isExpressSnoop() ? 0 : calcPacketTiming(pkt);
203 Tick packetFinishTime = pkt->isExpressSnoop() ? 0 : pkt->finishTime;
204
205 short dest = pkt->getDest();
206 int dest_port_id;
207 Port *dest_port;
208
209 if (dest == Packet::Broadcast) {
210 dest_port_id = findPort(pkt->getAddr());
211 dest_port = interfaces[dest_port_id];
212 SnoopIter s_end = snoopPorts.end();
213 for (SnoopIter s_iter = snoopPorts.begin(); s_iter != s_end; s_iter++) {
214 BusPort *p = *s_iter;
215 if (p != dest_port && p != src_port) {
216 // cache is not allowed to refuse snoop
217 bool success M5_VAR_USED = p->sendTiming(pkt);
218 assert(success);
219 }
220 }
221 } else {
222 assert(dest < interfaces.size());
223 assert(dest != src); // catch infinite loops
224 dest_port_id = dest;
225 dest_port = interfaces[dest_port_id];
226 }
227
228 if (dest_port_id == src) {
229 // Must be forwarded snoop up from below...
230 assert(dest == Packet::Broadcast);
231 } else {
232 // send to actual target
233 if (!dest_port->sendTiming(pkt)) {
234 // Packet not successfully sent. Leave or put it on the retry list.
235 // illegal to block responses... can lead to deadlock
236 assert(!pkt->isResponse());
237 // It's also illegal to force a transaction to retry after
238 // someone else has committed to respond.
239 assert(!pkt->memInhibitAsserted());
240 DPRINTF(Bus, "recvTiming: src %d dst %d %s 0x%x TGT RETRY\n",
241 src, pkt->getDest(), pkt->cmdString(), pkt->getAddr());
242 addToRetryList(src_port);
243 occupyBus(headerFinishTime);
244 return false;
245 }
246 // send OK, fall through... pkt may have been deleted by
247 // target at this point, so it should *not* be referenced
248 // again. We'll set it to NULL here just to be safe.
249 pkt = NULL;
250 }
251
252 occupyBus(packetFinishTime);
253
254 // Packet was successfully sent.
255 // Also take care of retries
256 if (inRetry) {
257 DPRINTF(Bus, "Remove retry from list %d\n", src);
258 retryList.pop_front();
259 inRetry = false;
260 }
261 return true;
262 }
263
264 void
265 Bus::recvRetry(int id)
266 {
267 // If there's anything waiting, and the bus isn't busy...
268 if (retryList.size() && curTick() >= tickNextIdle) {
269 //retryingPort = retryList.front();
270 inRetry = true;
271 DPRINTF(Bus, "Sending a retry to %s\n", retryList.front()->getPeer()->name());
272 retryList.front()->sendRetry();
273 // If inRetry is still true, sendTiming wasn't called
274 if (inRetry)
275 {
276 retryList.pop_front();
277 inRetry = false;
278
279 //Bring tickNextIdle up to the present
280 while (tickNextIdle < curTick())
281 tickNextIdle += clock;
282
283 //Burn a cycle for the missed grant.
284 tickNextIdle += clock;
285
286 reschedule(busIdle, tickNextIdle, true);
287 }
288 }
289 //If we weren't able to drain before, we might be able to now.
290 if (drainEvent && retryList.size() == 0 && curTick() >= tickNextIdle) {
291 drainEvent->process();
292 // Clear the drain event once we're done with it.
293 drainEvent = NULL;
294 }
295 }
296
297 int
298 Bus::findPort(Addr addr)
299 {
300 /* An interval tree would be a better way to do this. --ali. */
301 int dest_id;
302
303 dest_id = checkPortCache(addr);
304 if (dest_id != -1)
305 return dest_id;
306
307 // Check normal port ranges
308 PortIter i = portMap.find(RangeSize(addr,1));
309 if (i != portMap.end()) {
310 dest_id = i->second;
311 updatePortCache(dest_id, i->first.start, i->first.end);
312 return dest_id;
313 }
314
315 // Check if this matches the default range
316 if (useDefaultRange) {
317 AddrRangeIter a_end = defaultRange.end();
318 for (AddrRangeIter i = defaultRange.begin(); i != a_end; i++) {
319 if (*i == addr) {
320 DPRINTF(Bus, " found addr %#llx on default\n", addr);
321 return defaultPortId;
322 }
323 }
324
325 panic("Unable to find destination for addr %#llx\n", addr);
326 }
327
328 DPRINTF(Bus, "Unable to find destination for addr %#llx, "
329 "will use default port\n", addr);
330 return defaultPortId;
331 }
332
333
334 /** Function called by the port when the bus is receiving a Atomic
335 * transaction.*/
336 Tick
337 Bus::recvAtomic(PacketPtr pkt)
338 {
339 DPRINTF(Bus, "recvAtomic: packet src %d dest %d addr 0x%x cmd %s\n",
340 pkt->getSrc(), pkt->getDest(), pkt->getAddr(), pkt->cmdString());
341 assert(pkt->getDest() == Packet::Broadcast);
342 assert(pkt->isRequest());
343
344 // Variables for recording original command and snoop response (if
345 // any)... if a snooper respondes, we will need to restore
346 // original command so that additional snoops can take place
347 // properly
348 MemCmd orig_cmd = pkt->cmd;
349 MemCmd snoop_response_cmd = MemCmd::InvalidCmd;
350 Tick snoop_response_latency = 0;
351 int orig_src = pkt->getSrc();
352
353 int target_port_id = findPort(pkt->getAddr());
354 BusPort *target_port = interfaces[target_port_id];
355
356 SnoopIter s_end = snoopPorts.end();
357 for (SnoopIter s_iter = snoopPorts.begin(); s_iter != s_end; s_iter++) {
358 BusPort *p = *s_iter;
359 // same port should not have both target addresses and snooping
360 assert(p != target_port);
361 if (p->getId() != pkt->getSrc()) {
362 Tick latency = p->sendAtomic(pkt);
363 if (pkt->isResponse()) {
364 // response from snoop agent
365 assert(pkt->cmd != orig_cmd);
366 assert(pkt->memInhibitAsserted());
367 // should only happen once
368 assert(snoop_response_cmd == MemCmd::InvalidCmd);
369 // save response state
370 snoop_response_cmd = pkt->cmd;
371 snoop_response_latency = latency;
372 // restore original packet state for remaining snoopers
373 pkt->cmd = orig_cmd;
374 pkt->setSrc(orig_src);
375 pkt->setDest(Packet::Broadcast);
376 }
377 }
378 }
379
380 Tick response_latency = 0;
381
382 // we can get requests sent up from the memory side of the bus for
383 // snooping... don't send them back down!
384 if (target_port_id != pkt->getSrc()) {
385 response_latency = target_port->sendAtomic(pkt);
386 }
387
388 // if we got a response from a snooper, restore it here
389 if (snoop_response_cmd != MemCmd::InvalidCmd) {
390 // no one else should have responded
391 assert(!pkt->isResponse());
392 assert(pkt->cmd == orig_cmd);
393 pkt->cmd = snoop_response_cmd;
394 response_latency = snoop_response_latency;
395 }
396
397 // why do we have this packet field and the return value both???
398 pkt->finishTime = curTick() + response_latency;
399 return response_latency;
400 }
401
402 /** Function called by the port when the bus is receiving a Functional
403 * transaction.*/
404 void
405 Bus::recvFunctional(PacketPtr pkt)
406 {
407 assert(pkt->getDest() == Packet::Broadcast);
408
409 int port_id = findPort(pkt->getAddr());
410 Port *port = interfaces[port_id];
411 // The packet may be changed by another bus on snoops, restore the
412 // id after each
413 int src_id = pkt->getSrc();
414
415 if (!pkt->isPrint()) {
416 // don't do DPRINTFs on PrintReq as it clutters up the output
417 DPRINTF(Bus,
418 "recvFunctional: packet src %d dest %d addr 0x%x cmd %s\n",
419 src_id, port_id, pkt->getAddr(),
420 pkt->cmdString());
421 }
422
423 assert(pkt->isRequest()); // hasn't already been satisfied
424
425 SnoopIter s_end = snoopPorts.end();
426 for (SnoopIter s_iter = snoopPorts.begin(); s_iter != s_end; s_iter++) {
427 BusPort *p = *s_iter;
428 if (p != port && p->getId() != src_id) {
429 p->sendFunctional(pkt);
430 }
431 if (pkt->isResponse()) {
432 break;
433 }
434 pkt->setSrc(src_id);
435 }
436
437 // If the snooping hasn't found what we were looking for and it is not
438 // a forwarded snoop from below, keep going.
439 if (!pkt->isResponse() && port_id != pkt->getSrc()) {
440 port->sendFunctional(pkt);
441 }
442 }
443
444 /** Function called by the port when the bus is receiving a range change.*/
445 void
446 Bus::recvRangeChange(int id)
447 {
448 AddrRangeList ranges;
449 AddrRangeIter iter;
450
451 if (inRecvRangeChange.count(id))
452 return;
453 inRecvRangeChange.insert(id);
454
455 DPRINTF(BusAddrRanges, "received RangeChange from device id %d\n", id);
456
457 clearPortCache();
458 if (id == defaultPortId) {
459 defaultRange.clear();
460 // Only try to update these ranges if the user set a default responder.
461 if (useDefaultRange) {
462 AddrRangeList ranges = interfaces[id]->getPeer()->getAddrRanges();
463 for(iter = ranges.begin(); iter != ranges.end(); iter++) {
464 defaultRange.push_back(*iter);
465 DPRINTF(BusAddrRanges, "Adding range %#llx - %#llx for default range\n",
466 iter->start, iter->end);
467 }
468 }
469 } else {
470
471 assert(id < interfaces.size() && id >= 0);
472 BusPort *port = interfaces[id];
473
474 // Clean out any previously existent ids
475 for (PortIter portIter = portMap.begin();
476 portIter != portMap.end(); ) {
477 if (portIter->second == id)
478 portMap.erase(portIter++);
479 else
480 portIter++;
481 }
482
483 ranges = port->getPeer()->getAddrRanges();
484
485 for (iter = ranges.begin(); iter != ranges.end(); iter++) {
486 DPRINTF(BusAddrRanges, "Adding range %#llx - %#llx for id %d\n",
487 iter->start, iter->end, id);
488 if (portMap.insert(*iter, id) == portMap.end()) {
489 int conflict_id = portMap.find(*iter)->second;
490 fatal("%s has two ports with same range:\n\t%s\n\t%s\n",
491 name(), interfaces[id]->getPeer()->name(),
492 interfaces[conflict_id]->getPeer()->name());
493 }
494 }
495 }
496 DPRINTF(MMU, "port list has %d entries\n", portMap.size());
497
498 // tell all our peers that our address range has changed.
499 // Don't tell the device that caused this change, it already knows
500 std::vector<BusPort*>::const_iterator intIter;
501
502 for (intIter = interfaces.begin(); intIter != interfaces.end(); intIter++)
503 if ((*intIter)->getId() != id)
504 (*intIter)->sendRangeChange();
505
506 inRecvRangeChange.erase(id);
507 }
508
509 AddrRangeList
510 Bus::getAddrRanges(int id)
511 {
512 AddrRangeList ranges;
513
514 DPRINTF(BusAddrRanges, "received address range request, returning:\n");
515
516 for (AddrRangeIter dflt_iter = defaultRange.begin();
517 dflt_iter != defaultRange.end(); dflt_iter++) {
518 ranges.push_back(*dflt_iter);
519 DPRINTF(BusAddrRanges, " -- Dflt: %#llx : %#llx\n",dflt_iter->start,
520 dflt_iter->end);
521 }
522 for (PortIter portIter = portMap.begin();
523 portIter != portMap.end(); portIter++) {
524 bool subset = false;
525 for (AddrRangeIter dflt_iter = defaultRange.begin();
526 dflt_iter != defaultRange.end(); dflt_iter++) {
527 if ((portIter->first.start < dflt_iter->start &&
528 portIter->first.end >= dflt_iter->start) ||
529 (portIter->first.start < dflt_iter->end &&
530 portIter->first.end >= dflt_iter->end))
531 fatal("Devices can not set ranges that itersect the default set\
532 but are not a subset of the default set.\n");
533 if (portIter->first.start >= dflt_iter->start &&
534 portIter->first.end <= dflt_iter->end) {
535 subset = true;
536 DPRINTF(BusAddrRanges, " -- %#llx : %#llx is a SUBSET\n",
537 portIter->first.start, portIter->first.end);
538 }
539 }
540 if (portIter->second != id && !subset) {
541 ranges.push_back(portIter->first);
542 DPRINTF(BusAddrRanges, " -- %#llx : %#llx\n",
543 portIter->first.start, portIter->first.end);
544 }
545 }
546
547 return ranges;
548 }
549
550 bool
551 Bus::isSnooping(int id)
552 {
553 // in essence, answer the question if there are other snooping
554 // ports rather than the port that is asking
555 bool snoop = false;
556 for (SnoopIter s_iter = snoopPorts.begin(); s_iter != snoopPorts.end();
557 s_iter++) {
558 if ((*s_iter)->getId() != id) {
559 snoop = true;
560 break;
561 }
562 }
563 return snoop;
564 }
565
566 unsigned
567 Bus::findBlockSize(int id)
568 {
569 if (cachedBlockSizeValid)
570 return cachedBlockSize;
571
572 unsigned max_bs = 0;
573
574 PortIter p_end = portMap.end();
575 for (PortIter p_iter = portMap.begin(); p_iter != p_end; p_iter++) {
576 unsigned tmp_bs = interfaces[p_iter->second]->peerBlockSize();
577 if (tmp_bs > max_bs)
578 max_bs = tmp_bs;
579 }
580 SnoopIter s_end = snoopPorts.end();
581 for (SnoopIter s_iter = snoopPorts.begin(); s_iter != s_end; s_iter++) {
582 unsigned tmp_bs = (*s_iter)->peerBlockSize();
583 if (tmp_bs > max_bs)
584 max_bs = tmp_bs;
585 }
586 if (max_bs == 0)
587 max_bs = defaultBlockSize;
588
589 if (max_bs != 64)
590 warn_once("Blocksize found to not be 64... hmm... probably not.\n");
591 cachedBlockSize = max_bs;
592 cachedBlockSizeValid = true;
593 return max_bs;
594 }
595
596
597 unsigned int
598 Bus::drain(Event * de)
599 {
600 //We should check that we're not "doing" anything, and that noone is
601 //waiting. We might be idle but have someone waiting if the device we
602 //contacted for a retry didn't actually retry.
603 if (retryList.size() || (curTick() < tickNextIdle && busIdle.scheduled())) {
604 drainEvent = de;
605 return 1;
606 }
607 return 0;
608 }
609
610 void
611 Bus::startup()
612 {
613 if (tickNextIdle < curTick())
614 tickNextIdle = (curTick() / clock) * clock + clock;
615 }
616
617 Bus *
618 BusParams::create()
619 {
620 return new Bus(this);
621 }