1fad13c5a2b78ea793c0ab27907e2a6e883e7683
[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 short src = pkt->getSrc();
176 DPRINTF(Bus, "recvTiming: packet src %d dest %d addr 0x%x cmd %s\n",
177 src, pkt->getDest(), pkt->getAddr(), pkt->cmdString());
178
179 BusPort *src_port = (src == defaultId) ? defaultPort : interfaces[src];
180
181 // If the bus is busy, or other devices are in line ahead of the current
182 // one, put this device on the retry list.
183 if (!(pkt->isResponse() || pkt->isExpressSnoop()) &&
184 (tickNextIdle > curTick ||
185 (retryList.size() && (!inRetry || src_port != retryList.front()))))
186 {
187 addToRetryList(src_port);
188 DPRINTF(Bus, "recvTiming: Bus is busy, returning false\n");
189 return false;
190 }
191
192 occupyBus(pkt);
193
194 short dest = pkt->getDest();
195 int dest_port_id;
196 Port *dest_port;
197
198 if (dest == Packet::Broadcast) {
199 dest_port_id = findPort(pkt->getAddr());
200 dest_port = (dest_port_id == defaultId) ?
201 defaultPort : interfaces[dest_port_id];
202 for (SnoopIter s_iter = snoopPorts.begin();
203 s_iter != snoopPorts.end();
204 s_iter++) {
205 BusPort *p = *s_iter;
206 if (p != dest_port && p != src_port) {
207 #ifndef NDEBUG
208 // cache is not allowed to refuse snoop
209 bool success = p->sendTiming(pkt);
210 assert(success);
211 #else
212 // avoid unused variable warning
213 p->sendTiming(pkt);
214 #endif
215 }
216 }
217 } else {
218 assert(dest >= 0 && dest < maxId);
219 assert(dest != src); // catch infinite loops
220 dest_port_id = dest;
221 dest_port = (dest_port_id == defaultId) ?
222 defaultPort : interfaces[dest_port_id];
223 }
224
225 if (dest_port_id == src) {
226 // Must be forwarded snoop up from below...
227 assert(dest == Packet::Broadcast);
228 } else {
229 // send to actual target
230 if (!dest_port->sendTiming(pkt)) {
231 // Packet not successfully sent. Leave or put it on the retry list.
232 // illegal to block responses... can lead to deadlock
233 assert(!pkt->isResponse());
234 DPRINTF(Bus, "Adding2 a retry to RETRY list %d\n", src);
235 addToRetryList(src_port);
236 return false;
237 }
238 // send OK, fall through
239 }
240
241 // Packet was successfully sent.
242 // Also take care of retries
243 if (inRetry) {
244 DPRINTF(Bus, "Remove retry from list %d\n", src);
245 retryList.front()->onRetryList(false);
246 retryList.pop_front();
247 inRetry = false;
248 }
249 return true;
250 }
251
252 void
253 Bus::recvRetry(int id)
254 {
255 // If there's anything waiting, and the bus isn't busy...
256 if (retryList.size() && curTick >= tickNextIdle) {
257 //retryingPort = retryList.front();
258 inRetry = true;
259 DPRINTF(Bus, "Sending a retry to %s\n", retryList.front()->getPeer()->name());
260 retryList.front()->sendRetry();
261 // If inRetry is still true, sendTiming wasn't called
262 if (inRetry)
263 {
264 retryList.front()->onRetryList(false);
265 retryList.pop_front();
266 inRetry = false;
267
268 //Bring tickNextIdle up to the present
269 while (tickNextIdle < curTick)
270 tickNextIdle += clock;
271
272 //Burn a cycle for the missed grant.
273 tickNextIdle += clock;
274
275 busIdle.reschedule(tickNextIdle, true);
276 }
277 }
278 //If we weren't able to drain before, we might be able to now.
279 if (drainEvent && retryList.size() == 0 && curTick >= tickNextIdle) {
280 drainEvent->process();
281 // Clear the drain event once we're done with it.
282 drainEvent = NULL;
283 }
284 }
285
286 int
287 Bus::findPort(Addr addr)
288 {
289 /* An interval tree would be a better way to do this. --ali. */
290 int dest_id = -1;
291
292 PortIter i = portMap.find(RangeSize(addr,1));
293 if (i != portMap.end())
294 dest_id = i->second;
295
296 // Check if this matches the default range
297 if (dest_id == -1) {
298 for (AddrRangeIter iter = defaultRange.begin();
299 iter != defaultRange.end(); iter++) {
300 if (*iter == addr) {
301 DPRINTF(Bus, " found addr %#llx on default\n", addr);
302 return defaultId;
303 }
304 }
305
306 if (responderSet) {
307 panic("Unable to find destination for addr (user set default "
308 "responder): %#llx", addr);
309 } else {
310 DPRINTF(Bus, "Unable to find destination for addr: %#llx, will use "
311 "default port", addr);
312
313 return defaultId;
314 }
315 }
316
317 return dest_id;
318 }
319
320
321 /** Function called by the port when the bus is receiving a Atomic
322 * transaction.*/
323 Tick
324 Bus::recvAtomic(PacketPtr pkt)
325 {
326 DPRINTF(Bus, "recvAtomic: packet src %d dest %d addr 0x%x cmd %s\n",
327 pkt->getSrc(), pkt->getDest(), pkt->getAddr(), pkt->cmdString());
328 assert(pkt->getDest() == Packet::Broadcast);
329 assert(pkt->isRequest());
330
331 // Variables for recording original command and snoop response (if
332 // any)... if a snooper respondes, we will need to restore
333 // original command so that additional snoops can take place
334 // properly
335 MemCmd orig_cmd = pkt->cmd;
336 MemCmd snoop_response_cmd = MemCmd::InvalidCmd;
337 Tick snoop_response_latency = 0;
338 int orig_src = pkt->getSrc();
339
340 int target_port_id = findPort(pkt->getAddr());
341 Port *target_port = (target_port_id == defaultId) ?
342 defaultPort : interfaces[target_port_id];
343
344 SnoopIter s_end = snoopPorts.end();
345 for (SnoopIter s_iter = snoopPorts.begin(); s_iter != s_end; s_iter++) {
346 BusPort *p = *s_iter;
347 // same port should not have both target addresses and snooping
348 assert(p != target_port);
349 if (p->getId() != pkt->getSrc()) {
350 Tick latency = p->sendAtomic(pkt);
351 if (pkt->isResponse()) {
352 // response from snoop agent
353 assert(pkt->cmd != orig_cmd);
354 assert(pkt->memInhibitAsserted());
355 // should only happen once
356 assert(snoop_response_cmd == MemCmd::InvalidCmd);
357 // save response state
358 snoop_response_cmd = pkt->cmd;
359 snoop_response_latency = latency;
360 // restore original packet state for remaining snoopers
361 pkt->cmd = orig_cmd;
362 pkt->setSrc(orig_src);
363 pkt->setDest(Packet::Broadcast);
364 }
365 }
366 }
367
368 Tick response_latency = 0;
369
370 // we can get requests sent up from the memory side of the bus for
371 // snooping... don't send them back down!
372 if (target_port_id != pkt->getSrc()) {
373 response_latency = target_port->sendAtomic(pkt);
374 }
375
376 // if we got a response from a snooper, restore it here
377 if (snoop_response_cmd != MemCmd::InvalidCmd) {
378 // no one else should have responded
379 assert(!pkt->isResponse());
380 assert(pkt->cmd == orig_cmd);
381 pkt->cmd = snoop_response_cmd;
382 response_latency = snoop_response_latency;
383 }
384
385 // why do we have this packet field and the return value both???
386 pkt->finishTime = curTick + response_latency;
387 return response_latency;
388 }
389
390 /** Function called by the port when the bus is receiving a Functional
391 * transaction.*/
392 void
393 Bus::recvFunctional(PacketPtr pkt)
394 {
395 DPRINTF(Bus, "recvFunctional: packet src %d dest %d addr 0x%x cmd %s\n",
396 pkt->getSrc(), pkt->getDest(), pkt->getAddr(), pkt->cmdString());
397 assert(pkt->getDest() == Packet::Broadcast);
398
399 int port_id = findPort(pkt->getAddr());
400 Port *port = (port_id == defaultId) ? defaultPort : interfaces[port_id];
401 // The packet may be changed by another bus on snoops, restore the
402 // id after each
403 int src_id = pkt->getSrc();
404
405 assert(pkt->isRequest()); // hasn't already been satisfied
406
407 for (SnoopIter s_iter = snoopPorts.begin();
408 s_iter != snoopPorts.end();
409 s_iter++) {
410 BusPort *p = *s_iter;
411 if (p != port && p->getId() != src_id) {
412 p->sendFunctional(pkt);
413 }
414 if (pkt->isResponse()) {
415 break;
416 }
417 pkt->setSrc(src_id);
418 }
419
420 // If the snooping hasn't found what we were looking for, keep going.
421 if (!pkt->isResponse() && port_id != pkt->getSrc()) {
422 port->sendFunctional(pkt);
423 }
424 }
425
426 /** Function called by the port when the bus is receiving a status change.*/
427 void
428 Bus::recvStatusChange(Port::Status status, int id)
429 {
430 AddrRangeList ranges;
431 bool snoops;
432 AddrRangeIter iter;
433
434 assert(status == Port::RangeChange &&
435 "The other statuses need to be implemented.");
436
437 DPRINTF(BusAddrRanges, "received RangeChange from device id %d\n", id);
438
439 if (id == defaultId) {
440 defaultRange.clear();
441 // Only try to update these ranges if the user set a default responder.
442 if (responderSet) {
443 defaultPort->getPeerAddressRanges(ranges, snoops);
444 assert(snoops == false);
445 for(iter = ranges.begin(); iter != ranges.end(); iter++) {
446 defaultRange.push_back(*iter);
447 DPRINTF(BusAddrRanges, "Adding range %#llx - %#llx for default range\n",
448 iter->start, iter->end);
449 }
450 }
451 } else {
452
453 assert((id < maxId && id >= 0) || id == defaultId);
454 BusPort *port = interfaces[id];
455
456 // Clean out any previously existent ids
457 for (PortIter portIter = portMap.begin();
458 portIter != portMap.end(); ) {
459 if (portIter->second == id)
460 portMap.erase(portIter++);
461 else
462 portIter++;
463 }
464
465 for (SnoopIter s_iter = snoopPorts.begin();
466 s_iter != snoopPorts.end(); ) {
467 if ((*s_iter)->getId() == id)
468 s_iter = snoopPorts.erase(s_iter);
469 else
470 s_iter++;
471 }
472
473 port->getPeerAddressRanges(ranges, snoops);
474
475 if (snoops) {
476 DPRINTF(BusAddrRanges, "Adding id %d to snoop list\n", id);
477 snoopPorts.push_back(port);
478 }
479
480 for (iter = ranges.begin(); iter != ranges.end(); iter++) {
481 DPRINTF(BusAddrRanges, "Adding range %#llx - %#llx for id %d\n",
482 iter->start, iter->end, id);
483 if (portMap.insert(*iter, id) == portMap.end())
484 panic("Two devices with same range\n");
485
486 }
487 }
488 DPRINTF(MMU, "port list has %d entries\n", portMap.size());
489
490 // tell all our peers that our address range has changed.
491 // Don't tell the device that caused this change, it already knows
492 m5::hash_map<short,BusPort*>::iterator intIter;
493
494 for (intIter = interfaces.begin(); intIter != interfaces.end(); intIter++)
495 if (intIter->first != id && intIter->first != funcPortId)
496 intIter->second->sendStatusChange(Port::RangeChange);
497
498 if (id != defaultId && defaultPort)
499 defaultPort->sendStatusChange(Port::RangeChange);
500 }
501
502 void
503 Bus::addressRanges(AddrRangeList &resp, bool &snoop, int id)
504 {
505 resp.clear();
506 snoop = false;
507
508 DPRINTF(BusAddrRanges, "received address range request, returning:\n");
509
510 for (AddrRangeIter dflt_iter = defaultRange.begin();
511 dflt_iter != defaultRange.end(); dflt_iter++) {
512 resp.push_back(*dflt_iter);
513 DPRINTF(BusAddrRanges, " -- Dflt: %#llx : %#llx\n",dflt_iter->start,
514 dflt_iter->end);
515 }
516 for (PortIter portIter = portMap.begin();
517 portIter != portMap.end(); portIter++) {
518 bool subset = false;
519 for (AddrRangeIter dflt_iter = defaultRange.begin();
520 dflt_iter != defaultRange.end(); dflt_iter++) {
521 if ((portIter->first.start < dflt_iter->start &&
522 portIter->first.end >= dflt_iter->start) ||
523 (portIter->first.start < dflt_iter->end &&
524 portIter->first.end >= dflt_iter->end))
525 fatal("Devices can not set ranges that itersect the default set\
526 but are not a subset of the default set.\n");
527 if (portIter->first.start >= dflt_iter->start &&
528 portIter->first.end <= dflt_iter->end) {
529 subset = true;
530 DPRINTF(BusAddrRanges, " -- %#llx : %#llx is a SUBSET\n",
531 portIter->first.start, portIter->first.end);
532 }
533 }
534 if (portIter->second != id && !subset) {
535 resp.push_back(portIter->first);
536 DPRINTF(BusAddrRanges, " -- %#llx : %#llx\n",
537 portIter->first.start, portIter->first.end);
538 }
539 }
540
541 for (SnoopIter s_iter = snoopPorts.begin(); s_iter != snoopPorts.end();
542 s_iter++) {
543 if ((*s_iter)->getId() != id) {
544 snoop = true;
545 break;
546 }
547 }
548 }
549
550 int
551 Bus::findBlockSize(int id)
552 {
553 if (cachedBlockSizeValid)
554 return cachedBlockSize;
555
556 int max_bs = -1;
557
558 for (PortIter portIter = portMap.begin();
559 portIter != portMap.end(); portIter++) {
560 int tmp_bs = interfaces[portIter->second]->peerBlockSize();
561 if (tmp_bs > max_bs)
562 max_bs = tmp_bs;
563 }
564 for (SnoopIter s_iter = snoopPorts.begin();
565 s_iter != snoopPorts.end(); s_iter++) {
566 int tmp_bs = (*s_iter)->peerBlockSize();
567 if (tmp_bs > max_bs)
568 max_bs = tmp_bs;
569 }
570 if (max_bs <= 0)
571 max_bs = defaultBlockSize;
572
573 if (max_bs != 64)
574 warn_once("Blocksize found to not be 64... hmm... probably not.\n");
575 cachedBlockSize = max_bs;
576 cachedBlockSizeValid = true;
577 return max_bs;
578 }
579
580
581 unsigned int
582 Bus::drain(Event * de)
583 {
584 //We should check that we're not "doing" anything, and that noone is
585 //waiting. We might be idle but have someone waiting if the device we
586 //contacted for a retry didn't actually retry.
587 if (curTick >= tickNextIdle && retryList.size() == 0) {
588 return 0;
589 } else {
590 drainEvent = de;
591 return 1;
592 }
593 }
594
595 void
596 Bus::startup()
597 {
598 if (tickNextIdle < curTick)
599 tickNextIdle = (curTick / clock) * clock + clock;
600 }
601
602 BEGIN_DECLARE_SIM_OBJECT_PARAMS(Bus)
603
604 Param<int> bus_id;
605 Param<int> clock;
606 Param<int> width;
607 Param<bool> responder_set;
608 Param<int> block_size;
609
610 END_DECLARE_SIM_OBJECT_PARAMS(Bus)
611
612 BEGIN_INIT_SIM_OBJECT_PARAMS(Bus)
613 INIT_PARAM(bus_id, "a globally unique bus id"),
614 INIT_PARAM(clock, "bus clock speed"),
615 INIT_PARAM(width, "width of the bus (bits)"),
616 INIT_PARAM(responder_set, "Is a default responder set by the user"),
617 INIT_PARAM(block_size, "Default blocksize if no device has one")
618 END_INIT_SIM_OBJECT_PARAMS(Bus)
619
620 CREATE_SIM_OBJECT(Bus)
621 {
622 return new Bus(getInstanceName(), bus_id, clock, width, responder_set,
623 block_size);
624 }
625
626 REGISTER_SIM_OBJECT("Bus", Bus)