2eb8230514bebec9ba3e684a4f48bc1454357a8f
[gem5.git] / src / mem / bus.cc
1 /*
2 * Copyright (c) 2006 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Ali Saidi
29 */
30
31 /**
32 * @file
33 * Definition of a bus object.
34 */
35
36 #include <algorithm>
37 #include <limits>
38
39 #include "base/misc.hh"
40 #include "base/trace.hh"
41 #include "mem/bus.hh"
42
43 Port *
44 Bus::getPort(const std::string &if_name, int idx)
45 {
46 if (if_name == "default") {
47 if (defaultPort == NULL) {
48 defaultPort = new BusPort(csprintf("%s-default",name()), this,
49 defaultId);
50 cachedBlockSizeValid = false;
51 return defaultPort;
52 } else
53 fatal("Default port already set\n");
54 }
55 int id;
56 if (if_name == "functional") {
57 if (!funcPort) {
58 id = maxId++;
59 funcPort = new BusPort(csprintf("%s-p%d-func", name(), id), this, id);
60 funcPortId = id;
61 interfaces[id] = funcPort;
62 }
63 return funcPort;
64 }
65
66 // if_name ignored? forced to be empty?
67 id = maxId++;
68 assert(maxId < std::numeric_limits<typeof(maxId)>::max());
69 BusPort *bp = new BusPort(csprintf("%s-p%d", name(), id), this, id);
70 interfaces[id] = bp;
71 cachedBlockSizeValid = false;
72 return bp;
73 }
74
75 void
76 Bus::deletePortRefs(Port *p)
77 {
78
79 BusPort *bp = dynamic_cast<BusPort*>(p);
80 if (bp == NULL)
81 panic("Couldn't convert Port* to BusPort*\n");
82 // If this is our one functional port
83 if (funcPort == bp)
84 return;
85 interfaces.erase(bp->getId());
86 clearBusCache();
87 delete bp;
88 }
89
90 /** Get the ranges of anyone other buses that we are connected to. */
91 void
92 Bus::init()
93 {
94 m5::hash_map<short,BusPort*>::iterator intIter;
95
96 for (intIter = interfaces.begin(); intIter != interfaces.end(); intIter++)
97 intIter->second->sendStatusChange(Port::RangeChange);
98 }
99
100 Bus::BusFreeEvent::BusFreeEvent(Bus *_bus)
101 : bus(_bus)
102 {}
103
104 void
105 Bus::BusFreeEvent::process()
106 {
107 bus->recvRetry(-1);
108 }
109
110 const char *
111 Bus::BusFreeEvent::description() const
112 {
113 return "bus became available";
114 }
115
116 Tick
117 Bus::calcPacketTiming(PacketPtr pkt)
118 {
119 // Bring tickNextIdle up to the present tick.
120 // There is some potential ambiguity where a cycle starts, which
121 // might make a difference when devices are acting right around a
122 // cycle boundary. Using a < allows things which happen exactly on
123 // a cycle boundary to take up only the following cycle. Anything
124 // that happens later will have to "wait" for the end of that
125 // cycle, and then start using the bus after that.
126 if (tickNextIdle < curTick) {
127 tickNextIdle = curTick;
128 if (tickNextIdle % clock != 0)
129 tickNextIdle = curTick - (curTick % clock) + clock;
130 }
131
132 Tick headerTime = tickNextIdle + headerCycles * clock;
133
134 // The packet will be sent. Figure out how long it occupies the bus, and
135 // how much of that time is for the first "word", aka bus width.
136 int numCycles = 0;
137 if (pkt->hasData()) {
138 // If a packet has data, it needs ceil(size/width) cycles to send it
139 int dataSize = pkt->getSize();
140 numCycles += dataSize/width;
141 if (dataSize % width)
142 numCycles++;
143 }
144
145 // The first word will be delivered after the current tick, the delivery
146 // of the address if any, and one bus cycle to deliver the data
147 pkt->firstWordTime = headerTime + clock;
148
149 pkt->finishTime = headerTime + numCycles * clock;
150
151 return headerTime;
152 }
153
154 void Bus::occupyBus(Tick until)
155 {
156 if (until == 0) {
157 // shortcut for express snoop packets
158 return;
159 }
160
161 tickNextIdle = until;
162 reschedule(busIdle, tickNextIdle, true);
163
164 DPRINTF(Bus, "The bus is now occupied from tick %d to %d\n",
165 curTick, tickNextIdle);
166 }
167
168 /** Function called by the port when the bus is receiving a Timing
169 * transaction.*/
170 bool
171 Bus::recvTiming(PacketPtr pkt)
172 {
173 short src = pkt->getSrc();
174
175 BusPort *src_port;
176 if (src == defaultId)
177 src_port = defaultPort;
178 else {
179 src_port = checkBusCache(src);
180 if (src_port == NULL) {
181 src_port = interfaces[src];
182 updateBusCache(src, src_port);
183 }
184 }
185
186 // If the bus is busy, or other devices are in line ahead of the current
187 // one, put this device on the retry list.
188 if (!pkt->isExpressSnoop() &&
189 (tickNextIdle > curTick ||
190 (retryList.size() && (!inRetry || src_port != retryList.front()))))
191 {
192 addToRetryList(src_port);
193 DPRINTF(Bus, "recvTiming: src %d dst %d %s 0x%x BUSY\n",
194 src, pkt->getDest(), pkt->cmdString(), pkt->getAddr());
195 return false;
196 }
197
198 DPRINTF(Bus, "recvTiming: src %d dst %d %s 0x%x\n",
199 src, pkt->getDest(), pkt->cmdString(), pkt->getAddr());
200
201 Tick headerFinishTime = pkt->isExpressSnoop() ? 0 : calcPacketTiming(pkt);
202 Tick packetFinishTime = pkt->isExpressSnoop() ? 0 : pkt->finishTime;
203
204 short dest = pkt->getDest();
205 int dest_port_id;
206 Port *dest_port;
207
208 if (dest == Packet::Broadcast) {
209 dest_port_id = findPort(pkt->getAddr());
210 dest_port = (dest_port_id == defaultId) ?
211 defaultPort : 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 >= 0 && dest < maxId);
223 assert(dest != src); // catch infinite loops
224 dest_port_id = dest;
225 if (dest_port_id == defaultId)
226 dest_port = defaultPort;
227 else {
228 dest_port = checkBusCache(dest);
229 if (dest_port == NULL) {
230 dest_port = interfaces[dest_port_id];
231 // updateBusCache(dest_port_id, dest_port);
232 }
233 }
234 dest_port = (dest_port_id == defaultId) ?
235 defaultPort : interfaces[dest_port_id];
236 }
237
238 if (dest_port_id == src) {
239 // Must be forwarded snoop up from below...
240 assert(dest == Packet::Broadcast);
241 assert(src != defaultId); // catch infinite loops
242 } else {
243 // send to actual target
244 if (!dest_port->sendTiming(pkt)) {
245 // Packet not successfully sent. Leave or put it on the retry list.
246 // illegal to block responses... can lead to deadlock
247 assert(!pkt->isResponse());
248 DPRINTF(Bus, "recvTiming: src %d dst %d %s 0x%x TGT RETRY\n",
249 src, pkt->getDest(), pkt->cmdString(), pkt->getAddr());
250 addToRetryList(src_port);
251 occupyBus(headerFinishTime);
252 return false;
253 }
254 // send OK, fall through... pkt may have been deleted by
255 // target at this point, so it should *not* be referenced
256 // again. We'll set it to NULL here just to be safe.
257 pkt = NULL;
258 }
259
260 occupyBus(packetFinishTime);
261
262 // Packet was successfully sent.
263 // Also take care of retries
264 if (inRetry) {
265 DPRINTF(Bus, "Remove retry from list %d\n", src);
266 retryList.front()->onRetryList(false);
267 retryList.pop_front();
268 inRetry = false;
269 }
270 return true;
271 }
272
273 void
274 Bus::recvRetry(int id)
275 {
276 // If there's anything waiting, and the bus isn't busy...
277 if (retryList.size() && curTick >= tickNextIdle) {
278 //retryingPort = retryList.front();
279 inRetry = true;
280 DPRINTF(Bus, "Sending a retry to %s\n", retryList.front()->getPeer()->name());
281 retryList.front()->sendRetry();
282 // If inRetry is still true, sendTiming wasn't called
283 if (inRetry)
284 {
285 retryList.front()->onRetryList(false);
286 retryList.pop_front();
287 inRetry = false;
288
289 //Bring tickNextIdle up to the present
290 while (tickNextIdle < curTick)
291 tickNextIdle += clock;
292
293 //Burn a cycle for the missed grant.
294 tickNextIdle += clock;
295
296 reschedule(busIdle, tickNextIdle, true);
297 }
298 }
299 //If we weren't able to drain before, we might be able to now.
300 if (drainEvent && retryList.size() == 0 && curTick >= tickNextIdle) {
301 drainEvent->process();
302 // Clear the drain event once we're done with it.
303 drainEvent = NULL;
304 }
305 }
306
307 int
308 Bus::findPort(Addr addr)
309 {
310 /* An interval tree would be a better way to do this. --ali. */
311 int dest_id = -1;
312
313 dest_id = checkPortCache(addr);
314 if (dest_id == -1) {
315 PortIter i = portMap.find(RangeSize(addr,1));
316 if (i != portMap.end()) {
317 dest_id = i->second;
318 updatePortCache(dest_id, i->first.start, i->first.end);
319 }
320 }
321
322 // Check if this matches the default range
323 if (dest_id == -1) {
324 AddrRangeIter a_end = defaultRange.end();
325 for (AddrRangeIter i = defaultRange.begin(); i != a_end; i++) {
326 if (*i == addr) {
327 DPRINTF(Bus, " found addr %#llx on default\n", addr);
328 return defaultId;
329 }
330 }
331
332 if (responderSet) {
333 panic("Unable to find destination for addr (user set default "
334 "responder): %#llx\n", addr);
335 } else {
336 DPRINTF(Bus, "Unable to find destination for addr: %#llx, will use "
337 "default port\n", addr);
338
339 return defaultId;
340 }
341 }
342
343 return dest_id;
344 }
345
346
347 /** Function called by the port when the bus is receiving a Atomic
348 * transaction.*/
349 Tick
350 Bus::recvAtomic(PacketPtr pkt)
351 {
352 DPRINTF(Bus, "recvAtomic: packet src %d dest %d addr 0x%x cmd %s\n",
353 pkt->getSrc(), pkt->getDest(), pkt->getAddr(), pkt->cmdString());
354 assert(pkt->getDest() == Packet::Broadcast);
355 assert(pkt->isRequest());
356
357 // Variables for recording original command and snoop response (if
358 // any)... if a snooper respondes, we will need to restore
359 // original command so that additional snoops can take place
360 // properly
361 MemCmd orig_cmd = pkt->cmd;
362 MemCmd snoop_response_cmd = MemCmd::InvalidCmd;
363 Tick snoop_response_latency = 0;
364 int orig_src = pkt->getSrc();
365
366 int target_port_id = findPort(pkt->getAddr());
367 BusPort *target_port;
368 if (target_port_id == defaultId)
369 target_port = defaultPort;
370 else {
371 target_port = checkBusCache(target_port_id);
372 if (target_port == NULL) {
373 target_port = interfaces[target_port_id];
374 updateBusCache(target_port_id, target_port);
375 }
376 }
377
378 SnoopIter s_end = snoopPorts.end();
379 for (SnoopIter s_iter = snoopPorts.begin(); s_iter != s_end; s_iter++) {
380 BusPort *p = *s_iter;
381 // same port should not have both target addresses and snooping
382 assert(p != target_port);
383 if (p->getId() != pkt->getSrc()) {
384 Tick latency = p->sendAtomic(pkt);
385 if (pkt->isResponse()) {
386 // response from snoop agent
387 assert(pkt->cmd != orig_cmd);
388 assert(pkt->memInhibitAsserted());
389 // should only happen once
390 assert(snoop_response_cmd == MemCmd::InvalidCmd);
391 // save response state
392 snoop_response_cmd = pkt->cmd;
393 snoop_response_latency = latency;
394 // restore original packet state for remaining snoopers
395 pkt->cmd = orig_cmd;
396 pkt->setSrc(orig_src);
397 pkt->setDest(Packet::Broadcast);
398 }
399 }
400 }
401
402 Tick response_latency = 0;
403
404 // we can get requests sent up from the memory side of the bus for
405 // snooping... don't send them back down!
406 if (target_port_id != pkt->getSrc()) {
407 response_latency = target_port->sendAtomic(pkt);
408 }
409
410 // if we got a response from a snooper, restore it here
411 if (snoop_response_cmd != MemCmd::InvalidCmd) {
412 // no one else should have responded
413 assert(!pkt->isResponse());
414 assert(pkt->cmd == orig_cmd);
415 pkt->cmd = snoop_response_cmd;
416 response_latency = snoop_response_latency;
417 }
418
419 // why do we have this packet field and the return value both???
420 pkt->finishTime = curTick + response_latency;
421 return response_latency;
422 }
423
424 /** Function called by the port when the bus is receiving a Functional
425 * transaction.*/
426 void
427 Bus::recvFunctional(PacketPtr pkt)
428 {
429 if (!pkt->isPrint()) {
430 // don't do DPRINTFs on PrintReq as it clutters up the output
431 DPRINTF(Bus,
432 "recvFunctional: packet src %d dest %d addr 0x%x cmd %s\n",
433 pkt->getSrc(), pkt->getDest(), pkt->getAddr(),
434 pkt->cmdString());
435 }
436 assert(pkt->getDest() == Packet::Broadcast);
437
438 int port_id = findPort(pkt->getAddr());
439 Port *port = (port_id == defaultId) ? defaultPort : interfaces[port_id];
440 // The packet may be changed by another bus on snoops, restore the
441 // id after each
442 int src_id = pkt->getSrc();
443
444 assert(pkt->isRequest()); // hasn't already been satisfied
445
446 SnoopIter s_end = snoopPorts.end();
447 for (SnoopIter s_iter = snoopPorts.begin(); s_iter != s_end; s_iter++) {
448 BusPort *p = *s_iter;
449 if (p != port && p->getId() != src_id) {
450 p->sendFunctional(pkt);
451 }
452 if (pkt->isResponse()) {
453 break;
454 }
455 pkt->setSrc(src_id);
456 }
457
458 // If the snooping hasn't found what we were looking for, keep going.
459 if (!pkt->isResponse() && port_id != pkt->getSrc()) {
460 port->sendFunctional(pkt);
461 }
462 }
463
464 /** Function called by the port when the bus is receiving a status change.*/
465 void
466 Bus::recvStatusChange(Port::Status status, int id)
467 {
468 AddrRangeList ranges;
469 bool snoops;
470 AddrRangeIter iter;
471
472 if (inRecvStatusChange.count(id))
473 return;
474 inRecvStatusChange.insert(id);
475
476 assert(status == Port::RangeChange &&
477 "The other statuses need to be implemented.");
478
479 DPRINTF(BusAddrRanges, "received RangeChange from device id %d\n", id);
480
481 clearPortCache();
482 if (id == defaultId) {
483 defaultRange.clear();
484 // Only try to update these ranges if the user set a default responder.
485 if (responderSet) {
486 defaultPort->getPeerAddressRanges(ranges, snoops);
487 assert(snoops == false);
488 for(iter = ranges.begin(); iter != ranges.end(); iter++) {
489 defaultRange.push_back(*iter);
490 DPRINTF(BusAddrRanges, "Adding range %#llx - %#llx for default range\n",
491 iter->start, iter->end);
492 }
493 }
494 } else {
495
496 assert((id < maxId && id >= 0) || id == defaultId);
497 BusPort *port = interfaces[id];
498
499 // Clean out any previously existent ids
500 for (PortIter portIter = portMap.begin();
501 portIter != portMap.end(); ) {
502 if (portIter->second == id)
503 portMap.erase(portIter++);
504 else
505 portIter++;
506 }
507
508 for (SnoopIter s_iter = snoopPorts.begin();
509 s_iter != snoopPorts.end(); ) {
510 if ((*s_iter)->getId() == id)
511 s_iter = snoopPorts.erase(s_iter);
512 else
513 s_iter++;
514 }
515
516 port->getPeerAddressRanges(ranges, snoops);
517
518 if (snoops) {
519 DPRINTF(BusAddrRanges, "Adding id %d to snoop list\n", id);
520 snoopPorts.push_back(port);
521 }
522
523 for (iter = ranges.begin(); iter != ranges.end(); iter++) {
524 DPRINTF(BusAddrRanges, "Adding range %#llx - %#llx for id %d\n",
525 iter->start, iter->end, id);
526 if (portMap.insert(*iter, id) == portMap.end()) {
527 int conflict_id = portMap.find(*iter)->second;
528 fatal("%s has two ports with same range:\n\t%s\n\t%s\n",
529 name(), interfaces[id]->getPeer()->name(),
530 interfaces[conflict_id]->getPeer()->name());
531 }
532 }
533 }
534 DPRINTF(MMU, "port list has %d entries\n", portMap.size());
535
536 // tell all our peers that our address range has changed.
537 // Don't tell the device that caused this change, it already knows
538 m5::hash_map<short,BusPort*>::iterator intIter;
539
540 for (intIter = interfaces.begin(); intIter != interfaces.end(); intIter++)
541 if (intIter->first != id && intIter->first != funcPortId)
542 intIter->second->sendStatusChange(Port::RangeChange);
543
544 if (id != defaultId && defaultPort)
545 defaultPort->sendStatusChange(Port::RangeChange);
546 inRecvStatusChange.erase(id);
547 }
548
549 void
550 Bus::addressRanges(AddrRangeList &resp, bool &snoop, int id)
551 {
552 resp.clear();
553 snoop = false;
554
555 DPRINTF(BusAddrRanges, "received address range request, returning:\n");
556
557 for (AddrRangeIter dflt_iter = defaultRange.begin();
558 dflt_iter != defaultRange.end(); dflt_iter++) {
559 resp.push_back(*dflt_iter);
560 DPRINTF(BusAddrRanges, " -- Dflt: %#llx : %#llx\n",dflt_iter->start,
561 dflt_iter->end);
562 }
563 for (PortIter portIter = portMap.begin();
564 portIter != portMap.end(); portIter++) {
565 bool subset = false;
566 for (AddrRangeIter dflt_iter = defaultRange.begin();
567 dflt_iter != defaultRange.end(); dflt_iter++) {
568 if ((portIter->first.start < dflt_iter->start &&
569 portIter->first.end >= dflt_iter->start) ||
570 (portIter->first.start < dflt_iter->end &&
571 portIter->first.end >= dflt_iter->end))
572 fatal("Devices can not set ranges that itersect the default set\
573 but are not a subset of the default set.\n");
574 if (portIter->first.start >= dflt_iter->start &&
575 portIter->first.end <= dflt_iter->end) {
576 subset = true;
577 DPRINTF(BusAddrRanges, " -- %#llx : %#llx is a SUBSET\n",
578 portIter->first.start, portIter->first.end);
579 }
580 }
581 if (portIter->second != id && !subset) {
582 resp.push_back(portIter->first);
583 DPRINTF(BusAddrRanges, " -- %#llx : %#llx\n",
584 portIter->first.start, portIter->first.end);
585 }
586 }
587
588 for (SnoopIter s_iter = snoopPorts.begin(); s_iter != snoopPorts.end();
589 s_iter++) {
590 if ((*s_iter)->getId() != id) {
591 snoop = true;
592 break;
593 }
594 }
595 }
596
597 int
598 Bus::findBlockSize(int id)
599 {
600 if (cachedBlockSizeValid)
601 return cachedBlockSize;
602
603 int max_bs = -1;
604
605 PortIter p_end = portMap.end();
606 for (PortIter p_iter = portMap.begin(); p_iter != p_end; p_iter++) {
607 int tmp_bs = interfaces[p_iter->second]->peerBlockSize();
608 if (tmp_bs > max_bs)
609 max_bs = tmp_bs;
610 }
611 SnoopIter s_end = snoopPorts.end();
612 for (SnoopIter s_iter = snoopPorts.begin(); s_iter != s_end; s_iter++) {
613 int tmp_bs = (*s_iter)->peerBlockSize();
614 if (tmp_bs > max_bs)
615 max_bs = tmp_bs;
616 }
617 if (max_bs <= 0)
618 max_bs = defaultBlockSize;
619
620 if (max_bs != 64)
621 warn_once("Blocksize found to not be 64... hmm... probably not.\n");
622 cachedBlockSize = max_bs;
623 cachedBlockSizeValid = true;
624 return max_bs;
625 }
626
627
628 unsigned int
629 Bus::drain(Event * de)
630 {
631 //We should check that we're not "doing" anything, and that noone is
632 //waiting. We might be idle but have someone waiting if the device we
633 //contacted for a retry didn't actually retry.
634 if (retryList.size() || (curTick < tickNextIdle && busIdle.scheduled())) {
635 drainEvent = de;
636 return 1;
637 }
638 return 0;
639 }
640
641 void
642 Bus::startup()
643 {
644 if (tickNextIdle < curTick)
645 tickNextIdle = (curTick / clock) * clock + clock;
646 }
647
648 Bus *
649 BusParams::create()
650 {
651 return new Bus(this);
652 }