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