2 * Copyright (c) 2010-2016 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,2015 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
54 #include "mem/cache/cache.hh"
56 #include "base/logging.hh"
57 #include "base/types.hh"
58 #include "debug/Cache.hh"
59 #include "debug/CachePort.hh"
60 #include "debug/CacheTags.hh"
61 #include "debug/CacheVerbose.hh"
62 #include "mem/cache/blk.hh"
63 #include "mem/cache/mshr.hh"
64 #include "mem/cache/prefetch/base.hh"
65 #include "sim/sim_exit.hh"
67 Cache::Cache(const CacheParams
*p
)
68 : BaseCache(p
, p
->system
->cacheLineSize()),
70 prefetcher(p
->prefetcher
),
72 prefetchOnAccess(p
->prefetch_on_access
),
73 clusivity(p
->clusivity
),
74 writebackClean(p
->writeback_clean
),
75 tempBlockWriteback(nullptr),
76 writebackTempBlockAtomicEvent([this]{ writebackTempBlockAtomic(); },
78 EventBase::Delayed_Writeback_Pri
)
80 tempBlock
= new CacheBlk();
81 tempBlock
->data
= new uint8_t[blkSize
];
83 cpuSidePort
= new CpuSidePort(p
->name
+ ".cpu_side", this,
85 memSidePort
= new MemSidePort(p
->name
+ ".mem_side", this,
90 prefetcher
->setCache(this);
95 delete [] tempBlock
->data
;
105 BaseCache::regStats();
109 Cache::cmpAndSwap(CacheBlk
*blk
, PacketPtr pkt
)
111 assert(pkt
->isRequest());
113 uint64_t overwrite_val
;
115 uint64_t condition_val64
;
116 uint32_t condition_val32
;
118 int offset
= tags
->extractBlkOffset(pkt
->getAddr());
119 uint8_t *blk_data
= blk
->data
+ offset
;
121 assert(sizeof(uint64_t) >= pkt
->getSize());
123 overwrite_mem
= true;
124 // keep a copy of our possible write value, and copy what is at the
125 // memory address into the packet
126 pkt
->writeData((uint8_t *)&overwrite_val
);
127 pkt
->setData(blk_data
);
129 if (pkt
->req
->isCondSwap()) {
130 if (pkt
->getSize() == sizeof(uint64_t)) {
131 condition_val64
= pkt
->req
->getExtraData();
132 overwrite_mem
= !std::memcmp(&condition_val64
, blk_data
,
134 } else if (pkt
->getSize() == sizeof(uint32_t)) {
135 condition_val32
= (uint32_t)pkt
->req
->getExtraData();
136 overwrite_mem
= !std::memcmp(&condition_val32
, blk_data
,
139 panic("Invalid size for conditional read/write\n");
143 std::memcpy(blk_data
, &overwrite_val
, pkt
->getSize());
144 blk
->status
|= BlkDirty
;
150 Cache::satisfyRequest(PacketPtr pkt
, CacheBlk
*blk
,
151 bool deferred_response
, bool pending_downgrade
)
153 assert(pkt
->isRequest());
155 assert(blk
&& blk
->isValid());
156 // Occasionally this is not true... if we are a lower-level cache
157 // satisfying a string of Read and ReadEx requests from
158 // upper-level caches, a Read will mark the block as shared but we
159 // can satisfy a following ReadEx anyway since we can rely on the
160 // Read requester(s) to have buffered the ReadEx snoop and to
161 // invalidate their blocks after receiving them.
162 // assert(!pkt->needsWritable() || blk->isWritable());
163 assert(pkt
->getOffset(blkSize
) + pkt
->getSize() <= blkSize
);
165 // Check RMW operations first since both isRead() and
166 // isWrite() will be true for them
167 if (pkt
->cmd
== MemCmd::SwapReq
) {
168 cmpAndSwap(blk
, pkt
);
169 } else if (pkt
->isWrite()) {
170 // we have the block in a writable state and can go ahead,
171 // note that the line may be also be considered writable in
172 // downstream caches along the path to memory, but always
173 // Exclusive, and never Modified
174 assert(blk
->isWritable());
175 // Write or WriteLine at the first cache with block in writable state
176 if (blk
->checkWrite(pkt
)) {
177 pkt
->writeDataToBlock(blk
->data
, blkSize
);
179 // Always mark the line as dirty (and thus transition to the
180 // Modified state) even if we are a failed StoreCond so we
181 // supply data to any snoops that have appended themselves to
182 // this cache before knowing the store will fail.
183 blk
->status
|= BlkDirty
;
184 DPRINTF(CacheVerbose
, "%s for %s (write)\n", __func__
, pkt
->print());
185 } else if (pkt
->isRead()) {
187 blk
->trackLoadLocked(pkt
);
190 // all read responses have a data payload
191 assert(pkt
->hasRespData());
192 pkt
->setDataFromBlock(blk
->data
, blkSize
);
194 // determine if this read is from a (coherent) cache or not
195 if (pkt
->fromCache()) {
196 assert(pkt
->getSize() == blkSize
);
197 // special handling for coherent block requests from
198 // upper-level caches
199 if (pkt
->needsWritable()) {
201 assert(pkt
->cmd
== MemCmd::ReadExReq
||
202 pkt
->cmd
== MemCmd::SCUpgradeFailReq
);
203 assert(!pkt
->hasSharers());
205 // if we have a dirty copy, make sure the recipient
206 // keeps it marked dirty (in the modified state)
207 if (blk
->isDirty()) {
208 pkt
->setCacheResponding();
209 blk
->status
&= ~BlkDirty
;
211 } else if (blk
->isWritable() && !pending_downgrade
&&
212 !pkt
->hasSharers() &&
213 pkt
->cmd
!= MemCmd::ReadCleanReq
) {
214 // we can give the requester a writable copy on a read
216 // - we have a writable copy at this level (& below)
217 // - we don't have a pending snoop from below
218 // signaling another read request
219 // - no other cache above has a copy (otherwise it
220 // would have set hasSharers flag when
221 // snooping the packet)
222 // - the read has explicitly asked for a clean
224 if (blk
->isDirty()) {
225 // special considerations if we're owner:
226 if (!deferred_response
) {
227 // respond with the line in Modified state
228 // (cacheResponding set, hasSharers not set)
229 pkt
->setCacheResponding();
231 // if this cache is mostly inclusive, we
232 // keep the block in the Exclusive state,
233 // and pass it upwards as Modified
234 // (writable and dirty), hence we have
235 // multiple caches, all on the same path
236 // towards memory, all considering the
237 // same block writable, but only one
238 // considering it Modified
240 // we get away with multiple caches (on
241 // the same path to memory) considering
242 // the block writeable as we always enter
243 // the cache hierarchy through a cache,
244 // and first snoop upwards in all other
246 blk
->status
&= ~BlkDirty
;
248 // if we're responding after our own miss,
249 // there's a window where the recipient didn't
250 // know it was getting ownership and may not
251 // have responded to snoops correctly, so we
252 // have to respond with a shared line
253 pkt
->setHasSharers();
257 // otherwise only respond with a shared copy
258 pkt
->setHasSharers();
261 } else if (pkt
->isUpgrade()) {
263 assert(!pkt
->hasSharers());
265 if (blk
->isDirty()) {
266 // we were in the Owned state, and a cache above us that
267 // has the line in Shared state needs to be made aware
268 // that the data it already has is in fact dirty
269 pkt
->setCacheResponding();
270 blk
->status
&= ~BlkDirty
;
273 assert(pkt
->isInvalidate());
274 invalidateBlock(blk
);
275 DPRINTF(CacheVerbose
, "%s for %s (invalidation)\n", __func__
,
280 /////////////////////////////////////////////////////
282 // Access path: requests coming in from the CPU side
284 /////////////////////////////////////////////////////
287 Cache::access(PacketPtr pkt
, CacheBlk
*&blk
, Cycles
&lat
,
288 PacketList
&writebacks
)
291 assert(pkt
->isRequest());
293 chatty_assert(!(isReadOnly
&& pkt
->isWrite()),
294 "Should never see a write in a read-only cache %s\n",
297 DPRINTF(CacheVerbose
, "%s for %s\n", __func__
, pkt
->print());
299 if (pkt
->req
->isUncacheable()) {
300 DPRINTF(Cache
, "uncacheable: %s\n", pkt
->print());
302 // flush and invalidate any existing block
303 CacheBlk
*old_blk(tags
->findBlock(pkt
->getAddr(), pkt
->isSecure()));
304 if (old_blk
&& old_blk
->isValid()) {
305 if (old_blk
->isDirty() || writebackClean
)
306 writebacks
.push_back(writebackBlk(old_blk
));
308 writebacks
.push_back(cleanEvictBlk(old_blk
));
309 invalidateBlock(old_blk
);
313 // lookupLatency is the latency in case the request is uncacheable.
318 // Here lat is the value passed as parameter to accessBlock() function
319 // that can modify its value.
320 blk
= tags
->accessBlock(pkt
->getAddr(), pkt
->isSecure(), lat
);
322 DPRINTF(Cache
, "%s %s\n", pkt
->print(),
323 blk
? "hit " + blk
->print() : "miss");
326 if (pkt
->isEviction()) {
327 // We check for presence of block in above caches before issuing
328 // Writeback or CleanEvict to write buffer. Therefore the only
329 // possible cases can be of a CleanEvict packet coming from above
330 // encountering a Writeback generated in this cache peer cache and
331 // waiting in the write buffer. Cases of upper level peer caches
332 // generating CleanEvict and Writeback or simply CleanEvict and
333 // CleanEvict almost simultaneously will be caught by snoops sent out
335 WriteQueueEntry
*wb_entry
= writeBuffer
.findMatch(pkt
->getAddr(),
338 assert(wb_entry
->getNumTargets() == 1);
339 PacketPtr wbPkt
= wb_entry
->getTarget()->pkt
;
340 assert(wbPkt
->isWriteback());
342 if (pkt
->isCleanEviction()) {
343 // The CleanEvict and WritebackClean snoops into other
344 // peer caches of the same level while traversing the
345 // crossbar. If a copy of the block is found, the
346 // packet is deleted in the crossbar. Hence, none of
347 // the other upper level caches connected to this
348 // cache have the block, so we can clear the
349 // BLOCK_CACHED flag in the Writeback if set and
350 // discard the CleanEvict by returning true.
351 wbPkt
->clearBlockCached();
354 assert(pkt
->cmd
== MemCmd::WritebackDirty
);
355 // Dirty writeback from above trumps our clean
356 // writeback... discard here
357 // Note: markInService will remove entry from writeback buffer.
358 markInService(wb_entry
);
364 // Writeback handling is special case. We can write the block into
365 // the cache without having a writeable copy (or any copy at all).
366 if (pkt
->isWriteback()) {
367 assert(blkSize
== pkt
->getSize());
369 // we could get a clean writeback while we are having
370 // outstanding accesses to a block, do the simple thing for
371 // now and drop the clean writeback so that we do not upset
372 // any ordering/decisions about ownership already taken
373 if (pkt
->cmd
== MemCmd::WritebackClean
&&
374 mshrQueue
.findMatch(pkt
->getAddr(), pkt
->isSecure())) {
375 DPRINTF(Cache
, "Clean writeback %#llx to block with MSHR, "
376 "dropping\n", pkt
->getAddr());
380 if (blk
== nullptr) {
381 // need to do a replacement
382 blk
= allocateBlock(pkt
->getAddr(), pkt
->isSecure(), writebacks
);
383 if (blk
== nullptr) {
384 // no replaceable block available: give up, fwd to next level.
388 tags
->insertBlock(pkt
, blk
);
390 blk
->status
= (BlkValid
| BlkReadable
);
391 if (pkt
->isSecure()) {
392 blk
->status
|= BlkSecure
;
395 // only mark the block dirty if we got a writeback command,
396 // and leave it as is for a clean writeback
397 if (pkt
->cmd
== MemCmd::WritebackDirty
) {
398 blk
->status
|= BlkDirty
;
400 // if the packet does not have sharers, it is passing
401 // writable, and we got the writeback in Modified or Exclusive
402 // state, if not we are in the Owned or Shared state
403 if (!pkt
->hasSharers()) {
404 blk
->status
|= BlkWritable
;
406 // nothing else to do; writeback doesn't expect response
407 assert(!pkt
->needsResponse());
408 std::memcpy(blk
->data
, pkt
->getConstPtr
<uint8_t>(), blkSize
);
409 DPRINTF(Cache
, "%s new state is %s\n", __func__
, blk
->print());
412 } else if (pkt
->cmd
== MemCmd::CleanEvict
) {
413 if (blk
!= nullptr) {
414 // Found the block in the tags, need to stop CleanEvict from
415 // propagating further down the hierarchy. Returning true will
416 // treat the CleanEvict like a satisfied write request and delete
420 // We didn't find the block here, propagate the CleanEvict further
421 // down the memory hierarchy. Returning false will treat the CleanEvict
422 // like a Writeback which could not find a replaceable block so has to
425 } else if (blk
&& (pkt
->needsWritable() ? blk
->isWritable() :
426 blk
->isReadable())) {
427 // OK to satisfy access
429 satisfyRequest(pkt
, blk
);
430 maintainClusivity(pkt
->fromCache(), blk
);
435 // Can't satisfy access normally... either no block (blk == nullptr)
436 // or have block but need writable
440 if (blk
== nullptr && pkt
->isLLSC() && pkt
->isWrite()) {
441 // complete miss on store conditional... just give up now
442 pkt
->req
->setExtraData(0);
450 Cache::maintainClusivity(bool from_cache
, CacheBlk
*blk
)
452 if (from_cache
&& blk
&& blk
->isValid() && !blk
->isDirty() &&
453 clusivity
== Enums::mostly_excl
) {
454 // if we have responded to a cache, and our block is still
455 // valid, but not dirty, and this cache is mostly exclusive
456 // with respect to the cache above, drop the block
457 invalidateBlock(blk
);
462 Cache::doWritebacks(PacketList
& writebacks
, Tick forward_time
)
464 while (!writebacks
.empty()) {
465 PacketPtr wbPkt
= writebacks
.front();
466 // We use forwardLatency here because we are copying writebacks to
467 // write buffer. Call isCachedAbove for both Writebacks and
468 // CleanEvicts. If isCachedAbove returns true we set BLOCK_CACHED flag
469 // in Writebacks and discard CleanEvicts.
470 if (isCachedAbove(wbPkt
)) {
471 if (wbPkt
->cmd
== MemCmd::CleanEvict
) {
472 // Delete CleanEvict because cached copies exist above. The
473 // packet destructor will delete the request object because
474 // this is a non-snoop request packet which does not require a
477 } else if (wbPkt
->cmd
== MemCmd::WritebackClean
) {
478 // clean writeback, do not send since the block is
479 // still cached above
480 assert(writebackClean
);
483 assert(wbPkt
->cmd
== MemCmd::WritebackDirty
);
484 // Set BLOCK_CACHED flag in Writeback and send below, so that
485 // the Writeback does not reset the bit corresponding to this
486 // address in the snoop filter below.
487 wbPkt
->setBlockCached();
488 allocateWriteBuffer(wbPkt
, forward_time
);
491 // If the block is not cached above, send packet below. Both
492 // CleanEvict and Writeback with BLOCK_CACHED flag cleared will
493 // reset the bit corresponding to this address in the snoop filter
495 allocateWriteBuffer(wbPkt
, forward_time
);
497 writebacks
.pop_front();
502 Cache::doWritebacksAtomic(PacketList
& writebacks
)
504 while (!writebacks
.empty()) {
505 PacketPtr wbPkt
= writebacks
.front();
506 // Call isCachedAbove for both Writebacks and CleanEvicts. If
507 // isCachedAbove returns true we set BLOCK_CACHED flag in Writebacks
508 // and discard CleanEvicts.
509 if (isCachedAbove(wbPkt
, false)) {
510 if (wbPkt
->cmd
== MemCmd::WritebackDirty
) {
511 // Set BLOCK_CACHED flag in Writeback and send below,
512 // so that the Writeback does not reset the bit
513 // corresponding to this address in the snoop filter
514 // below. We can discard CleanEvicts because cached
515 // copies exist above. Atomic mode isCachedAbove
516 // modifies packet to set BLOCK_CACHED flag
517 memSidePort
->sendAtomic(wbPkt
);
520 // If the block is not cached above, send packet below. Both
521 // CleanEvict and Writeback with BLOCK_CACHED flag cleared will
522 // reset the bit corresponding to this address in the snoop filter
524 memSidePort
->sendAtomic(wbPkt
);
526 writebacks
.pop_front();
527 // In case of CleanEvicts, the packet destructor will delete the
528 // request object because this is a non-snoop request packet which
529 // does not require a response.
536 Cache::recvTimingSnoopResp(PacketPtr pkt
)
538 DPRINTF(Cache
, "%s for %s\n", __func__
, pkt
->print());
540 assert(pkt
->isResponse());
541 assert(!system
->bypassCaches());
543 // determine if the response is from a snoop request we created
544 // (in which case it should be in the outstandingSnoop), or if we
545 // merely forwarded someone else's snoop request
546 const bool forwardAsSnoop
= outstandingSnoop
.find(pkt
->req
) ==
547 outstandingSnoop
.end();
549 if (!forwardAsSnoop
) {
550 // the packet came from this cache, so sink it here and do not
552 assert(pkt
->cmd
== MemCmd::HardPFResp
);
554 outstandingSnoop
.erase(pkt
->req
);
556 DPRINTF(Cache
, "Got prefetch response from above for addr "
557 "%#llx (%s)\n", pkt
->getAddr(), pkt
->isSecure() ? "s" : "ns");
562 // forwardLatency is set here because there is a response from an
563 // upper level cache.
564 // To pay the delay that occurs if the packet comes from the bus,
565 // we charge also headerDelay.
566 Tick snoop_resp_time
= clockEdge(forwardLatency
) + pkt
->headerDelay
;
567 // Reset the timing of the packet.
568 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
569 memSidePort
->schedTimingSnoopResp(pkt
, snoop_resp_time
);
573 Cache::promoteWholeLineWrites(PacketPtr pkt
)
575 // Cache line clearing instructions
576 if (doFastWrites
&& (pkt
->cmd
== MemCmd::WriteReq
) &&
577 (pkt
->getSize() == blkSize
) && (pkt
->getOffset(blkSize
) == 0)) {
578 pkt
->cmd
= MemCmd::WriteLineReq
;
579 DPRINTF(Cache
, "packet promoted from Write to WriteLineReq\n");
584 Cache::recvTimingReq(PacketPtr pkt
)
586 DPRINTF(CacheTags
, "%s tags:\n%s\n", __func__
, tags
->print());
588 assert(pkt
->isRequest());
590 // Just forward the packet if caches are disabled.
591 if (system
->bypassCaches()) {
592 // @todo This should really enqueue the packet rather
593 bool M5_VAR_USED success
= memSidePort
->sendTimingReq(pkt
);
598 promoteWholeLineWrites(pkt
);
600 if (pkt
->cacheResponding()) {
601 // a cache above us (but not where the packet came from) is
602 // responding to the request, in other words it has the line
603 // in Modified or Owned state
604 DPRINTF(Cache
, "Cache above responding to %s: not responding\n",
607 // if the packet needs the block to be writable, and the cache
608 // that has promised to respond (setting the cache responding
609 // flag) is not providing writable (it is in Owned rather than
610 // the Modified state), we know that there may be other Shared
611 // copies in the system; go out and invalidate them all
612 assert(pkt
->needsWritable() && !pkt
->responderHadWritable());
614 // an upstream cache that had the line in Owned state
615 // (dirty, but not writable), is responding and thus
616 // transferring the dirty line from one branch of the
617 // cache hierarchy to another
619 // send out an express snoop and invalidate all other
620 // copies (snooping a packet that needs writable is the
621 // same as an invalidation), thus turning the Owned line
622 // into a Modified line, note that we don't invalidate the
623 // block in the current cache or any other cache on the
626 // create a downstream express snoop with cleared packet
627 // flags, there is no need to allocate any data as the
628 // packet is merely used to co-ordinate state transitions
629 Packet
*snoop_pkt
= new Packet(pkt
, true, false);
631 // also reset the bus time that the original packet has
633 snoop_pkt
->headerDelay
= snoop_pkt
->payloadDelay
= 0;
635 // make this an instantaneous express snoop, and let the
636 // other caches in the system know that the another cache
637 // is responding, because we have found the authorative
638 // copy (Modified or Owned) that will supply the right
640 snoop_pkt
->setExpressSnoop();
641 snoop_pkt
->setCacheResponding();
643 // this express snoop travels towards the memory, and at
644 // every crossbar it is snooped upwards thus reaching
645 // every cache in the system
646 bool M5_VAR_USED success
= memSidePort
->sendTimingReq(snoop_pkt
);
647 // express snoops always succeed
650 // main memory will delete the snoop packet
652 // queue for deletion, as opposed to immediate deletion, as
653 // the sending cache is still relying on the packet
654 pendingDelete
.reset(pkt
);
656 // no need to take any further action in this particular cache
657 // as an upstram cache has already committed to responding,
658 // and we have already sent out any express snoops in the
659 // section above to ensure all other copies in the system are
664 // anything that is merely forwarded pays for the forward latency and
665 // the delay provided by the crossbar
666 Tick forward_time
= clockEdge(forwardLatency
) + pkt
->headerDelay
;
668 // We use lookupLatency here because it is used to specify the latency
670 Cycles lat
= lookupLatency
;
671 CacheBlk
*blk
= nullptr;
672 bool satisfied
= false;
674 PacketList writebacks
;
675 // Note that lat is passed by reference here. The function
676 // access() calls accessBlock() which can modify lat value.
677 satisfied
= access(pkt
, blk
, lat
, writebacks
);
679 // copy writebacks to write buffer here to ensure they logically
680 // proceed anything happening below
681 doWritebacks(writebacks
, forward_time
);
684 // Here we charge the headerDelay that takes into account the latencies
685 // of the bus, if the packet comes from it.
686 // The latency charged it is just lat that is the value of lookupLatency
687 // modified by access() function, or if not just lookupLatency.
688 // In case of a hit we are neglecting response latency.
689 // In case of a miss we are neglecting forward latency.
690 Tick request_time
= clockEdge(lat
) + pkt
->headerDelay
;
691 // Here we reset the timing of the packet.
692 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
694 // track time of availability of next prefetch, if any
695 Tick next_pf_time
= MaxTick
;
697 bool needsResponse
= pkt
->needsResponse();
700 // should never be satisfying an uncacheable access as we
701 // flush and invalidate any existing block as part of the
703 assert(!pkt
->req
->isUncacheable());
705 // hit (for all other request types)
707 if (prefetcher
&& (prefetchOnAccess
||
708 (blk
&& blk
->wasPrefetched()))) {
710 blk
->status
&= ~BlkHWPrefetched
;
712 // Don't notify on SWPrefetch
713 if (!pkt
->cmd
.isSWPrefetch())
714 next_pf_time
= prefetcher
->notify(pkt
);
718 pkt
->makeTimingResponse();
719 // @todo: Make someone pay for this
720 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
722 // In this case we are considering request_time that takes
723 // into account the delay of the xbar, if any, and just
724 // lat, neglecting responseLatency, modelling hit latency
725 // just as lookupLatency or or the value of lat overriden
726 // by access(), that calls accessBlock() function.
727 cpuSidePort
->schedTimingResp(pkt
, request_time
, true);
729 DPRINTF(Cache
, "%s satisfied %s, no response needed\n", __func__
,
732 // queue the packet for deletion, as the sending cache is
733 // still relying on it; if the block is found in access(),
734 // CleanEvict and Writeback messages will be deleted
736 pendingDelete
.reset(pkt
);
741 Addr blk_addr
= pkt
->getBlockAddr(blkSize
);
743 // ignore any existing MSHR if we are dealing with an
744 // uncacheable request
745 MSHR
*mshr
= pkt
->req
->isUncacheable() ? nullptr :
746 mshrQueue
.findMatch(blk_addr
, pkt
->isSecure());
748 // Software prefetch handling:
749 // To keep the core from waiting on data it won't look at
750 // anyway, send back a response with dummy data. Miss handling
751 // will continue asynchronously. Unfortunately, the core will
752 // insist upon freeing original Packet/Request, so we have to
753 // create a new pair with a different lifecycle. Note that this
754 // processing happens before any MSHR munging on the behalf of
755 // this request because this new Request will be the one stored
756 // into the MSHRs, not the original.
757 if (pkt
->cmd
.isSWPrefetch()) {
758 assert(needsResponse
);
759 assert(pkt
->req
->hasPaddr());
760 assert(!pkt
->req
->isUncacheable());
762 // There's no reason to add a prefetch as an additional target
763 // to an existing MSHR. If an outstanding request is already
764 // in progress, there is nothing for the prefetch to do.
765 // If this is the case, we don't even create a request at all.
766 PacketPtr pf
= nullptr;
769 // copy the request and create a new SoftPFReq packet
770 RequestPtr req
= new Request(pkt
->req
->getPaddr(),
772 pkt
->req
->getFlags(),
773 pkt
->req
->masterId());
774 pf
= new Packet(req
, pkt
->cmd
);
776 assert(pf
->getAddr() == pkt
->getAddr());
777 assert(pf
->getSize() == pkt
->getSize());
780 pkt
->makeTimingResponse();
782 // request_time is used here, taking into account lat and the delay
783 // charged if the packet comes from the xbar.
784 cpuSidePort
->schedTimingResp(pkt
, request_time
, true);
786 // If an outstanding request is in progress (we found an
787 // MSHR) this is set to null
793 /// @note writebacks will be checked in getNextMSHR()
794 /// for any conflicting requests to the same block
796 //@todo remove hw_pf here
798 // Coalesce unless it was a software prefetch (see above).
800 assert(!pkt
->isWriteback());
801 // CleanEvicts corresponding to blocks which have
802 // outstanding requests in MSHRs are simply sunk here
803 if (pkt
->cmd
== MemCmd::CleanEvict
) {
804 pendingDelete
.reset(pkt
);
806 DPRINTF(Cache
, "%s coalescing MSHR for %s\n", __func__
,
809 assert(pkt
->req
->masterId() < system
->maxMasters());
810 mshr_hits
[pkt
->cmdToIndex()][pkt
->req
->masterId()]++;
811 // We use forward_time here because it is the same
812 // considering new targets. We have multiple
813 // requests for the same address here. It
814 // specifies the latency to allocate an internal
815 // buffer and to schedule an event to the queued
816 // port and also takes into account the additional
817 // delay of the xbar.
818 mshr
->allocateTarget(pkt
, forward_time
, order
++,
819 allocOnFill(pkt
->cmd
));
820 if (mshr
->getNumTargets() == numTarget
) {
822 setBlocked(Blocked_NoTargets
);
823 // need to be careful with this... if this mshr isn't
824 // ready yet (i.e. time > curTick()), we don't want to
825 // move it ahead of mshrs that are ready
826 // mshrQueue.moveToFront(mshr);
829 // We should call the prefetcher reguardless if the request is
830 // satisfied or not, reguardless if the request is in the MSHR
831 // or not. The request could be a ReadReq hit, but still not
832 // satisfied (potentially because of a prior write to the same
833 // cache line. So, even when not satisfied, tehre is an MSHR
834 // already allocated for this, we need to let the prefetcher
835 // know about the request
837 // Don't notify on SWPrefetch
838 if (!pkt
->cmd
.isSWPrefetch())
839 next_pf_time
= prefetcher
->notify(pkt
);
844 assert(pkt
->req
->masterId() < system
->maxMasters());
845 if (pkt
->req
->isUncacheable()) {
846 mshr_uncacheable
[pkt
->cmdToIndex()][pkt
->req
->masterId()]++;
848 mshr_misses
[pkt
->cmdToIndex()][pkt
->req
->masterId()]++;
851 if (pkt
->isEviction() ||
852 (pkt
->req
->isUncacheable() && pkt
->isWrite())) {
853 // We use forward_time here because there is an
854 // uncached memory write, forwarded to WriteBuffer.
855 allocateWriteBuffer(pkt
, forward_time
);
857 if (blk
&& blk
->isValid()) {
858 // should have flushed and have no valid block
859 assert(!pkt
->req
->isUncacheable());
861 // If we have a write miss to a valid block, we
862 // need to mark the block non-readable. Otherwise
863 // if we allow reads while there's an outstanding
864 // write miss, the read could return stale data
865 // out of the cache block... a more aggressive
866 // system could detect the overlap (if any) and
867 // forward data out of the MSHRs, but we don't do
868 // that yet. Note that we do need to leave the
869 // block valid so that it stays in the cache, in
870 // case we get an upgrade response (and hence no
871 // new data) when the write miss completes.
872 // As long as CPUs do proper store/load forwarding
873 // internally, and have a sufficiently weak memory
874 // model, this is probably unnecessary, but at some
875 // point it must have seemed like we needed it...
876 assert(pkt
->needsWritable());
877 assert(!blk
->isWritable());
878 blk
->status
&= ~BlkReadable
;
880 // Here we are using forward_time, modelling the latency of
881 // a miss (outbound) just as forwardLatency, neglecting the
882 // lookupLatency component.
883 allocateMissBuffer(pkt
, forward_time
);
887 // Don't notify on SWPrefetch
888 if (!pkt
->cmd
.isSWPrefetch())
889 next_pf_time
= prefetcher
->notify(pkt
);
894 if (next_pf_time
!= MaxTick
)
895 schedMemSideSendEvent(next_pf_time
);
901 Cache::createMissPacket(PacketPtr cpu_pkt
, CacheBlk
*blk
,
902 bool needsWritable
) const
904 // should never see evictions here
905 assert(!cpu_pkt
->isEviction());
907 bool blkValid
= blk
&& blk
->isValid();
909 if (cpu_pkt
->req
->isUncacheable() ||
910 (!blkValid
&& cpu_pkt
->isUpgrade()) ||
911 cpu_pkt
->cmd
== MemCmd::InvalidateReq
) {
912 // uncacheable requests and upgrades from upper-level caches
913 // that missed completely just go through as is
917 assert(cpu_pkt
->needsResponse());
920 // @TODO make useUpgrades a parameter.
921 // Note that ownership protocols require upgrade, otherwise a
922 // write miss on a shared owned block will generate a ReadExcl,
923 // which will clobber the owned copy.
924 const bool useUpgrades
= true;
925 if (cpu_pkt
->cmd
== MemCmd::WriteLineReq
) {
926 assert(!blkValid
|| !blk
->isWritable());
927 // forward as invalidate to all other caches, this gives us
928 // the line in Exclusive state, and invalidates all other
930 cmd
= MemCmd::InvalidateReq
;
931 } else if (blkValid
&& useUpgrades
) {
932 // only reason to be here is that blk is read only and we need
934 assert(needsWritable
);
935 assert(!blk
->isWritable());
936 cmd
= cpu_pkt
->isLLSC() ? MemCmd::SCUpgradeReq
: MemCmd::UpgradeReq
;
937 } else if (cpu_pkt
->cmd
== MemCmd::SCUpgradeFailReq
||
938 cpu_pkt
->cmd
== MemCmd::StoreCondFailReq
) {
939 // Even though this SC will fail, we still need to send out the
940 // request and get the data to supply it to other snoopers in the case
941 // where the determination the StoreCond fails is delayed due to
942 // all caches not being on the same local bus.
943 cmd
= MemCmd::SCUpgradeFailReq
;
946 cmd
= needsWritable
? MemCmd::ReadExReq
:
947 (isReadOnly
? MemCmd::ReadCleanReq
: MemCmd::ReadSharedReq
);
949 PacketPtr pkt
= new Packet(cpu_pkt
->req
, cmd
, blkSize
);
951 // if there are upstream caches that have already marked the
952 // packet as having sharers (not passing writable), pass that info
954 if (cpu_pkt
->hasSharers() && !needsWritable
) {
955 // note that cpu_pkt may have spent a considerable time in the
956 // MSHR queue and that the information could possibly be out
957 // of date, however, there is no harm in conservatively
958 // assuming the block has sharers
959 pkt
->setHasSharers();
960 DPRINTF(Cache
, "%s: passing hasSharers from %s to %s\n",
961 __func__
, cpu_pkt
->print(), pkt
->print());
964 // the packet should be block aligned
965 assert(pkt
->getAddr() == pkt
->getBlockAddr(blkSize
));
968 DPRINTF(Cache
, "%s: created %s from %s\n", __func__
, pkt
->print(),
975 Cache::recvAtomic(PacketPtr pkt
)
977 // We are in atomic mode so we pay just for lookupLatency here.
978 Cycles lat
= lookupLatency
;
980 // Forward the request if the system is in cache bypass mode.
981 if (system
->bypassCaches())
982 return ticksToCycles(memSidePort
->sendAtomic(pkt
));
984 promoteWholeLineWrites(pkt
);
986 // follow the same flow as in recvTimingReq, and check if a cache
987 // above us is responding
988 if (pkt
->cacheResponding()) {
989 DPRINTF(Cache
, "Cache above responding to %s: not responding\n",
992 // if a cache is responding, and it had the line in Owned
993 // rather than Modified state, we need to invalidate any
994 // copies that are not on the same path to memory
995 assert(pkt
->needsWritable() && !pkt
->responderHadWritable());
996 lat
+= ticksToCycles(memSidePort
->sendAtomic(pkt
));
998 return lat
* clockPeriod();
1001 // should assert here that there are no outstanding MSHRs or
1002 // writebacks... that would mean that someone used an atomic
1003 // access in timing mode
1005 CacheBlk
*blk
= nullptr;
1006 PacketList writebacks
;
1007 bool satisfied
= access(pkt
, blk
, lat
, writebacks
);
1009 // handle writebacks resulting from the access here to ensure they
1010 // logically proceed anything happening below
1011 doWritebacksAtomic(writebacks
);
1016 // deal with the packets that go through the write path of
1017 // the cache, i.e. any evictions and uncacheable writes
1018 if (pkt
->isEviction() ||
1019 (pkt
->req
->isUncacheable() && pkt
->isWrite())) {
1020 lat
+= ticksToCycles(memSidePort
->sendAtomic(pkt
));
1021 return lat
* clockPeriod();
1025 PacketPtr bus_pkt
= createMissPacket(pkt
, blk
, pkt
->needsWritable());
1027 bool is_forward
= (bus_pkt
== nullptr);
1030 // just forwarding the same request to the next level
1031 // no local cache operation involved
1035 DPRINTF(Cache
, "%s: Sending an atomic %s\n", __func__
,
1039 CacheBlk::State old_state
= blk
? blk
->status
: 0;
1042 lat
+= ticksToCycles(memSidePort
->sendAtomic(bus_pkt
));
1044 bool is_invalidate
= bus_pkt
->isInvalidate();
1046 // We are now dealing with the response handling
1047 DPRINTF(Cache
, "%s: Receive response: %s in state %i\n", __func__
,
1048 bus_pkt
->print(), old_state
);
1050 // If packet was a forward, the response (if any) is already
1051 // in place in the bus_pkt == pkt structure, so we don't need
1052 // to do anything. Otherwise, use the separate bus_pkt to
1053 // generate response to pkt and then delete it.
1055 if (pkt
->needsResponse()) {
1056 assert(bus_pkt
->isResponse());
1057 if (bus_pkt
->isError()) {
1058 pkt
->makeAtomicResponse();
1059 pkt
->copyError(bus_pkt
);
1060 } else if (pkt
->cmd
== MemCmd::WriteLineReq
) {
1061 // note the use of pkt, not bus_pkt here.
1063 // write-line request to the cache that promoted
1064 // the write to a whole line
1065 blk
= handleFill(pkt
, blk
, writebacks
,
1066 allocOnFill(pkt
->cmd
));
1067 assert(blk
!= NULL
);
1068 is_invalidate
= false;
1069 satisfyRequest(pkt
, blk
);
1070 } else if (bus_pkt
->isRead() ||
1071 bus_pkt
->cmd
== MemCmd::UpgradeResp
) {
1072 // we're updating cache state to allow us to
1073 // satisfy the upstream request from the cache
1074 blk
= handleFill(bus_pkt
, blk
, writebacks
,
1075 allocOnFill(pkt
->cmd
));
1076 satisfyRequest(pkt
, blk
);
1077 maintainClusivity(pkt
->fromCache(), blk
);
1079 // we're satisfying the upstream request without
1080 // modifying cache state, e.g., a write-through
1081 pkt
->makeAtomicResponse();
1087 if (is_invalidate
&& blk
&& blk
->isValid()) {
1088 invalidateBlock(blk
);
1092 // Note that we don't invoke the prefetcher at all in atomic mode.
1093 // It's not clear how to do it properly, particularly for
1094 // prefetchers that aggressively generate prefetch candidates and
1095 // rely on bandwidth contention to throttle them; these will tend
1096 // to pollute the cache in atomic mode since there is no bandwidth
1097 // contention. If we ever do want to enable prefetching in atomic
1098 // mode, though, this is the place to do it... see timingAccess()
1099 // for an example (though we'd want to issue the prefetch(es)
1100 // immediately rather than calling requestMemSideBus() as we do
1103 // do any writebacks resulting from the response handling
1104 doWritebacksAtomic(writebacks
);
1106 // if we used temp block, check to see if its valid and if so
1107 // clear it out, but only do so after the call to recvAtomic is
1108 // finished so that any downstream observers (such as a snoop
1109 // filter), first see the fill, and only then see the eviction
1110 if (blk
== tempBlock
&& tempBlock
->isValid()) {
1111 // the atomic CPU calls recvAtomic for fetch and load/store
1112 // sequentuially, and we may already have a tempBlock
1113 // writeback from the fetch that we have not yet sent
1114 if (tempBlockWriteback
) {
1115 // if that is the case, write the prevoius one back, and
1116 // do not schedule any new event
1117 writebackTempBlockAtomic();
1119 // the writeback/clean eviction happens after the call to
1120 // recvAtomic has finished (but before any successive
1121 // calls), so that the response handling from the fill is
1122 // allowed to happen first
1123 schedule(writebackTempBlockAtomicEvent
, curTick());
1126 tempBlockWriteback
= (blk
->isDirty() || writebackClean
) ?
1127 writebackBlk(blk
) : cleanEvictBlk(blk
);
1128 invalidateBlock(blk
);
1131 if (pkt
->needsResponse()) {
1132 pkt
->makeAtomicResponse();
1135 return lat
* clockPeriod();
1140 Cache::functionalAccess(PacketPtr pkt
, bool fromCpuSide
)
1142 if (system
->bypassCaches()) {
1143 // Packets from the memory side are snoop request and
1144 // shouldn't happen in bypass mode.
1145 assert(fromCpuSide
);
1147 // The cache should be flushed if we are in cache bypass mode,
1148 // so we don't need to check if we need to update anything.
1149 memSidePort
->sendFunctional(pkt
);
1153 Addr blk_addr
= pkt
->getBlockAddr(blkSize
);
1154 bool is_secure
= pkt
->isSecure();
1155 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), is_secure
);
1156 MSHR
*mshr
= mshrQueue
.findMatch(blk_addr
, is_secure
);
1158 pkt
->pushLabel(name());
1160 CacheBlkPrintWrapper
cbpw(blk
);
1162 // Note that just because an L2/L3 has valid data doesn't mean an
1163 // L1 doesn't have a more up-to-date modified copy that still
1164 // needs to be found. As a result we always update the request if
1165 // we have it, but only declare it satisfied if we are the owner.
1167 // see if we have data at all (owned or otherwise)
1168 bool have_data
= blk
&& blk
->isValid()
1169 && pkt
->checkFunctional(&cbpw
, blk_addr
, is_secure
, blkSize
,
1172 // data we have is dirty if marked as such or if we have an
1173 // in-service MSHR that is pending a modified line
1175 have_data
&& (blk
->isDirty() ||
1176 (mshr
&& mshr
->inService
&& mshr
->isPendingModified()));
1178 bool done
= have_dirty
1179 || cpuSidePort
->checkFunctional(pkt
)
1180 || mshrQueue
.checkFunctional(pkt
, blk_addr
)
1181 || writeBuffer
.checkFunctional(pkt
, blk_addr
)
1182 || memSidePort
->checkFunctional(pkt
);
1184 DPRINTF(CacheVerbose
, "%s: %s %s%s%s\n", __func__
, pkt
->print(),
1185 (blk
&& blk
->isValid()) ? "valid " : "",
1186 have_data
? "data " : "", done
? "done " : "");
1188 // We're leaving the cache, so pop cache->name() label
1192 pkt
->makeResponse();
1194 // if it came as a request from the CPU side then make sure it
1195 // continues towards the memory side
1197 memSidePort
->sendFunctional(pkt
);
1198 } else if (cpuSidePort
->isSnooping()) {
1199 // if it came from the memory side, it must be a snoop request
1200 // and we should only forward it if we are forwarding snoops
1201 cpuSidePort
->sendFunctionalSnoop(pkt
);
1207 /////////////////////////////////////////////////////
1209 // Response handling: responses from the memory side
1211 /////////////////////////////////////////////////////
1215 Cache::handleUncacheableWriteResp(PacketPtr pkt
)
1217 Tick completion_time
= clockEdge(responseLatency
) +
1218 pkt
->headerDelay
+ pkt
->payloadDelay
;
1220 // Reset the bus additional time as it is now accounted for
1221 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
1223 cpuSidePort
->schedTimingResp(pkt
, completion_time
, true);
1227 Cache::recvTimingResp(PacketPtr pkt
)
1229 assert(pkt
->isResponse());
1231 // all header delay should be paid for by the crossbar, unless
1232 // this is a prefetch response from above
1233 panic_if(pkt
->headerDelay
!= 0 && pkt
->cmd
!= MemCmd::HardPFResp
,
1234 "%s saw a non-zero packet delay\n", name());
1236 bool is_error
= pkt
->isError();
1239 DPRINTF(Cache
, "%s: Cache received %s with error\n", __func__
,
1243 DPRINTF(Cache
, "%s: Handling response %s\n", __func__
,
1246 // if this is a write, we should be looking at an uncacheable
1248 if (pkt
->isWrite()) {
1249 assert(pkt
->req
->isUncacheable());
1250 handleUncacheableWriteResp(pkt
);
1254 // we have dealt with any (uncacheable) writes above, from here on
1255 // we know we are dealing with an MSHR due to a miss or a prefetch
1256 MSHR
*mshr
= dynamic_cast<MSHR
*>(pkt
->popSenderState());
1259 if (mshr
== noTargetMSHR
) {
1260 // we always clear at least one target
1261 clearBlocked(Blocked_NoTargets
);
1262 noTargetMSHR
= nullptr;
1265 // Initial target is used just for stats
1266 MSHR::Target
*initial_tgt
= mshr
->getTarget();
1267 int stats_cmd_idx
= initial_tgt
->pkt
->cmdToIndex();
1268 Tick miss_latency
= curTick() - initial_tgt
->recvTime
;
1270 if (pkt
->req
->isUncacheable()) {
1271 assert(pkt
->req
->masterId() < system
->maxMasters());
1272 mshr_uncacheable_lat
[stats_cmd_idx
][pkt
->req
->masterId()] +=
1275 assert(pkt
->req
->masterId() < system
->maxMasters());
1276 mshr_miss_latency
[stats_cmd_idx
][pkt
->req
->masterId()] +=
1280 bool wasFull
= mshrQueue
.isFull();
1282 PacketList writebacks
;
1284 Tick forward_time
= clockEdge(forwardLatency
) + pkt
->headerDelay
;
1286 // upgrade deferred targets if the response has no sharers, and is
1287 // thus passing writable
1288 if (!pkt
->hasSharers()) {
1289 mshr
->promoteWritable();
1292 bool is_fill
= !mshr
->isForward
&&
1293 (pkt
->isRead() || pkt
->cmd
== MemCmd::UpgradeResp
);
1295 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), pkt
->isSecure());
1297 if (is_fill
&& !is_error
) {
1298 DPRINTF(Cache
, "Block for addr %#llx being updated in Cache\n",
1301 blk
= handleFill(pkt
, blk
, writebacks
, mshr
->allocOnFill());
1302 assert(blk
!= nullptr);
1305 // allow invalidation responses originating from write-line
1306 // requests to be discarded
1307 bool is_invalidate
= pkt
->isInvalidate();
1309 // First offset for critical word first calculations
1310 int initial_offset
= initial_tgt
->pkt
->getOffset(blkSize
);
1312 bool from_cache
= false;
1313 MSHR::TargetList targets
= mshr
->extractServiceableTargets(pkt
);
1314 for (auto &target
: targets
) {
1315 Packet
*tgt_pkt
= target
.pkt
;
1316 switch (target
.source
) {
1317 case MSHR::Target::FromCPU
:
1318 Tick completion_time
;
1319 // Here we charge on completion_time the delay of the xbar if the
1320 // packet comes from it, charged on headerDelay.
1321 completion_time
= pkt
->headerDelay
;
1323 // Software prefetch handling for cache closest to core
1324 if (tgt_pkt
->cmd
.isSWPrefetch()) {
1325 // a software prefetch would have already been ack'd
1326 // immediately with dummy data so the core would be able to
1327 // retire it. This request completes right here, so we
1329 delete tgt_pkt
->req
;
1331 break; // skip response
1334 // keep track of whether we have responded to another
1336 from_cache
= from_cache
|| tgt_pkt
->fromCache();
1338 // unlike the other packet flows, where data is found in other
1339 // caches or memory and brought back, write-line requests always
1340 // have the data right away, so the above check for "is fill?"
1341 // cannot actually be determined until examining the stored MSHR
1342 // state. We "catch up" with that logic here, which is duplicated
1344 if (tgt_pkt
->cmd
== MemCmd::WriteLineReq
) {
1346 // we got the block in a writable state, so promote
1347 // any deferred targets if possible
1348 mshr
->promoteWritable();
1349 // NB: we use the original packet here and not the response!
1350 blk
= handleFill(tgt_pkt
, blk
, writebacks
,
1351 targets
.allocOnFill
);
1352 assert(blk
!= nullptr);
1354 // treat as a fill, and discard the invalidation
1357 is_invalidate
= false;
1361 satisfyRequest(tgt_pkt
, blk
, true, mshr
->hasPostDowngrade());
1363 // How many bytes past the first request is this one
1364 int transfer_offset
=
1365 tgt_pkt
->getOffset(blkSize
) - initial_offset
;
1366 if (transfer_offset
< 0) {
1367 transfer_offset
+= blkSize
;
1370 // If not critical word (offset) return payloadDelay.
1371 // responseLatency is the latency of the return path
1372 // from lower level caches/memory to an upper level cache or
1374 completion_time
+= clockEdge(responseLatency
) +
1375 (transfer_offset
? pkt
->payloadDelay
: 0);
1377 assert(!tgt_pkt
->req
->isUncacheable());
1379 assert(tgt_pkt
->req
->masterId() < system
->maxMasters());
1380 missLatency
[tgt_pkt
->cmdToIndex()][tgt_pkt
->req
->masterId()] +=
1381 completion_time
- target
.recvTime
;
1382 } else if (pkt
->cmd
== MemCmd::UpgradeFailResp
) {
1383 // failed StoreCond upgrade
1384 assert(tgt_pkt
->cmd
== MemCmd::StoreCondReq
||
1385 tgt_pkt
->cmd
== MemCmd::StoreCondFailReq
||
1386 tgt_pkt
->cmd
== MemCmd::SCUpgradeFailReq
);
1387 // responseLatency is the latency of the return path
1388 // from lower level caches/memory to an upper level cache or
1390 completion_time
+= clockEdge(responseLatency
) +
1392 tgt_pkt
->req
->setExtraData(0);
1394 // We are about to send a response to a cache above
1395 // that asked for an invalidation; we need to
1396 // invalidate our copy immediately as the most
1397 // up-to-date copy of the block will now be in the
1398 // cache above. It will also prevent this cache from
1399 // responding (if the block was previously dirty) to
1400 // snoops as they should snoop the caches above where
1401 // they will get the response from.
1402 if (is_invalidate
&& blk
&& blk
->isValid()) {
1403 invalidateBlock(blk
);
1405 // not a cache fill, just forwarding response
1406 // responseLatency is the latency of the return path
1407 // from lower level cahces/memory to the core.
1408 completion_time
+= clockEdge(responseLatency
) +
1410 if (pkt
->isRead() && !is_error
) {
1412 assert(pkt
->getAddr() == tgt_pkt
->getAddr());
1413 assert(pkt
->getSize() >= tgt_pkt
->getSize());
1415 tgt_pkt
->setData(pkt
->getConstPtr
<uint8_t>());
1418 tgt_pkt
->makeTimingResponse();
1419 // if this packet is an error copy that to the new packet
1421 tgt_pkt
->copyError(pkt
);
1422 if (tgt_pkt
->cmd
== MemCmd::ReadResp
&&
1423 (is_invalidate
|| mshr
->hasPostInvalidate())) {
1424 // If intermediate cache got ReadRespWithInvalidate,
1425 // propagate that. Response should not have
1426 // isInvalidate() set otherwise.
1427 tgt_pkt
->cmd
= MemCmd::ReadRespWithInvalidate
;
1428 DPRINTF(Cache
, "%s: updated cmd to %s\n", __func__
,
1431 // Reset the bus additional time as it is now accounted for
1432 tgt_pkt
->headerDelay
= tgt_pkt
->payloadDelay
= 0;
1433 cpuSidePort
->schedTimingResp(tgt_pkt
, completion_time
, true);
1436 case MSHR::Target::FromPrefetcher
:
1437 assert(tgt_pkt
->cmd
== MemCmd::HardPFReq
);
1439 blk
->status
|= BlkHWPrefetched
;
1440 delete tgt_pkt
->req
;
1444 case MSHR::Target::FromSnoop
:
1445 // I don't believe that a snoop can be in an error state
1447 // response to snoop request
1448 DPRINTF(Cache
, "processing deferred snoop...\n");
1449 // If the response is invalidating, a snooping target can
1450 // be satisfied if it is also invalidating. If the reponse is, not
1451 // only invalidating, but more specifically an InvalidateResp, the
1452 // MSHR was created due to an InvalidateReq and a cache above is
1453 // waiting to satisfy a WriteLineReq. In this case even an
1454 // non-invalidating snoop is added as a target here since this is
1455 // the ordering point. When the InvalidateResp reaches this cache,
1456 // the snooping target will snoop further the cache above with the
1458 assert(!(is_invalidate
&&
1459 pkt
->cmd
!= MemCmd::InvalidateResp
&&
1460 !mshr
->hasPostInvalidate()));
1461 handleSnoop(tgt_pkt
, blk
, true, true, mshr
->hasPostInvalidate());
1465 panic("Illegal target->source enum %d\n", target
.source
);
1469 maintainClusivity(from_cache
, blk
);
1471 if (blk
&& blk
->isValid()) {
1472 // an invalidate response stemming from a write line request
1473 // should not invalidate the block, so check if the
1474 // invalidation should be discarded
1475 if (is_invalidate
|| mshr
->hasPostInvalidate()) {
1476 invalidateBlock(blk
);
1477 } else if (mshr
->hasPostDowngrade()) {
1478 blk
->status
&= ~BlkWritable
;
1482 if (mshr
->promoteDeferredTargets()) {
1483 // avoid later read getting stale data while write miss is
1484 // outstanding.. see comment in timingAccess()
1486 blk
->status
&= ~BlkReadable
;
1488 mshrQueue
.markPending(mshr
);
1489 schedMemSideSendEvent(clockEdge() + pkt
->payloadDelay
);
1491 mshrQueue
.deallocate(mshr
);
1492 if (wasFull
&& !mshrQueue
.isFull()) {
1493 clearBlocked(Blocked_NoMSHRs
);
1496 // Request the bus for a prefetch if this deallocation freed enough
1497 // MSHRs for a prefetch to take place
1498 if (prefetcher
&& mshrQueue
.canPrefetch()) {
1499 Tick next_pf_time
= std::max(prefetcher
->nextPrefetchReadyTime(),
1501 if (next_pf_time
!= MaxTick
)
1502 schedMemSideSendEvent(next_pf_time
);
1505 // reset the xbar additional timinig as it is now accounted for
1506 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
1508 // copy writebacks to write buffer
1509 doWritebacks(writebacks
, forward_time
);
1511 // if we used temp block, check to see if its valid and then clear it out
1512 if (blk
== tempBlock
&& tempBlock
->isValid()) {
1513 // We use forwardLatency here because we are copying
1514 // Writebacks/CleanEvicts to write buffer. It specifies the latency to
1515 // allocate an internal buffer and to schedule an event to the
1517 if (blk
->isDirty() || writebackClean
) {
1518 PacketPtr wbPkt
= writebackBlk(blk
);
1519 allocateWriteBuffer(wbPkt
, forward_time
);
1520 // Set BLOCK_CACHED flag if cached above.
1521 if (isCachedAbove(wbPkt
))
1522 wbPkt
->setBlockCached();
1524 PacketPtr wcPkt
= cleanEvictBlk(blk
);
1525 // Check to see if block is cached above. If not allocate
1527 if (isCachedAbove(wcPkt
))
1530 allocateWriteBuffer(wcPkt
, forward_time
);
1532 invalidateBlock(blk
);
1535 DPRINTF(CacheVerbose
, "%s: Leaving with %s\n", __func__
, pkt
->print());
1540 Cache::writebackBlk(CacheBlk
*blk
)
1542 chatty_assert(!isReadOnly
|| writebackClean
,
1543 "Writeback from read-only cache");
1544 assert(blk
&& blk
->isValid() && (blk
->isDirty() || writebackClean
));
1546 writebacks
[Request::wbMasterId
]++;
1548 Request
*req
= new Request(tags
->regenerateBlkAddr(blk
->tag
, blk
->set
),
1549 blkSize
, 0, Request::wbMasterId
);
1550 if (blk
->isSecure())
1551 req
->setFlags(Request::SECURE
);
1553 req
->taskId(blk
->task_id
);
1554 blk
->task_id
= ContextSwitchTaskId::Unknown
;
1555 blk
->tickInserted
= curTick();
1558 new Packet(req
, blk
->isDirty() ?
1559 MemCmd::WritebackDirty
: MemCmd::WritebackClean
);
1561 DPRINTF(Cache
, "Create Writeback %s writable: %d, dirty: %d\n",
1562 pkt
->print(), blk
->isWritable(), blk
->isDirty());
1564 if (blk
->isWritable()) {
1565 // not asserting shared means we pass the block in modified
1566 // state, mark our own block non-writeable
1567 blk
->status
&= ~BlkWritable
;
1569 // we are in the Owned state, tell the receiver
1570 pkt
->setHasSharers();
1573 // make sure the block is not marked dirty
1574 blk
->status
&= ~BlkDirty
;
1577 std::memcpy(pkt
->getPtr
<uint8_t>(), blk
->data
, blkSize
);
1583 Cache::cleanEvictBlk(CacheBlk
*blk
)
1585 assert(!writebackClean
);
1586 assert(blk
&& blk
->isValid() && !blk
->isDirty());
1587 // Creating a zero sized write, a message to the snoop filter
1589 new Request(tags
->regenerateBlkAddr(blk
->tag
, blk
->set
), blkSize
, 0,
1590 Request::wbMasterId
);
1591 if (blk
->isSecure())
1592 req
->setFlags(Request::SECURE
);
1594 req
->taskId(blk
->task_id
);
1595 blk
->task_id
= ContextSwitchTaskId::Unknown
;
1596 blk
->tickInserted
= curTick();
1598 PacketPtr pkt
= new Packet(req
, MemCmd::CleanEvict
);
1600 DPRINTF(Cache
, "Create CleanEvict %s\n", pkt
->print());
1606 Cache::memWriteback()
1608 CacheBlkVisitorWrapper
visitor(*this, &Cache::writebackVisitor
);
1609 tags
->forEachBlk(visitor
);
1613 Cache::memInvalidate()
1615 CacheBlkVisitorWrapper
visitor(*this, &Cache::invalidateVisitor
);
1616 tags
->forEachBlk(visitor
);
1620 Cache::isDirty() const
1622 CacheBlkIsDirtyVisitor visitor
;
1623 tags
->forEachBlk(visitor
);
1625 return visitor
.isDirty();
1629 Cache::writebackVisitor(CacheBlk
&blk
)
1631 if (blk
.isDirty()) {
1632 assert(blk
.isValid());
1634 Request
request(tags
->regenerateBlkAddr(blk
.tag
, blk
.set
),
1635 blkSize
, 0, Request::funcMasterId
);
1636 request
.taskId(blk
.task_id
);
1637 if (blk
.isSecure()) {
1638 request
.setFlags(Request::SECURE
);
1641 Packet
packet(&request
, MemCmd::WriteReq
);
1642 packet
.dataStatic(blk
.data
);
1644 memSidePort
->sendFunctional(&packet
);
1646 blk
.status
&= ~BlkDirty
;
1653 Cache::invalidateVisitor(CacheBlk
&blk
)
1657 warn_once("Invalidating dirty cache lines. Expect things to break.\n");
1659 if (blk
.isValid()) {
1660 assert(!blk
.isDirty());
1661 invalidateBlock(&blk
);
1668 Cache::allocateBlock(Addr addr
, bool is_secure
, PacketList
&writebacks
)
1670 CacheBlk
*blk
= tags
->findVictim(addr
);
1672 // It is valid to return nullptr if there is no victim
1676 if (blk
->isValid()) {
1677 Addr repl_addr
= tags
->regenerateBlkAddr(blk
->tag
, blk
->set
);
1678 MSHR
*repl_mshr
= mshrQueue
.findMatch(repl_addr
, blk
->isSecure());
1680 // must be an outstanding upgrade request
1681 // on a block we're about to replace...
1682 assert(!blk
->isWritable() || blk
->isDirty());
1683 assert(repl_mshr
->needsWritable());
1684 // too hard to replace block with transient state
1685 // allocation failed, block not inserted
1688 DPRINTF(Cache
, "replacement: replacing %#llx (%s) with %#llx "
1689 "(%s): %s\n", repl_addr
, blk
->isSecure() ? "s" : "ns",
1690 addr
, is_secure
? "s" : "ns",
1691 blk
->isDirty() ? "writeback" : "clean");
1693 if (blk
->wasPrefetched()) {
1696 // Will send up Writeback/CleanEvict snoops via isCachedAbove
1697 // when pushing this writeback list into the write buffer.
1698 if (blk
->isDirty() || writebackClean
) {
1699 // Save writeback packet for handling by caller
1700 writebacks
.push_back(writebackBlk(blk
));
1702 writebacks
.push_back(cleanEvictBlk(blk
));
1711 Cache::invalidateBlock(CacheBlk
*blk
)
1713 if (blk
!= tempBlock
)
1714 tags
->invalidate(blk
);
1718 // Note that the reason we return a list of writebacks rather than
1719 // inserting them directly in the write buffer is that this function
1720 // is called by both atomic and timing-mode accesses, and in atomic
1721 // mode we don't mess with the write buffer (we just perform the
1722 // writebacks atomically once the original request is complete).
1724 Cache::handleFill(PacketPtr pkt
, CacheBlk
*blk
, PacketList
&writebacks
,
1727 assert(pkt
->isResponse() || pkt
->cmd
== MemCmd::WriteLineReq
);
1728 Addr addr
= pkt
->getAddr();
1729 bool is_secure
= pkt
->isSecure();
1731 CacheBlk::State old_state
= blk
? blk
->status
: 0;
1734 // When handling a fill, we should have no writes to this line.
1735 assert(addr
== pkt
->getBlockAddr(blkSize
));
1736 assert(!writeBuffer
.findMatch(addr
, is_secure
));
1738 if (blk
== nullptr) {
1739 // better have read new data...
1740 assert(pkt
->hasData());
1742 // only read responses and write-line requests have data;
1743 // note that we don't write the data here for write-line - that
1744 // happens in the subsequent call to satisfyRequest
1745 assert(pkt
->isRead() || pkt
->cmd
== MemCmd::WriteLineReq
);
1747 // need to do a replacement if allocating, otherwise we stick
1748 // with the temporary storage
1749 blk
= allocate
? allocateBlock(addr
, is_secure
, writebacks
) : nullptr;
1751 if (blk
== nullptr) {
1752 // No replaceable block or a mostly exclusive
1753 // cache... just use temporary storage to complete the
1754 // current request and then get rid of it
1755 assert(!tempBlock
->isValid());
1757 tempBlock
->set
= tags
->extractSet(addr
);
1758 tempBlock
->tag
= tags
->extractTag(addr
);
1759 // @todo: set security state as well...
1760 DPRINTF(Cache
, "using temp block for %#llx (%s)\n", addr
,
1761 is_secure
? "s" : "ns");
1763 tags
->insertBlock(pkt
, blk
);
1766 // we should never be overwriting a valid block
1767 assert(!blk
->isValid());
1769 // existing block... probably an upgrade
1770 assert(blk
->tag
== tags
->extractTag(addr
));
1771 // either we're getting new data or the block should already be valid
1772 assert(pkt
->hasData() || blk
->isValid());
1773 // don't clear block status... if block is already dirty we
1774 // don't want to lose that
1778 blk
->status
|= BlkSecure
;
1779 blk
->status
|= BlkValid
| BlkReadable
;
1781 // sanity check for whole-line writes, which should always be
1782 // marked as writable as part of the fill, and then later marked
1783 // dirty as part of satisfyRequest
1784 if (pkt
->cmd
== MemCmd::WriteLineReq
) {
1785 assert(!pkt
->hasSharers());
1788 // here we deal with setting the appropriate state of the line,
1789 // and we start by looking at the hasSharers flag, and ignore the
1790 // cacheResponding flag (normally signalling dirty data) if the
1791 // packet has sharers, thus the line is never allocated as Owned
1792 // (dirty but not writable), and always ends up being either
1793 // Shared, Exclusive or Modified, see Packet::setCacheResponding
1795 if (!pkt
->hasSharers()) {
1796 // we could get a writable line from memory (rather than a
1797 // cache) even in a read-only cache, note that we set this bit
1798 // even for a read-only cache, possibly revisit this decision
1799 blk
->status
|= BlkWritable
;
1801 // check if we got this via cache-to-cache transfer (i.e., from a
1802 // cache that had the block in Modified or Owned state)
1803 if (pkt
->cacheResponding()) {
1804 // we got the block in Modified state, and invalidated the
1806 blk
->status
|= BlkDirty
;
1808 chatty_assert(!isReadOnly
, "Should never see dirty snoop response "
1809 "in read-only cache %s\n", name());
1813 DPRINTF(Cache
, "Block addr %#llx (%s) moving from state %x to %s\n",
1814 addr
, is_secure
? "s" : "ns", old_state
, blk
->print());
1816 // if we got new data, copy it in (checking for a read response
1817 // and a response that has data is the same in the end)
1818 if (pkt
->isRead()) {
1820 assert(pkt
->hasData());
1821 assert(pkt
->getSize() == blkSize
);
1823 std::memcpy(blk
->data
, pkt
->getConstPtr
<uint8_t>(), blkSize
);
1825 // We pay for fillLatency here.
1826 blk
->whenReady
= clockEdge() + fillLatency
* clockPeriod() +
1833 /////////////////////////////////////////////////////
1835 // Snoop path: requests coming in from the memory side
1837 /////////////////////////////////////////////////////
1840 Cache::doTimingSupplyResponse(PacketPtr req_pkt
, const uint8_t *blk_data
,
1841 bool already_copied
, bool pending_inval
)
1844 assert(req_pkt
->isRequest());
1845 assert(req_pkt
->needsResponse());
1847 DPRINTF(Cache
, "%s: for %s\n", __func__
, req_pkt
->print());
1848 // timing-mode snoop responses require a new packet, unless we
1849 // already made a copy...
1850 PacketPtr pkt
= req_pkt
;
1851 if (!already_copied
)
1852 // do not clear flags, and allocate space for data if the
1853 // packet needs it (the only packets that carry data are read
1855 pkt
= new Packet(req_pkt
, false, req_pkt
->isRead());
1857 assert(req_pkt
->req
->isUncacheable() || req_pkt
->isInvalidate() ||
1859 pkt
->makeTimingResponse();
1860 if (pkt
->isRead()) {
1861 pkt
->setDataFromBlock(blk_data
, blkSize
);
1863 if (pkt
->cmd
== MemCmd::ReadResp
&& pending_inval
) {
1864 // Assume we defer a response to a read from a far-away cache
1865 // A, then later defer a ReadExcl from a cache B on the same
1866 // bus as us. We'll assert cacheResponding in both cases, but
1867 // in the latter case cacheResponding will keep the
1868 // invalidation from reaching cache A. This special response
1869 // tells cache A that it gets the block to satisfy its read,
1870 // but must immediately invalidate it.
1871 pkt
->cmd
= MemCmd::ReadRespWithInvalidate
;
1873 // Here we consider forward_time, paying for just forward latency and
1874 // also charging the delay provided by the xbar.
1875 // forward_time is used as send_time in next allocateWriteBuffer().
1876 Tick forward_time
= clockEdge(forwardLatency
) + pkt
->headerDelay
;
1877 // Here we reset the timing of the packet.
1878 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
1879 DPRINTF(CacheVerbose
, "%s: created response: %s tick: %lu\n", __func__
,
1880 pkt
->print(), forward_time
);
1881 memSidePort
->schedTimingSnoopResp(pkt
, forward_time
, true);
1885 Cache::handleSnoop(PacketPtr pkt
, CacheBlk
*blk
, bool is_timing
,
1886 bool is_deferred
, bool pending_inval
)
1888 DPRINTF(CacheVerbose
, "%s: for %s\n", __func__
, pkt
->print());
1889 // deferred snoops can only happen in timing mode
1890 assert(!(is_deferred
&& !is_timing
));
1891 // pending_inval only makes sense on deferred snoops
1892 assert(!(pending_inval
&& !is_deferred
));
1893 assert(pkt
->isRequest());
1895 // the packet may get modified if we or a forwarded snooper
1896 // responds in atomic mode, so remember a few things about the
1897 // original packet up front
1898 bool invalidate
= pkt
->isInvalidate();
1899 bool M5_VAR_USED needs_writable
= pkt
->needsWritable();
1901 // at the moment we could get an uncacheable write which does not
1902 // have the invalidate flag, and we need a suitable way of dealing
1904 panic_if(invalidate
&& pkt
->req
->isUncacheable(),
1905 "%s got an invalidating uncacheable snoop request %s",
1906 name(), pkt
->print());
1908 uint32_t snoop_delay
= 0;
1910 if (forwardSnoops
) {
1911 // first propagate snoop upward to see if anyone above us wants to
1912 // handle it. save & restore packet src since it will get
1913 // rewritten to be relative to cpu-side bus (if any)
1914 bool alreadyResponded
= pkt
->cacheResponding();
1916 // copy the packet so that we can clear any flags before
1917 // forwarding it upwards, we also allocate data (passing
1918 // the pointer along in case of static data), in case
1919 // there is a snoop hit in upper levels
1920 Packet
snoopPkt(pkt
, true, true);
1921 snoopPkt
.setExpressSnoop();
1922 // the snoop packet does not need to wait any additional
1924 snoopPkt
.headerDelay
= snoopPkt
.payloadDelay
= 0;
1925 cpuSidePort
->sendTimingSnoopReq(&snoopPkt
);
1927 // add the header delay (including crossbar and snoop
1928 // delays) of the upward snoop to the snoop delay for this
1930 snoop_delay
+= snoopPkt
.headerDelay
;
1932 if (snoopPkt
.cacheResponding()) {
1933 // cache-to-cache response from some upper cache
1934 assert(!alreadyResponded
);
1935 pkt
->setCacheResponding();
1937 // upstream cache has the block, or has an outstanding
1938 // MSHR, pass the flag on
1939 if (snoopPkt
.hasSharers()) {
1940 pkt
->setHasSharers();
1942 // If this request is a prefetch or clean evict and an upper level
1943 // signals block present, make sure to propagate the block
1944 // presence to the requester.
1945 if (snoopPkt
.isBlockCached()) {
1946 pkt
->setBlockCached();
1949 cpuSidePort
->sendAtomicSnoop(pkt
);
1950 if (!alreadyResponded
&& pkt
->cacheResponding()) {
1951 // cache-to-cache response from some upper cache:
1952 // forward response to original requester
1953 assert(pkt
->isResponse());
1958 if (!blk
|| !blk
->isValid()) {
1959 DPRINTF(CacheVerbose
, "%s: snoop miss for %s\n", __func__
,
1962 // we no longer have the block, and will not respond, but a
1963 // packet was allocated in MSHR::handleSnoop and we have
1965 assert(pkt
->needsResponse());
1967 // we have passed the block to a cache upstream, that
1968 // cache should be responding
1969 assert(pkt
->cacheResponding());
1975 DPRINTF(Cache
, "%s: snoop hit for %s, old state is %s\n", __func__
,
1976 pkt
->print(), blk
->print());
1979 chatty_assert(!(isReadOnly
&& blk
->isDirty()),
1980 "Should never have a dirty block in a read-only cache %s\n",
1983 // We may end up modifying both the block state and the packet (if
1984 // we respond in atomic mode), so just figure out what to do now
1985 // and then do it later. We respond to all snoops that need
1986 // responses provided we have the block in dirty state. The
1987 // invalidation itself is taken care of below.
1988 bool respond
= blk
->isDirty() && pkt
->needsResponse();
1989 bool have_writable
= blk
->isWritable();
1991 // Invalidate any prefetch's from below that would strip write permissions
1992 // MemCmd::HardPFReq is only observed by upstream caches. After missing
1993 // above and in it's own cache, a new MemCmd::ReadReq is created that
1994 // downstream caches observe.
1995 if (pkt
->mustCheckAbove()) {
1996 DPRINTF(Cache
, "Found addr %#llx in upper level cache for snoop %s "
1997 "from lower cache\n", pkt
->getAddr(), pkt
->print());
1998 pkt
->setBlockCached();
2002 if (pkt
->isRead() && !invalidate
) {
2003 // reading without requiring the line in a writable state
2004 assert(!needs_writable
);
2005 pkt
->setHasSharers();
2007 // if the requesting packet is uncacheable, retain the line in
2008 // the current state, otherwhise unset the writable flag,
2009 // which means we go from Modified to Owned (and will respond
2010 // below), remain in Owned (and will respond below), from
2011 // Exclusive to Shared, or remain in Shared
2012 if (!pkt
->req
->isUncacheable())
2013 blk
->status
&= ~BlkWritable
;
2017 // prevent anyone else from responding, cache as well as
2018 // memory, and also prevent any memory from even seeing the
2020 pkt
->setCacheResponding();
2021 if (have_writable
) {
2022 // inform the cache hierarchy that this cache had the line
2023 // in the Modified state so that we avoid unnecessary
2024 // invalidations (see Packet::setResponderHadWritable)
2025 pkt
->setResponderHadWritable();
2027 // in the case of an uncacheable request there is no point
2028 // in setting the responderHadWritable flag, but since the
2029 // recipient does not care there is no harm in doing so
2031 // if the packet has needsWritable set we invalidate our
2032 // copy below and all other copies will be invalidates
2033 // through express snoops, and if needsWritable is not set
2034 // we already called setHasSharers above
2037 // if we are returning a writable and dirty (Modified) line,
2038 // we should be invalidating the line
2039 panic_if(!invalidate
&& !pkt
->hasSharers(),
2040 "%s is passing a Modified line through %s, "
2041 "but keeping the block", name(), pkt
->print());
2044 doTimingSupplyResponse(pkt
, blk
->data
, is_deferred
, pending_inval
);
2046 pkt
->makeAtomicResponse();
2047 // packets such as upgrades do not actually have any data
2050 pkt
->setDataFromBlock(blk
->data
, blkSize
);
2054 if (!respond
&& is_deferred
) {
2055 assert(pkt
->needsResponse());
2057 // if we copied the deferred packet with the intention to
2058 // respond, but are not responding, then a cache above us must
2059 // be, and we can use this as the indication of whether this
2060 // is a packet where we created a copy of the request or not
2061 if (!pkt
->cacheResponding()) {
2068 // Do this last in case it deallocates block data or something
2071 invalidateBlock(blk
);
2074 DPRINTF(Cache
, "new state is %s\n", blk
->print());
2081 Cache::recvTimingSnoopReq(PacketPtr pkt
)
2083 DPRINTF(CacheVerbose
, "%s: for %s\n", __func__
, pkt
->print());
2085 // Snoops shouldn't happen when bypassing caches
2086 assert(!system
->bypassCaches());
2088 // no need to snoop requests that are not in range
2089 if (!inRange(pkt
->getAddr())) {
2093 bool is_secure
= pkt
->isSecure();
2094 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), is_secure
);
2096 Addr blk_addr
= pkt
->getBlockAddr(blkSize
);
2097 MSHR
*mshr
= mshrQueue
.findMatch(blk_addr
, is_secure
);
2099 // Update the latency cost of the snoop so that the crossbar can
2100 // account for it. Do not overwrite what other neighbouring caches
2101 // have already done, rather take the maximum. The update is
2102 // tentative, for cases where we return before an upward snoop
2104 pkt
->snoopDelay
= std::max
<uint32_t>(pkt
->snoopDelay
,
2105 lookupLatency
* clockPeriod());
2107 // Inform request(Prefetch, CleanEvict or Writeback) from below of
2108 // MSHR hit, set setBlockCached.
2109 if (mshr
&& pkt
->mustCheckAbove()) {
2110 DPRINTF(Cache
, "Setting block cached for %s from lower cache on "
2111 "mshr hit\n", pkt
->print());
2112 pkt
->setBlockCached();
2116 // Let the MSHR itself track the snoop and decide whether we want
2117 // to go ahead and do the regular cache snoop
2118 if (mshr
&& mshr
->handleSnoop(pkt
, order
++)) {
2119 DPRINTF(Cache
, "Deferring snoop on in-service MSHR to blk %#llx (%s)."
2120 "mshrs: %s\n", blk_addr
, is_secure
? "s" : "ns",
2123 if (mshr
->getNumTargets() > numTarget
)
2124 warn("allocating bonus target for snoop"); //handle later
2128 //We also need to check the writeback buffers and handle those
2129 WriteQueueEntry
*wb_entry
= writeBuffer
.findMatch(blk_addr
, is_secure
);
2131 DPRINTF(Cache
, "Snoop hit in writeback to addr %#llx (%s)\n",
2132 pkt
->getAddr(), is_secure
? "s" : "ns");
2133 // Expect to see only Writebacks and/or CleanEvicts here, both of
2134 // which should not be generated for uncacheable data.
2135 assert(!wb_entry
->isUncacheable());
2136 // There should only be a single request responsible for generating
2137 // Writebacks/CleanEvicts.
2138 assert(wb_entry
->getNumTargets() == 1);
2139 PacketPtr wb_pkt
= wb_entry
->getTarget()->pkt
;
2140 assert(wb_pkt
->isEviction());
2142 if (pkt
->isEviction()) {
2143 // if the block is found in the write queue, set the BLOCK_CACHED
2144 // flag for Writeback/CleanEvict snoop. On return the snoop will
2145 // propagate the BLOCK_CACHED flag in Writeback packets and prevent
2146 // any CleanEvicts from travelling down the memory hierarchy.
2147 pkt
->setBlockCached();
2148 DPRINTF(Cache
, "%s: Squashing %s from lower cache on writequeue "
2149 "hit\n", __func__
, pkt
->print());
2153 // conceptually writebacks are no different to other blocks in
2154 // this cache, so the behaviour is modelled after handleSnoop,
2155 // the difference being that instead of querying the block
2156 // state to determine if it is dirty and writable, we use the
2157 // command and fields of the writeback packet
2158 bool respond
= wb_pkt
->cmd
== MemCmd::WritebackDirty
&&
2159 pkt
->needsResponse();
2160 bool have_writable
= !wb_pkt
->hasSharers();
2161 bool invalidate
= pkt
->isInvalidate();
2163 if (!pkt
->req
->isUncacheable() && pkt
->isRead() && !invalidate
) {
2164 assert(!pkt
->needsWritable());
2165 pkt
->setHasSharers();
2166 wb_pkt
->setHasSharers();
2170 pkt
->setCacheResponding();
2172 if (have_writable
) {
2173 pkt
->setResponderHadWritable();
2176 doTimingSupplyResponse(pkt
, wb_pkt
->getConstPtr
<uint8_t>(),
2181 // Invalidation trumps our writeback... discard here
2182 // Note: markInService will remove entry from writeback buffer.
2183 markInService(wb_entry
);
2188 // If this was a shared writeback, there may still be
2189 // other shared copies above that require invalidation.
2190 // We could be more selective and return here if the
2191 // request is non-exclusive or if the writeback is
2193 uint32_t snoop_delay
= handleSnoop(pkt
, blk
, true, false, false);
2195 // Override what we did when we first saw the snoop, as we now
2196 // also have the cost of the upwards snoops to account for
2197 pkt
->snoopDelay
= std::max
<uint32_t>(pkt
->snoopDelay
, snoop_delay
+
2198 lookupLatency
* clockPeriod());
2202 Cache::CpuSidePort::recvTimingSnoopResp(PacketPtr pkt
)
2204 // Express snoop responses from master to slave, e.g., from L1 to L2
2205 cache
->recvTimingSnoopResp(pkt
);
2210 Cache::recvAtomicSnoop(PacketPtr pkt
)
2212 // Snoops shouldn't happen when bypassing caches
2213 assert(!system
->bypassCaches());
2215 // no need to snoop requests that are not in range.
2216 if (!inRange(pkt
->getAddr())) {
2220 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), pkt
->isSecure());
2221 uint32_t snoop_delay
= handleSnoop(pkt
, blk
, false, false, false);
2222 return snoop_delay
+ lookupLatency
* clockPeriod();
2227 Cache::getNextQueueEntry()
2229 // Check both MSHR queue and write buffer for potential requests,
2230 // note that null does not mean there is no request, it could
2231 // simply be that it is not ready
2232 MSHR
*miss_mshr
= mshrQueue
.getNext();
2233 WriteQueueEntry
*wq_entry
= writeBuffer
.getNext();
2235 // If we got a write buffer request ready, first priority is a
2236 // full write buffer, otherwise we favour the miss requests
2237 if (wq_entry
&& (writeBuffer
.isFull() || !miss_mshr
)) {
2238 // need to search MSHR queue for conflicting earlier miss.
2239 MSHR
*conflict_mshr
=
2240 mshrQueue
.findPending(wq_entry
->blkAddr
,
2241 wq_entry
->isSecure
);
2243 if (conflict_mshr
&& conflict_mshr
->order
< wq_entry
->order
) {
2244 // Service misses in order until conflict is cleared.
2245 return conflict_mshr
;
2247 // @todo Note that we ignore the ready time of the conflict here
2250 // No conflicts; issue write
2252 } else if (miss_mshr
) {
2253 // need to check for conflicting earlier writeback
2254 WriteQueueEntry
*conflict_mshr
=
2255 writeBuffer
.findPending(miss_mshr
->blkAddr
,
2256 miss_mshr
->isSecure
);
2257 if (conflict_mshr
) {
2258 // not sure why we don't check order here... it was in the
2259 // original code but commented out.
2261 // The only way this happens is if we are
2262 // doing a write and we didn't have permissions
2263 // then subsequently saw a writeback (owned got evicted)
2264 // We need to make sure to perform the writeback first
2265 // To preserve the dirty data, then we can issue the write
2267 // should we return wq_entry here instead? I.e. do we
2268 // have to flush writes in order? I don't think so... not
2269 // for Alpha anyway. Maybe for x86?
2270 return conflict_mshr
;
2272 // @todo Note that we ignore the ready time of the conflict here
2275 // No conflicts; issue read
2279 // fall through... no pending requests. Try a prefetch.
2280 assert(!miss_mshr
&& !wq_entry
);
2281 if (prefetcher
&& mshrQueue
.canPrefetch()) {
2282 // If we have a miss queue slot, we can try a prefetch
2283 PacketPtr pkt
= prefetcher
->getPacket();
2285 Addr pf_addr
= pkt
->getBlockAddr(blkSize
);
2286 if (!tags
->findBlock(pf_addr
, pkt
->isSecure()) &&
2287 !mshrQueue
.findMatch(pf_addr
, pkt
->isSecure()) &&
2288 !writeBuffer
.findMatch(pf_addr
, pkt
->isSecure())) {
2289 // Update statistic on number of prefetches issued
2290 // (hwpf_mshr_misses)
2291 assert(pkt
->req
->masterId() < system
->maxMasters());
2292 mshr_misses
[pkt
->cmdToIndex()][pkt
->req
->masterId()]++;
2294 // allocate an MSHR and return it, note
2295 // that we send the packet straight away, so do not
2296 // schedule the send
2297 return allocateMissBuffer(pkt
, curTick(), false);
2299 // free the request and packet
2310 Cache::isCachedAbove(PacketPtr pkt
, bool is_timing
) const
2314 // Mirroring the flow of HardPFReqs, the cache sends CleanEvict and
2315 // Writeback snoops into upper level caches to check for copies of the
2316 // same block. Using the BLOCK_CACHED flag with the Writeback/CleanEvict
2317 // packet, the cache can inform the crossbar below of presence or absence
2320 Packet
snoop_pkt(pkt
, true, false);
2321 snoop_pkt
.setExpressSnoop();
2322 // Assert that packet is either Writeback or CleanEvict and not a
2323 // prefetch request because prefetch requests need an MSHR and may
2324 // generate a snoop response.
2325 assert(pkt
->isEviction());
2326 snoop_pkt
.senderState
= nullptr;
2327 cpuSidePort
->sendTimingSnoopReq(&snoop_pkt
);
2328 // Writeback/CleanEvict snoops do not generate a snoop response.
2329 assert(!(snoop_pkt
.cacheResponding()));
2330 return snoop_pkt
.isBlockCached();
2332 cpuSidePort
->sendAtomicSnoop(pkt
);
2333 return pkt
->isBlockCached();
2338 Cache::nextQueueReadyTime() const
2340 Tick nextReady
= std::min(mshrQueue
.nextReadyTime(),
2341 writeBuffer
.nextReadyTime());
2343 // Don't signal prefetch ready time if no MSHRs available
2344 // Will signal once enoguh MSHRs are deallocated
2345 if (prefetcher
&& mshrQueue
.canPrefetch()) {
2346 nextReady
= std::min(nextReady
,
2347 prefetcher
->nextPrefetchReadyTime());
2354 Cache::sendMSHRQueuePacket(MSHR
* mshr
)
2358 // use request from 1st target
2359 PacketPtr tgt_pkt
= mshr
->getTarget()->pkt
;
2361 DPRINTF(Cache
, "%s: MSHR %s\n", __func__
, tgt_pkt
->print());
2363 CacheBlk
*blk
= tags
->findBlock(mshr
->blkAddr
, mshr
->isSecure
);
2365 if (tgt_pkt
->cmd
== MemCmd::HardPFReq
&& forwardSnoops
) {
2366 // we should never have hardware prefetches to allocated
2368 assert(blk
== nullptr);
2370 // We need to check the caches above us to verify that
2371 // they don't have a copy of this block in the dirty state
2372 // at the moment. Without this check we could get a stale
2373 // copy from memory that might get used in place of the
2375 Packet
snoop_pkt(tgt_pkt
, true, false);
2376 snoop_pkt
.setExpressSnoop();
2377 // We are sending this packet upwards, but if it hits we will
2378 // get a snoop response that we end up treating just like a
2379 // normal response, hence it needs the MSHR as its sender
2381 snoop_pkt
.senderState
= mshr
;
2382 cpuSidePort
->sendTimingSnoopReq(&snoop_pkt
);
2384 // Check to see if the prefetch was squashed by an upper cache (to
2385 // prevent us from grabbing the line) or if a Check to see if a
2386 // writeback arrived between the time the prefetch was placed in
2387 // the MSHRs and when it was selected to be sent or if the
2388 // prefetch was squashed by an upper cache.
2390 // It is important to check cacheResponding before
2391 // prefetchSquashed. If another cache has committed to
2392 // responding, it will be sending a dirty response which will
2393 // arrive at the MSHR allocated for this request. Checking the
2394 // prefetchSquash first may result in the MSHR being
2395 // prematurely deallocated.
2396 if (snoop_pkt
.cacheResponding()) {
2397 auto M5_VAR_USED r
= outstandingSnoop
.insert(snoop_pkt
.req
);
2400 // if we are getting a snoop response with no sharers it
2401 // will be allocated as Modified
2402 bool pending_modified_resp
= !snoop_pkt
.hasSharers();
2403 markInService(mshr
, pending_modified_resp
);
2405 DPRINTF(Cache
, "Upward snoop of prefetch for addr"
2407 tgt_pkt
->getAddr(), tgt_pkt
->isSecure()? "s": "ns");
2411 if (snoop_pkt
.isBlockCached()) {
2412 DPRINTF(Cache
, "Block present, prefetch squashed by cache. "
2413 "Deallocating mshr target %#x.\n",
2416 // Deallocate the mshr target
2417 if (mshrQueue
.forceDeallocateTarget(mshr
)) {
2418 // Clear block if this deallocation resulted freed an
2419 // mshr when all had previously been utilized
2420 clearBlocked(Blocked_NoMSHRs
);
2423 // given that no response is expected, delete Request and Packet
2424 delete tgt_pkt
->req
;
2431 // either a prefetch that is not present upstream, or a normal
2432 // MSHR request, proceed to get the packet to send downstream
2433 PacketPtr pkt
= createMissPacket(tgt_pkt
, blk
, mshr
->needsWritable());
2435 mshr
->isForward
= (pkt
== nullptr);
2437 if (mshr
->isForward
) {
2438 // not a cache block request, but a response is expected
2439 // make copy of current packet to forward, keep current
2440 // copy for response handling
2441 pkt
= new Packet(tgt_pkt
, false, true);
2442 assert(!pkt
->isWrite());
2445 // play it safe and append (rather than set) the sender state,
2446 // as forwarded packets may already have existing state
2447 pkt
->pushSenderState(mshr
);
2449 if (!memSidePort
->sendTimingReq(pkt
)) {
2450 // we are awaiting a retry, but we
2451 // delete the packet and will be creating a new packet
2452 // when we get the opportunity
2455 // note that we have now masked any requestBus and
2456 // schedSendEvent (we will wait for a retry before
2457 // doing anything), and this is so even if we do not
2458 // care about this packet and might override it before
2462 // As part of the call to sendTimingReq the packet is
2463 // forwarded to all neighbouring caches (and any caches
2464 // above them) as a snoop. Thus at this point we know if
2465 // any of the neighbouring caches are responding, and if
2466 // so, we know it is dirty, and we can determine if it is
2467 // being passed as Modified, making our MSHR the ordering
2469 bool pending_modified_resp
= !pkt
->hasSharers() &&
2470 pkt
->cacheResponding();
2471 markInService(mshr
, pending_modified_resp
);
2477 Cache::sendWriteQueuePacket(WriteQueueEntry
* wq_entry
)
2481 // always a single target for write queue entries
2482 PacketPtr tgt_pkt
= wq_entry
->getTarget()->pkt
;
2484 DPRINTF(Cache
, "%s: write %s\n", __func__
, tgt_pkt
->print());
2486 // forward as is, both for evictions and uncacheable writes
2487 if (!memSidePort
->sendTimingReq(tgt_pkt
)) {
2488 // note that we have now masked any requestBus and
2489 // schedSendEvent (we will wait for a retry before
2490 // doing anything), and this is so even if we do not
2491 // care about this packet and might override it before
2495 markInService(wq_entry
);
2501 Cache::serialize(CheckpointOut
&cp
) const
2503 bool dirty(isDirty());
2506 warn("*** The cache still contains dirty data. ***\n");
2507 warn(" Make sure to drain the system using the correct flags.\n");
2508 warn(" This checkpoint will not restore correctly and dirty data "
2509 " in the cache will be lost!\n");
2512 // Since we don't checkpoint the data in the cache, any dirty data
2513 // will be lost when restoring from a checkpoint of a system that
2514 // wasn't drained properly. Flag the checkpoint as invalid if the
2515 // cache contains dirty data.
2516 bool bad_checkpoint(dirty
);
2517 SERIALIZE_SCALAR(bad_checkpoint
);
2521 Cache::unserialize(CheckpointIn
&cp
)
2523 bool bad_checkpoint
;
2524 UNSERIALIZE_SCALAR(bad_checkpoint
);
2525 if (bad_checkpoint
) {
2526 fatal("Restoring from checkpoints with dirty caches is not supported "
2527 "in the classic memory system. Please remove any caches or "
2528 " drain them properly before taking checkpoints.\n");
2539 Cache::CpuSidePort::getAddrRanges() const
2541 return cache
->getAddrRanges();
2545 Cache::CpuSidePort::recvTimingReq(PacketPtr pkt
)
2547 assert(!cache
->system
->bypassCaches());
2549 bool success
= false;
2551 // always let express snoop packets through if even if blocked
2552 if (pkt
->isExpressSnoop()) {
2553 // do not change the current retry state
2554 bool M5_VAR_USED bypass_success
= cache
->recvTimingReq(pkt
);
2555 assert(bypass_success
);
2557 } else if (blocked
|| mustSendRetry
) {
2558 // either already committed to send a retry, or blocked
2561 // pass it on to the cache, and let the cache decide if we
2562 // have to retry or not
2563 success
= cache
->recvTimingReq(pkt
);
2566 // remember if we have to retry
2567 mustSendRetry
= !success
;
2572 Cache::CpuSidePort::recvAtomic(PacketPtr pkt
)
2574 return cache
->recvAtomic(pkt
);
2578 Cache::CpuSidePort::recvFunctional(PacketPtr pkt
)
2580 // functional request
2581 cache
->functionalAccess(pkt
, true);
2585 CpuSidePort::CpuSidePort(const std::string
&_name
, Cache
*_cache
,
2586 const std::string
&_label
)
2587 : BaseCache::CacheSlavePort(_name
, _cache
, _label
), cache(_cache
)
2592 CacheParams::create()
2596 return new Cache(this);
2605 Cache::MemSidePort::recvTimingResp(PacketPtr pkt
)
2607 cache
->recvTimingResp(pkt
);
2611 // Express snooping requests to memside port
2613 Cache::MemSidePort::recvTimingSnoopReq(PacketPtr pkt
)
2615 // handle snooping requests
2616 cache
->recvTimingSnoopReq(pkt
);
2620 Cache::MemSidePort::recvAtomicSnoop(PacketPtr pkt
)
2622 return cache
->recvAtomicSnoop(pkt
);
2626 Cache::MemSidePort::recvFunctionalSnoop(PacketPtr pkt
)
2628 // functional snoop (note that in contrast to atomic we don't have
2629 // a specific functionalSnoop method, as they have the same
2630 // behaviour regardless)
2631 cache
->functionalAccess(pkt
, false);
2635 Cache::CacheReqPacketQueue::sendDeferredPacket()
2638 assert(!waitingOnRetry
);
2640 // there should never be any deferred request packets in the
2641 // queue, instead we resly on the cache to provide the packets
2642 // from the MSHR queue or write queue
2643 assert(deferredPacketReadyTime() == MaxTick
);
2645 // check for request packets (requests & writebacks)
2646 QueueEntry
* entry
= cache
.getNextQueueEntry();
2649 // can happen if e.g. we attempt a writeback and fail, but
2650 // before the retry, the writeback is eliminated because
2651 // we snoop another cache's ReadEx.
2653 // let our snoop responses go first if there are responses to
2654 // the same addresses
2655 if (checkConflictingSnoop(entry
->blkAddr
)) {
2658 waitingOnRetry
= entry
->sendPacket(cache
);
2661 // if we succeeded and are not waiting for a retry, schedule the
2662 // next send considering when the next queue is ready, note that
2663 // snoop responses have their own packet queue and thus schedule
2665 if (!waitingOnRetry
) {
2666 schedSendEvent(cache
.nextQueueReadyTime());
2671 MemSidePort::MemSidePort(const std::string
&_name
, Cache
*_cache
,
2672 const std::string
&_label
)
2673 : BaseCache::CacheMasterPort(_name
, _cache
, _reqQueue
, _snoopRespQueue
),
2674 _reqQueue(*_cache
, *this, _snoopRespQueue
, _label
),
2675 _snoopRespQueue(*_cache
, *this, _label
), cache(_cache
)