2 * Copyright (c) 2010-2012 ARM Limited
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder. You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
14 * Copyright (c) 2002-2005 The Regents of The University of Michigan
15 * Copyright (c) 2010 Advanced Micro Devices, Inc.
16 * All rights reserved.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met: redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer;
22 * redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution;
25 * neither the name of the copyright holders nor the names of its
26 * contributors may be used to endorse or promote products derived from
27 * this software without specific prior written permission.
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41 * Authors: Erik Hallnor
53 #include "base/fast_alloc.hh"
54 #include "base/misc.hh"
55 #include "base/range.hh"
56 #include "base/types.hh"
57 #include "debug/Cache.hh"
58 #include "debug/CachePort.hh"
59 #include "mem/cache/prefetch/base.hh"
60 #include "mem/cache/blk.hh"
61 #include "mem/cache/cache.hh"
62 #include "mem/cache/mshr.hh"
63 #include "sim/sim_exit.hh"
65 template<class TagStore>
66 Cache<TagStore>::Cache(const Params *p, TagStore *tags)
69 prefetcher(p->prefetcher),
71 prefetchOnAccess(p->prefetch_on_access)
73 tempBlock = new BlkType();
74 tempBlock->data = new uint8_t[blkSize];
76 cpuSidePort = new CpuSidePort(p->name + "-cpu_side_port", this,
78 memSidePort = new MemSidePort(p->name + "-mem_side_port", this,
83 prefetcher->setCache(this);
86 template<class TagStore>
88 Cache<TagStore>::regStats()
90 BaseCache::regStats();
91 tags->regStats(name());
94 template<class TagStore>
96 Cache<TagStore>::getPort(const std::string &if_name, int idx)
98 if (if_name == "" || if_name == "cpu_side") {
100 } else if (if_name == "mem_side") {
103 panic("Port name %s unrecognized\n", if_name);
107 template<class TagStore>
109 Cache<TagStore>::cmpAndSwap(BlkType *blk, PacketPtr pkt)
111 uint64_t overwrite_val;
113 uint64_t condition_val64;
114 uint32_t condition_val32;
116 int offset = tags->extractBlkOffset(pkt->getAddr());
117 uint8_t *blk_data = blk->data + offset;
119 assert(sizeof(uint64_t) >= pkt->getSize());
121 overwrite_mem = true;
122 // keep a copy of our possible write value, and copy what is at the
123 // memory address into the packet
124 pkt->writeData((uint8_t *)&overwrite_val);
125 pkt->setData(blk_data);
127 if (pkt->req->isCondSwap()) {
128 if (pkt->getSize() == sizeof(uint64_t)) {
129 condition_val64 = pkt->req->getExtraData();
130 overwrite_mem = !std::memcmp(&condition_val64, blk_data,
132 } else if (pkt->getSize() == sizeof(uint32_t)) {
133 condition_val32 = (uint32_t)pkt->req->getExtraData();
134 overwrite_mem = !std::memcmp(&condition_val32, blk_data,
137 panic("Invalid size for conditional read/write\n");
141 std::memcpy(blk_data, &overwrite_val, pkt->getSize());
142 blk->status |= BlkDirty;
147 template<class TagStore>
149 Cache<TagStore>::satisfyCpuSideRequest(PacketPtr pkt, BlkType *blk,
150 bool deferred_response,
151 bool pending_downgrade)
153 assert(blk && blk->isValid());
154 // Occasionally this is not true... if we are a lower-level cache
155 // satisfying a string of Read and ReadEx requests from
156 // upper-level caches, a Read will mark the block as shared but we
157 // can satisfy a following ReadEx anyway since we can rely on the
158 // Read requester(s) to have buffered the ReadEx snoop and to
159 // invalidate their blocks after receiving them.
160 // assert(!pkt->needsExclusive() || blk->isWritable());
161 assert(pkt->getOffset(blkSize) + pkt->getSize() <= blkSize);
163 // Check RMW operations first since both isRead() and
164 // isWrite() will be true for them
165 if (pkt->cmd == MemCmd::SwapReq) {
166 cmpAndSwap(blk, pkt);
167 } else if (pkt->isWrite()) {
168 if (blk->checkWrite(pkt)) {
169 pkt->writeDataToBlock(blk->data, blkSize);
170 blk->status |= BlkDirty;
172 } else if (pkt->isRead()) {
174 blk->trackLoadLocked(pkt);
176 pkt->setDataFromBlock(blk->data, blkSize);
177 if (pkt->getSize() == blkSize) {
178 // special handling for coherent block requests from
179 // upper-level caches
180 if (pkt->needsExclusive()) {
181 // if we have a dirty copy, make sure the recipient
182 // keeps it marked dirty
183 if (blk->isDirty()) {
184 pkt->assertMemInhibit();
186 // on ReadExReq we give up our copy unconditionally
187 tags->invalidateBlk(blk);
188 } else if (blk->isWritable() && !pending_downgrade
189 && !pkt->sharedAsserted()) {
190 // we can give the requester an exclusive copy (by not
191 // asserting shared line) on a read request if:
192 // - we have an exclusive copy at this level (& below)
193 // - we don't have a pending snoop from below
194 // signaling another read request
195 // - no other cache above has a copy (otherwise it
196 // would have asseretd shared line on request)
198 if (blk->isDirty()) {
199 // special considerations if we're owner:
200 if (!deferred_response && !isTopLevel) {
201 // if we are responding immediately and can
202 // signal that we're transferring ownership
203 // along with exclusivity, do so
204 pkt->assertMemInhibit();
205 blk->status &= ~BlkDirty;
207 // if we're responding after our own miss,
208 // there's a window where the recipient didn't
209 // know it was getting ownership and may not
210 // have responded to snoops correctly, so we
211 // can't pass off ownership *or* exclusivity
216 // otherwise only respond with a shared copy
221 // Not a read or write... must be an upgrade. it's OK
222 // to just ack those as long as we have an exclusive
223 // copy at this level.
224 assert(pkt->isUpgrade());
225 tags->invalidateBlk(blk);
230 /////////////////////////////////////////////////////
232 // MSHR helper functions
234 /////////////////////////////////////////////////////
237 template<class TagStore>
239 Cache<TagStore>::markInService(MSHR *mshr, PacketPtr pkt)
241 markInServiceInternal(mshr, pkt);
243 if (mshr->originalCmd == MemCmd::HardPFReq) {
244 DPRINTF(HWPrefetch, "%s:Marking a HW_PF in service\n",
246 //Also clear pending if need be
247 if (!prefetcher->havePending())
249 deassertMemSideBusRequest(Request_PF);
256 template<class TagStore>
258 Cache<TagStore>::squash(int threadNum)
260 bool unblock = false;
261 BlockedCause cause = NUM_BLOCKED_CAUSES;
263 if (noTargetMSHR && noTargetMSHR->threadNum == threadNum) {
266 cause = Blocked_NoTargets;
268 if (mshrQueue.isFull()) {
270 cause = Blocked_NoMSHRs;
272 mshrQueue.squash(threadNum);
273 if (unblock && !mshrQueue.isFull()) {
278 /////////////////////////////////////////////////////
280 // Access path: requests coming in from the CPU side
282 /////////////////////////////////////////////////////
284 template<class TagStore>
286 Cache<TagStore>::access(PacketPtr pkt, BlkType *&blk,
287 int &lat, PacketList &writebacks)
289 if (pkt->req->isUncacheable()) {
290 if (pkt->req->isClearLL()) {
293 blk = tags->findBlock(pkt->getAddr());
295 tags->invalidateBlk(blk);
304 int id = pkt->req->hasContextId() ? pkt->req->contextId() : -1;
305 blk = tags->accessBlock(pkt->getAddr(), lat, id);
307 DPRINTF(Cache, "%s%s %x %s\n", pkt->cmdString(),
308 pkt->req->isInstFetch() ? " (ifetch)" : "",
309 pkt->getAddr(), (blk) ? "hit" : "miss");
313 if (pkt->needsExclusive() ? blk->isWritable() : blk->isReadable()) {
314 // OK to satisfy access
316 satisfyCpuSideRequest(pkt, blk);
321 // Can't satisfy access normally... either no block (blk == NULL)
322 // or have block but need exclusive & only have shared.
324 // Writeback handling is special case. We can write the block
325 // into the cache without having a writeable copy (or any copy at
327 if (pkt->cmd == MemCmd::Writeback) {
328 assert(blkSize == pkt->getSize());
330 // need to do a replacement
331 blk = allocateBlock(pkt->getAddr(), writebacks);
333 // no replaceable block available, give up.
334 // writeback will be forwarded to next level.
338 int id = pkt->req->masterId();
339 tags->insertBlock(pkt->getAddr(), blk, id);
340 blk->status = BlkValid | BlkReadable;
342 std::memcpy(blk->data, pkt->getPtr<uint8_t>(), blkSize);
343 blk->status |= BlkDirty;
344 if (pkt->isSupplyExclusive()) {
345 blk->status |= BlkWritable;
347 // nothing else to do; writeback doesn't expect response
348 assert(!pkt->needsResponse());
355 if (blk == NULL && pkt->isLLSC() && pkt->isWrite()) {
356 // complete miss on store conditional... just give up now
357 pkt->req->setExtraData(0);
365 class ForwardResponseRecord : public Packet::SenderState, public FastAlloc
367 Packet::SenderState *prevSenderState;
373 ForwardResponseRecord(Packet *pkt, BaseCache *_cache)
374 : prevSenderState(pkt->senderState), prevSrc(pkt->getSrc())
379 void restore(Packet *pkt, BaseCache *_cache)
381 assert(_cache == cache);
382 pkt->senderState = prevSenderState;
383 pkt->setDest(prevSrc);
388 template<class TagStore>
390 Cache<TagStore>::timingAccess(PacketPtr pkt)
392 //@todo Add back in MemDebug Calls
393 // MemDebug::cacheAccess(pkt);
395 // we charge hitLatency for doing just about anything here
396 Tick time = curTick() + hitLatency;
398 if (pkt->isResponse()) {
399 // must be cache-to-cache response from upper to lower level
400 ForwardResponseRecord *rec =
401 dynamic_cast<ForwardResponseRecord *>(pkt->senderState);
404 assert(pkt->cmd == MemCmd::HardPFResp);
405 // Check if it's a prefetch response and handle it. We shouldn't
406 // get any other kinds of responses without FRRs.
407 DPRINTF(Cache, "Got prefetch response from above for addr %#x\n",
413 rec->restore(pkt, this);
415 memSidePort->respond(pkt, time);
419 assert(pkt->isRequest());
421 if (pkt->memInhibitAsserted()) {
422 DPRINTF(Cache, "mem inhibited on 0x%x: not responding\n",
424 assert(!pkt->req->isUncacheable());
425 // Special tweak for multilevel coherence: snoop downward here
426 // on invalidates since there may be other caches below here
427 // that have shared copies. Not necessary if we know that
428 // supplier had exclusive copy to begin with.
429 if (pkt->needsExclusive() && !pkt->isSupplyExclusive()) {
430 Packet *snoopPkt = new Packet(pkt, true); // clear flags
431 snoopPkt->setExpressSnoop();
432 snoopPkt->assertMemInhibit();
433 memSidePort->sendTiming(snoopPkt);
434 // main memory will delete snoopPkt
436 // since we're the official target but we aren't responding,
437 // delete the packet now.
442 if (pkt->req->isUncacheable()) {
443 if (pkt->req->isClearLL()) {
446 BlkType *blk = tags->findBlock(pkt->getAddr());
448 tags->invalidateBlk(blk);
452 // writes go in write buffer, reads use MSHR
453 if (pkt->isWrite() && !pkt->isRead()) {
454 allocateWriteBuffer(pkt, time, true);
456 allocateUncachedReadBuffer(pkt, time, true);
458 assert(pkt->needsResponse()); // else we should delete it here??
462 int lat = hitLatency;
464 PacketList writebacks;
466 bool satisfied = access(pkt, blk, lat, writebacks);
469 /** @todo make the fast write alloc (wh64) work with coherence. */
471 // If this is a block size write/hint (WH64) allocate the block here
472 // if the coherence protocol allows it.
473 if (!blk && pkt->getSize() >= blkSize && coherence->allowFastWrites() &&
474 (pkt->cmd == MemCmd::WriteReq
475 || pkt->cmd == MemCmd::WriteInvalidateReq) ) {
476 // not outstanding misses, can do this
477 MSHR *outstanding_miss = mshrQueue.findMatch(pkt->getAddr());
478 if (pkt->cmd == MemCmd::WriteInvalidateReq || !outstanding_miss) {
479 if (outstanding_miss) {
480 warn("WriteInv doing a fastallocate"
481 "with an outstanding miss to the same address\n");
483 blk = handleFill(NULL, pkt, BlkValid | BlkWritable,
490 // track time of availability of next prefetch, if any
491 Tick next_pf_time = 0;
493 bool needsResponse = pkt->needsResponse();
496 if (prefetcher && (prefetchOnAccess || (blk && blk->wasPrefetched()))) {
498 blk->status &= ~BlkHWPrefetched;
499 next_pf_time = prefetcher->notify(pkt, time);
503 pkt->makeTimingResponse();
504 cpuSidePort->respond(pkt, curTick()+lat);
511 Addr blk_addr = blockAlign(pkt->getAddr());
512 MSHR *mshr = mshrQueue.findMatch(blk_addr);
516 //@todo remove hw_pf here
517 assert(pkt->req->masterId() < system->maxMasters());
518 mshr_hits[pkt->cmdToIndex()][pkt->req->masterId()]++;
519 if (mshr->threadNum != 0/*pkt->req->threadId()*/) {
520 mshr->threadNum = -1;
522 mshr->allocateTarget(pkt, time, order++);
523 if (mshr->getNumTargets() == numTarget) {
525 setBlocked(Blocked_NoTargets);
526 // need to be careful with this... if this mshr isn't
527 // ready yet (i.e. time > curTick()_, we don't want to
528 // move it ahead of mshrs that are ready
529 // mshrQueue.moveToFront(mshr);
533 assert(pkt->req->masterId() < system->maxMasters());
534 mshr_misses[pkt->cmdToIndex()][pkt->req->masterId()]++;
535 // always mark as cache fill for now... if we implement
536 // no-write-allocate or bypass accesses this will have to
538 if (pkt->cmd == MemCmd::Writeback) {
539 allocateWriteBuffer(pkt, time, true);
541 if (blk && blk->isValid()) {
542 // If we have a write miss to a valid block, we
543 // need to mark the block non-readable. Otherwise
544 // if we allow reads while there's an outstanding
545 // write miss, the read could return stale data
546 // out of the cache block... a more aggressive
547 // system could detect the overlap (if any) and
548 // forward data out of the MSHRs, but we don't do
549 // that yet. Note that we do need to leave the
550 // block valid so that it stays in the cache, in
551 // case we get an upgrade response (and hence no
552 // new data) when the write miss completes.
553 // As long as CPUs do proper store/load forwarding
554 // internally, and have a sufficiently weak memory
555 // model, this is probably unnecessary, but at some
556 // point it must have seemed like we needed it...
557 assert(pkt->needsExclusive() && !blk->isWritable());
558 blk->status &= ~BlkReadable;
561 allocateMissBuffer(pkt, time, true);
565 next_pf_time = prefetcher->notify(pkt, time);
570 if (next_pf_time != 0)
571 requestMemSideBus(Request_PF, std::max(time, next_pf_time));
573 // copy writebacks to write buffer
574 while (!writebacks.empty()) {
575 PacketPtr wbPkt = writebacks.front();
576 allocateWriteBuffer(wbPkt, time, true);
577 writebacks.pop_front();
584 // See comment in cache.hh.
585 template<class TagStore>
587 Cache<TagStore>::getBusPacket(PacketPtr cpu_pkt, BlkType *blk,
590 bool blkValid = blk && blk->isValid();
592 if (cpu_pkt->req->isUncacheable()) {
593 //assert(blk == NULL);
598 (cpu_pkt->cmd == MemCmd::Writeback || cpu_pkt->isUpgrade())) {
599 // Writebacks that weren't allocated in access() and upgrades
600 // from upper-level caches that missed completely just go
605 assert(cpu_pkt->needsResponse());
608 // @TODO make useUpgrades a parameter.
609 // Note that ownership protocols require upgrade, otherwise a
610 // write miss on a shared owned block will generate a ReadExcl,
611 // which will clobber the owned copy.
612 const bool useUpgrades = true;
613 if (blkValid && useUpgrades) {
614 // only reason to be here is that blk is shared
615 // (read-only) and we need exclusive
616 assert(needsExclusive && !blk->isWritable());
617 cmd = cpu_pkt->isLLSC() ? MemCmd::SCUpgradeReq : MemCmd::UpgradeReq;
620 cmd = needsExclusive ? MemCmd::ReadExReq : MemCmd::ReadReq;
622 PacketPtr pkt = new Packet(cpu_pkt->req, cmd, Packet::Broadcast, blkSize);
629 template<class TagStore>
631 Cache<TagStore>::atomicAccess(PacketPtr pkt)
633 int lat = hitLatency;
635 // @TODO: make this a parameter
636 bool last_level_cache = false;
638 if (pkt->memInhibitAsserted()) {
639 assert(!pkt->req->isUncacheable());
640 // have to invalidate ourselves and any lower caches even if
641 // upper cache will be responding
642 if (pkt->isInvalidate()) {
643 BlkType *blk = tags->findBlock(pkt->getAddr());
644 if (blk && blk->isValid()) {
645 tags->invalidateBlk(blk);
646 DPRINTF(Cache, "rcvd mem-inhibited %s on 0x%x: invalidating\n",
647 pkt->cmdString(), pkt->getAddr());
649 if (!last_level_cache) {
650 DPRINTF(Cache, "forwarding mem-inhibited %s on 0x%x\n",
651 pkt->cmdString(), pkt->getAddr());
652 lat += memSidePort->sendAtomic(pkt);
655 DPRINTF(Cache, "rcvd mem-inhibited %s on 0x%x: not responding\n",
656 pkt->cmdString(), pkt->getAddr());
662 // should assert here that there are no outstanding MSHRs or
663 // writebacks... that would mean that someone used an atomic
664 // access in timing mode
667 PacketList writebacks;
669 if (!access(pkt, blk, lat, writebacks)) {
671 PacketPtr bus_pkt = getBusPacket(pkt, blk, pkt->needsExclusive());
673 bool is_forward = (bus_pkt == NULL);
676 // just forwarding the same request to the next level
677 // no local cache operation involved
681 DPRINTF(Cache, "Sending an atomic %s for %x\n",
682 bus_pkt->cmdString(), bus_pkt->getAddr());
685 CacheBlk::State old_state = blk ? blk->status : 0;
688 lat += memSidePort->sendAtomic(bus_pkt);
690 DPRINTF(Cache, "Receive response: %s for addr %x in state %i\n",
691 bus_pkt->cmdString(), bus_pkt->getAddr(), old_state);
693 assert(!bus_pkt->wasNacked());
695 // If packet was a forward, the response (if any) is already
696 // in place in the bus_pkt == pkt structure, so we don't need
697 // to do anything. Otherwise, use the separate bus_pkt to
698 // generate response to pkt and then delete it.
700 if (pkt->needsResponse()) {
701 assert(bus_pkt->isResponse());
702 if (bus_pkt->isError()) {
703 pkt->makeAtomicResponse();
704 pkt->copyError(bus_pkt);
705 } else if (bus_pkt->isRead() ||
706 bus_pkt->cmd == MemCmd::UpgradeResp) {
707 // we're updating cache state to allow us to
708 // satisfy the upstream request from the cache
709 blk = handleFill(bus_pkt, blk, writebacks);
710 satisfyCpuSideRequest(pkt, blk);
712 // we're satisfying the upstream request without
713 // modifying cache state, e.g., a write-through
714 pkt->makeAtomicResponse();
721 // Note that we don't invoke the prefetcher at all in atomic mode.
722 // It's not clear how to do it properly, particularly for
723 // prefetchers that aggressively generate prefetch candidates and
724 // rely on bandwidth contention to throttle them; these will tend
725 // to pollute the cache in atomic mode since there is no bandwidth
726 // contention. If we ever do want to enable prefetching in atomic
727 // mode, though, this is the place to do it... see timingAccess()
728 // for an example (though we'd want to issue the prefetch(es)
729 // immediately rather than calling requestMemSideBus() as we do
732 // Handle writebacks if needed
733 while (!writebacks.empty()){
734 PacketPtr wbPkt = writebacks.front();
735 memSidePort->sendAtomic(wbPkt);
736 writebacks.pop_front();
740 // We now have the block one way or another (hit or completed miss)
742 if (pkt->needsResponse()) {
743 pkt->makeAtomicResponse();
750 template<class TagStore>
752 Cache<TagStore>::functionalAccess(PacketPtr pkt, bool fromCpuSide)
754 Addr blk_addr = blockAlign(pkt->getAddr());
755 BlkType *blk = tags->findBlock(pkt->getAddr());
756 MSHR *mshr = mshrQueue.findMatch(blk_addr);
758 pkt->pushLabel(name());
760 CacheBlkPrintWrapper cbpw(blk);
762 // Note that just because an L2/L3 has valid data doesn't mean an
763 // L1 doesn't have a more up-to-date modified copy that still
764 // needs to be found. As a result we always update the request if
765 // we have it, but only declare it satisfied if we are the owner.
767 // see if we have data at all (owned or otherwise)
768 bool have_data = blk && blk->isValid()
769 && pkt->checkFunctional(&cbpw, blk_addr, blkSize, blk->data);
771 // data we have is dirty if marked as such or if valid & ownership
772 // pending due to outstanding UpgradeReq
774 have_data && (blk->isDirty() ||
775 (mshr && mshr->inService && mshr->isPendingDirty()));
777 bool done = have_dirty
778 || cpuSidePort->checkFunctional(pkt)
779 || mshrQueue.checkFunctional(pkt, blk_addr)
780 || writeBuffer.checkFunctional(pkt, blk_addr)
781 || memSidePort->checkFunctional(pkt);
783 DPRINTF(Cache, "functional %s %x %s%s%s\n",
784 pkt->cmdString(), pkt->getAddr(),
785 (blk && blk->isValid()) ? "valid " : "",
786 have_data ? "data " : "", done ? "done " : "");
788 // We're leaving the cache, so pop cache->name() label
794 // if it came as a request from the CPU side then make sure it
795 // continues towards the memory side
797 memSidePort->sendFunctional(pkt);
798 } else if (forwardSnoops) {
799 // if it came from the memory side, it must be a snoop request
800 // and we should only forward it if we are forwarding snoops
801 cpuSidePort->sendFunctional(pkt);
807 /////////////////////////////////////////////////////
809 // Response handling: responses from the memory side
811 /////////////////////////////////////////////////////
814 template<class TagStore>
816 Cache<TagStore>::handleResponse(PacketPtr pkt)
818 Tick time = curTick() + hitLatency;
819 MSHR *mshr = dynamic_cast<MSHR*>(pkt->senderState);
820 bool is_error = pkt->isError();
824 if (pkt->wasNacked()) {
825 //pkt->reinitFromRequest();
826 warn("NACKs from devices not connected to the same bus "
827 "not implemented\n");
831 DPRINTF(Cache, "Cache received packet with error for address %x, "
832 "cmd: %s\n", pkt->getAddr(), pkt->cmdString());
835 DPRINTF(Cache, "Handling response to %x\n", pkt->getAddr());
837 MSHRQueue *mq = mshr->queue;
838 bool wasFull = mq->isFull();
840 if (mshr == noTargetMSHR) {
841 // we always clear at least one target
842 clearBlocked(Blocked_NoTargets);
846 // Initial target is used just for stats
847 MSHR::Target *initial_tgt = mshr->getTarget();
848 BlkType *blk = tags->findBlock(pkt->getAddr());
849 int stats_cmd_idx = initial_tgt->pkt->cmdToIndex();
850 Tick miss_latency = curTick() - initial_tgt->recvTime;
851 PacketList writebacks;
853 if (pkt->req->isUncacheable()) {
854 assert(pkt->req->masterId() < system->maxMasters());
855 mshr_uncacheable_lat[stats_cmd_idx][pkt->req->masterId()] +=
858 assert(pkt->req->masterId() < system->maxMasters());
859 mshr_miss_latency[stats_cmd_idx][pkt->req->masterId()] +=
863 bool is_fill = !mshr->isForward &&
864 (pkt->isRead() || pkt->cmd == MemCmd::UpgradeResp);
866 if (is_fill && !is_error) {
867 DPRINTF(Cache, "Block for addr %x being updated in Cache\n",
870 // give mshr a chance to do some dirty work
871 mshr->handleFill(pkt, blk);
873 blk = handleFill(pkt, blk, writebacks);
877 // First offset for critical word first calculations
878 int initial_offset = 0;
880 if (mshr->hasTargets()) {
881 initial_offset = mshr->getTarget()->pkt->getOffset(blkSize);
884 while (mshr->hasTargets()) {
885 MSHR::Target *target = mshr->getTarget();
887 switch (target->source) {
888 case MSHR::Target::FromCPU:
889 Tick completion_time;
891 satisfyCpuSideRequest(target->pkt, blk,
892 true, mshr->hasPostDowngrade());
893 // How many bytes past the first request is this one
894 int transfer_offset =
895 target->pkt->getOffset(blkSize) - initial_offset;
896 if (transfer_offset < 0) {
897 transfer_offset += blkSize;
900 // If critical word (no offset) return first word time
901 completion_time = tags->getHitLatency() +
902 (transfer_offset ? pkt->finishTime : pkt->firstWordTime);
904 assert(!target->pkt->req->isUncacheable());
906 assert(pkt->req->masterId() < system->maxMasters());
907 missLatency[target->pkt->cmdToIndex()][target->pkt->req->masterId()] +=
908 completion_time - target->recvTime;
909 } else if (pkt->cmd == MemCmd::UpgradeFailResp) {
910 // failed StoreCond upgrade
911 assert(target->pkt->cmd == MemCmd::StoreCondReq ||
912 target->pkt->cmd == MemCmd::StoreCondFailReq ||
913 target->pkt->cmd == MemCmd::SCUpgradeFailReq);
914 completion_time = tags->getHitLatency() + pkt->finishTime;
915 target->pkt->req->setExtraData(0);
917 // not a cache fill, just forwarding response
918 completion_time = tags->getHitLatency() + pkt->finishTime;
919 if (pkt->isRead() && !is_error) {
920 target->pkt->setData(pkt->getPtr<uint8_t>());
923 target->pkt->makeTimingResponse();
924 // if this packet is an error copy that to the new packet
926 target->pkt->copyError(pkt);
927 if (target->pkt->cmd == MemCmd::ReadResp &&
928 (pkt->isInvalidate() || mshr->hasPostInvalidate())) {
929 // If intermediate cache got ReadRespWithInvalidate,
930 // propagate that. Response should not have
931 // isInvalidate() set otherwise.
932 target->pkt->cmd = MemCmd::ReadRespWithInvalidate;
934 cpuSidePort->respond(target->pkt, completion_time);
937 case MSHR::Target::FromPrefetcher:
938 assert(target->pkt->cmd == MemCmd::HardPFReq);
940 blk->status |= BlkHWPrefetched;
941 delete target->pkt->req;
945 case MSHR::Target::FromSnoop:
946 // I don't believe that a snoop can be in an error state
948 // response to snoop request
949 DPRINTF(Cache, "processing deferred snoop...\n");
950 assert(!(pkt->isInvalidate() && !mshr->hasPostInvalidate()));
951 handleSnoop(target->pkt, blk, true, true,
952 mshr->hasPostInvalidate());
956 panic("Illegal target->source enum %d\n", target->source);
963 if (pkt->isInvalidate() || mshr->hasPostInvalidate()) {
964 tags->invalidateBlk(blk);
965 } else if (mshr->hasPostDowngrade()) {
966 blk->status &= ~BlkWritable;
970 if (mshr->promoteDeferredTargets()) {
971 // avoid later read getting stale data while write miss is
972 // outstanding.. see comment in timingAccess()
974 blk->status &= ~BlkReadable;
976 MSHRQueue *mq = mshr->queue;
977 mq->markPending(mshr);
978 requestMemSideBus((RequestCause)mq->index, pkt->finishTime);
980 mq->deallocate(mshr);
981 if (wasFull && !mq->isFull()) {
982 clearBlocked((BlockedCause)mq->index);
986 // copy writebacks to write buffer
987 while (!writebacks.empty()) {
988 PacketPtr wbPkt = writebacks.front();
989 allocateWriteBuffer(wbPkt, time, true);
990 writebacks.pop_front();
992 // if we used temp block, clear it out
993 if (blk == tempBlock) {
994 if (blk->isDirty()) {
995 allocateWriteBuffer(writebackBlk(blk), time, true);
997 tags->invalidateBlk(blk);
1006 template<class TagStore>
1008 Cache<TagStore>::writebackBlk(BlkType *blk)
1010 assert(blk && blk->isValid() && blk->isDirty());
1012 writebacks[Request::wbMasterId]++;
1014 Request *writebackReq =
1015 new Request(tags->regenerateBlkAddr(blk->tag, blk->set), blkSize, 0,
1016 Request::wbMasterId);
1017 PacketPtr writeback = new Packet(writebackReq, MemCmd::Writeback, -1);
1018 if (blk->isWritable()) {
1019 writeback->setSupplyExclusive();
1021 writeback->allocate();
1022 std::memcpy(writeback->getPtr<uint8_t>(), blk->data, blkSize);
1024 blk->status &= ~BlkDirty;
1029 template<class TagStore>
1030 typename Cache<TagStore>::BlkType*
1031 Cache<TagStore>::allocateBlock(Addr addr, PacketList &writebacks)
1033 BlkType *blk = tags->findVictim(addr, writebacks);
1035 if (blk->isValid()) {
1036 Addr repl_addr = tags->regenerateBlkAddr(blk->tag, blk->set);
1037 MSHR *repl_mshr = mshrQueue.findMatch(repl_addr);
1039 // must be an outstanding upgrade request on block
1040 // we're about to replace...
1041 assert(!blk->isWritable());
1042 assert(repl_mshr->needsExclusive());
1043 // too hard to replace block with transient state
1044 // allocation failed, block not inserted
1047 DPRINTF(Cache, "replacement: replacing %x with %x: %s\n",
1049 blk->isDirty() ? "writeback" : "clean");
1051 if (blk->isDirty()) {
1052 // Save writeback packet for handling by caller
1053 writebacks.push_back(writebackBlk(blk));
1062 // Note that the reason we return a list of writebacks rather than
1063 // inserting them directly in the write buffer is that this function
1064 // is called by both atomic and timing-mode accesses, and in atomic
1065 // mode we don't mess with the write buffer (we just perform the
1066 // writebacks atomically once the original request is complete).
1067 template<class TagStore>
1068 typename Cache<TagStore>::BlkType*
1069 Cache<TagStore>::handleFill(PacketPtr pkt, BlkType *blk,
1070 PacketList &writebacks)
1072 Addr addr = pkt->getAddr();
1074 CacheBlk::State old_state = blk ? blk->status : 0;
1078 // better have read new data...
1079 assert(pkt->hasData());
1080 // need to do a replacement
1081 blk = allocateBlock(addr, writebacks);
1083 // No replaceable block... just use temporary storage to
1084 // complete the current request and then get rid of it
1085 assert(!tempBlock->isValid());
1087 tempBlock->set = tags->extractSet(addr);
1088 tempBlock->tag = tags->extractTag(addr);
1089 DPRINTF(Cache, "using temp block for %x\n", addr);
1091 int id = pkt->req->masterId();
1092 tags->insertBlock(pkt->getAddr(), blk, id);
1095 // starting from scratch with a new block
1098 // existing block... probably an upgrade
1099 assert(blk->tag == tags->extractTag(addr));
1100 // either we're getting new data or the block should already be valid
1101 assert(pkt->hasData() || blk->isValid());
1102 // don't clear block status... if block is already dirty we
1103 // don't want to lose that
1106 blk->status |= BlkValid | BlkReadable;
1108 if (!pkt->sharedAsserted()) {
1109 blk->status |= BlkWritable;
1110 // If we got this via cache-to-cache transfer (i.e., from a
1111 // cache that was an owner) and took away that owner's copy,
1112 // then we need to write it back. Normally this happens
1113 // anyway as a side effect of getting a copy to write it, but
1114 // there are cases (such as failed store conditionals or
1115 // compare-and-swaps) where we'll demand an exclusive copy but
1116 // end up not writing it.
1117 if (pkt->memInhibitAsserted())
1118 blk->status |= BlkDirty;
1121 DPRINTF(Cache, "Block addr %x moving from state %i to %i\n",
1122 addr, old_state, blk->status);
1124 // if we got new data, copy it in
1125 if (pkt->isRead()) {
1126 std::memcpy(blk->data, pkt->getPtr<uint8_t>(), blkSize);
1129 blk->whenReady = pkt->finishTime;
1135 /////////////////////////////////////////////////////
1137 // Snoop path: requests coming in from the memory side
1139 /////////////////////////////////////////////////////
1141 template<class TagStore>
1144 doTimingSupplyResponse(PacketPtr req_pkt, uint8_t *blk_data,
1145 bool already_copied, bool pending_inval)
1147 // timing-mode snoop responses require a new packet, unless we
1148 // already made a copy...
1149 PacketPtr pkt = already_copied ? req_pkt : new Packet(req_pkt);
1150 assert(req_pkt->isInvalidate() || pkt->sharedAsserted());
1152 pkt->makeTimingResponse();
1153 if (pkt->isRead()) {
1154 pkt->setDataFromBlock(blk_data, blkSize);
1156 if (pkt->cmd == MemCmd::ReadResp && pending_inval) {
1157 // Assume we defer a response to a read from a far-away cache
1158 // A, then later defer a ReadExcl from a cache B on the same
1159 // bus as us. We'll assert MemInhibit in both cases, but in
1160 // the latter case MemInhibit will keep the invalidation from
1161 // reaching cache A. This special response tells cache A that
1162 // it gets the block to satisfy its read, but must immediately
1164 pkt->cmd = MemCmd::ReadRespWithInvalidate;
1166 memSidePort->respond(pkt, curTick() + hitLatency);
1169 template<class TagStore>
1171 Cache<TagStore>::handleSnoop(PacketPtr pkt, BlkType *blk,
1172 bool is_timing, bool is_deferred,
1175 // deferred snoops can only happen in timing mode
1176 assert(!(is_deferred && !is_timing));
1177 // pending_inval only makes sense on deferred snoops
1178 assert(!(pending_inval && !is_deferred));
1179 assert(pkt->isRequest());
1181 // the packet may get modified if we or a forwarded snooper
1182 // responds in atomic mode, so remember a few things about the
1183 // original packet up front
1184 bool invalidate = pkt->isInvalidate();
1185 bool M5_VAR_USED needs_exclusive = pkt->needsExclusive();
1187 if (forwardSnoops) {
1188 // first propagate snoop upward to see if anyone above us wants to
1189 // handle it. save & restore packet src since it will get
1190 // rewritten to be relative to cpu-side bus (if any)
1191 bool alreadyResponded = pkt->memInhibitAsserted();
1193 Packet *snoopPkt = new Packet(pkt, true); // clear flags
1194 snoopPkt->setExpressSnoop();
1195 snoopPkt->senderState = new ForwardResponseRecord(pkt, this);
1196 cpuSidePort->sendTiming(snoopPkt);
1197 if (snoopPkt->memInhibitAsserted()) {
1198 // cache-to-cache response from some upper cache
1199 assert(!alreadyResponded);
1200 pkt->assertMemInhibit();
1202 delete snoopPkt->senderState;
1204 if (snoopPkt->sharedAsserted()) {
1205 pkt->assertShared();
1209 int origSrc = pkt->getSrc();
1210 cpuSidePort->sendAtomic(pkt);
1211 if (!alreadyResponded && pkt->memInhibitAsserted()) {
1212 // cache-to-cache response from some upper cache:
1213 // forward response to original requester
1214 assert(pkt->isResponse());
1216 pkt->setSrc(origSrc);
1220 if (!blk || !blk->isValid()) {
1224 // we may end up modifying both the block state and the packet (if
1225 // we respond in atomic mode), so just figure out what to do now
1226 // and then do it later
1227 bool respond = blk->isDirty() && pkt->needsResponse();
1228 bool have_exclusive = blk->isWritable();
1230 if (pkt->isRead() && !invalidate) {
1231 assert(!needs_exclusive);
1232 pkt->assertShared();
1233 int bits_to_clear = BlkWritable;
1234 const bool haveOwnershipState = true; // for now
1235 if (!haveOwnershipState) {
1236 // if we don't support pure ownership (dirty && !writable),
1237 // have to clear dirty bit here, assume memory snarfs data
1238 // on cache-to-cache xfer
1239 bits_to_clear |= BlkDirty;
1241 blk->status &= ~bits_to_clear;
1244 DPRINTF(Cache, "snooped a %s request for addr %x, %snew state is %i\n",
1245 pkt->cmdString(), blockAlign(pkt->getAddr()),
1246 respond ? "responding, " : "", invalidate ? 0 : blk->status);
1249 assert(!pkt->memInhibitAsserted());
1250 pkt->assertMemInhibit();
1251 if (have_exclusive) {
1252 pkt->setSupplyExclusive();
1255 doTimingSupplyResponse(pkt, blk->data, is_deferred, pending_inval);
1257 pkt->makeAtomicResponse();
1258 pkt->setDataFromBlock(blk->data, blkSize);
1260 } else if (is_timing && is_deferred) {
1261 // if it's a deferred timing snoop then we've made a copy of
1262 // the packet, and so if we're not using that copy to respond
1263 // then we need to delete it here.
1267 // Do this last in case it deallocates block data or something
1270 tags->invalidateBlk(blk);
1275 template<class TagStore>
1277 Cache<TagStore>::snoopTiming(PacketPtr pkt)
1279 // Note that some deferred snoops don't have requests, since the
1280 // original access may have already completed
1281 if ((pkt->req && pkt->req->isUncacheable()) ||
1282 pkt->cmd == MemCmd::Writeback) {
1283 //Can't get a hit on an uncacheable address
1284 //Revisit this for multi level coherence
1288 BlkType *blk = tags->findBlock(pkt->getAddr());
1290 Addr blk_addr = blockAlign(pkt->getAddr());
1291 MSHR *mshr = mshrQueue.findMatch(blk_addr);
1293 // Let the MSHR itself track the snoop and decide whether we want
1294 // to go ahead and do the regular cache snoop
1295 if (mshr && mshr->handleSnoop(pkt, order++)) {
1296 DPRINTF(Cache, "Deferring snoop on in-service MSHR to blk %x\n",
1298 if (mshr->getNumTargets() > numTarget)
1299 warn("allocating bonus target for snoop"); //handle later
1303 //We also need to check the writeback buffers and handle those
1304 std::vector<MSHR *> writebacks;
1305 if (writeBuffer.findMatches(blk_addr, writebacks)) {
1306 DPRINTF(Cache, "Snoop hit in writeback to addr: %x\n",
1309 //Look through writebacks for any non-uncachable writes, use that
1310 for (int i = 0; i < writebacks.size(); i++) {
1311 mshr = writebacks[i];
1312 assert(!mshr->isUncacheable());
1313 assert(mshr->getNumTargets() == 1);
1314 PacketPtr wb_pkt = mshr->getTarget()->pkt;
1315 assert(wb_pkt->cmd == MemCmd::Writeback);
1317 assert(!pkt->memInhibitAsserted());
1318 pkt->assertMemInhibit();
1319 if (!pkt->needsExclusive()) {
1320 pkt->assertShared();
1321 // the writeback is no longer the exclusive copy in the system
1322 wb_pkt->clearSupplyExclusive();
1324 // if we're not asserting the shared line, we need to
1325 // invalidate our copy. we'll do that below as long as
1326 // the packet's invalidate flag is set...
1327 assert(pkt->isInvalidate());
1329 doTimingSupplyResponse(pkt, wb_pkt->getPtr<uint8_t>(),
1332 if (pkt->isInvalidate()) {
1333 // Invalidation trumps our writeback... discard here
1334 markInService(mshr);
1338 // If this was a shared writeback, there may still be
1339 // other shared copies above that require invalidation.
1340 // We could be more selective and return here if the
1341 // request is non-exclusive or if the writeback is
1347 handleSnoop(pkt, blk, true, false, false);
1351 template<class TagStore>
1353 Cache<TagStore>::snoopAtomic(PacketPtr pkt)
1355 if (pkt->req->isUncacheable() || pkt->cmd == MemCmd::Writeback) {
1356 // Can't get a hit on an uncacheable address
1357 // Revisit this for multi level coherence
1361 BlkType *blk = tags->findBlock(pkt->getAddr());
1362 handleSnoop(pkt, blk, false, false, false);
1367 template<class TagStore>
1369 Cache<TagStore>::getNextMSHR()
1371 // Check both MSHR queue and write buffer for potential requests
1372 MSHR *miss_mshr = mshrQueue.getNextMSHR();
1373 MSHR *write_mshr = writeBuffer.getNextMSHR();
1375 // Now figure out which one to send... some cases are easy
1376 if (miss_mshr && !write_mshr) {
1379 if (write_mshr && !miss_mshr) {
1383 if (miss_mshr && write_mshr) {
1384 // We have one of each... normally we favor the miss request
1385 // unless the write buffer is full
1386 if (writeBuffer.isFull() && writeBuffer.inServiceEntries == 0) {
1387 // Write buffer is full, so we'd like to issue a write;
1388 // need to search MSHR queue for conflicting earlier miss.
1389 MSHR *conflict_mshr =
1390 mshrQueue.findPending(write_mshr->addr, write_mshr->size);
1392 if (conflict_mshr && conflict_mshr->order < write_mshr->order) {
1393 // Service misses in order until conflict is cleared.
1394 return conflict_mshr;
1397 // No conflicts; issue write
1401 // Write buffer isn't full, but need to check it for
1402 // conflicting earlier writeback
1403 MSHR *conflict_mshr =
1404 writeBuffer.findPending(miss_mshr->addr, miss_mshr->size);
1405 if (conflict_mshr) {
1406 // not sure why we don't check order here... it was in the
1407 // original code but commented out.
1409 // The only way this happens is if we are
1410 // doing a write and we didn't have permissions
1411 // then subsequently saw a writeback (owned got evicted)
1412 // We need to make sure to perform the writeback first
1413 // To preserve the dirty data, then we can issue the write
1415 // should we return write_mshr here instead? I.e. do we
1416 // have to flush writes in order? I don't think so... not
1417 // for Alpha anyway. Maybe for x86?
1418 return conflict_mshr;
1421 // No conflicts; issue read
1425 // fall through... no pending requests. Try a prefetch.
1426 assert(!miss_mshr && !write_mshr);
1427 if (prefetcher && !mshrQueue.isFull()) {
1428 // If we have a miss queue slot, we can try a prefetch
1429 PacketPtr pkt = prefetcher->getPacket();
1431 Addr pf_addr = blockAlign(pkt->getAddr());
1432 if (!tags->findBlock(pf_addr) && !mshrQueue.findMatch(pf_addr) &&
1433 !writeBuffer.findMatch(pf_addr)) {
1434 // Update statistic on number of prefetches issued
1435 // (hwpf_mshr_misses)
1436 assert(pkt->req->masterId() < system->maxMasters());
1437 mshr_misses[pkt->cmdToIndex()][pkt->req->masterId()]++;
1438 // Don't request bus, since we already have it
1439 return allocateMissBuffer(pkt, curTick(), false);
1441 // free the request and packet
1452 template<class TagStore>
1454 Cache<TagStore>::getTimingPacket()
1456 MSHR *mshr = getNextMSHR();
1462 // use request from 1st target
1463 PacketPtr tgt_pkt = mshr->getTarget()->pkt;
1464 PacketPtr pkt = NULL;
1466 if (tgt_pkt->cmd == MemCmd::SCUpgradeFailReq ||
1467 tgt_pkt->cmd == MemCmd::StoreCondFailReq) {
1468 // SCUpgradeReq or StoreCondReq saw invalidation while queued
1469 // in MSHR, so now that we are getting around to processing
1470 // it, just treat it as if we got a failure response
1471 pkt = new Packet(tgt_pkt);
1472 pkt->cmd = MemCmd::UpgradeFailResp;
1473 pkt->senderState = mshr;
1474 pkt->firstWordTime = pkt->finishTime = curTick();
1475 handleResponse(pkt);
1477 } else if (mshr->isForwardNoResponse()) {
1478 // no response expected, just forward packet as it is
1479 assert(tags->findBlock(mshr->addr) == NULL);
1482 BlkType *blk = tags->findBlock(mshr->addr);
1484 if (tgt_pkt->cmd == MemCmd::HardPFReq) {
1485 // It might be possible for a writeback to arrive between
1486 // the time the prefetch is placed in the MSHRs and when
1487 // it's selected to send... if so, this assert will catch
1488 // that, and then we'll have to figure out what to do.
1489 assert(blk == NULL);
1491 // We need to check the caches above us to verify that they don't have
1492 // a copy of this block in the dirty state at the moment. Without this
1493 // check we could get a stale copy from memory that might get used
1494 // in place of the dirty one.
1495 PacketPtr snoop_pkt = new Packet(tgt_pkt, true);
1496 snoop_pkt->setExpressSnoop();
1497 snoop_pkt->senderState = mshr;
1498 cpuSidePort->sendTiming(snoop_pkt);
1500 if (snoop_pkt->memInhibitAsserted()) {
1501 markInService(mshr, snoop_pkt);
1502 DPRINTF(Cache, "Upward snoop of prefetch for addr %#x hit\n",
1503 tgt_pkt->getAddr());
1510 pkt = getBusPacket(tgt_pkt, blk, mshr->needsExclusive());
1512 mshr->isForward = (pkt == NULL);
1514 if (mshr->isForward) {
1515 // not a cache block request, but a response is expected
1516 // make copy of current packet to forward, keep current
1517 // copy for response handling
1518 pkt = new Packet(tgt_pkt);
1520 if (pkt->isWrite()) {
1521 pkt->setData(tgt_pkt->getPtr<uint8_t>());
1526 assert(pkt != NULL);
1527 pkt->senderState = mshr;
1532 template<class TagStore>
1534 Cache<TagStore>::nextMSHRReadyTime()
1536 Tick nextReady = std::min(mshrQueue.nextMSHRReadyTime(),
1537 writeBuffer.nextMSHRReadyTime());
1540 nextReady = std::min(nextReady,
1541 prefetcher->nextPrefetchReadyTime());
1554 template<class TagStore>
1556 Cache<TagStore>::CpuSidePort::
1559 // CPU side port doesn't snoop; it's a target only. It can
1560 // potentially respond to any address.
1561 AddrRangeList ranges;
1562 ranges.push_back(myCache()->getAddrRange());
1567 template<class TagStore>
1569 Cache<TagStore>::CpuSidePort::recvTiming(PacketPtr pkt)
1571 // illegal to block responses... can lead to deadlock
1572 if (pkt->isRequest() && !pkt->memInhibitAsserted() && blocked) {
1573 DPRINTF(Cache,"Scheduling a retry while blocked\n");
1574 mustSendRetry = true;
1578 myCache()->timingAccess(pkt);
1583 template<class TagStore>
1585 Cache<TagStore>::CpuSidePort::recvAtomic(PacketPtr pkt)
1587 return myCache()->atomicAccess(pkt);
1591 template<class TagStore>
1593 Cache<TagStore>::CpuSidePort::recvFunctional(PacketPtr pkt)
1595 myCache()->functionalAccess(pkt, true);
1599 template<class TagStore>
1601 CpuSidePort::CpuSidePort(const std::string &_name, Cache<TagStore> *_cache,
1602 const std::string &_label)
1603 : BaseCache::CachePort(_name, _cache, _label)
1613 template<class TagStore>
1615 Cache<TagStore>::MemSidePort::isSnooping()
1617 // Memory-side port always snoops, but never passes requests
1618 // through to targets on the cpu side (so we don't add anything to
1619 // the address range list).
1624 template<class TagStore>
1626 Cache<TagStore>::MemSidePort::recvTiming(PacketPtr pkt)
1628 // this needs to be fixed so that the cache updates the mshr and sends the
1629 // packet back out on the link, but it probably won't happen so until this
1630 // gets fixed, just panic when it does
1631 if (pkt->wasNacked())
1632 panic("Need to implement cache resending nacked packets!\n");
1634 if (pkt->isRequest() && blocked) {
1635 DPRINTF(Cache,"Scheduling a retry while blocked\n");
1636 mustSendRetry = true;
1640 if (pkt->isResponse()) {
1641 myCache()->handleResponse(pkt);
1643 myCache()->snoopTiming(pkt);
1649 template<class TagStore>
1651 Cache<TagStore>::MemSidePort::recvAtomic(PacketPtr pkt)
1653 // in atomic mode, responses go back to the sender via the
1654 // function return from sendAtomic(), not via a separate
1655 // sendAtomic() from the responder. Thus we should never see a
1656 // response packet in recvAtomic() (anywhere, not just here).
1657 assert(!pkt->isResponse());
1658 return myCache()->snoopAtomic(pkt);
1662 template<class TagStore>
1664 Cache<TagStore>::MemSidePort::recvFunctional(PacketPtr pkt)
1666 myCache()->functionalAccess(pkt, false);
1671 template<class TagStore>
1673 Cache<TagStore>::MemSidePort::sendPacket()
1675 // if we have responses that are ready, they take precedence
1676 if (deferredPacketReady()) {
1677 bool success = sendTiming(transmitList.front().pkt);
1680 //send successful, remove packet
1681 transmitList.pop_front();
1684 waitingOnRetry = !success;
1686 // check for non-response packets (requests & writebacks)
1687 PacketPtr pkt = myCache()->getTimingPacket();
1689 // can happen if e.g. we attempt a writeback and fail, but
1690 // before the retry, the writeback is eliminated because
1691 // we snoop another cache's ReadEx.
1692 waitingOnRetry = false;
1694 MSHR *mshr = dynamic_cast<MSHR*>(pkt->senderState);
1696 bool success = sendTiming(pkt);
1698 waitingOnRetry = !success;
1699 if (waitingOnRetry) {
1700 DPRINTF(CachePort, "now waiting on a retry\n");
1701 if (!mshr->isForwardNoResponse()) {
1705 myCache()->markInService(mshr, pkt);
1711 // tried to send packet... if it was successful (no retry), see if
1712 // we need to rerequest bus or not
1713 if (!waitingOnRetry) {
1714 Tick nextReady = std::min(deferredPacketReadyTime(),
1715 myCache()->nextMSHRReadyTime());
1716 // @TODO: need to facotr in prefetch requests here somehow
1717 if (nextReady != MaxTick) {
1718 DPRINTF(CachePort, "more packets to send @ %d\n", nextReady);
1719 cache->schedule(sendEvent, std::max(nextReady, curTick() + 1));
1721 // no more to send right now: if we're draining, we may be done
1722 if (drainEvent && !sendEvent->scheduled()) {
1723 drainEvent->process();
1730 template<class TagStore>
1732 Cache<TagStore>::MemSidePort::recvRetry()
1734 assert(waitingOnRetry);
1739 template<class TagStore>
1741 Cache<TagStore>::MemSidePort::processSendEvent()
1743 assert(!waitingOnRetry);
1748 template<class TagStore>
1750 MemSidePort::MemSidePort(const std::string &_name, Cache<TagStore> *_cache,
1751 const std::string &_label)
1752 : BaseCache::CachePort(_name, _cache, _label)
1754 // override default send event from SimpleTimingPort
1756 sendEvent = new SendEvent(this);