2 * Copyright (c) 2002-2005 The Regents of The University of Michigan
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.
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.
28 * Authors: Erik Hallnor
45 #include "sim/host.hh"
46 #include "base/misc.hh"
49 #include "mem/cache/cache.hh"
50 #include "mem/cache/cache_blk.hh"
51 #include "mem/cache/miss/mshr.hh"
52 #include "mem/cache/prefetch/prefetcher.hh"
54 #include "sim/sim_exit.hh" // for SimExitEvent
56 template<class TagStore, class Buffering, class Coherence>
58 Cache<TagStore,Buffering,Coherence>::
59 doTimingAccess(PacketPtr pkt, CachePort *cachePort, bool isCpuSide)
63 if (pkt->isWrite() && (pkt->req->isLocked())) {
64 pkt->req->setScResult(1);
71 if (pkt->isResponse())
74 //Check if we should do the snoop
75 if (pkt->flags & SNOOP_COMMIT)
82 template<class TagStore, class Buffering, class Coherence>
84 Cache<TagStore,Buffering,Coherence>::
85 doAtomicAccess(PacketPtr pkt, bool isCpuSide)
89 probe(pkt, true, NULL);
90 //TEMP ALWAYS SUCCES FOR NOW
91 pkt->result = Packet::Success;
95 if (pkt->isResponse())
98 return snoopProbe(pkt);
100 //Fix this timing info
104 template<class TagStore, class Buffering, class Coherence>
106 Cache<TagStore,Buffering,Coherence>::
107 doFunctionalAccess(PacketPtr pkt, bool isCpuSide)
111 //TEMP USE CPU?THREAD 0 0
112 pkt->req->setThreadContext(0,0);
114 probe(pkt, false, memSidePort);
115 //TEMP ALWAYS SUCCESFUL FOR NOW
116 pkt->result = Packet::Success;
120 probe(pkt, false, cpuSidePort);
124 template<class TagStore, class Buffering, class Coherence>
126 Cache<TagStore,Buffering,Coherence>::
127 recvStatusChange(Port::Status status, bool isCpuSide)
133 template<class TagStore, class Buffering, class Coherence>
134 Cache<TagStore,Buffering,Coherence>::
135 Cache(const std::string &_name,
136 Cache<TagStore,Buffering,Coherence>::Params ¶ms)
137 : BaseCache(_name, params.baseParams),
138 prefetchAccess(params.prefetchAccess),
139 tags(params.tags), missQueue(params.missQueue),
140 coherence(params.coherence), prefetcher(params.prefetcher),
141 hitLatency(params.hitLatency)
143 tags->setCache(this);
144 tags->setPrefetcher(prefetcher);
145 missQueue->setCache(this);
146 missQueue->setPrefetcher(prefetcher);
147 coherence->setCache(this);
148 prefetcher->setCache(this);
149 prefetcher->setTags(tags);
150 prefetcher->setBuffer(missQueue);
151 invalidateReq = new Request((Addr) NULL, blkSize, 0);
152 invalidatePkt = new Packet(invalidateReq, Packet::InvalidateReq, 0);
155 template<class TagStore, class Buffering, class Coherence>
157 Cache<TagStore,Buffering,Coherence>::regStats()
159 BaseCache::regStats();
160 tags->regStats(name());
161 missQueue->regStats(name());
162 coherence->regStats(name());
163 prefetcher->regStats(name());
166 template<class TagStore, class Buffering, class Coherence>
168 Cache<TagStore,Buffering,Coherence>::access(PacketPtr &pkt)
170 //@todo Add back in MemDebug Calls
171 // MemDebug::cacheAccess(pkt);
173 PacketList writebacks;
175 int lat = hitLatency;
176 if (prefetchAccess) {
177 //We are determining prefetches on access stream, call prefetcher
178 prefetcher->handleMiss(pkt, curTick);
180 if (!pkt->req->isUncacheable()) {
181 blk = tags->handleAccess(pkt, lat, writebacks);
183 size = pkt->getSize();
185 // If this is a block size write/hint (WH64) allocate the block here
186 // if the coherence protocol allows it.
187 /** @todo make the fast write alloc (wh64) work with coherence. */
188 /** @todo Do we want to do fast writes for writebacks as well? */
189 if (!blk && pkt->getSize() >= blkSize && coherence->allowFastWrites() &&
190 (pkt->cmd == Packet::WriteReq
191 || pkt->cmd == Packet::WriteInvalidateReq) ) {
192 // not outstanding misses, can do this
193 MSHR* outstanding_miss = missQueue->findMSHR(pkt->getAddr());
194 if (pkt->cmd == Packet::WriteInvalidateReq || !outstanding_miss) {
195 if (outstanding_miss) {
196 warn("WriteInv doing a fastallocate"
197 "with an outstanding miss to the same address\n");
199 blk = tags->handleFill(NULL, pkt, BlkValid | BlkWritable,
204 while (!writebacks.empty()) {
205 missQueue->doWriteback(writebacks.front());
206 writebacks.pop_front();
209 DPRINTF(Cache, "%s %x %s\n", pkt->cmdString(), pkt->getAddr(),
210 (blk) ? "hit" : "miss");
214 hits[pkt->cmdToIndex()][0/*pkt->req->getThreadNum()*/]++;
215 // clear dirty bit if write through
216 if (pkt->needsResponse())
217 respond(pkt, curTick+lat);
218 if (pkt->cmd == Packet::Writeback) {
219 //Signal that you can kill the pkt/req
220 pkt->flags |= SATISFIED;
226 if (!pkt->req->isUncacheable()) {
227 misses[pkt->cmdToIndex()][0/*pkt->req->getThreadNum()*/]++;
228 /** @todo Move miss count code into BaseCache */
232 exitSimLoop("A cache reached the maximum miss count");
236 if (pkt->flags & SATISFIED) {
237 // happens when a store conditional fails because it missed
238 // the cache completely
239 if (pkt->needsResponse())
240 respond(pkt, curTick+lat);
242 missQueue->handleMiss(pkt, size, curTick + hitLatency);
249 template<class TagStore, class Buffering, class Coherence>
251 Cache<TagStore,Buffering,Coherence>::getPacket()
253 assert(missQueue->havePending());
254 PacketPtr pkt = missQueue->getPacket();
256 if (!pkt->req->isUncacheable()) {
257 if (pkt->cmd == Packet::HardPFReq)
258 misses[Packet::HardPFReq][0/*pkt->req->getThreadNum()*/]++;
259 BlkType *blk = tags->findBlock(pkt);
260 Packet::Command cmd = coherence->getBusCmd(pkt->cmd,
261 (blk)? blk->status : 0);
262 missQueue->setBusCmd(pkt, cmd);
266 assert(!doMasterRequest() || missQueue->havePending());
267 assert(!pkt || pkt->time <= curTick);
271 template<class TagStore, class Buffering, class Coherence>
273 Cache<TagStore,Buffering,Coherence>::sendResult(PacketPtr &pkt, MSHR* mshr,
276 if (success && !(pkt && (pkt->flags & NACKED_LINE))) {
277 if (!mshr->pkt->needsResponse()
278 && !(mshr->pkt->cmd == Packet::UpgradeReq)
279 && (pkt && (pkt->flags & SATISFIED))) {
280 //Writeback, clean up the non copy version of the packet
283 missQueue->markInService(mshr->pkt, mshr);
284 //Temp Hack for UPGRADES
285 if (mshr->pkt && mshr->pkt->cmd == Packet::UpgradeReq) {
286 assert(pkt); //Upgrades need to be fixed
287 pkt->flags &= ~CACHE_LINE_FILL;
288 BlkType *blk = tags->findBlock(pkt);
289 CacheBlk::State old_state = (blk) ? blk->status : 0;
290 CacheBlk::State new_state = coherence->getNewState(pkt,old_state);
291 if (old_state != new_state)
292 DPRINTF(Cache, "Block for blk addr %x moving from state "
293 "%i to %i\n", pkt->getAddr(), old_state, new_state);
294 //Set the state on the upgrade
295 memcpy(pkt->getPtr<uint8_t>(), blk->data, blkSize);
296 PacketList writebacks;
297 tags->handleFill(blk, mshr, new_state, writebacks, pkt);
298 assert(writebacks.empty());
299 missQueue->handleResponse(pkt, curTick + hitLatency);
301 } else if (pkt && !pkt->req->isUncacheable()) {
302 pkt->flags &= ~NACKED_LINE;
303 pkt->flags &= ~SATISFIED;
304 pkt->flags &= ~SNOOP_COMMIT;
306 //Rmove copy from mshr
310 missQueue->restoreOrigCmd(pkt);
314 template<class TagStore, class Buffering, class Coherence>
316 Cache<TagStore,Buffering,Coherence>::handleResponse(PacketPtr &pkt)
319 if (pkt->senderState) {
320 //Delete temp copy in MSHR, restore it.
321 delete ((MSHR*)pkt->senderState)->pkt;
322 ((MSHR*)pkt->senderState)->pkt = pkt;
323 if (pkt->result == Packet::Nacked) {
324 //pkt->reinitFromRequest();
325 warn("NACKs from devices not connected to the same bus "
326 "not implemented\n");
329 if (pkt->result == Packet::BadAddress) {
330 //Make the response a Bad address and send it
332 // MemDebug::cacheResponse(pkt);
333 DPRINTF(Cache, "Handling reponse to %x\n", pkt->getAddr());
335 if (pkt->isCacheFill() && !pkt->isNoAllocate()) {
336 DPRINTF(Cache, "Block for addr %x being updated in Cache\n",
338 blk = tags->findBlock(pkt);
339 CacheBlk::State old_state = (blk) ? blk->status : 0;
340 PacketList writebacks;
341 CacheBlk::State new_state = coherence->getNewState(pkt,old_state);
342 if (old_state != new_state)
343 DPRINTF(Cache, "Block for blk addr %x moving from "
346 old_state, new_state);
347 blk = tags->handleFill(blk, (MSHR*)pkt->senderState,
348 new_state, writebacks, pkt);
349 while (!writebacks.empty()) {
350 missQueue->doWriteback(writebacks.front());
351 writebacks.pop_front();
354 missQueue->handleResponse(pkt, curTick + hitLatency);
358 template<class TagStore, class Buffering, class Coherence>
360 Cache<TagStore,Buffering,Coherence>::getCoherencePacket()
362 return coherence->getPacket();
365 template<class TagStore, class Buffering, class Coherence>
367 Cache<TagStore,Buffering,Coherence>::sendCoherenceResult(PacketPtr &pkt,
371 coherence->sendResult(pkt, cshr, success);
375 template<class TagStore, class Buffering, class Coherence>
377 Cache<TagStore,Buffering,Coherence>::snoop(PacketPtr &pkt)
379 if (pkt->req->isUncacheable()) {
380 //Can't get a hit on an uncacheable address
381 //Revisit this for multi level coherence
385 //Send a timing (true) invalidate up if the protocol calls for it
386 coherence->propogateInvalidate(pkt, true);
388 Addr blk_addr = pkt->getAddr() & ~(Addr(blkSize-1));
389 BlkType *blk = tags->findBlock(pkt);
390 MSHR *mshr = missQueue->findMSHR(blk_addr);
391 if (coherence->hasProtocol() || pkt->isInvalidate()) {
392 //@todo Move this into handle bus req
393 //If we find an mshr, and it is in service, we need to NACK or
396 if (mshr->inService) {
397 if ((mshr->pkt->isInvalidate() || !mshr->pkt->isCacheFill())
398 && (pkt->cmd != Packet::InvalidateReq
399 && pkt->cmd != Packet::WriteInvalidateReq)) {
400 //If the outstanding request was an invalidate
401 //(upgrade,readex,..) Then we need to ACK the request
402 //until we get the data Also NACK if the outstanding
403 //request is not a cachefill (writeback)
404 assert(!(pkt->flags & SATISFIED));
405 pkt->flags |= SATISFIED;
406 pkt->flags |= NACKED_LINE;
407 ///@todo NACK's from other levels
408 //warn("NACKs from devices not connected to the same bus "
409 //"not implemented\n");
410 //respondToSnoop(pkt, curTick + hitLatency);
414 //The supplier will be someone else, because we are
415 //waiting for the data. This should cause this cache to
416 //be forced to go to the shared state, not the exclusive
417 //even though the shared line won't be asserted. But for
418 //now we will just invlidate ourselves and allow the other
419 //cache to go into the exclusive state. @todo Make it so
420 //a read to a pending read doesn't invalidate. @todo Make
421 //it so that a read to a pending read can't be exclusive
424 //Set the address so find match works
425 //panic("Don't have invalidates yet\n");
426 invalidatePkt->addrOverride(pkt->getAddr());
428 //Append the invalidate on
429 missQueue->addTarget(mshr,invalidatePkt);
430 DPRINTF(Cache, "Appending Invalidate to addr: %x\n",
436 //We also need to check the writeback buffers and handle those
437 std::vector<MSHR *> writebacks;
438 if (missQueue->findWrites(blk_addr, writebacks)) {
439 DPRINTF(Cache, "Snoop hit in writeback to addr: %x\n",
442 //Look through writebacks for any non-uncachable writes, use that
443 for (int i=0; i<writebacks.size(); i++) {
444 mshr = writebacks[i];
446 if (!mshr->pkt->req->isUncacheable()) {
448 //Only Upgrades don't get here
450 assert(!(pkt->flags & SATISFIED));
451 pkt->flags |= SATISFIED;
453 //If we are in an exclusive protocol, make it ask again
454 //to get write permissions (upgrade), signal shared
455 pkt->flags |= SHARED_LINE;
457 assert(pkt->isRead());
458 Addr offset = pkt->getAddr() & (blkSize - 1);
459 assert(offset < blkSize);
460 assert(pkt->getSize() <= blkSize);
461 assert(offset + pkt->getSize() <=blkSize);
462 memcpy(pkt->getPtr<uint8_t>(), mshr->pkt->getPtr<uint8_t>() + offset, pkt->getSize());
464 respondToSnoop(pkt, curTick + hitLatency);
467 if (pkt->isInvalidate()) {
468 //This must be an upgrade or other cache will take
470 missQueue->markInService(mshr->pkt, mshr);
477 CacheBlk::State new_state;
478 bool satisfy = coherence->handleBusRequest(pkt,blk,mshr, new_state);
480 DPRINTF(Cache, "Cache snooped a %s request for addr %x and "
481 "now supplying data, new state is %i\n",
482 pkt->cmdString(), blk_addr, new_state);
484 tags->handleSnoop(blk, new_state, pkt);
485 respondToSnoop(pkt, curTick + hitLatency);
489 DPRINTF(Cache, "Cache snooped a %s request for addr %x, "
490 "new state is %i\n", pkt->cmdString(), blk_addr, new_state);
491 if (mshr && !mshr->inService && new_state == 0) {
492 //There was a outstanding write to a shared block, not need ReadEx
493 //not update, so change No Allocate param in MSHR
494 mshr->pkt->flags &= ~NO_ALLOCATE;
497 tags->handleSnoop(blk, new_state);
500 template<class TagStore, class Buffering, class Coherence>
502 Cache<TagStore,Buffering,Coherence>::snoopResponse(PacketPtr &pkt)
504 //Need to handle the response, if NACKED
505 if (pkt->flags & NACKED_LINE) {
506 //Need to mark it as not in service, and retry for bus
507 assert(0); //Yeah, we saw a NACK come through
509 //For now this should never get called, we return false when we see a
510 //NACK instead, by doing this we allow the bus_blocked mechanism to
511 //handle the retry For now it retrys in just 2 cycles, need to figure
512 //out how to change that Eventually we will want to also have success
513 //come in as a parameter Need to make sure that we handle the
514 //functionality that happens on successufl return of the sendAddr
519 template<class TagStore, class Buffering, class Coherence>
521 Cache<TagStore,Buffering,Coherence>::invalidateBlk(Addr addr)
523 tags->invalidateBlk(addr);
528 * @todo Fix to not assume write allocate
530 template<class TagStore, class Buffering, class Coherence>
532 Cache<TagStore,Buffering,Coherence>::probe(PacketPtr &pkt, bool update,
533 CachePort* otherSidePort)
535 // MemDebug::cacheProbe(pkt);
536 if (!pkt->req->isUncacheable()) {
537 if (pkt->isInvalidate() && !pkt->isRead() && !pkt->isWrite()) {
538 //Upgrade or Invalidate, satisfy it, don't forward
539 DPRINTF(Cache, "%s %x ?\n", pkt->cmdString(), pkt->getAddr());
540 pkt->flags |= SATISFIED;
545 if (!update && (otherSidePort == cpuSidePort)) {
546 // Still need to change data in all locations.
547 otherSidePort->checkAndSendFunctional(pkt);
548 if (pkt->isRead() && pkt->result == Packet::Success)
552 PacketList writebacks;
554 BlkType *blk = tags->handleAccess(pkt, lat, writebacks, update);
556 DPRINTF(Cache, "%s %x %s\n", pkt->cmdString(),
557 pkt->getAddr(), (blk) ? "hit" : "miss");
560 // Need to check for outstanding misses and writes
561 Addr blk_addr = pkt->getAddr() & ~(blkSize - 1);
563 // There can only be one matching outstanding miss.
564 MSHR* mshr = missQueue->findMSHR(blk_addr);
566 // There can be many matching outstanding writes.
567 std::vector<MSHR*> writes;
568 missQueue->findWrites(blk_addr, writes);
571 bool notDone = !(pkt->flags & SATISFIED); //Hit in cache (was a block)
572 // Check for data in MSHR and writebuffer.
574 MSHR::TargetList *targets = mshr->getTargetList();
575 MSHR::TargetList::iterator i = targets->begin();
576 MSHR::TargetList::iterator end = targets->end();
577 for (; i != end && notDone; ++i) {
578 PacketPtr target = *i;
579 // If the target contains data, and it overlaps the
580 // probed request, need to update data
581 if (target->intersect(pkt)) {
582 DPRINTF(Cache, "Functional %s access to blk_addr %x intersects a MSHR\n",
583 pkt->cmdString(), blk_addr);
584 notDone = fixPacket(pkt, target);
588 for (int i = 0; i < writes.size() && notDone; ++i) {
589 PacketPtr write = writes[i]->pkt;
590 if (write->intersect(pkt)) {
591 DPRINTF(Cache, "Functional %s access to blk_addr %x intersects a writeback\n",
592 pkt->cmdString(), blk_addr);
593 notDone = fixPacket(pkt, write);
596 if (notDone && otherSidePort == memSidePort) {
597 otherSidePort->checkAndSendFunctional(pkt);
598 assert(pkt->result == Packet::Success);
601 } else if (!blk && !(pkt->flags & SATISFIED)) {
602 // update the cache state and statistics
603 if (mshr || !writes.empty()){
604 // Can't handle it, return request unsatisfied.
605 panic("Atomic access ran into outstanding MSHR's or WB's!");
607 if (!pkt->req->isUncacheable()) {
608 // Fetch the cache block to fill
609 BlkType *blk = tags->findBlock(pkt);
610 Packet::Command temp_cmd = coherence->getBusCmd(pkt->cmd,
611 (blk)? blk->status : 0);
613 PacketPtr busPkt = new Packet(pkt->req,temp_cmd, -1, blkSize);
617 busPkt->time = curTick;
619 DPRINTF(Cache, "Sending a atomic %s for %x\n",
620 busPkt->cmdString(), busPkt->getAddr());
622 lat = memSidePort->sendAtomic(busPkt);
624 //Be sure to flip the response to a request for coherence
625 if (busPkt->needsResponse()) {
626 busPkt->makeAtomicResponse();
629 /* if (!(busPkt->flags & SATISFIED)) {
630 // blocked at a higher level, just return
634 */ misses[pkt->cmdToIndex()][0/*pkt->req->getThreadNum()*/]++;
636 CacheBlk::State old_state = (blk) ? blk->status : 0;
637 CacheBlk::State new_state =
638 coherence->getNewState(busPkt, old_state);
639 DPRINTF(Cache, "Receive response: %s for addr %x in state %i\n",
640 busPkt->cmdString(), busPkt->getAddr(), old_state);
641 if (old_state != new_state)
642 DPRINTF(Cache, "Block for blk addr %x moving from state "
643 "%i to %i\n", busPkt->getAddr(), old_state, new_state);
645 tags->handleFill(blk, busPkt, new_state, writebacks, pkt);
649 // Handle writebacks if needed
650 while (!writebacks.empty()){
651 PacketPtr wbPkt = writebacks.front();
652 memSidePort->sendAtomic(wbPkt);
653 writebacks.pop_front();
656 return lat + hitLatency;
658 return memSidePort->sendAtomic(pkt);
662 // There was a cache hit.
663 // Handle writebacks if needed
664 while (!writebacks.empty()){
665 memSidePort->sendAtomic(writebacks.front());
666 writebacks.pop_front();
669 hits[pkt->cmdToIndex()][0/*pkt->req->getThreadNum()*/]++;
678 template<class TagStore, class Buffering, class Coherence>
680 Cache<TagStore,Buffering,Coherence>::snoopProbe(PacketPtr &pkt)
682 //Send a atomic (false) invalidate up if the protocol calls for it
683 coherence->propogateInvalidate(pkt, false);
685 Addr blk_addr = pkt->getAddr() & ~(Addr(blkSize-1));
686 BlkType *blk = tags->findBlock(pkt);
687 MSHR *mshr = missQueue->findMSHR(blk_addr);
688 CacheBlk::State new_state = 0;
689 bool satisfy = coherence->handleBusRequest(pkt,blk,mshr, new_state);
691 DPRINTF(Cache, "Cache snooped a %s request for addr %x and "
692 "now supplying data, new state is %i\n",
693 pkt->cmdString(), blk_addr, new_state);
695 tags->handleSnoop(blk, new_state, pkt);
699 DPRINTF(Cache, "Cache snooped a %s request for addr %x, "
701 pkt->cmdString(), blk_addr, new_state);
702 tags->handleSnoop(blk, new_state);