Merge zizzer:/bk/sparcfs/
[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
37 #include "base/misc.hh"
38 #include "base/trace.hh"
39 #include "mem/bus.hh"
40 #include "sim/builder.hh"
41
42 Port *
43 Bus::getPort(const std::string &if_name, int idx)
44 {
45 if (if_name == "default") {
46 if (defaultPort == NULL) {
47 defaultPort = new BusPort(csprintf("%s-default",name()), this,
48 defaultId);
49 return defaultPort;
50 } else
51 fatal("Default port already set\n");
52 }
53
54 // if_name ignored? forced to be empty?
55 int id = interfaces.size();
56 BusPort *bp = new BusPort(csprintf("%s-p%d", name(), id), this, id);
57 interfaces.push_back(bp);
58 return bp;
59 }
60
61 /** Get the ranges of anyone other buses that we are connected to. */
62 void
63 Bus::init()
64 {
65 std::vector<BusPort*>::iterator intIter;
66
67 for (intIter = interfaces.begin(); intIter != interfaces.end(); intIter++)
68 (*intIter)->sendStatusChange(Port::RangeChange);
69 }
70
71 Bus::BusFreeEvent::BusFreeEvent(Bus *_bus) : Event(&mainEventQueue), bus(_bus)
72 {}
73
74 void Bus::BusFreeEvent::process()
75 {
76 bus->recvRetry(-1);
77 }
78
79 const char * Bus::BusFreeEvent::description()
80 {
81 return "bus became available";
82 }
83
84 void Bus::occupyBus(PacketPtr pkt)
85 {
86 //Bring tickNextIdle up to the present tick
87 //There is some potential ambiguity where a cycle starts, which might make
88 //a difference when devices are acting right around a cycle boundary. Using
89 //a < allows things which happen exactly on a cycle boundary to take up only
90 //the following cycle. Anthing that happens later will have to "wait" for
91 //the end of that cycle, and then start using the bus after that.
92 while (tickNextIdle < curTick)
93 tickNextIdle += clock;
94
95 // The packet will be sent. Figure out how long it occupies the bus, and
96 // how much of that time is for the first "word", aka bus width.
97 int numCycles = 0;
98 // Requests need one cycle to send an address
99 if (pkt->isRequest())
100 numCycles++;
101 else if (pkt->isResponse() || pkt->hasData()) {
102 // If a packet has data, it needs ceil(size/width) cycles to send it
103 // We're using the "adding instead of dividing" trick again here
104 if (pkt->hasData()) {
105 int dataSize = pkt->getSize();
106 for (int transmitted = 0; transmitted < dataSize;
107 transmitted += width) {
108 numCycles++;
109 }
110 } else {
111 // If the packet didn't have data, it must have been a response.
112 // Those use the bus for one cycle to send their data.
113 numCycles++;
114 }
115 }
116
117 // The first word will be delivered after the current tick, the delivery
118 // of the address if any, and one bus cycle to deliver the data
119 pkt->firstWordTime =
120 tickNextIdle +
121 pkt->isRequest() ? clock : 0 +
122 clock;
123
124 //Advance it numCycles bus cycles.
125 //XXX Should this use the repeated addition trick as well?
126 tickNextIdle += (numCycles * clock);
127 if (!busIdle.scheduled()) {
128 busIdle.schedule(tickNextIdle);
129 } else {
130 busIdle.reschedule(tickNextIdle);
131 }
132 DPRINTF(Bus, "The bus is now occupied from tick %d to %d\n",
133 curTick, tickNextIdle);
134
135 // The bus will become idle once the current packet is delivered.
136 pkt->finishTime = tickNextIdle;
137 }
138
139 /** Function called by the port when the bus is receiving a Timing
140 * transaction.*/
141 bool
142 Bus::recvTiming(PacketPtr pkt)
143 {
144 Port *port;
145 DPRINTF(Bus, "recvTiming: packet src %d dest %d addr 0x%x cmd %s\n",
146 pkt->getSrc(), pkt->getDest(), pkt->getAddr(), pkt->cmdString());
147
148 BusPort *pktPort;
149 if (pkt->getSrc() == defaultId)
150 pktPort = defaultPort;
151 else pktPort = interfaces[pkt->getSrc()];
152
153 // If the bus is busy, or other devices are in line ahead of the current
154 // one, put this device on the retry list.
155 if (tickNextIdle > curTick ||
156 (retryList.size() && (!inRetry || pktPort != retryList.front()))) {
157 addToRetryList(pktPort);
158 return false;
159 }
160
161 short dest = pkt->getDest();
162 if (dest == Packet::Broadcast) {
163 port = findPort(pkt->getAddr(), pkt->getSrc());
164 if (timingSnoop(pkt, port ? port : interfaces[pkt->getSrc()])) {
165 bool success;
166
167 pkt->flags |= SNOOP_COMMIT;
168 success = timingSnoop(pkt, port ? port : interfaces[pkt->getSrc()]);
169 assert(success);
170
171 if (pkt->flags & SATISFIED) {
172 //Cache-Cache transfer occuring
173 if (inRetry) {
174 retryList.front()->onRetryList(false);
175 retryList.pop_front();
176 inRetry = false;
177 }
178 occupyBus(pkt);
179 return true;
180 }
181 } else {
182 //Snoop didn't succeed
183 DPRINTF(Bus, "Adding a retry to RETRY list %i\n", pktPort);
184 addToRetryList(pktPort);
185 return false;
186 }
187 } else {
188 assert(dest >= 0 && dest < interfaces.size());
189 assert(dest != pkt->getSrc()); // catch infinite loops
190 port = interfaces[dest];
191 }
192
193 occupyBus(pkt);
194
195 if (port) {
196 if (port->sendTiming(pkt)) {
197 // Packet was successfully sent. Return true.
198 // Also take care of retries
199 if (inRetry) {
200 DPRINTF(Bus, "Remove retry from list %i\n", retryList.front());
201 retryList.front()->onRetryList(false);
202 retryList.pop_front();
203 inRetry = false;
204 }
205 return true;
206 }
207
208 // Packet not successfully sent. Leave or put it on the retry list.
209 DPRINTF(Bus, "Adding a retry to RETRY list %i\n", pktPort);
210 addToRetryList(pktPort);
211 return false;
212 }
213 else {
214 //Forwarding up from responder, just return true;
215 return true;
216 }
217 }
218
219 void
220 Bus::recvRetry(int id)
221 {
222 DPRINTF(Bus, "Received a retry\n");
223 // If there's anything waiting, and the bus isn't busy...
224 if (retryList.size() && curTick >= tickNextIdle) {
225 //retryingPort = retryList.front();
226 inRetry = true;
227 DPRINTF(Bus, "Sending a retry\n");
228 retryList.front()->sendRetry();
229 // If inRetry is still true, sendTiming wasn't called
230 if (inRetry)
231 {
232 retryList.front()->onRetryList(false);
233 retryList.pop_front();
234 inRetry = false;
235
236 //Bring tickNextIdle up to the present
237 while (tickNextIdle < curTick)
238 tickNextIdle += clock;
239
240 //Burn a cycle for the missed grant.
241 tickNextIdle += clock;
242
243 if (!busIdle.scheduled()) {
244 busIdle.schedule(tickNextIdle);
245 } else {
246 busIdle.reschedule(tickNextIdle);
247 }
248 }
249 }
250 //If we weren't able to drain before, we might be able to now.
251 if (drainEvent && retryList.size() == 0 && curTick >= tickNextIdle) {
252 drainEvent->process();
253 // Clear the drain event once we're done with it.
254 drainEvent = NULL;
255 }
256 }
257
258 Port *
259 Bus::findPort(Addr addr, int id)
260 {
261 /* An interval tree would be a better way to do this. --ali. */
262 int dest_id = -1;
263 AddrRangeIter iter;
264 range_map<Addr,int>::iterator i;
265
266 i = portMap.find(RangeSize(addr,1));
267 if (i != portMap.end())
268 dest_id = i->second;
269
270 // Check if this matches the default range
271 if (dest_id == -1) {
272 for (iter = defaultRange.begin(); iter != defaultRange.end(); iter++) {
273 if (*iter == addr) {
274 DPRINTF(Bus, " found addr %#llx on default\n", addr);
275 return defaultPort;
276 }
277 }
278
279 if (responderSet) {
280 panic("Unable to find destination for addr (user set default "
281 "responder): %#llx", addr);
282 } else {
283 DPRINTF(Bus, "Unable to find destination for addr: %#llx, will use "
284 "default port", addr);
285
286 return defaultPort;
287 }
288 }
289
290
291 // we shouldn't be sending this back to where it came from
292 // do the snoop access and then we should terminate
293 // the cyclical call.
294 if (dest_id == id)
295 return 0;
296
297 return interfaces[dest_id];
298 }
299
300 std::vector<int>
301 Bus::findSnoopPorts(Addr addr, int id)
302 {
303 int i = 0;
304 AddrRangeIter iter;
305 std::vector<int> ports;
306
307 while (i < portSnoopList.size())
308 {
309 if (portSnoopList[i].range == addr && portSnoopList[i].portId != id) {
310 //Careful to not overlap ranges
311 //or snoop will be called more than once on the port
312
313 //@todo Fix this hack because ranges are overlapping
314 //need to make sure we dont't create overlapping ranges
315 bool hack_overlap = false;
316 int size = ports.size();
317 for (int j=0; j < size; j++) {
318 if (ports[j] == portSnoopList[i].portId)
319 hack_overlap = true;
320 }
321
322 if (!hack_overlap)
323 ports.push_back(portSnoopList[i].portId);
324 // DPRINTF(Bus, " found snoop addr %#llx on device%d\n", addr,
325 // portSnoopList[i].portId);
326 }
327 i++;
328 }
329 return ports;
330 }
331
332 Tick
333 Bus::atomicSnoop(PacketPtr pkt, Port *responder)
334 {
335 std::vector<int> ports = findSnoopPorts(pkt->getAddr(), pkt->getSrc());
336 Tick response_time = 0;
337
338 while (!ports.empty())
339 {
340 if (interfaces[ports.back()] != responder) {
341 Tick response = interfaces[ports.back()]->sendAtomic(pkt);
342 if (response) {
343 assert(!response_time); //Multiple responders
344 response_time = response;
345 }
346 }
347 ports.pop_back();
348 }
349 return response_time;
350 }
351
352 void
353 Bus::functionalSnoop(PacketPtr pkt, Port *responder)
354 {
355 std::vector<int> ports = findSnoopPorts(pkt->getAddr(), pkt->getSrc());
356
357 //The packet may be changed by another bus on snoops, restore the id after each
358 int id = pkt->getSrc();
359 while (!ports.empty() && pkt->result != Packet::Success)
360 {
361 if (interfaces[ports.back()] != responder)
362 interfaces[ports.back()]->sendFunctional(pkt);
363 ports.pop_back();
364 pkt->setSrc(id);
365 }
366 }
367
368 bool
369 Bus::timingSnoop(PacketPtr pkt, Port* responder)
370 {
371 std::vector<int> ports = findSnoopPorts(pkt->getAddr(), pkt->getSrc());
372 bool success = true;
373
374 while (!ports.empty() && success)
375 {
376 if (interfaces[ports.back()] != responder) //Don't call if responder also, once will do
377 success = interfaces[ports.back()]->sendTiming(pkt);
378 ports.pop_back();
379 }
380
381 return success;
382 }
383
384
385 /** Function called by the port when the bus is receiving a Atomic
386 * transaction.*/
387 Tick
388 Bus::recvAtomic(PacketPtr pkt)
389 {
390 DPRINTF(Bus, "recvAtomic: packet src %d dest %d addr 0x%x cmd %s\n",
391 pkt->getSrc(), pkt->getDest(), pkt->getAddr(), pkt->cmdString());
392 assert(pkt->getDest() == Packet::Broadcast);
393 pkt->flags |= SNOOP_COMMIT;
394
395 // Assume one bus cycle in order to get through. This may have
396 // some clock skew issues yet again...
397 pkt->finishTime = curTick + clock;
398
399 Port *port = findPort(pkt->getAddr(), pkt->getSrc());
400 Tick snoopTime = atomicSnoop(pkt, port ? port : interfaces[pkt->getSrc()]);
401
402 if (snoopTime)
403 return snoopTime; //Snoop satisfies it
404 else if (port)
405 return port->sendAtomic(pkt);
406 else
407 return 0;
408 }
409
410 /** Function called by the port when the bus is receiving a Functional
411 * transaction.*/
412 void
413 Bus::recvFunctional(PacketPtr pkt)
414 {
415 DPRINTF(Bus, "recvFunctional: packet src %d dest %d addr 0x%x cmd %s\n",
416 pkt->getSrc(), pkt->getDest(), pkt->getAddr(), pkt->cmdString());
417 assert(pkt->getDest() == Packet::Broadcast);
418 pkt->flags |= SNOOP_COMMIT;
419
420 Port* port = findPort(pkt->getAddr(), pkt->getSrc());
421 functionalSnoop(pkt, port ? port : interfaces[pkt->getSrc()]);
422
423 // If the snooping found what we were looking for, we're done.
424 if (pkt->result != Packet::Success && port) {
425 port->sendFunctional(pkt);
426 }
427 }
428
429 /** Function called by the port when the bus is receiving a status change.*/
430 void
431 Bus::recvStatusChange(Port::Status status, int id)
432 {
433 AddrRangeList ranges;
434 AddrRangeList snoops;
435 int x;
436 AddrRangeIter iter;
437
438 assert(status == Port::RangeChange &&
439 "The other statuses need to be implemented.");
440
441 DPRINTF(BusAddrRanges, "received RangeChange from device id %d\n", id);
442
443 if (id == defaultId) {
444 defaultRange.clear();
445 // Only try to update these ranges if the user set a default responder.
446 if (responderSet) {
447 defaultPort->getPeerAddressRanges(ranges, snoops);
448 assert(snoops.size() == 0);
449 for(iter = ranges.begin(); iter != ranges.end(); iter++) {
450 defaultRange.push_back(*iter);
451 DPRINTF(BusAddrRanges, "Adding range %#llx - %#llx for default range\n",
452 iter->start, iter->end);
453 }
454 }
455 } else {
456
457 assert((id < interfaces.size() && id >= 0) || id == defaultId);
458 Port *port = interfaces[id];
459 range_map<Addr,int>::iterator portIter;
460 std::vector<DevMap>::iterator snoopIter;
461
462 // Clean out any previously existent ids
463 for (portIter = portMap.begin(); portIter != portMap.end(); ) {
464 if (portIter->second == id)
465 portMap.erase(portIter++);
466 else
467 portIter++;
468 }
469
470 for (snoopIter = portSnoopList.begin(); snoopIter != portSnoopList.end(); ) {
471 if (snoopIter->portId == id)
472 snoopIter = portSnoopList.erase(snoopIter);
473 else
474 snoopIter++;
475 }
476
477 port->getPeerAddressRanges(ranges, snoops);
478
479 for(iter = snoops.begin(); iter != snoops.end(); iter++) {
480 DevMap dm;
481 dm.portId = id;
482 dm.range = *iter;
483
484 //@todo, make sure we don't overlap ranges
485 DPRINTF(BusAddrRanges, "Adding snoop range %#llx - %#llx for id %d\n",
486 dm.range.start, dm.range.end, id);
487 portSnoopList.push_back(dm);
488 }
489
490 for(iter = ranges.begin(); iter != ranges.end(); iter++) {
491 DPRINTF(BusAddrRanges, "Adding range %#llx - %#llx for id %d\n",
492 iter->start, iter->end, id);
493 if (portMap.insert(*iter, id) == portMap.end())
494 panic("Two devices with same range\n");
495
496 }
497 }
498 DPRINTF(MMU, "port list has %d entries\n", portMap.size());
499
500 // tell all our peers that our address range has changed.
501 // Don't tell the device that caused this change, it already knows
502 for (x = 0; x < interfaces.size(); x++)
503 if (x != id)
504 interfaces[x]->sendStatusChange(Port::RangeChange);
505
506 if (id != defaultId && defaultPort)
507 defaultPort->sendStatusChange(Port::RangeChange);
508 }
509
510 void
511 Bus::addressRanges(AddrRangeList &resp, AddrRangeList &snoop, int id)
512 {
513 std::vector<DevMap>::iterator snoopIter;
514 range_map<Addr,int>::iterator portIter;
515 AddrRangeIter dflt_iter;
516 bool subset;
517
518 resp.clear();
519 snoop.clear();
520
521 DPRINTF(BusAddrRanges, "received address range request, returning:\n");
522
523 for (dflt_iter = defaultRange.begin(); dflt_iter != defaultRange.end();
524 dflt_iter++) {
525 resp.push_back(*dflt_iter);
526 DPRINTF(BusAddrRanges, " -- Dflt: %#llx : %#llx\n",dflt_iter->start,
527 dflt_iter->end);
528 }
529 for (portIter = portMap.begin(); portIter != portMap.end(); portIter++) {
530 subset = false;
531 for (dflt_iter = defaultRange.begin(); dflt_iter != defaultRange.end();
532 dflt_iter++) {
533 if ((portIter->first.start < dflt_iter->start &&
534 portIter->first.end >= dflt_iter->start) ||
535 (portIter->first.start < dflt_iter->end &&
536 portIter->first.end >= dflt_iter->end))
537 fatal("Devices can not set ranges that itersect the default set\
538 but are not a subset of the default set.\n");
539 if (portIter->first.start >= dflt_iter->start &&
540 portIter->first.end <= dflt_iter->end) {
541 subset = true;
542 DPRINTF(BusAddrRanges, " -- %#llx : %#llx is a SUBSET\n",
543 portIter->first.start, portIter->first.end);
544 }
545 }
546 if (portIter->second != id && !subset) {
547 resp.push_back(portIter->first);
548 DPRINTF(BusAddrRanges, " -- %#llx : %#llx\n",
549 portIter->first.start, portIter->first.end);
550 }
551 }
552
553 for (snoopIter = portSnoopList.begin();
554 snoopIter != portSnoopList.end(); snoopIter++)
555 {
556 if (snoopIter->portId != id) {
557 snoop.push_back(snoopIter->range);
558 DPRINTF(BusAddrRanges, " -- Snoop: %#llx : %#llx\n",
559 snoopIter->range.start, snoopIter->range.end);
560 //@todo We need to properly insert snoop ranges
561 //not overlapping the ranges (multiple)
562 }
563 }
564 }
565
566 unsigned int
567 Bus::drain(Event * de)
568 {
569 //We should check that we're not "doing" anything, and that noone is
570 //waiting. We might be idle but have someone waiting if the device we
571 //contacted for a retry didn't actually retry.
572 if (curTick >= tickNextIdle && retryList.size() == 0) {
573 return 0;
574 } else {
575 drainEvent = de;
576 return 1;
577 }
578 }
579
580 BEGIN_DECLARE_SIM_OBJECT_PARAMS(Bus)
581
582 Param<int> bus_id;
583 Param<int> clock;
584 Param<int> width;
585 Param<bool> responder_set;
586
587 END_DECLARE_SIM_OBJECT_PARAMS(Bus)
588
589 BEGIN_INIT_SIM_OBJECT_PARAMS(Bus)
590 INIT_PARAM(bus_id, "a globally unique bus id"),
591 INIT_PARAM(clock, "bus clock speed"),
592 INIT_PARAM(width, "width of the bus (bits)"),
593 INIT_PARAM(responder_set, "Is a default responder set by the user")
594 END_INIT_SIM_OBJECT_PARAMS(Bus)
595
596 CREATE_SIM_OBJECT(Bus)
597 {
598 return new Bus(getInstanceName(), bus_id, clock, width, responder_set);
599 }
600
601 REGISTER_SIM_OBJECT("Bus", Bus)