2 * Copyright (c) 2010-2015 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/misc.hh"
57 #include "base/types.hh"
58 #include "debug/Cache.hh"
59 #include "debug/CachePort.hh"
60 #include "debug/CacheTags.hh"
61 #include "mem/cache/blk.hh"
62 #include "mem/cache/mshr.hh"
63 #include "mem/cache/prefetch/base.hh"
64 #include "sim/sim_exit.hh"
66 Cache::Cache(const CacheParams
*p
)
67 : BaseCache(p
, p
->system
->cacheLineSize()),
69 prefetcher(p
->prefetcher
),
71 prefetchOnAccess(p
->prefetch_on_access
)
73 tempBlock
= new CacheBlk();
74 tempBlock
->data
= new uint8_t[blkSize
];
76 cpuSidePort
= new CpuSidePort(p
->name
+ ".cpu_side", this,
78 memSidePort
= new MemSidePort(p
->name
+ ".mem_side", this,
83 prefetcher
->setCache(this);
88 delete [] tempBlock
->data
;
98 BaseCache::regStats();
102 Cache::cmpAndSwap(CacheBlk
*blk
, PacketPtr pkt
)
104 assert(pkt
->isRequest());
106 uint64_t overwrite_val
;
108 uint64_t condition_val64
;
109 uint32_t condition_val32
;
111 int offset
= tags
->extractBlkOffset(pkt
->getAddr());
112 uint8_t *blk_data
= blk
->data
+ offset
;
114 assert(sizeof(uint64_t) >= pkt
->getSize());
116 overwrite_mem
= true;
117 // keep a copy of our possible write value, and copy what is at the
118 // memory address into the packet
119 pkt
->writeData((uint8_t *)&overwrite_val
);
120 pkt
->setData(blk_data
);
122 if (pkt
->req
->isCondSwap()) {
123 if (pkt
->getSize() == sizeof(uint64_t)) {
124 condition_val64
= pkt
->req
->getExtraData();
125 overwrite_mem
= !std::memcmp(&condition_val64
, blk_data
,
127 } else if (pkt
->getSize() == sizeof(uint32_t)) {
128 condition_val32
= (uint32_t)pkt
->req
->getExtraData();
129 overwrite_mem
= !std::memcmp(&condition_val32
, blk_data
,
132 panic("Invalid size for conditional read/write\n");
136 std::memcpy(blk_data
, &overwrite_val
, pkt
->getSize());
137 blk
->status
|= BlkDirty
;
143 Cache::satisfyCpuSideRequest(PacketPtr pkt
, CacheBlk
*blk
,
144 bool deferred_response
, bool pending_downgrade
)
146 assert(pkt
->isRequest());
148 assert(blk
&& blk
->isValid());
149 // Occasionally this is not true... if we are a lower-level cache
150 // satisfying a string of Read and ReadEx requests from
151 // upper-level caches, a Read will mark the block as shared but we
152 // can satisfy a following ReadEx anyway since we can rely on the
153 // Read requester(s) to have buffered the ReadEx snoop and to
154 // invalidate their blocks after receiving them.
155 // assert(!pkt->needsExclusive() || blk->isWritable());
156 assert(pkt
->getOffset(blkSize
) + pkt
->getSize() <= blkSize
);
158 // Check RMW operations first since both isRead() and
159 // isWrite() will be true for them
160 if (pkt
->cmd
== MemCmd::SwapReq
) {
161 cmpAndSwap(blk
, pkt
);
162 } else if (pkt
->isWrite()) {
163 assert(blk
->isWritable());
164 // Write or WriteLine at the first cache with block in Exclusive
165 if (blk
->checkWrite(pkt
)) {
166 pkt
->writeDataToBlock(blk
->data
, blkSize
);
168 // Always mark the line as dirty even if we are a failed
169 // StoreCond so we supply data to any snoops that have
170 // appended themselves to this cache before knowing the store
172 blk
->status
|= BlkDirty
;
173 DPRINTF(Cache
, "%s for %s addr %#llx size %d (write)\n", __func__
,
174 pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize());
175 } else if (pkt
->isRead()) {
177 blk
->trackLoadLocked(pkt
);
179 pkt
->setDataFromBlock(blk
->data
, blkSize
);
180 // determine if this read is from a (coherent) cache, or not
181 // by looking at the command type; we could potentially add a
182 // packet attribute such as 'FromCache' to make this check a
184 if (pkt
->cmd
== MemCmd::ReadExReq
||
185 pkt
->cmd
== MemCmd::ReadSharedReq
||
186 pkt
->cmd
== MemCmd::ReadCleanReq
||
187 pkt
->cmd
== MemCmd::SCUpgradeFailReq
) {
188 assert(pkt
->getSize() == blkSize
);
189 // special handling for coherent block requests from
190 // upper-level caches
191 if (pkt
->needsExclusive()) {
193 assert(pkt
->cmd
== MemCmd::ReadExReq
||
194 pkt
->cmd
== MemCmd::SCUpgradeFailReq
);
196 // if we have a dirty copy, make sure the recipient
197 // keeps it marked dirty
198 if (blk
->isDirty()) {
199 pkt
->assertMemInhibit();
201 // on ReadExReq we give up our copy unconditionally
202 if (blk
!= tempBlock
)
203 tags
->invalidate(blk
);
205 } else if (blk
->isWritable() && !pending_downgrade
&&
206 !pkt
->sharedAsserted() &&
207 pkt
->cmd
!= MemCmd::ReadCleanReq
) {
208 // we can give the requester an exclusive copy (by not
209 // asserting shared line) on a read request if:
210 // - we have an exclusive copy at this level (& below)
211 // - we don't have a pending snoop from below
212 // signaling another read request
213 // - no other cache above has a copy (otherwise it
214 // would have asseretd shared line on request)
215 // - we are not satisfying an instruction fetch (this
216 // prevents dirty data in the i-cache)
218 if (blk
->isDirty()) {
219 // special considerations if we're owner:
220 if (!deferred_response
) {
221 // if we are responding immediately and can
222 // signal that we're transferring ownership
223 // along with exclusivity, do so
224 pkt
->assertMemInhibit();
225 blk
->status
&= ~BlkDirty
;
227 // if we're responding after our own miss,
228 // there's a window where the recipient didn't
229 // know it was getting ownership and may not
230 // have responded to snoops correctly, so we
231 // can't pass off ownership *or* exclusivity
236 // otherwise only respond with a shared copy
241 // Upgrade or Invalidate, since we have it Exclusively (E or
242 // M), we ack then invalidate.
243 assert(pkt
->isUpgrade() || pkt
->isInvalidate());
244 assert(blk
!= tempBlock
);
245 tags
->invalidate(blk
);
247 DPRINTF(Cache
, "%s for %s addr %#llx size %d (invalidation)\n",
248 __func__
, pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize());
253 /////////////////////////////////////////////////////
255 // MSHR helper functions
257 /////////////////////////////////////////////////////
261 Cache::markInService(MSHR
*mshr
, bool pending_dirty_resp
)
263 markInServiceInternal(mshr
, pending_dirty_resp
);
266 /////////////////////////////////////////////////////
268 // Access path: requests coming in from the CPU side
270 /////////////////////////////////////////////////////
273 Cache::access(PacketPtr pkt
, CacheBlk
*&blk
, Cycles
&lat
,
274 PacketList
&writebacks
)
277 assert(pkt
->isRequest());
279 chatty_assert(!(isReadOnly
&& pkt
->isWrite()),
280 "Should never see a write in a read-only cache %s\n",
283 DPRINTF(Cache
, "%s for %s addr %#llx size %d\n", __func__
,
284 pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize());
286 if (pkt
->req
->isUncacheable()) {
287 DPRINTF(Cache
, "%s%s addr %#llx uncacheable\n", pkt
->cmdString(),
288 pkt
->req
->isInstFetch() ? " (ifetch)" : "",
291 // flush and invalidate any existing block
292 CacheBlk
*old_blk(tags
->findBlock(pkt
->getAddr(), pkt
->isSecure()));
293 if (old_blk
&& old_blk
->isValid()) {
294 if (old_blk
->isDirty())
295 writebacks
.push_back(writebackBlk(old_blk
));
297 writebacks
.push_back(cleanEvictBlk(old_blk
));
298 tags
->invalidate(old_blk
);
299 old_blk
->invalidate();
303 // lookupLatency is the latency in case the request is uncacheable.
308 ContextID id
= pkt
->req
->hasContextId() ?
309 pkt
->req
->contextId() : InvalidContextID
;
310 // Here lat is the value passed as parameter to accessBlock() function
311 // that can modify its value.
312 blk
= tags
->accessBlock(pkt
->getAddr(), pkt
->isSecure(), lat
, id
);
314 DPRINTF(Cache
, "%s%s addr %#llx size %d (%s) %s\n", pkt
->cmdString(),
315 pkt
->req
->isInstFetch() ? " (ifetch)" : "",
316 pkt
->getAddr(), pkt
->getSize(), pkt
->isSecure() ? "s" : "ns",
317 blk
? "hit " + blk
->print() : "miss");
320 if (pkt
->evictingBlock()) {
321 // We check for presence of block in above caches before issuing
322 // Writeback or CleanEvict to write buffer. Therefore the only
323 // possible cases can be of a CleanEvict packet coming from above
324 // encountering a Writeback generated in this cache peer cache and
325 // waiting in the write buffer. Cases of upper level peer caches
326 // generating CleanEvict and Writeback or simply CleanEvict and
327 // CleanEvict almost simultaneously will be caught by snoops sent out
329 std::vector
<MSHR
*> outgoing
;
330 if (writeBuffer
.findMatches(pkt
->getAddr(), pkt
->isSecure(),
332 assert(outgoing
.size() == 1);
333 PacketPtr wbPkt
= outgoing
[0]->getTarget()->pkt
;
334 assert(pkt
->cmd
== MemCmd::CleanEvict
&&
335 wbPkt
->cmd
== MemCmd::Writeback
);
336 // As the CleanEvict is coming from above, it would have snooped
337 // into other peer caches of the same level while traversing the
338 // crossbar. If a copy of the block had been found, the CleanEvict
339 // would have been deleted in the crossbar. Now that the
340 // CleanEvict is here we can be sure none of the other upper level
341 // caches connected to this cache have the block, so we can clear
342 // the BLOCK_CACHED flag in the Writeback if set and discard the
343 // CleanEvict by returning true.
344 wbPkt
->clearBlockCached();
349 // Writeback handling is special case. We can write the block into
350 // the cache without having a writeable copy (or any copy at all).
351 if (pkt
->cmd
== MemCmd::Writeback
) {
352 assert(blkSize
== pkt
->getSize());
354 // need to do a replacement
355 blk
= allocateBlock(pkt
->getAddr(), pkt
->isSecure(), writebacks
);
357 // no replaceable block available: give up, fwd to next level.
361 tags
->insertBlock(pkt
, blk
);
363 blk
->status
= (BlkValid
| BlkReadable
);
364 if (pkt
->isSecure()) {
365 blk
->status
|= BlkSecure
;
368 blk
->status
|= BlkDirty
;
369 // if shared is not asserted we got the writeback in modified
370 // state, if it is asserted we are in the owned state
371 if (!pkt
->sharedAsserted()) {
372 blk
->status
|= BlkWritable
;
374 // nothing else to do; writeback doesn't expect response
375 assert(!pkt
->needsResponse());
376 std::memcpy(blk
->data
, pkt
->getConstPtr
<uint8_t>(), blkSize
);
377 DPRINTF(Cache
, "%s new state is %s\n", __func__
, blk
->print());
380 } else if (pkt
->cmd
== MemCmd::CleanEvict
) {
382 // Found the block in the tags, need to stop CleanEvict from
383 // propagating further down the hierarchy. Returning true will
384 // treat the CleanEvict like a satisfied write request and delete
388 // We didn't find the block here, propagate the CleanEvict further
389 // down the memory hierarchy. Returning false will treat the CleanEvict
390 // like a Writeback which could not find a replaceable block so has to
393 } else if ((blk
!= NULL
) &&
394 (pkt
->needsExclusive() ? blk
->isWritable()
395 : blk
->isReadable())) {
396 // OK to satisfy access
398 satisfyCpuSideRequest(pkt
, blk
);
402 // Can't satisfy access normally... either no block (blk == NULL)
403 // or have block but need exclusive & only have shared.
407 if (blk
== NULL
&& pkt
->isLLSC() && pkt
->isWrite()) {
408 // complete miss on store conditional... just give up now
409 pkt
->req
->setExtraData(0);
417 class ForwardResponseRecord
: public Packet::SenderState
421 ForwardResponseRecord() {}
425 Cache::doWritebacks(PacketList
& writebacks
, Tick forward_time
)
427 while (!writebacks
.empty()) {
428 PacketPtr wbPkt
= writebacks
.front();
429 // We use forwardLatency here because we are copying writebacks to
430 // write buffer. Call isCachedAbove for both Writebacks and
431 // CleanEvicts. If isCachedAbove returns true we set BLOCK_CACHED flag
432 // in Writebacks and discard CleanEvicts.
433 if (isCachedAbove(wbPkt
)) {
434 if (wbPkt
->cmd
== MemCmd::CleanEvict
) {
435 // Delete CleanEvict because cached copies exist above. The
436 // packet destructor will delete the request object because
437 // this is a non-snoop request packet which does not require a
441 // Set BLOCK_CACHED flag in Writeback and send below, so that
442 // the Writeback does not reset the bit corresponding to this
443 // address in the snoop filter below.
444 wbPkt
->setBlockCached();
445 allocateWriteBuffer(wbPkt
, forward_time
);
448 // If the block is not cached above, send packet below. Both
449 // CleanEvict and Writeback with BLOCK_CACHED flag cleared will
450 // reset the bit corresponding to this address in the snoop filter
452 allocateWriteBuffer(wbPkt
, forward_time
);
454 writebacks
.pop_front();
460 Cache::recvTimingSnoopResp(PacketPtr pkt
)
462 DPRINTF(Cache
, "%s for %s addr %#llx size %d\n", __func__
,
463 pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize());
465 assert(pkt
->isResponse());
467 // must be cache-to-cache response from upper to lower level
468 ForwardResponseRecord
*rec
=
469 dynamic_cast<ForwardResponseRecord
*>(pkt
->senderState
);
470 assert(!system
->bypassCaches());
473 // @todo What guarantee do we have that this HardPFResp is
474 // actually for this cache, and not a cache closer to the
476 assert(pkt
->cmd
== MemCmd::HardPFResp
);
477 // Check if it's a prefetch response and handle it. We shouldn't
478 // get any other kinds of responses without FRRs.
479 DPRINTF(Cache
, "Got prefetch response from above for addr %#llx (%s)\n",
480 pkt
->getAddr(), pkt
->isSecure() ? "s" : "ns");
485 pkt
->popSenderState();
487 // forwardLatency is set here because there is a response from an
488 // upper level cache.
489 // To pay the delay that occurs if the packet comes from the bus,
490 // we charge also headerDelay.
491 Tick snoop_resp_time
= clockEdge(forwardLatency
) + pkt
->headerDelay
;
492 // Reset the timing of the packet.
493 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
494 memSidePort
->schedTimingSnoopResp(pkt
, snoop_resp_time
);
498 Cache::promoteWholeLineWrites(PacketPtr pkt
)
500 // Cache line clearing instructions
501 if (doFastWrites
&& (pkt
->cmd
== MemCmd::WriteReq
) &&
502 (pkt
->getSize() == blkSize
) && (pkt
->getOffset(blkSize
) == 0)) {
503 pkt
->cmd
= MemCmd::WriteLineReq
;
504 DPRINTF(Cache
, "packet promoted from Write to WriteLineReq\n");
509 Cache::recvTimingReq(PacketPtr pkt
)
511 DPRINTF(CacheTags
, "%s tags: %s\n", __func__
, tags
->print());
512 //@todo Add back in MemDebug Calls
513 // MemDebug::cacheAccess(pkt);
516 /// @todo temporary hack to deal with memory corruption issue until
517 /// 4-phase transactions are complete
518 for (int x
= 0; x
< pendingDelete
.size(); x
++)
519 delete pendingDelete
[x
];
520 pendingDelete
.clear();
522 assert(pkt
->isRequest());
524 // Just forward the packet if caches are disabled.
525 if (system
->bypassCaches()) {
526 // @todo This should really enqueue the packet rather
527 bool M5_VAR_USED success
= memSidePort
->sendTimingReq(pkt
);
532 promoteWholeLineWrites(pkt
);
534 if (pkt
->memInhibitAsserted()) {
535 // a cache above us (but not where the packet came from) is
536 // responding to the request
537 DPRINTF(Cache
, "mem inhibited on addr %#llx (%s): not responding\n",
538 pkt
->getAddr(), pkt
->isSecure() ? "s" : "ns");
540 // if the packet needs exclusive, and the cache that has
541 // promised to respond (setting the inhibit flag) is not
542 // providing exclusive (it is in O vs M state), we know that
543 // there may be other shared copies in the system; go out and
544 // invalidate them all
545 if (pkt
->needsExclusive() && !pkt
->isSupplyExclusive()) {
546 // create a downstream express snoop with cleared packet
547 // flags, there is no need to allocate any data as the
548 // packet is merely used to co-ordinate state transitions
549 Packet
*snoop_pkt
= new Packet(pkt
, true, false);
551 // also reset the bus time that the original packet has
553 snoop_pkt
->headerDelay
= snoop_pkt
->payloadDelay
= 0;
555 // make this an instantaneous express snoop, and let the
556 // other caches in the system know that the packet is
557 // inhibited, because we have found the authorative copy
558 // (O) that will supply the right data
559 snoop_pkt
->setExpressSnoop();
560 snoop_pkt
->assertMemInhibit();
562 // this express snoop travels towards the memory, and at
563 // every crossbar it is snooped upwards thus reaching
564 // every cache in the system
565 bool M5_VAR_USED success
= memSidePort
->sendTimingReq(snoop_pkt
);
566 // express snoops always succeed
569 // main memory will delete the packet
572 /// @todo nominally we should just delete the packet here,
573 /// however, until 4-phase stuff we can't because sending
574 /// cache is still relying on it.
575 pendingDelete
.push_back(pkt
);
577 // no need to take any action in this particular cache as the
578 // caches along the path to memory are allowed to keep lines
579 // in a shared state, and a cache above us already committed
584 // anything that is merely forwarded pays for the forward latency and
585 // the delay provided by the crossbar
586 Tick forward_time
= clockEdge(forwardLatency
) + pkt
->headerDelay
;
588 // We use lookupLatency here because it is used to specify the latency
590 Cycles lat
= lookupLatency
;
591 CacheBlk
*blk
= NULL
;
592 bool satisfied
= false;
594 PacketList writebacks
;
595 // Note that lat is passed by reference here. The function
596 // access() calls accessBlock() which can modify lat value.
597 satisfied
= access(pkt
, blk
, lat
, writebacks
);
599 // copy writebacks to write buffer here to ensure they logically
600 // proceed anything happening below
601 doWritebacks(writebacks
, forward_time
);
604 // Here we charge the headerDelay that takes into account the latencies
605 // of the bus, if the packet comes from it.
606 // The latency charged it is just lat that is the value of lookupLatency
607 // modified by access() function, or if not just lookupLatency.
608 // In case of a hit we are neglecting response latency.
609 // In case of a miss we are neglecting forward latency.
610 Tick request_time
= clockEdge(lat
) + pkt
->headerDelay
;
611 // Here we reset the timing of the packet.
612 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
614 // track time of availability of next prefetch, if any
615 Tick next_pf_time
= MaxTick
;
617 bool needsResponse
= pkt
->needsResponse();
620 // should never be satisfying an uncacheable access as we
621 // flush and invalidate any existing block as part of the
623 assert(!pkt
->req
->isUncacheable());
625 // hit (for all other request types)
627 if (prefetcher
&& (prefetchOnAccess
|| (blk
&& blk
->wasPrefetched()))) {
629 blk
->status
&= ~BlkHWPrefetched
;
631 // Don't notify on SWPrefetch
632 if (!pkt
->cmd
.isSWPrefetch())
633 next_pf_time
= prefetcher
->notify(pkt
);
637 pkt
->makeTimingResponse();
638 // @todo: Make someone pay for this
639 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
641 // In this case we are considering request_time that takes
642 // into account the delay of the xbar, if any, and just
643 // lat, neglecting responseLatency, modelling hit latency
644 // just as lookupLatency or or the value of lat overriden
645 // by access(), that calls accessBlock() function.
646 cpuSidePort
->schedTimingResp(pkt
, request_time
);
648 /// @todo nominally we should just delete the packet here,
649 /// however, until 4-phase stuff we can't because sending cache is
650 /// still relying on it. If the block is found in access(),
651 /// CleanEvict and Writeback messages will be deleted here as
653 pendingDelete
.push_back(pkt
);
658 Addr blk_addr
= blockAlign(pkt
->getAddr());
660 // ignore any existing MSHR if we are dealing with an
661 // uncacheable request
662 MSHR
*mshr
= pkt
->req
->isUncacheable() ? nullptr :
663 mshrQueue
.findMatch(blk_addr
, pkt
->isSecure());
665 // Software prefetch handling:
666 // To keep the core from waiting on data it won't look at
667 // anyway, send back a response with dummy data. Miss handling
668 // will continue asynchronously. Unfortunately, the core will
669 // insist upon freeing original Packet/Request, so we have to
670 // create a new pair with a different lifecycle. Note that this
671 // processing happens before any MSHR munging on the behalf of
672 // this request because this new Request will be the one stored
673 // into the MSHRs, not the original.
674 if (pkt
->cmd
.isSWPrefetch()) {
675 assert(needsResponse
);
676 assert(pkt
->req
->hasPaddr());
677 assert(!pkt
->req
->isUncacheable());
679 // There's no reason to add a prefetch as an additional target
680 // to an existing MSHR. If an outstanding request is already
681 // in progress, there is nothing for the prefetch to do.
682 // If this is the case, we don't even create a request at all.
683 PacketPtr pf
= nullptr;
686 // copy the request and create a new SoftPFReq packet
687 RequestPtr req
= new Request(pkt
->req
->getPaddr(),
689 pkt
->req
->getFlags(),
690 pkt
->req
->masterId());
691 pf
= new Packet(req
, pkt
->cmd
);
693 assert(pf
->getAddr() == pkt
->getAddr());
694 assert(pf
->getSize() == pkt
->getSize());
697 pkt
->makeTimingResponse();
698 // for debugging, set all the bits in the response data
699 // (also keeps valgrind from complaining when debugging settings
700 // print out instruction results)
701 std::memset(pkt
->getPtr
<uint8_t>(), 0xFF, pkt
->getSize());
702 // request_time is used here, taking into account lat and the delay
703 // charged if the packet comes from the xbar.
704 cpuSidePort
->schedTimingResp(pkt
, request_time
);
706 // If an outstanding request is in progress (we found an
707 // MSHR) this is set to null
713 /// @note writebacks will be checked in getNextMSHR()
714 /// for any conflicting requests to the same block
716 //@todo remove hw_pf here
718 // Coalesce unless it was a software prefetch (see above).
720 assert(pkt
->cmd
!= MemCmd::Writeback
);
721 // CleanEvicts corresponding to blocks which have outstanding
722 // requests in MSHRs can be deleted here.
723 if (pkt
->cmd
== MemCmd::CleanEvict
) {
724 pendingDelete
.push_back(pkt
);
726 DPRINTF(Cache
, "%s coalescing MSHR for %s addr %#llx size %d\n",
727 __func__
, pkt
->cmdString(), pkt
->getAddr(),
730 assert(pkt
->req
->masterId() < system
->maxMasters());
731 mshr_hits
[pkt
->cmdToIndex()][pkt
->req
->masterId()]++;
732 if (mshr
->threadNum
!= 0/*pkt->req->threadId()*/) {
733 mshr
->threadNum
= -1;
735 // We use forward_time here because it is the same
736 // considering new targets. We have multiple
737 // requests for the same address here. It
738 // specifies the latency to allocate an internal
739 // buffer and to schedule an event to the queued
740 // port and also takes into account the additional
741 // delay of the xbar.
742 mshr
->allocateTarget(pkt
, forward_time
, order
++);
743 if (mshr
->getNumTargets() == numTarget
) {
745 setBlocked(Blocked_NoTargets
);
746 // need to be careful with this... if this mshr isn't
747 // ready yet (i.e. time > curTick()), we don't want to
748 // move it ahead of mshrs that are ready
749 // mshrQueue.moveToFront(mshr);
752 // We should call the prefetcher reguardless if the request is
753 // satisfied or not, reguardless if the request is in the MSHR or
754 // not. The request could be a ReadReq hit, but still not
755 // satisfied (potentially because of a prior write to the same
756 // cache line. So, even when not satisfied, tehre is an MSHR
757 // already allocated for this, we need to let the prefetcher know
760 // Don't notify on SWPrefetch
761 if (!pkt
->cmd
.isSWPrefetch())
762 next_pf_time
= prefetcher
->notify(pkt
);
767 assert(pkt
->req
->masterId() < system
->maxMasters());
768 if (pkt
->req
->isUncacheable()) {
769 mshr_uncacheable
[pkt
->cmdToIndex()][pkt
->req
->masterId()]++;
771 mshr_misses
[pkt
->cmdToIndex()][pkt
->req
->masterId()]++;
774 if (pkt
->evictingBlock() ||
775 (pkt
->req
->isUncacheable() && pkt
->isWrite())) {
776 // We use forward_time here because there is an
777 // uncached memory write, forwarded to WriteBuffer.
778 allocateWriteBuffer(pkt
, forward_time
);
780 if (blk
&& blk
->isValid()) {
781 // should have flushed and have no valid block
782 assert(!pkt
->req
->isUncacheable());
784 // If we have a write miss to a valid block, we
785 // need to mark the block non-readable. Otherwise
786 // if we allow reads while there's an outstanding
787 // write miss, the read could return stale data
788 // out of the cache block... a more aggressive
789 // system could detect the overlap (if any) and
790 // forward data out of the MSHRs, but we don't do
791 // that yet. Note that we do need to leave the
792 // block valid so that it stays in the cache, in
793 // case we get an upgrade response (and hence no
794 // new data) when the write miss completes.
795 // As long as CPUs do proper store/load forwarding
796 // internally, and have a sufficiently weak memory
797 // model, this is probably unnecessary, but at some
798 // point it must have seemed like we needed it...
799 assert(pkt
->needsExclusive());
800 assert(!blk
->isWritable());
801 blk
->status
&= ~BlkReadable
;
803 // Here we are using forward_time, modelling the latency of
804 // a miss (outbound) just as forwardLatency, neglecting the
805 // lookupLatency component.
806 allocateMissBuffer(pkt
, forward_time
);
810 // Don't notify on SWPrefetch
811 if (!pkt
->cmd
.isSWPrefetch())
812 next_pf_time
= prefetcher
->notify(pkt
);
817 if (next_pf_time
!= MaxTick
)
818 schedMemSideSendEvent(next_pf_time
);
824 // See comment in cache.hh.
826 Cache::getBusPacket(PacketPtr cpu_pkt
, CacheBlk
*blk
,
827 bool needsExclusive
) const
829 bool blkValid
= blk
&& blk
->isValid();
831 if (cpu_pkt
->req
->isUncacheable()) {
832 // note that at the point we see the uncacheable request we
833 // flush any block, but there could be an outstanding MSHR,
834 // and the cache could have filled again before we actually
835 // send out the forwarded uncacheable request (blk could thus
841 (cpu_pkt
->isUpgrade() ||
842 cpu_pkt
->evictingBlock())) {
843 // Writebacks that weren't allocated in access() and upgrades
844 // from upper-level caches that missed completely just go
849 assert(cpu_pkt
->needsResponse());
852 // @TODO make useUpgrades a parameter.
853 // Note that ownership protocols require upgrade, otherwise a
854 // write miss on a shared owned block will generate a ReadExcl,
855 // which will clobber the owned copy.
856 const bool useUpgrades
= true;
857 if (blkValid
&& useUpgrades
) {
858 // only reason to be here is that blk is shared
859 // (read-only) and we need exclusive
860 assert(needsExclusive
);
861 assert(!blk
->isWritable());
862 cmd
= cpu_pkt
->isLLSC() ? MemCmd::SCUpgradeReq
: MemCmd::UpgradeReq
;
863 } else if (cpu_pkt
->cmd
== MemCmd::SCUpgradeFailReq
||
864 cpu_pkt
->cmd
== MemCmd::StoreCondFailReq
) {
865 // Even though this SC will fail, we still need to send out the
866 // request and get the data to supply it to other snoopers in the case
867 // where the determination the StoreCond fails is delayed due to
868 // all caches not being on the same local bus.
869 cmd
= MemCmd::SCUpgradeFailReq
;
870 } else if (cpu_pkt
->cmd
== MemCmd::WriteLineReq
) {
871 // forward as invalidate to all other caches, this gives us
872 // the line in exclusive state, and invalidates all other
874 cmd
= MemCmd::InvalidateReq
;
877 cmd
= needsExclusive
? MemCmd::ReadExReq
:
878 (isReadOnly
? MemCmd::ReadCleanReq
: MemCmd::ReadSharedReq
);
880 PacketPtr pkt
= new Packet(cpu_pkt
->req
, cmd
, blkSize
);
882 // if there are sharers in the upper levels, pass that info downstream
883 if (cpu_pkt
->sharedAsserted()) {
884 // note that cpu_pkt may have spent a considerable time in the
885 // MSHR queue and that the information could possibly be out
886 // of date, however, there is no harm in conservatively
887 // assuming the block is shared
889 DPRINTF(Cache
, "%s passing shared from %s to %s addr %#llx size %d\n",
890 __func__
, cpu_pkt
->cmdString(), pkt
->cmdString(),
891 pkt
->getAddr(), pkt
->getSize());
894 // the packet should be block aligned
895 assert(pkt
->getAddr() == blockAlign(pkt
->getAddr()));
898 DPRINTF(Cache
, "%s created %s from %s for addr %#llx size %d\n",
899 __func__
, pkt
->cmdString(), cpu_pkt
->cmdString(), pkt
->getAddr(),
906 Cache::recvAtomic(PacketPtr pkt
)
908 // We are in atomic mode so we pay just for lookupLatency here.
909 Cycles lat
= lookupLatency
;
910 // @TODO: make this a parameter
911 bool last_level_cache
= false;
913 // Forward the request if the system is in cache bypass mode.
914 if (system
->bypassCaches())
915 return ticksToCycles(memSidePort
->sendAtomic(pkt
));
917 promoteWholeLineWrites(pkt
);
919 if (pkt
->memInhibitAsserted()) {
920 // have to invalidate ourselves and any lower caches even if
921 // upper cache will be responding
922 if (pkt
->isInvalidate()) {
923 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), pkt
->isSecure());
924 if (blk
&& blk
->isValid()) {
925 tags
->invalidate(blk
);
927 DPRINTF(Cache
, "rcvd mem-inhibited %s on %#llx (%s):"
929 pkt
->cmdString(), pkt
->getAddr(),
930 pkt
->isSecure() ? "s" : "ns");
932 if (!last_level_cache
) {
933 DPRINTF(Cache
, "forwarding mem-inhibited %s on %#llx (%s)\n",
934 pkt
->cmdString(), pkt
->getAddr(),
935 pkt
->isSecure() ? "s" : "ns");
936 lat
+= ticksToCycles(memSidePort
->sendAtomic(pkt
));
939 DPRINTF(Cache
, "rcvd mem-inhibited %s on %#llx: not responding\n",
940 pkt
->cmdString(), pkt
->getAddr());
943 return lat
* clockPeriod();
946 // should assert here that there are no outstanding MSHRs or
947 // writebacks... that would mean that someone used an atomic
948 // access in timing mode
950 CacheBlk
*blk
= NULL
;
951 PacketList writebacks
;
952 bool satisfied
= access(pkt
, blk
, lat
, writebacks
);
954 // handle writebacks resulting from the access here to ensure they
955 // logically proceed anything happening below
956 while (!writebacks
.empty()){
957 PacketPtr wbPkt
= writebacks
.front();
958 memSidePort
->sendAtomic(wbPkt
);
959 writebacks
.pop_front();
966 PacketPtr bus_pkt
= getBusPacket(pkt
, blk
, pkt
->needsExclusive());
968 bool is_forward
= (bus_pkt
== NULL
);
971 // just forwarding the same request to the next level
972 // no local cache operation involved
976 DPRINTF(Cache
, "Sending an atomic %s for %#llx (%s)\n",
977 bus_pkt
->cmdString(), bus_pkt
->getAddr(),
978 bus_pkt
->isSecure() ? "s" : "ns");
981 CacheBlk::State old_state
= blk
? blk
->status
: 0;
984 lat
+= ticksToCycles(memSidePort
->sendAtomic(bus_pkt
));
986 // We are now dealing with the response handling
987 DPRINTF(Cache
, "Receive response: %s for addr %#llx (%s) in state %i\n",
988 bus_pkt
->cmdString(), bus_pkt
->getAddr(),
989 bus_pkt
->isSecure() ? "s" : "ns",
992 // If packet was a forward, the response (if any) is already
993 // in place in the bus_pkt == pkt structure, so we don't need
994 // to do anything. Otherwise, use the separate bus_pkt to
995 // generate response to pkt and then delete it.
997 if (pkt
->needsResponse()) {
998 assert(bus_pkt
->isResponse());
999 if (bus_pkt
->isError()) {
1000 pkt
->makeAtomicResponse();
1001 pkt
->copyError(bus_pkt
);
1002 } else if (pkt
->cmd
== MemCmd::InvalidateReq
) {
1004 // invalidate response to a cache that received
1005 // an invalidate request
1006 satisfyCpuSideRequest(pkt
, blk
);
1008 } else if (pkt
->cmd
== MemCmd::WriteLineReq
) {
1009 // note the use of pkt, not bus_pkt here.
1011 // write-line request to the cache that promoted
1012 // the write to a whole line
1013 blk
= handleFill(pkt
, blk
, writebacks
);
1014 satisfyCpuSideRequest(pkt
, blk
);
1015 } else if (bus_pkt
->isRead() ||
1016 bus_pkt
->cmd
== MemCmd::UpgradeResp
) {
1017 // we're updating cache state to allow us to
1018 // satisfy the upstream request from the cache
1019 blk
= handleFill(bus_pkt
, blk
, writebacks
);
1020 satisfyCpuSideRequest(pkt
, blk
);
1022 // we're satisfying the upstream request without
1023 // modifying cache state, e.g., a write-through
1024 pkt
->makeAtomicResponse();
1031 // Note that we don't invoke the prefetcher at all in atomic mode.
1032 // It's not clear how to do it properly, particularly for
1033 // prefetchers that aggressively generate prefetch candidates and
1034 // rely on bandwidth contention to throttle them; these will tend
1035 // to pollute the cache in atomic mode since there is no bandwidth
1036 // contention. If we ever do want to enable prefetching in atomic
1037 // mode, though, this is the place to do it... see timingAccess()
1038 // for an example (though we'd want to issue the prefetch(es)
1039 // immediately rather than calling requestMemSideBus() as we do
1042 // Handle writebacks (from the response handling) if needed
1043 while (!writebacks
.empty()){
1044 PacketPtr wbPkt
= writebacks
.front();
1045 memSidePort
->sendAtomic(wbPkt
);
1046 writebacks
.pop_front();
1050 if (pkt
->needsResponse()) {
1051 pkt
->makeAtomicResponse();
1054 return lat
* clockPeriod();
1059 Cache::functionalAccess(PacketPtr pkt
, bool fromCpuSide
)
1061 if (system
->bypassCaches()) {
1062 // Packets from the memory side are snoop request and
1063 // shouldn't happen in bypass mode.
1064 assert(fromCpuSide
);
1066 // The cache should be flushed if we are in cache bypass mode,
1067 // so we don't need to check if we need to update anything.
1068 memSidePort
->sendFunctional(pkt
);
1072 Addr blk_addr
= blockAlign(pkt
->getAddr());
1073 bool is_secure
= pkt
->isSecure();
1074 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), is_secure
);
1075 MSHR
*mshr
= mshrQueue
.findMatch(blk_addr
, is_secure
);
1077 pkt
->pushLabel(name());
1079 CacheBlkPrintWrapper
cbpw(blk
);
1081 // Note that just because an L2/L3 has valid data doesn't mean an
1082 // L1 doesn't have a more up-to-date modified copy that still
1083 // needs to be found. As a result we always update the request if
1084 // we have it, but only declare it satisfied if we are the owner.
1086 // see if we have data at all (owned or otherwise)
1087 bool have_data
= blk
&& blk
->isValid()
1088 && pkt
->checkFunctional(&cbpw
, blk_addr
, is_secure
, blkSize
,
1091 // data we have is dirty if marked as such or if valid & ownership
1092 // pending due to outstanding UpgradeReq
1094 have_data
&& (blk
->isDirty() ||
1095 (mshr
&& mshr
->inService
&& mshr
->isPendingDirty()));
1097 bool done
= have_dirty
1098 || cpuSidePort
->checkFunctional(pkt
)
1099 || mshrQueue
.checkFunctional(pkt
, blk_addr
)
1100 || writeBuffer
.checkFunctional(pkt
, blk_addr
)
1101 || memSidePort
->checkFunctional(pkt
);
1103 DPRINTF(Cache
, "functional %s %#llx (%s) %s%s%s\n",
1104 pkt
->cmdString(), pkt
->getAddr(), is_secure
? "s" : "ns",
1105 (blk
&& blk
->isValid()) ? "valid " : "",
1106 have_data
? "data " : "", done
? "done " : "");
1108 // We're leaving the cache, so pop cache->name() label
1112 pkt
->makeResponse();
1114 // if it came as a request from the CPU side then make sure it
1115 // continues towards the memory side
1117 memSidePort
->sendFunctional(pkt
);
1118 } else if (forwardSnoops
&& cpuSidePort
->isSnooping()) {
1119 // if it came from the memory side, it must be a snoop request
1120 // and we should only forward it if we are forwarding snoops
1121 cpuSidePort
->sendFunctionalSnoop(pkt
);
1127 /////////////////////////////////////////////////////
1129 // Response handling: responses from the memory side
1131 /////////////////////////////////////////////////////
1135 Cache::recvTimingResp(PacketPtr pkt
)
1137 assert(pkt
->isResponse());
1139 // all header delay should be paid for by the crossbar, unless
1140 // this is a prefetch response from above
1141 panic_if(pkt
->headerDelay
!= 0 && pkt
->cmd
!= MemCmd::HardPFResp
,
1142 "%s saw a non-zero packet delay\n", name());
1144 MSHR
*mshr
= dynamic_cast<MSHR
*>(pkt
->senderState
);
1145 bool is_error
= pkt
->isError();
1150 DPRINTF(Cache
, "Cache received packet with error for addr %#llx (%s), "
1151 "cmd: %s\n", pkt
->getAddr(), pkt
->isSecure() ? "s" : "ns",
1155 DPRINTF(Cache
, "Handling response %s for addr %#llx size %d (%s)\n",
1156 pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize(),
1157 pkt
->isSecure() ? "s" : "ns");
1159 MSHRQueue
*mq
= mshr
->queue
;
1160 bool wasFull
= mq
->isFull();
1162 if (mshr
== noTargetMSHR
) {
1163 // we always clear at least one target
1164 clearBlocked(Blocked_NoTargets
);
1165 noTargetMSHR
= NULL
;
1168 // Initial target is used just for stats
1169 MSHR::Target
*initial_tgt
= mshr
->getTarget();
1170 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), pkt
->isSecure());
1171 int stats_cmd_idx
= initial_tgt
->pkt
->cmdToIndex();
1172 Tick miss_latency
= curTick() - initial_tgt
->recvTime
;
1173 PacketList writebacks
;
1174 // We need forward_time here because we have a call of
1175 // allocateWriteBuffer() that need this parameter to specify the
1176 // time to request the bus. In this case we use forward latency
1177 // because there is a writeback. We pay also here for headerDelay
1178 // that is charged of bus latencies if the packet comes from the
1180 Tick forward_time
= clockEdge(forwardLatency
) + pkt
->headerDelay
;
1182 if (pkt
->req
->isUncacheable()) {
1183 assert(pkt
->req
->masterId() < system
->maxMasters());
1184 mshr_uncacheable_lat
[stats_cmd_idx
][pkt
->req
->masterId()] +=
1187 assert(pkt
->req
->masterId() < system
->maxMasters());
1188 mshr_miss_latency
[stats_cmd_idx
][pkt
->req
->masterId()] +=
1192 bool is_fill
= !mshr
->isForward
&&
1193 (pkt
->isRead() || pkt
->cmd
== MemCmd::UpgradeResp
);
1195 if (is_fill
&& !is_error
) {
1196 DPRINTF(Cache
, "Block for addr %#llx being updated in Cache\n",
1199 // give mshr a chance to do some dirty work
1200 mshr
->handleFill(pkt
, blk
);
1202 blk
= handleFill(pkt
, blk
, writebacks
);
1203 assert(blk
!= NULL
);
1206 // allow invalidation responses originating from write-line
1207 // requests to be discarded
1208 bool discard_invalidate
= false;
1210 // First offset for critical word first calculations
1211 int initial_offset
= initial_tgt
->pkt
->getOffset(blkSize
);
1213 while (mshr
->hasTargets()) {
1214 MSHR::Target
*target
= mshr
->getTarget();
1215 Packet
*tgt_pkt
= target
->pkt
;
1217 switch (target
->source
) {
1218 case MSHR::Target::FromCPU
:
1219 Tick completion_time
;
1220 // Here we charge on completion_time the delay of the xbar if the
1221 // packet comes from it, charged on headerDelay.
1222 completion_time
= pkt
->headerDelay
;
1224 // Software prefetch handling for cache closest to core
1225 if (tgt_pkt
->cmd
.isSWPrefetch()) {
1226 // a software prefetch would have already been ack'd immediately
1227 // with dummy data so the core would be able to retire it.
1228 // this request completes right here, so we deallocate it.
1229 delete tgt_pkt
->req
;
1231 break; // skip response
1234 // unlike the other packet flows, where data is found in other
1235 // caches or memory and brought back, write-line requests always
1236 // have the data right away, so the above check for "is fill?"
1237 // cannot actually be determined until examining the stored MSHR
1238 // state. We "catch up" with that logic here, which is duplicated
1240 if (tgt_pkt
->cmd
== MemCmd::WriteLineReq
) {
1243 // NB: we use the original packet here and not the response!
1244 mshr
->handleFill(tgt_pkt
, blk
);
1245 blk
= handleFill(tgt_pkt
, blk
, writebacks
);
1246 assert(blk
!= NULL
);
1248 // treat as a fill, and discard the invalidation
1251 discard_invalidate
= true;
1255 satisfyCpuSideRequest(tgt_pkt
, blk
,
1256 true, mshr
->hasPostDowngrade());
1258 // How many bytes past the first request is this one
1259 int transfer_offset
=
1260 tgt_pkt
->getOffset(blkSize
) - initial_offset
;
1261 if (transfer_offset
< 0) {
1262 transfer_offset
+= blkSize
;
1265 // If not critical word (offset) return payloadDelay.
1266 // responseLatency is the latency of the return path
1267 // from lower level caches/memory to an upper level cache or
1269 completion_time
+= clockEdge(responseLatency
) +
1270 (transfer_offset
? pkt
->payloadDelay
: 0);
1272 assert(!tgt_pkt
->req
->isUncacheable());
1274 assert(tgt_pkt
->req
->masterId() < system
->maxMasters());
1275 missLatency
[tgt_pkt
->cmdToIndex()][tgt_pkt
->req
->masterId()] +=
1276 completion_time
- target
->recvTime
;
1277 } else if (pkt
->cmd
== MemCmd::UpgradeFailResp
) {
1278 // failed StoreCond upgrade
1279 assert(tgt_pkt
->cmd
== MemCmd::StoreCondReq
||
1280 tgt_pkt
->cmd
== MemCmd::StoreCondFailReq
||
1281 tgt_pkt
->cmd
== MemCmd::SCUpgradeFailReq
);
1282 // responseLatency is the latency of the return path
1283 // from lower level caches/memory to an upper level cache or
1285 completion_time
+= clockEdge(responseLatency
) +
1287 tgt_pkt
->req
->setExtraData(0);
1289 // not a cache fill, just forwarding response
1290 // responseLatency is the latency of the return path
1291 // from lower level cahces/memory to the core.
1292 completion_time
+= clockEdge(responseLatency
) +
1294 if (pkt
->isRead() && !is_error
) {
1296 assert(pkt
->getAddr() == tgt_pkt
->getAddr());
1297 assert(pkt
->getSize() >= tgt_pkt
->getSize());
1299 tgt_pkt
->setData(pkt
->getConstPtr
<uint8_t>());
1302 tgt_pkt
->makeTimingResponse();
1303 // if this packet is an error copy that to the new packet
1305 tgt_pkt
->copyError(pkt
);
1306 if (tgt_pkt
->cmd
== MemCmd::ReadResp
&&
1307 (pkt
->isInvalidate() || mshr
->hasPostInvalidate())) {
1308 // If intermediate cache got ReadRespWithInvalidate,
1309 // propagate that. Response should not have
1310 // isInvalidate() set otherwise.
1311 tgt_pkt
->cmd
= MemCmd::ReadRespWithInvalidate
;
1312 DPRINTF(Cache
, "%s updated cmd to %s for addr %#llx\n",
1313 __func__
, tgt_pkt
->cmdString(), tgt_pkt
->getAddr());
1315 // Reset the bus additional time as it is now accounted for
1316 tgt_pkt
->headerDelay
= tgt_pkt
->payloadDelay
= 0;
1317 cpuSidePort
->schedTimingResp(tgt_pkt
, completion_time
);
1320 case MSHR::Target::FromPrefetcher
:
1321 assert(tgt_pkt
->cmd
== MemCmd::HardPFReq
);
1323 blk
->status
|= BlkHWPrefetched
;
1324 delete tgt_pkt
->req
;
1328 case MSHR::Target::FromSnoop
:
1329 // I don't believe that a snoop can be in an error state
1331 // response to snoop request
1332 DPRINTF(Cache
, "processing deferred snoop...\n");
1333 assert(!(pkt
->isInvalidate() && !mshr
->hasPostInvalidate()));
1334 handleSnoop(tgt_pkt
, blk
, true, true, mshr
->hasPostInvalidate());
1338 panic("Illegal target->source enum %d\n", target
->source
);
1344 if (blk
&& blk
->isValid()) {
1345 // an invalidate response stemming from a write line request
1346 // should not invalidate the block, so check if the
1347 // invalidation should be discarded
1348 if ((pkt
->isInvalidate() || mshr
->hasPostInvalidate()) &&
1349 !discard_invalidate
) {
1350 assert(blk
!= tempBlock
);
1351 tags
->invalidate(blk
);
1353 } else if (mshr
->hasPostDowngrade()) {
1354 blk
->status
&= ~BlkWritable
;
1358 if (mshr
->promoteDeferredTargets()) {
1359 // avoid later read getting stale data while write miss is
1360 // outstanding.. see comment in timingAccess()
1362 blk
->status
&= ~BlkReadable
;
1365 mq
->markPending(mshr
);
1366 schedMemSideSendEvent(clockEdge() + pkt
->payloadDelay
);
1368 mq
->deallocate(mshr
);
1369 if (wasFull
&& !mq
->isFull()) {
1370 clearBlocked((BlockedCause
)mq
->index
);
1373 // Request the bus for a prefetch if this deallocation freed enough
1374 // MSHRs for a prefetch to take place
1375 if (prefetcher
&& mq
== &mshrQueue
&& mshrQueue
.canPrefetch()) {
1376 Tick next_pf_time
= std::max(prefetcher
->nextPrefetchReadyTime(),
1378 if (next_pf_time
!= MaxTick
)
1379 schedMemSideSendEvent(next_pf_time
);
1382 // reset the xbar additional timinig as it is now accounted for
1383 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
1385 // copy writebacks to write buffer
1386 doWritebacks(writebacks
, forward_time
);
1388 // if we used temp block, check to see if its valid and then clear it out
1389 if (blk
== tempBlock
&& tempBlock
->isValid()) {
1390 // We use forwardLatency here because we are copying
1391 // Writebacks/CleanEvicts to write buffer. It specifies the latency to
1392 // allocate an internal buffer and to schedule an event to the
1394 if (blk
->isDirty()) {
1395 PacketPtr wbPkt
= writebackBlk(blk
);
1396 allocateWriteBuffer(wbPkt
, forward_time
);
1397 // Set BLOCK_CACHED flag if cached above.
1398 if (isCachedAbove(wbPkt
))
1399 wbPkt
->setBlockCached();
1401 PacketPtr wcPkt
= cleanEvictBlk(blk
);
1402 // Check to see if block is cached above. If not allocate
1404 if (isCachedAbove(wcPkt
))
1407 allocateWriteBuffer(wcPkt
, forward_time
);
1412 DPRINTF(Cache
, "Leaving %s with %s for addr %#llx\n", __func__
,
1413 pkt
->cmdString(), pkt
->getAddr());
1418 Cache::writebackBlk(CacheBlk
*blk
)
1420 chatty_assert(!isReadOnly
, "Writeback from read-only cache");
1421 assert(blk
&& blk
->isValid() && blk
->isDirty());
1423 writebacks
[Request::wbMasterId
]++;
1425 Request
*writebackReq
=
1426 new Request(tags
->regenerateBlkAddr(blk
->tag
, blk
->set
), blkSize
, 0,
1427 Request::wbMasterId
);
1428 if (blk
->isSecure())
1429 writebackReq
->setFlags(Request::SECURE
);
1431 writebackReq
->taskId(blk
->task_id
);
1432 blk
->task_id
= ContextSwitchTaskId::Unknown
;
1433 blk
->tickInserted
= curTick();
1435 PacketPtr writeback
= new Packet(writebackReq
, MemCmd::Writeback
);
1436 if (blk
->isWritable()) {
1437 // not asserting shared means we pass the block in modified
1438 // state, mark our own block non-writeable
1439 blk
->status
&= ~BlkWritable
;
1441 // we are in the owned state, tell the receiver
1442 writeback
->assertShared();
1445 writeback
->allocate();
1446 std::memcpy(writeback
->getPtr
<uint8_t>(), blk
->data
, blkSize
);
1448 blk
->status
&= ~BlkDirty
;
1453 Cache::cleanEvictBlk(CacheBlk
*blk
)
1455 assert(blk
&& blk
->isValid() && !blk
->isDirty());
1456 // Creating a zero sized write, a message to the snoop filter
1458 new Request(tags
->regenerateBlkAddr(blk
->tag
, blk
->set
), blkSize
, 0,
1459 Request::wbMasterId
);
1460 if (blk
->isSecure())
1461 req
->setFlags(Request::SECURE
);
1463 req
->taskId(blk
->task_id
);
1464 blk
->task_id
= ContextSwitchTaskId::Unknown
;
1465 blk
->tickInserted
= curTick();
1467 PacketPtr pkt
= new Packet(req
, MemCmd::CleanEvict
);
1469 DPRINTF(Cache
, "%s%s %x Create CleanEvict\n", pkt
->cmdString(),
1470 pkt
->req
->isInstFetch() ? " (ifetch)" : "",
1477 Cache::memWriteback()
1479 CacheBlkVisitorWrapper
visitor(*this, &Cache::writebackVisitor
);
1480 tags
->forEachBlk(visitor
);
1484 Cache::memInvalidate()
1486 CacheBlkVisitorWrapper
visitor(*this, &Cache::invalidateVisitor
);
1487 tags
->forEachBlk(visitor
);
1491 Cache::isDirty() const
1493 CacheBlkIsDirtyVisitor visitor
;
1494 tags
->forEachBlk(visitor
);
1496 return visitor
.isDirty();
1500 Cache::writebackVisitor(CacheBlk
&blk
)
1502 if (blk
.isDirty()) {
1503 assert(blk
.isValid());
1505 Request
request(tags
->regenerateBlkAddr(blk
.tag
, blk
.set
),
1506 blkSize
, 0, Request::funcMasterId
);
1507 request
.taskId(blk
.task_id
);
1509 Packet
packet(&request
, MemCmd::WriteReq
);
1510 packet
.dataStatic(blk
.data
);
1512 memSidePort
->sendFunctional(&packet
);
1514 blk
.status
&= ~BlkDirty
;
1521 Cache::invalidateVisitor(CacheBlk
&blk
)
1525 warn_once("Invalidating dirty cache lines. Expect things to break.\n");
1527 if (blk
.isValid()) {
1528 assert(!blk
.isDirty());
1529 tags
->invalidate(&blk
);
1537 Cache::allocateBlock(Addr addr
, bool is_secure
, PacketList
&writebacks
)
1539 CacheBlk
*blk
= tags
->findVictim(addr
);
1541 // It is valid to return NULL if there is no victim
1545 if (blk
->isValid()) {
1546 Addr repl_addr
= tags
->regenerateBlkAddr(blk
->tag
, blk
->set
);
1547 MSHR
*repl_mshr
= mshrQueue
.findMatch(repl_addr
, blk
->isSecure());
1549 // must be an outstanding upgrade request
1550 // on a block we're about to replace...
1551 assert(!blk
->isWritable() || blk
->isDirty());
1552 assert(repl_mshr
->needsExclusive());
1553 // too hard to replace block with transient state
1554 // allocation failed, block not inserted
1557 DPRINTF(Cache
, "replacement: replacing %#llx (%s) with %#llx (%s): %s\n",
1558 repl_addr
, blk
->isSecure() ? "s" : "ns",
1559 addr
, is_secure
? "s" : "ns",
1560 blk
->isDirty() ? "writeback" : "clean");
1562 // Will send up Writeback/CleanEvict snoops via isCachedAbove
1563 // when pushing this writeback list into the write buffer.
1564 if (blk
->isDirty()) {
1565 // Save writeback packet for handling by caller
1566 writebacks
.push_back(writebackBlk(blk
));
1568 writebacks
.push_back(cleanEvictBlk(blk
));
1577 // Note that the reason we return a list of writebacks rather than
1578 // inserting them directly in the write buffer is that this function
1579 // is called by both atomic and timing-mode accesses, and in atomic
1580 // mode we don't mess with the write buffer (we just perform the
1581 // writebacks atomically once the original request is complete).
1583 Cache::handleFill(PacketPtr pkt
, CacheBlk
*blk
, PacketList
&writebacks
)
1585 assert(pkt
->isResponse() || pkt
->cmd
== MemCmd::WriteLineReq
);
1586 Addr addr
= pkt
->getAddr();
1587 bool is_secure
= pkt
->isSecure();
1589 CacheBlk::State old_state
= blk
? blk
->status
: 0;
1592 // When handling a fill, discard any CleanEvicts for the
1593 // same address in write buffer.
1594 Addr M5_VAR_USED blk_addr
= blockAlign(pkt
->getAddr());
1595 std::vector
<MSHR
*> M5_VAR_USED wbs
;
1596 assert (!writeBuffer
.findMatches(blk_addr
, is_secure
, wbs
));
1599 // better have read new data...
1600 assert(pkt
->hasData());
1602 // only read responses and write-line requests have data;
1603 // note that we don't write the data here for write-line - that
1604 // happens in the subsequent satisfyCpuSideRequest.
1605 assert(pkt
->isRead() || pkt
->cmd
== MemCmd::WriteLineReq
);
1607 // need to do a replacement
1608 blk
= allocateBlock(addr
, is_secure
, writebacks
);
1610 // No replaceable block... just use temporary storage to
1611 // complete the current request and then get rid of it
1612 assert(!tempBlock
->isValid());
1614 tempBlock
->set
= tags
->extractSet(addr
);
1615 tempBlock
->tag
= tags
->extractTag(addr
);
1616 // @todo: set security state as well...
1617 DPRINTF(Cache
, "using temp block for %#llx (%s)\n", addr
,
1618 is_secure
? "s" : "ns");
1620 tags
->insertBlock(pkt
, blk
);
1623 // we should never be overwriting a valid block
1624 assert(!blk
->isValid());
1626 // existing block... probably an upgrade
1627 assert(blk
->tag
== tags
->extractTag(addr
));
1628 // either we're getting new data or the block should already be valid
1629 assert(pkt
->hasData() || blk
->isValid());
1630 // don't clear block status... if block is already dirty we
1631 // don't want to lose that
1635 blk
->status
|= BlkSecure
;
1636 blk
->status
|= BlkValid
| BlkReadable
;
1638 if (!pkt
->sharedAsserted()) {
1639 // we could get non-shared responses from memory (rather than
1640 // a cache) even in a read-only cache, note that we set this
1641 // bit even for a read-only cache as we use it to represent
1642 // the exclusive state
1643 blk
->status
|= BlkWritable
;
1645 // If we got this via cache-to-cache transfer (i.e., from a
1646 // cache that was an owner) and took away that owner's copy,
1647 // then we need to write it back. Normally this happens
1648 // anyway as a side effect of getting a copy to write it, but
1649 // there are cases (such as failed store conditionals or
1650 // compare-and-swaps) where we'll demand an exclusive copy but
1651 // end up not writing it.
1652 if (pkt
->memInhibitAsserted()) {
1653 blk
->status
|= BlkDirty
;
1655 chatty_assert(!isReadOnly
, "Should never see dirty snoop response "
1656 "in read-only cache %s\n", name());
1660 DPRINTF(Cache
, "Block addr %#llx (%s) moving from state %x to %s\n",
1661 addr
, is_secure
? "s" : "ns", old_state
, blk
->print());
1663 // if we got new data, copy it in (checking for a read response
1664 // and a response that has data is the same in the end)
1665 if (pkt
->isRead()) {
1667 assert(pkt
->hasData());
1668 assert(pkt
->getSize() == blkSize
);
1670 std::memcpy(blk
->data
, pkt
->getConstPtr
<uint8_t>(), blkSize
);
1672 // We pay for fillLatency here.
1673 blk
->whenReady
= clockEdge() + fillLatency
* clockPeriod() +
1680 /////////////////////////////////////////////////////
1682 // Snoop path: requests coming in from the memory side
1684 /////////////////////////////////////////////////////
1687 Cache::doTimingSupplyResponse(PacketPtr req_pkt
, const uint8_t *blk_data
,
1688 bool already_copied
, bool pending_inval
)
1691 assert(req_pkt
->isRequest());
1692 assert(req_pkt
->needsResponse());
1694 DPRINTF(Cache
, "%s for %s addr %#llx size %d\n", __func__
,
1695 req_pkt
->cmdString(), req_pkt
->getAddr(), req_pkt
->getSize());
1696 // timing-mode snoop responses require a new packet, unless we
1697 // already made a copy...
1698 PacketPtr pkt
= req_pkt
;
1699 if (!already_copied
)
1700 // do not clear flags, and allocate space for data if the
1701 // packet needs it (the only packets that carry data are read
1703 pkt
= new Packet(req_pkt
, false, req_pkt
->isRead());
1705 assert(req_pkt
->req
->isUncacheable() || req_pkt
->isInvalidate() ||
1706 pkt
->sharedAsserted());
1707 pkt
->makeTimingResponse();
1708 if (pkt
->isRead()) {
1709 pkt
->setDataFromBlock(blk_data
, blkSize
);
1711 if (pkt
->cmd
== MemCmd::ReadResp
&& pending_inval
) {
1712 // Assume we defer a response to a read from a far-away cache
1713 // A, then later defer a ReadExcl from a cache B on the same
1714 // bus as us. We'll assert MemInhibit in both cases, but in
1715 // the latter case MemInhibit will keep the invalidation from
1716 // reaching cache A. This special response tells cache A that
1717 // it gets the block to satisfy its read, but must immediately
1719 pkt
->cmd
= MemCmd::ReadRespWithInvalidate
;
1721 // Here we consider forward_time, paying for just forward latency and
1722 // also charging the delay provided by the xbar.
1723 // forward_time is used as send_time in next allocateWriteBuffer().
1724 Tick forward_time
= clockEdge(forwardLatency
) + pkt
->headerDelay
;
1725 // Here we reset the timing of the packet.
1726 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
1727 DPRINTF(Cache
, "%s created response: %s addr %#llx size %d tick: %lu\n",
1728 __func__
, pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize(),
1730 memSidePort
->schedTimingSnoopResp(pkt
, forward_time
, true);
1734 Cache::handleSnoop(PacketPtr pkt
, CacheBlk
*blk
, bool is_timing
,
1735 bool is_deferred
, bool pending_inval
)
1737 DPRINTF(Cache
, "%s for %s addr %#llx size %d\n", __func__
,
1738 pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize());
1739 // deferred snoops can only happen in timing mode
1740 assert(!(is_deferred
&& !is_timing
));
1741 // pending_inval only makes sense on deferred snoops
1742 assert(!(pending_inval
&& !is_deferred
));
1743 assert(pkt
->isRequest());
1745 // the packet may get modified if we or a forwarded snooper
1746 // responds in atomic mode, so remember a few things about the
1747 // original packet up front
1748 bool invalidate
= pkt
->isInvalidate();
1749 bool M5_VAR_USED needs_exclusive
= pkt
->needsExclusive();
1751 if (forwardSnoops
) {
1752 // first propagate snoop upward to see if anyone above us wants to
1753 // handle it. save & restore packet src since it will get
1754 // rewritten to be relative to cpu-side bus (if any)
1755 bool alreadyResponded
= pkt
->memInhibitAsserted();
1757 // copy the packet so that we can clear any flags before
1758 // forwarding it upwards, we also allocate data (passing
1759 // the pointer along in case of static data), in case
1760 // there is a snoop hit in upper levels
1761 Packet
snoopPkt(pkt
, true, true);
1762 snoopPkt
.setExpressSnoop();
1763 snoopPkt
.pushSenderState(new ForwardResponseRecord());
1764 // the snoop packet does not need to wait any additional
1766 snoopPkt
.headerDelay
= snoopPkt
.payloadDelay
= 0;
1767 cpuSidePort
->sendTimingSnoopReq(&snoopPkt
);
1768 if (snoopPkt
.memInhibitAsserted()) {
1769 // cache-to-cache response from some upper cache
1770 assert(!alreadyResponded
);
1771 pkt
->assertMemInhibit();
1773 // no cache (or anyone else for that matter) will
1774 // respond, so delete the ForwardResponseRecord here
1775 delete snoopPkt
.popSenderState();
1777 if (snoopPkt
.sharedAsserted()) {
1778 pkt
->assertShared();
1780 // If this request is a prefetch or clean evict and an upper level
1781 // signals block present, make sure to propagate the block
1782 // presence to the requester.
1783 if (snoopPkt
.isBlockCached()) {
1784 pkt
->setBlockCached();
1787 cpuSidePort
->sendAtomicSnoop(pkt
);
1788 if (!alreadyResponded
&& pkt
->memInhibitAsserted()) {
1789 // cache-to-cache response from some upper cache:
1790 // forward response to original requester
1791 assert(pkt
->isResponse());
1796 if (!blk
|| !blk
->isValid()) {
1797 DPRINTF(Cache
, "%s snoop miss for %s addr %#llx size %d\n",
1798 __func__
, pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize());
1801 DPRINTF(Cache
, "%s snoop hit for %s for addr %#llx size %d, "
1802 "old state is %s\n", __func__
, pkt
->cmdString(),
1803 pkt
->getAddr(), pkt
->getSize(), blk
->print());
1806 chatty_assert(!(isReadOnly
&& blk
->isDirty()),
1807 "Should never have a dirty block in a read-only cache %s\n",
1810 // We may end up modifying both the block state and the packet (if
1811 // we respond in atomic mode), so just figure out what to do now
1812 // and then do it later. If we find dirty data while snooping for
1813 // an invalidate, we don't need to send a response. The
1814 // invalidation itself is taken care of below.
1815 bool respond
= blk
->isDirty() && pkt
->needsResponse() &&
1816 pkt
->cmd
!= MemCmd::InvalidateReq
;
1817 bool have_exclusive
= blk
->isWritable();
1819 // Invalidate any prefetch's from below that would strip write permissions
1820 // MemCmd::HardPFReq is only observed by upstream caches. After missing
1821 // above and in it's own cache, a new MemCmd::ReadReq is created that
1822 // downstream caches observe.
1823 if (pkt
->mustCheckAbove()) {
1824 DPRINTF(Cache
, "Found addr %#llx in upper level cache for snoop %s from"
1825 " lower cache\n", pkt
->getAddr(), pkt
->cmdString());
1826 pkt
->setBlockCached();
1830 if (!pkt
->req
->isUncacheable() && pkt
->isRead() && !invalidate
) {
1831 assert(!needs_exclusive
);
1832 pkt
->assertShared();
1833 int bits_to_clear
= BlkWritable
;
1834 const bool haveOwnershipState
= true; // for now
1835 if (!haveOwnershipState
) {
1836 // if we don't support pure ownership (dirty && !writable),
1837 // have to clear dirty bit here, assume memory snarfs data
1838 // on cache-to-cache xfer
1839 bits_to_clear
|= BlkDirty
;
1841 blk
->status
&= ~bits_to_clear
;
1845 // prevent anyone else from responding, cache as well as
1846 // memory, and also prevent any memory from even seeing the
1847 // request (with current inhibited semantics), note that this
1848 // applies both to reads and writes and that for writes it
1849 // works thanks to the fact that we still have dirty data and
1850 // will write it back at a later point
1851 pkt
->assertMemInhibit();
1852 if (have_exclusive
) {
1853 // in the case of an uncacheable request there is no need
1854 // to set the exclusive flag, but since the recipient does
1855 // not care there is no harm in doing so
1856 pkt
->setSupplyExclusive();
1859 doTimingSupplyResponse(pkt
, blk
->data
, is_deferred
, pending_inval
);
1861 pkt
->makeAtomicResponse();
1862 pkt
->setDataFromBlock(blk
->data
, blkSize
);
1866 if (!respond
&& is_timing
&& is_deferred
) {
1867 // if it's a deferred timing snoop then we've made a copy of
1868 // both the request and the packet, and so if we're not using
1869 // those copies to respond and delete them here
1870 DPRINTF(Cache
, "Deleting pkt %p and request %p for cmd %s addr: %p\n",
1871 pkt
, pkt
->req
, pkt
->cmdString(), pkt
->getAddr());
1873 // the packets needs a response (just not from us), so we also
1874 // need to delete the request and not rely on the packet
1876 assert(pkt
->needsResponse());
1881 // Do this last in case it deallocates block data or something
1884 if (blk
!= tempBlock
)
1885 tags
->invalidate(blk
);
1889 DPRINTF(Cache
, "new state is %s\n", blk
->print());
1894 Cache::recvTimingSnoopReq(PacketPtr pkt
)
1896 DPRINTF(Cache
, "%s for %s addr %#llx size %d\n", __func__
,
1897 pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize());
1899 // Snoops shouldn't happen when bypassing caches
1900 assert(!system
->bypassCaches());
1902 // no need to snoop writebacks or requests that are not in range
1903 if (!inRange(pkt
->getAddr())) {
1907 bool is_secure
= pkt
->isSecure();
1908 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), is_secure
);
1910 Addr blk_addr
= blockAlign(pkt
->getAddr());
1911 MSHR
*mshr
= mshrQueue
.findMatch(blk_addr
, is_secure
);
1913 // Inform request(Prefetch, CleanEvict or Writeback) from below of
1914 // MSHR hit, set setBlockCached.
1915 if (mshr
&& pkt
->mustCheckAbove()) {
1916 DPRINTF(Cache
, "Setting block cached for %s from"
1917 "lower cache on mshr hit %#x\n",
1918 pkt
->cmdString(), pkt
->getAddr());
1919 pkt
->setBlockCached();
1923 // Let the MSHR itself track the snoop and decide whether we want
1924 // to go ahead and do the regular cache snoop
1925 if (mshr
&& mshr
->handleSnoop(pkt
, order
++)) {
1926 DPRINTF(Cache
, "Deferring snoop on in-service MSHR to blk %#llx (%s)."
1927 "mshrs: %s\n", blk_addr
, is_secure
? "s" : "ns",
1930 if (mshr
->getNumTargets() > numTarget
)
1931 warn("allocating bonus target for snoop"); //handle later
1935 //We also need to check the writeback buffers and handle those
1936 std::vector
<MSHR
*> writebacks
;
1937 if (writeBuffer
.findMatches(blk_addr
, is_secure
, writebacks
)) {
1938 DPRINTF(Cache
, "Snoop hit in writeback to addr %#llx (%s)\n",
1939 pkt
->getAddr(), is_secure
? "s" : "ns");
1941 // Look through writebacks for any cachable writes.
1942 // We should only ever find a single match
1943 assert(writebacks
.size() == 1);
1944 MSHR
*wb_entry
= writebacks
[0];
1945 // Expect to see only Writebacks and/or CleanEvicts here, both of
1946 // which should not be generated for uncacheable data.
1947 assert(!wb_entry
->isUncacheable());
1948 // There should only be a single request responsible for generating
1949 // Writebacks/CleanEvicts.
1950 assert(wb_entry
->getNumTargets() == 1);
1951 PacketPtr wb_pkt
= wb_entry
->getTarget()->pkt
;
1952 assert(wb_pkt
->evictingBlock());
1954 if (pkt
->evictingBlock()) {
1955 // if the block is found in the write queue, set the BLOCK_CACHED
1956 // flag for Writeback/CleanEvict snoop. On return the snoop will
1957 // propagate the BLOCK_CACHED flag in Writeback packets and prevent
1958 // any CleanEvicts from travelling down the memory hierarchy.
1959 pkt
->setBlockCached();
1960 DPRINTF(Cache
, "Squashing %s from lower cache on writequeue hit"
1961 " %#x\n", pkt
->cmdString(), pkt
->getAddr());
1965 if (wb_pkt
->cmd
== MemCmd::Writeback
) {
1966 assert(!pkt
->memInhibitAsserted());
1967 pkt
->assertMemInhibit();
1968 if (!pkt
->needsExclusive()) {
1969 pkt
->assertShared();
1970 // the writeback is no longer passing exclusivity (the
1971 // receiving cache should consider the block owned
1972 // rather than modified)
1973 wb_pkt
->assertShared();
1975 // if we're not asserting the shared line, we need to
1976 // invalidate our copy. we'll do that below as long as
1977 // the packet's invalidate flag is set...
1978 assert(pkt
->isInvalidate());
1980 doTimingSupplyResponse(pkt
, wb_pkt
->getConstPtr
<uint8_t>(),
1983 assert(wb_pkt
->cmd
== MemCmd::CleanEvict
);
1984 // The cache technically holds the block until the
1985 // corresponding CleanEvict message reaches the crossbar
1986 // below. Therefore when a snoop encounters a CleanEvict
1987 // message we must set assertShared (just like when it
1988 // encounters a Writeback) to avoid the snoop filter
1989 // prematurely clearing the holder bit in the crossbar
1991 if (!pkt
->needsExclusive())
1992 pkt
->assertShared();
1994 assert(pkt
->isInvalidate());
1997 if (pkt
->isInvalidate()) {
1998 // Invalidation trumps our writeback... discard here
1999 // Note: markInService will remove entry from writeback buffer.
2000 markInService(wb_entry
, false);
2005 // If this was a shared writeback, there may still be
2006 // other shared copies above that require invalidation.
2007 // We could be more selective and return here if the
2008 // request is non-exclusive or if the writeback is
2010 handleSnoop(pkt
, blk
, true, false, false);
2014 Cache::CpuSidePort::recvTimingSnoopResp(PacketPtr pkt
)
2016 // Express snoop responses from master to slave, e.g., from L1 to L2
2017 cache
->recvTimingSnoopResp(pkt
);
2022 Cache::recvAtomicSnoop(PacketPtr pkt
)
2024 // Snoops shouldn't happen when bypassing caches
2025 assert(!system
->bypassCaches());
2027 // no need to snoop writebacks or requests that are not in range. In
2028 // atomic we have no Writebacks/CleanEvicts queued and no prefetches,
2029 // hence there is no need to snoop upwards and determine if they are
2031 if (pkt
->evictingBlock() || !inRange(pkt
->getAddr())) {
2035 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), pkt
->isSecure());
2036 handleSnoop(pkt
, blk
, false, false, false);
2037 // We consider forwardLatency here because a snoop occurs in atomic mode
2038 return forwardLatency
* clockPeriod();
2043 Cache::getNextMSHR()
2045 // Check both MSHR queue and write buffer for potential requests,
2046 // note that null does not mean there is no request, it could
2047 // simply be that it is not ready
2048 MSHR
*miss_mshr
= mshrQueue
.getNextMSHR();
2049 MSHR
*write_mshr
= writeBuffer
.getNextMSHR();
2051 // If we got a write buffer request ready, first priority is a
2052 // full write buffer, otherwhise we favour the miss requests
2054 ((writeBuffer
.isFull() && writeBuffer
.inServiceEntries
== 0) ||
2056 // need to search MSHR queue for conflicting earlier miss.
2057 MSHR
*conflict_mshr
=
2058 mshrQueue
.findPending(write_mshr
->blkAddr
,
2059 write_mshr
->isSecure
);
2061 if (conflict_mshr
&& conflict_mshr
->order
< write_mshr
->order
) {
2062 // Service misses in order until conflict is cleared.
2063 return conflict_mshr
;
2065 // @todo Note that we ignore the ready time of the conflict here
2068 // No conflicts; issue write
2070 } else if (miss_mshr
) {
2071 // need to check for conflicting earlier writeback
2072 MSHR
*conflict_mshr
=
2073 writeBuffer
.findPending(miss_mshr
->blkAddr
,
2074 miss_mshr
->isSecure
);
2075 if (conflict_mshr
) {
2076 // not sure why we don't check order here... it was in the
2077 // original code but commented out.
2079 // The only way this happens is if we are
2080 // doing a write and we didn't have permissions
2081 // then subsequently saw a writeback (owned got evicted)
2082 // We need to make sure to perform the writeback first
2083 // To preserve the dirty data, then we can issue the write
2085 // should we return write_mshr here instead? I.e. do we
2086 // have to flush writes in order? I don't think so... not
2087 // for Alpha anyway. Maybe for x86?
2088 return conflict_mshr
;
2090 // @todo Note that we ignore the ready time of the conflict here
2093 // No conflicts; issue read
2097 // fall through... no pending requests. Try a prefetch.
2098 assert(!miss_mshr
&& !write_mshr
);
2099 if (prefetcher
&& mshrQueue
.canPrefetch()) {
2100 // If we have a miss queue slot, we can try a prefetch
2101 PacketPtr pkt
= prefetcher
->getPacket();
2103 Addr pf_addr
= blockAlign(pkt
->getAddr());
2104 if (!tags
->findBlock(pf_addr
, pkt
->isSecure()) &&
2105 !mshrQueue
.findMatch(pf_addr
, pkt
->isSecure()) &&
2106 !writeBuffer
.findMatch(pf_addr
, pkt
->isSecure())) {
2107 // Update statistic on number of prefetches issued
2108 // (hwpf_mshr_misses)
2109 assert(pkt
->req
->masterId() < system
->maxMasters());
2110 mshr_misses
[pkt
->cmdToIndex()][pkt
->req
->masterId()]++;
2112 // allocate an MSHR and return it, note
2113 // that we send the packet straight away, so do not
2114 // schedule the send
2115 return allocateMissBuffer(pkt
, curTick(), false);
2117 // free the request and packet
2128 Cache::isCachedAbove(const PacketPtr pkt
) const
2132 // Mirroring the flow of HardPFReqs, the cache sends CleanEvict and
2133 // Writeback snoops into upper level caches to check for copies of the
2134 // same block. Using the BLOCK_CACHED flag with the Writeback/CleanEvict
2135 // packet, the cache can inform the crossbar below of presence or absence
2138 Packet
snoop_pkt(pkt
, true, false);
2139 snoop_pkt
.setExpressSnoop();
2140 // Assert that packet is either Writeback or CleanEvict and not a prefetch
2141 // request because prefetch requests need an MSHR and may generate a snoop
2143 assert(pkt
->evictingBlock());
2144 snoop_pkt
.senderState
= NULL
;
2145 cpuSidePort
->sendTimingSnoopReq(&snoop_pkt
);
2146 // Writeback/CleanEvict snoops do not generate a separate snoop response.
2147 assert(!(snoop_pkt
.memInhibitAsserted()));
2148 return snoop_pkt
.isBlockCached();
2152 Cache::getTimingPacket()
2154 MSHR
*mshr
= getNextMSHR();
2160 // use request from 1st target
2161 PacketPtr tgt_pkt
= mshr
->getTarget()->pkt
;
2162 PacketPtr pkt
= NULL
;
2164 DPRINTF(CachePort
, "%s %s for addr %#llx size %d\n", __func__
,
2165 tgt_pkt
->cmdString(), tgt_pkt
->getAddr(), tgt_pkt
->getSize());
2167 CacheBlk
*blk
= tags
->findBlock(mshr
->blkAddr
, mshr
->isSecure
);
2169 if (tgt_pkt
->cmd
== MemCmd::HardPFReq
&& forwardSnoops
) {
2170 // We need to check the caches above us to verify that
2171 // they don't have a copy of this block in the dirty state
2172 // at the moment. Without this check we could get a stale
2173 // copy from memory that might get used in place of the
2175 Packet
snoop_pkt(tgt_pkt
, true, false);
2176 snoop_pkt
.setExpressSnoop();
2177 snoop_pkt
.senderState
= mshr
;
2178 cpuSidePort
->sendTimingSnoopReq(&snoop_pkt
);
2180 // Check to see if the prefetch was squashed by an upper cache (to
2181 // prevent us from grabbing the line) or if a Check to see if a
2182 // writeback arrived between the time the prefetch was placed in
2183 // the MSHRs and when it was selected to be sent or if the
2184 // prefetch was squashed by an upper cache.
2186 // It is important to check memInhibitAsserted before
2187 // prefetchSquashed. If another cache has asserted MEM_INGIBIT, it
2188 // will be sending a response which will arrive at the MSHR
2189 // allocated ofr this request. Checking the prefetchSquash first
2190 // may result in the MSHR being prematurely deallocated.
2192 if (snoop_pkt
.memInhibitAsserted()) {
2193 // If we are getting a non-shared response it is dirty
2194 bool pending_dirty_resp
= !snoop_pkt
.sharedAsserted();
2195 markInService(mshr
, pending_dirty_resp
);
2196 DPRINTF(Cache
, "Upward snoop of prefetch for addr"
2198 tgt_pkt
->getAddr(), tgt_pkt
->isSecure()? "s": "ns");
2202 if (snoop_pkt
.isBlockCached() || blk
!= NULL
) {
2203 DPRINTF(Cache
, "Block present, prefetch squashed by cache. "
2204 "Deallocating mshr target %#x.\n",
2207 // Deallocate the mshr target
2208 if (tgt_pkt
->cmd
!= MemCmd::Writeback
) {
2209 if (mshr
->queue
->forceDeallocateTarget(mshr
)) {
2210 // Clear block if this deallocation resulted freed an
2211 // mshr when all had previously been utilized
2212 clearBlocked((BlockedCause
)(mshr
->queue
->index
));
2216 // If this is a Writeback, and the snoops indicate that the blk
2217 // is cached above, set the BLOCK_CACHED flag in the Writeback
2218 // packet, so that it does not reset the bits corresponding to
2219 // this block in the snoop filter below.
2220 tgt_pkt
->setBlockCached();
2225 if (mshr
->isForwardNoResponse()) {
2226 // no response expected, just forward packet as it is
2227 assert(tags
->findBlock(mshr
->blkAddr
, mshr
->isSecure
) == NULL
);
2230 pkt
= getBusPacket(tgt_pkt
, blk
, mshr
->needsExclusive());
2232 mshr
->isForward
= (pkt
== NULL
);
2234 if (mshr
->isForward
) {
2235 // not a cache block request, but a response is expected
2236 // make copy of current packet to forward, keep current
2237 // copy for response handling
2238 pkt
= new Packet(tgt_pkt
, false, true);
2239 if (pkt
->isWrite()) {
2240 pkt
->setData(tgt_pkt
->getConstPtr
<uint8_t>());
2245 assert(pkt
!= NULL
);
2246 pkt
->senderState
= mshr
;
2252 Cache::nextMSHRReadyTime() const
2254 Tick nextReady
= std::min(mshrQueue
.nextMSHRReadyTime(),
2255 writeBuffer
.nextMSHRReadyTime());
2257 // Don't signal prefetch ready time if no MSHRs available
2258 // Will signal once enoguh MSHRs are deallocated
2259 if (prefetcher
&& mshrQueue
.canPrefetch()) {
2260 nextReady
= std::min(nextReady
,
2261 prefetcher
->nextPrefetchReadyTime());
2268 Cache::serialize(CheckpointOut
&cp
) const
2270 bool dirty(isDirty());
2273 warn("*** The cache still contains dirty data. ***\n");
2274 warn(" Make sure to drain the system using the correct flags.\n");
2275 warn(" This checkpoint will not restore correctly and dirty data in "
2276 "the cache will be lost!\n");
2279 // Since we don't checkpoint the data in the cache, any dirty data
2280 // will be lost when restoring from a checkpoint of a system that
2281 // wasn't drained properly. Flag the checkpoint as invalid if the
2282 // cache contains dirty data.
2283 bool bad_checkpoint(dirty
);
2284 SERIALIZE_SCALAR(bad_checkpoint
);
2288 Cache::unserialize(CheckpointIn
&cp
)
2290 bool bad_checkpoint
;
2291 UNSERIALIZE_SCALAR(bad_checkpoint
);
2292 if (bad_checkpoint
) {
2293 fatal("Restoring from checkpoints with dirty caches is not supported "
2294 "in the classic memory system. Please remove any caches or "
2295 " drain them properly before taking checkpoints.\n");
2306 Cache::CpuSidePort::getAddrRanges() const
2308 return cache
->getAddrRanges();
2312 Cache::CpuSidePort::recvTimingReq(PacketPtr pkt
)
2314 assert(!cache
->system
->bypassCaches());
2316 bool success
= false;
2318 // always let inhibited requests through, even if blocked,
2319 // ultimately we should check if this is an express snoop, but at
2320 // the moment that flag is only set in the cache itself
2321 if (pkt
->memInhibitAsserted()) {
2322 // do not change the current retry state
2323 bool M5_VAR_USED bypass_success
= cache
->recvTimingReq(pkt
);
2324 assert(bypass_success
);
2326 } else if (blocked
|| mustSendRetry
) {
2327 // either already committed to send a retry, or blocked
2330 // pass it on to the cache, and let the cache decide if we
2331 // have to retry or not
2332 success
= cache
->recvTimingReq(pkt
);
2335 // remember if we have to retry
2336 mustSendRetry
= !success
;
2341 Cache::CpuSidePort::recvAtomic(PacketPtr pkt
)
2343 return cache
->recvAtomic(pkt
);
2347 Cache::CpuSidePort::recvFunctional(PacketPtr pkt
)
2349 // functional request
2350 cache
->functionalAccess(pkt
, true);
2354 CpuSidePort::CpuSidePort(const std::string
&_name
, Cache
*_cache
,
2355 const std::string
&_label
)
2356 : BaseCache::CacheSlavePort(_name
, _cache
, _label
), cache(_cache
)
2361 CacheParams::create()
2365 return new Cache(this);
2374 Cache::MemSidePort::recvTimingResp(PacketPtr pkt
)
2376 cache
->recvTimingResp(pkt
);
2380 // Express snooping requests to memside port
2382 Cache::MemSidePort::recvTimingSnoopReq(PacketPtr pkt
)
2384 // handle snooping requests
2385 cache
->recvTimingSnoopReq(pkt
);
2389 Cache::MemSidePort::recvAtomicSnoop(PacketPtr pkt
)
2391 return cache
->recvAtomicSnoop(pkt
);
2395 Cache::MemSidePort::recvFunctionalSnoop(PacketPtr pkt
)
2397 // functional snoop (note that in contrast to atomic we don't have
2398 // a specific functionalSnoop method, as they have the same
2399 // behaviour regardless)
2400 cache
->functionalAccess(pkt
, false);
2404 Cache::CacheReqPacketQueue::sendDeferredPacket()
2407 assert(!waitingOnRetry
);
2409 // there should never be any deferred request packets in the
2410 // queue, instead we resly on the cache to provide the packets
2411 // from the MSHR queue or write queue
2412 assert(deferredPacketReadyTime() == MaxTick
);
2414 // check for request packets (requests & writebacks)
2415 PacketPtr pkt
= cache
.getTimingPacket();
2417 // can happen if e.g. we attempt a writeback and fail, but
2418 // before the retry, the writeback is eliminated because
2419 // we snoop another cache's ReadEx.
2421 MSHR
*mshr
= dynamic_cast<MSHR
*>(pkt
->senderState
);
2422 // in most cases getTimingPacket allocates a new packet, and
2423 // we must delete it unless it is successfully sent
2424 bool delete_pkt
= !mshr
->isForwardNoResponse();
2426 // let our snoop responses go first if there are responses to
2427 // the same addresses we are about to writeback, note that
2428 // this creates a dependency between requests and snoop
2429 // responses, but that should not be a problem since there is
2430 // a chain already and the key is that the snoop responses can
2431 // sink unconditionally
2432 if (snoopRespQueue
.hasAddr(pkt
->getAddr())) {
2433 DPRINTF(CachePort
, "Waiting for snoop response to be sent\n");
2434 Tick when
= snoopRespQueue
.deferredPacketReadyTime();
2435 schedSendEvent(when
);
2444 waitingOnRetry
= !masterPort
.sendTimingReq(pkt
);
2446 if (waitingOnRetry
) {
2447 DPRINTF(CachePort
, "now waiting on a retry\n");
2449 // we are awaiting a retry, but we
2450 // delete the packet and will be creating a new packet
2451 // when we get the opportunity
2454 // note that we have now masked any requestBus and
2455 // schedSendEvent (we will wait for a retry before
2456 // doing anything), and this is so even if we do not
2457 // care about this packet and might override it before
2460 // As part of the call to sendTimingReq the packet is
2461 // forwarded to all neighbouring caches (and any
2462 // caches above them) as a snoop. The packet is also
2463 // sent to any potential cache below as the
2464 // interconnect is not allowed to buffer the
2465 // packet. Thus at this point we know if any of the
2466 // neighbouring, or the downstream cache is
2467 // responding, and if so, if it is with a dirty line
2469 bool pending_dirty_resp
= !pkt
->sharedAsserted() &&
2470 pkt
->memInhibitAsserted();
2472 cache
.markInService(mshr
, pending_dirty_resp
);
2476 // if we succeeded and are not waiting for a retry, schedule the
2477 // next send considering when the next MSHR is ready, note that
2478 // snoop responses have their own packet queue and thus schedule
2480 if (!waitingOnRetry
) {
2481 schedSendEvent(cache
.nextMSHRReadyTime());
2486 MemSidePort::MemSidePort(const std::string
&_name
, Cache
*_cache
,
2487 const std::string
&_label
)
2488 : BaseCache::CacheMasterPort(_name
, _cache
, _reqQueue
, _snoopRespQueue
),
2489 _reqQueue(*_cache
, *this, _snoopRespQueue
, _label
),
2490 _snoopRespQueue(*_cache
, *this, _label
), cache(_cache
)