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