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();
459 Cache::doWritebacksAtomic(PacketList
& writebacks
)
461 while (!writebacks
.empty()) {
462 PacketPtr wbPkt
= writebacks
.front();
463 // Call isCachedAbove for both Writebacks and CleanEvicts. If
464 // isCachedAbove returns true we set BLOCK_CACHED flag in Writebacks
465 // and discard CleanEvicts.
466 if (isCachedAbove(wbPkt
, false)) {
467 if (wbPkt
->cmd
== MemCmd::Writeback
) {
468 // Set BLOCK_CACHED flag in Writeback and send below,
469 // so that the Writeback does not reset the bit
470 // corresponding to this address in the snoop filter
471 // below. We can discard CleanEvicts because cached
472 // copies exist above. Atomic mode isCachedAbove
473 // modifies packet to set BLOCK_CACHED flag
474 memSidePort
->sendAtomic(wbPkt
);
477 // If the block is not cached above, send packet below. Both
478 // CleanEvict and Writeback with BLOCK_CACHED flag cleared will
479 // reset the bit corresponding to this address in the snoop filter
481 memSidePort
->sendAtomic(wbPkt
);
483 writebacks
.pop_front();
484 // In case of CleanEvicts, the packet destructor will delete the
485 // request object because this is a non-snoop request packet which
486 // does not require a response.
493 Cache::recvTimingSnoopResp(PacketPtr pkt
)
495 DPRINTF(Cache
, "%s for %s addr %#llx size %d\n", __func__
,
496 pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize());
498 assert(pkt
->isResponse());
500 // must be cache-to-cache response from upper to lower level
501 ForwardResponseRecord
*rec
=
502 dynamic_cast<ForwardResponseRecord
*>(pkt
->senderState
);
503 assert(!system
->bypassCaches());
506 // @todo What guarantee do we have that this HardPFResp is
507 // actually for this cache, and not a cache closer to the
509 assert(pkt
->cmd
== MemCmd::HardPFResp
);
510 // Check if it's a prefetch response and handle it. We shouldn't
511 // get any other kinds of responses without FRRs.
512 DPRINTF(Cache
, "Got prefetch response from above for addr %#llx (%s)\n",
513 pkt
->getAddr(), pkt
->isSecure() ? "s" : "ns");
518 pkt
->popSenderState();
520 // forwardLatency is set here because there is a response from an
521 // upper level cache.
522 // To pay the delay that occurs if the packet comes from the bus,
523 // we charge also headerDelay.
524 Tick snoop_resp_time
= clockEdge(forwardLatency
) + pkt
->headerDelay
;
525 // Reset the timing of the packet.
526 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
527 memSidePort
->schedTimingSnoopResp(pkt
, snoop_resp_time
);
531 Cache::promoteWholeLineWrites(PacketPtr pkt
)
533 // Cache line clearing instructions
534 if (doFastWrites
&& (pkt
->cmd
== MemCmd::WriteReq
) &&
535 (pkt
->getSize() == blkSize
) && (pkt
->getOffset(blkSize
) == 0)) {
536 pkt
->cmd
= MemCmd::WriteLineReq
;
537 DPRINTF(Cache
, "packet promoted from Write to WriteLineReq\n");
542 Cache::recvTimingReq(PacketPtr pkt
)
544 DPRINTF(CacheTags
, "%s tags: %s\n", __func__
, tags
->print());
545 //@todo Add back in MemDebug Calls
546 // MemDebug::cacheAccess(pkt);
549 /// @todo temporary hack to deal with memory corruption issue until
550 /// 4-phase transactions are complete
551 for (int x
= 0; x
< pendingDelete
.size(); x
++)
552 delete pendingDelete
[x
];
553 pendingDelete
.clear();
555 assert(pkt
->isRequest());
557 // Just forward the packet if caches are disabled.
558 if (system
->bypassCaches()) {
559 // @todo This should really enqueue the packet rather
560 bool M5_VAR_USED success
= memSidePort
->sendTimingReq(pkt
);
565 promoteWholeLineWrites(pkt
);
567 if (pkt
->memInhibitAsserted()) {
568 // a cache above us (but not where the packet came from) is
569 // responding to the request
570 DPRINTF(Cache
, "mem inhibited on addr %#llx (%s): not responding\n",
571 pkt
->getAddr(), pkt
->isSecure() ? "s" : "ns");
573 // if the packet needs exclusive, and the cache that has
574 // promised to respond (setting the inhibit flag) is not
575 // providing exclusive (it is in O vs M state), we know that
576 // there may be other shared copies in the system; go out and
577 // invalidate them all
578 if (pkt
->needsExclusive() && !pkt
->isSupplyExclusive()) {
579 // create a downstream express snoop with cleared packet
580 // flags, there is no need to allocate any data as the
581 // packet is merely used to co-ordinate state transitions
582 Packet
*snoop_pkt
= new Packet(pkt
, true, false);
584 // also reset the bus time that the original packet has
586 snoop_pkt
->headerDelay
= snoop_pkt
->payloadDelay
= 0;
588 // make this an instantaneous express snoop, and let the
589 // other caches in the system know that the packet is
590 // inhibited, because we have found the authorative copy
591 // (O) that will supply the right data
592 snoop_pkt
->setExpressSnoop();
593 snoop_pkt
->assertMemInhibit();
595 // this express snoop travels towards the memory, and at
596 // every crossbar it is snooped upwards thus reaching
597 // every cache in the system
598 bool M5_VAR_USED success
= memSidePort
->sendTimingReq(snoop_pkt
);
599 // express snoops always succeed
602 // main memory will delete the packet
605 /// @todo nominally we should just delete the packet here,
606 /// however, until 4-phase stuff we can't because sending
607 /// cache is still relying on it.
608 pendingDelete
.push_back(pkt
);
610 // no need to take any action in this particular cache as the
611 // caches along the path to memory are allowed to keep lines
612 // in a shared state, and a cache above us already committed
617 // anything that is merely forwarded pays for the forward latency and
618 // the delay provided by the crossbar
619 Tick forward_time
= clockEdge(forwardLatency
) + pkt
->headerDelay
;
621 // We use lookupLatency here because it is used to specify the latency
623 Cycles lat
= lookupLatency
;
624 CacheBlk
*blk
= NULL
;
625 bool satisfied
= false;
627 PacketList writebacks
;
628 // Note that lat is passed by reference here. The function
629 // access() calls accessBlock() which can modify lat value.
630 satisfied
= access(pkt
, blk
, lat
, writebacks
);
632 // copy writebacks to write buffer here to ensure they logically
633 // proceed anything happening below
634 doWritebacks(writebacks
, forward_time
);
637 // Here we charge the headerDelay that takes into account the latencies
638 // of the bus, if the packet comes from it.
639 // The latency charged it is just lat that is the value of lookupLatency
640 // modified by access() function, or if not just lookupLatency.
641 // In case of a hit we are neglecting response latency.
642 // In case of a miss we are neglecting forward latency.
643 Tick request_time
= clockEdge(lat
) + pkt
->headerDelay
;
644 // Here we reset the timing of the packet.
645 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
647 // track time of availability of next prefetch, if any
648 Tick next_pf_time
= MaxTick
;
650 bool needsResponse
= pkt
->needsResponse();
653 // should never be satisfying an uncacheable access as we
654 // flush and invalidate any existing block as part of the
656 assert(!pkt
->req
->isUncacheable());
658 // hit (for all other request types)
660 if (prefetcher
&& (prefetchOnAccess
|| (blk
&& blk
->wasPrefetched()))) {
662 blk
->status
&= ~BlkHWPrefetched
;
664 // Don't notify on SWPrefetch
665 if (!pkt
->cmd
.isSWPrefetch())
666 next_pf_time
= prefetcher
->notify(pkt
);
670 pkt
->makeTimingResponse();
671 // @todo: Make someone pay for this
672 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
674 // In this case we are considering request_time that takes
675 // into account the delay of the xbar, if any, and just
676 // lat, neglecting responseLatency, modelling hit latency
677 // just as lookupLatency or or the value of lat overriden
678 // by access(), that calls accessBlock() function.
679 cpuSidePort
->schedTimingResp(pkt
, request_time
);
681 /// @todo nominally we should just delete the packet here,
682 /// however, until 4-phase stuff we can't because sending cache is
683 /// still relying on it. If the block is found in access(),
684 /// CleanEvict and Writeback messages will be deleted here as
686 pendingDelete
.push_back(pkt
);
691 Addr blk_addr
= blockAlign(pkt
->getAddr());
693 // ignore any existing MSHR if we are dealing with an
694 // uncacheable request
695 MSHR
*mshr
= pkt
->req
->isUncacheable() ? nullptr :
696 mshrQueue
.findMatch(blk_addr
, pkt
->isSecure());
698 // Software prefetch handling:
699 // To keep the core from waiting on data it won't look at
700 // anyway, send back a response with dummy data. Miss handling
701 // will continue asynchronously. Unfortunately, the core will
702 // insist upon freeing original Packet/Request, so we have to
703 // create a new pair with a different lifecycle. Note that this
704 // processing happens before any MSHR munging on the behalf of
705 // this request because this new Request will be the one stored
706 // into the MSHRs, not the original.
707 if (pkt
->cmd
.isSWPrefetch()) {
708 assert(needsResponse
);
709 assert(pkt
->req
->hasPaddr());
710 assert(!pkt
->req
->isUncacheable());
712 // There's no reason to add a prefetch as an additional target
713 // to an existing MSHR. If an outstanding request is already
714 // in progress, there is nothing for the prefetch to do.
715 // If this is the case, we don't even create a request at all.
716 PacketPtr pf
= nullptr;
719 // copy the request and create a new SoftPFReq packet
720 RequestPtr req
= new Request(pkt
->req
->getPaddr(),
722 pkt
->req
->getFlags(),
723 pkt
->req
->masterId());
724 pf
= new Packet(req
, pkt
->cmd
);
726 assert(pf
->getAddr() == pkt
->getAddr());
727 assert(pf
->getSize() == pkt
->getSize());
730 pkt
->makeTimingResponse();
731 // for debugging, set all the bits in the response data
732 // (also keeps valgrind from complaining when debugging settings
733 // print out instruction results)
734 std::memset(pkt
->getPtr
<uint8_t>(), 0xFF, pkt
->getSize());
735 // request_time is used here, taking into account lat and the delay
736 // charged if the packet comes from the xbar.
737 cpuSidePort
->schedTimingResp(pkt
, request_time
);
739 // If an outstanding request is in progress (we found an
740 // MSHR) this is set to null
746 /// @note writebacks will be checked in getNextMSHR()
747 /// for any conflicting requests to the same block
749 //@todo remove hw_pf here
751 // Coalesce unless it was a software prefetch (see above).
753 assert(pkt
->cmd
!= MemCmd::Writeback
);
754 // CleanEvicts corresponding to blocks which have outstanding
755 // requests in MSHRs can be deleted here.
756 if (pkt
->cmd
== MemCmd::CleanEvict
) {
757 pendingDelete
.push_back(pkt
);
759 DPRINTF(Cache
, "%s coalescing MSHR for %s addr %#llx size %d\n",
760 __func__
, pkt
->cmdString(), pkt
->getAddr(),
763 assert(pkt
->req
->masterId() < system
->maxMasters());
764 mshr_hits
[pkt
->cmdToIndex()][pkt
->req
->masterId()]++;
765 if (mshr
->threadNum
!= 0/*pkt->req->threadId()*/) {
766 mshr
->threadNum
= -1;
768 // We use forward_time here because it is the same
769 // considering new targets. We have multiple
770 // requests for the same address here. It
771 // specifies the latency to allocate an internal
772 // buffer and to schedule an event to the queued
773 // port and also takes into account the additional
774 // delay of the xbar.
775 mshr
->allocateTarget(pkt
, forward_time
, order
++);
776 if (mshr
->getNumTargets() == numTarget
) {
778 setBlocked(Blocked_NoTargets
);
779 // need to be careful with this... if this mshr isn't
780 // ready yet (i.e. time > curTick()), we don't want to
781 // move it ahead of mshrs that are ready
782 // mshrQueue.moveToFront(mshr);
785 // We should call the prefetcher reguardless if the request is
786 // satisfied or not, reguardless if the request is in the MSHR or
787 // not. The request could be a ReadReq hit, but still not
788 // satisfied (potentially because of a prior write to the same
789 // cache line. So, even when not satisfied, tehre is an MSHR
790 // already allocated for this, we need to let the prefetcher know
793 // Don't notify on SWPrefetch
794 if (!pkt
->cmd
.isSWPrefetch())
795 next_pf_time
= prefetcher
->notify(pkt
);
800 assert(pkt
->req
->masterId() < system
->maxMasters());
801 if (pkt
->req
->isUncacheable()) {
802 mshr_uncacheable
[pkt
->cmdToIndex()][pkt
->req
->masterId()]++;
804 mshr_misses
[pkt
->cmdToIndex()][pkt
->req
->masterId()]++;
807 if (pkt
->evictingBlock() ||
808 (pkt
->req
->isUncacheable() && pkt
->isWrite())) {
809 // We use forward_time here because there is an
810 // uncached memory write, forwarded to WriteBuffer.
811 allocateWriteBuffer(pkt
, forward_time
);
813 if (blk
&& blk
->isValid()) {
814 // should have flushed and have no valid block
815 assert(!pkt
->req
->isUncacheable());
817 // If we have a write miss to a valid block, we
818 // need to mark the block non-readable. Otherwise
819 // if we allow reads while there's an outstanding
820 // write miss, the read could return stale data
821 // out of the cache block... a more aggressive
822 // system could detect the overlap (if any) and
823 // forward data out of the MSHRs, but we don't do
824 // that yet. Note that we do need to leave the
825 // block valid so that it stays in the cache, in
826 // case we get an upgrade response (and hence no
827 // new data) when the write miss completes.
828 // As long as CPUs do proper store/load forwarding
829 // internally, and have a sufficiently weak memory
830 // model, this is probably unnecessary, but at some
831 // point it must have seemed like we needed it...
832 assert(pkt
->needsExclusive());
833 assert(!blk
->isWritable());
834 blk
->status
&= ~BlkReadable
;
836 // Here we are using forward_time, modelling the latency of
837 // a miss (outbound) just as forwardLatency, neglecting the
838 // lookupLatency component.
839 allocateMissBuffer(pkt
, forward_time
);
843 // Don't notify on SWPrefetch
844 if (!pkt
->cmd
.isSWPrefetch())
845 next_pf_time
= prefetcher
->notify(pkt
);
850 if (next_pf_time
!= MaxTick
)
851 schedMemSideSendEvent(next_pf_time
);
857 // See comment in cache.hh.
859 Cache::getBusPacket(PacketPtr cpu_pkt
, CacheBlk
*blk
,
860 bool needsExclusive
) const
862 bool blkValid
= blk
&& blk
->isValid();
864 if (cpu_pkt
->req
->isUncacheable()) {
865 // note that at the point we see the uncacheable request we
866 // flush any block, but there could be an outstanding MSHR,
867 // and the cache could have filled again before we actually
868 // send out the forwarded uncacheable request (blk could thus
874 (cpu_pkt
->isUpgrade() ||
875 cpu_pkt
->evictingBlock())) {
876 // Writebacks that weren't allocated in access() and upgrades
877 // from upper-level caches that missed completely just go
882 assert(cpu_pkt
->needsResponse());
885 // @TODO make useUpgrades a parameter.
886 // Note that ownership protocols require upgrade, otherwise a
887 // write miss on a shared owned block will generate a ReadExcl,
888 // which will clobber the owned copy.
889 const bool useUpgrades
= true;
890 if (blkValid
&& useUpgrades
) {
891 // only reason to be here is that blk is shared
892 // (read-only) and we need exclusive
893 assert(needsExclusive
);
894 assert(!blk
->isWritable());
895 cmd
= cpu_pkt
->isLLSC() ? MemCmd::SCUpgradeReq
: MemCmd::UpgradeReq
;
896 } else if (cpu_pkt
->cmd
== MemCmd::SCUpgradeFailReq
||
897 cpu_pkt
->cmd
== MemCmd::StoreCondFailReq
) {
898 // Even though this SC will fail, we still need to send out the
899 // request and get the data to supply it to other snoopers in the case
900 // where the determination the StoreCond fails is delayed due to
901 // all caches not being on the same local bus.
902 cmd
= MemCmd::SCUpgradeFailReq
;
903 } else if (cpu_pkt
->cmd
== MemCmd::WriteLineReq
) {
904 // forward as invalidate to all other caches, this gives us
905 // the line in exclusive state, and invalidates all other
907 cmd
= MemCmd::InvalidateReq
;
910 cmd
= needsExclusive
? MemCmd::ReadExReq
:
911 (isReadOnly
? MemCmd::ReadCleanReq
: MemCmd::ReadSharedReq
);
913 PacketPtr pkt
= new Packet(cpu_pkt
->req
, cmd
, blkSize
);
915 // if there are sharers in the upper levels, pass that info downstream
916 if (cpu_pkt
->sharedAsserted()) {
917 // note that cpu_pkt may have spent a considerable time in the
918 // MSHR queue and that the information could possibly be out
919 // of date, however, there is no harm in conservatively
920 // assuming the block is shared
922 DPRINTF(Cache
, "%s passing shared from %s to %s addr %#llx size %d\n",
923 __func__
, cpu_pkt
->cmdString(), pkt
->cmdString(),
924 pkt
->getAddr(), pkt
->getSize());
927 // the packet should be block aligned
928 assert(pkt
->getAddr() == blockAlign(pkt
->getAddr()));
931 DPRINTF(Cache
, "%s created %s from %s for addr %#llx size %d\n",
932 __func__
, pkt
->cmdString(), cpu_pkt
->cmdString(), pkt
->getAddr(),
939 Cache::recvAtomic(PacketPtr pkt
)
941 // We are in atomic mode so we pay just for lookupLatency here.
942 Cycles lat
= lookupLatency
;
943 // @TODO: make this a parameter
944 bool last_level_cache
= false;
946 // Forward the request if the system is in cache bypass mode.
947 if (system
->bypassCaches())
948 return ticksToCycles(memSidePort
->sendAtomic(pkt
));
950 promoteWholeLineWrites(pkt
);
952 if (pkt
->memInhibitAsserted()) {
953 // have to invalidate ourselves and any lower caches even if
954 // upper cache will be responding
955 if (pkt
->isInvalidate()) {
956 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), pkt
->isSecure());
957 if (blk
&& blk
->isValid()) {
958 tags
->invalidate(blk
);
960 DPRINTF(Cache
, "rcvd mem-inhibited %s on %#llx (%s):"
962 pkt
->cmdString(), pkt
->getAddr(),
963 pkt
->isSecure() ? "s" : "ns");
965 if (!last_level_cache
) {
966 DPRINTF(Cache
, "forwarding mem-inhibited %s on %#llx (%s)\n",
967 pkt
->cmdString(), pkt
->getAddr(),
968 pkt
->isSecure() ? "s" : "ns");
969 lat
+= ticksToCycles(memSidePort
->sendAtomic(pkt
));
972 DPRINTF(Cache
, "rcvd mem-inhibited %s on %#llx: not responding\n",
973 pkt
->cmdString(), pkt
->getAddr());
976 return lat
* clockPeriod();
979 // should assert here that there are no outstanding MSHRs or
980 // writebacks... that would mean that someone used an atomic
981 // access in timing mode
983 CacheBlk
*blk
= NULL
;
984 PacketList writebacks
;
985 bool satisfied
= access(pkt
, blk
, lat
, writebacks
);
987 // handle writebacks resulting from the access here to ensure they
988 // logically proceed anything happening below
989 doWritebacksAtomic(writebacks
);
994 PacketPtr bus_pkt
= getBusPacket(pkt
, blk
, pkt
->needsExclusive());
996 bool is_forward
= (bus_pkt
== NULL
);
999 // just forwarding the same request to the next level
1000 // no local cache operation involved
1004 DPRINTF(Cache
, "Sending an atomic %s for %#llx (%s)\n",
1005 bus_pkt
->cmdString(), bus_pkt
->getAddr(),
1006 bus_pkt
->isSecure() ? "s" : "ns");
1009 CacheBlk::State old_state
= blk
? blk
->status
: 0;
1012 lat
+= ticksToCycles(memSidePort
->sendAtomic(bus_pkt
));
1014 // We are now dealing with the response handling
1015 DPRINTF(Cache
, "Receive response: %s for addr %#llx (%s) in state %i\n",
1016 bus_pkt
->cmdString(), bus_pkt
->getAddr(),
1017 bus_pkt
->isSecure() ? "s" : "ns",
1020 // If packet was a forward, the response (if any) is already
1021 // in place in the bus_pkt == pkt structure, so we don't need
1022 // to do anything. Otherwise, use the separate bus_pkt to
1023 // generate response to pkt and then delete it.
1025 if (pkt
->needsResponse()) {
1026 assert(bus_pkt
->isResponse());
1027 if (bus_pkt
->isError()) {
1028 pkt
->makeAtomicResponse();
1029 pkt
->copyError(bus_pkt
);
1030 } else if (pkt
->cmd
== MemCmd::InvalidateReq
) {
1032 // invalidate response to a cache that received
1033 // an invalidate request
1034 satisfyCpuSideRequest(pkt
, blk
);
1036 } else if (pkt
->cmd
== MemCmd::WriteLineReq
) {
1037 // note the use of pkt, not bus_pkt here.
1039 // write-line request to the cache that promoted
1040 // the write to a whole line
1041 blk
= handleFill(pkt
, blk
, writebacks
);
1042 satisfyCpuSideRequest(pkt
, blk
);
1043 } else if (bus_pkt
->isRead() ||
1044 bus_pkt
->cmd
== MemCmd::UpgradeResp
) {
1045 // we're updating cache state to allow us to
1046 // satisfy the upstream request from the cache
1047 blk
= handleFill(bus_pkt
, blk
, writebacks
);
1048 satisfyCpuSideRequest(pkt
, blk
);
1050 // we're satisfying the upstream request without
1051 // modifying cache state, e.g., a write-through
1052 pkt
->makeAtomicResponse();
1059 // Note that we don't invoke the prefetcher at all in atomic mode.
1060 // It's not clear how to do it properly, particularly for
1061 // prefetchers that aggressively generate prefetch candidates and
1062 // rely on bandwidth contention to throttle them; these will tend
1063 // to pollute the cache in atomic mode since there is no bandwidth
1064 // contention. If we ever do want to enable prefetching in atomic
1065 // mode, though, this is the place to do it... see timingAccess()
1066 // for an example (though we'd want to issue the prefetch(es)
1067 // immediately rather than calling requestMemSideBus() as we do
1070 // Handle writebacks (from the response handling) if needed
1071 doWritebacksAtomic(writebacks
);
1073 if (pkt
->needsResponse()) {
1074 pkt
->makeAtomicResponse();
1077 return lat
* clockPeriod();
1082 Cache::functionalAccess(PacketPtr pkt
, bool fromCpuSide
)
1084 if (system
->bypassCaches()) {
1085 // Packets from the memory side are snoop request and
1086 // shouldn't happen in bypass mode.
1087 assert(fromCpuSide
);
1089 // The cache should be flushed if we are in cache bypass mode,
1090 // so we don't need to check if we need to update anything.
1091 memSidePort
->sendFunctional(pkt
);
1095 Addr blk_addr
= blockAlign(pkt
->getAddr());
1096 bool is_secure
= pkt
->isSecure();
1097 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), is_secure
);
1098 MSHR
*mshr
= mshrQueue
.findMatch(blk_addr
, is_secure
);
1100 pkt
->pushLabel(name());
1102 CacheBlkPrintWrapper
cbpw(blk
);
1104 // Note that just because an L2/L3 has valid data doesn't mean an
1105 // L1 doesn't have a more up-to-date modified copy that still
1106 // needs to be found. As a result we always update the request if
1107 // we have it, but only declare it satisfied if we are the owner.
1109 // see if we have data at all (owned or otherwise)
1110 bool have_data
= blk
&& blk
->isValid()
1111 && pkt
->checkFunctional(&cbpw
, blk_addr
, is_secure
, blkSize
,
1114 // data we have is dirty if marked as such or if valid & ownership
1115 // pending due to outstanding UpgradeReq
1117 have_data
&& (blk
->isDirty() ||
1118 (mshr
&& mshr
->inService
&& mshr
->isPendingDirty()));
1120 bool done
= have_dirty
1121 || cpuSidePort
->checkFunctional(pkt
)
1122 || mshrQueue
.checkFunctional(pkt
, blk_addr
)
1123 || writeBuffer
.checkFunctional(pkt
, blk_addr
)
1124 || memSidePort
->checkFunctional(pkt
);
1126 DPRINTF(Cache
, "functional %s %#llx (%s) %s%s%s\n",
1127 pkt
->cmdString(), pkt
->getAddr(), is_secure
? "s" : "ns",
1128 (blk
&& blk
->isValid()) ? "valid " : "",
1129 have_data
? "data " : "", done
? "done " : "");
1131 // We're leaving the cache, so pop cache->name() label
1135 pkt
->makeResponse();
1137 // if it came as a request from the CPU side then make sure it
1138 // continues towards the memory side
1140 memSidePort
->sendFunctional(pkt
);
1141 } else if (forwardSnoops
&& cpuSidePort
->isSnooping()) {
1142 // if it came from the memory side, it must be a snoop request
1143 // and we should only forward it if we are forwarding snoops
1144 cpuSidePort
->sendFunctionalSnoop(pkt
);
1150 /////////////////////////////////////////////////////
1152 // Response handling: responses from the memory side
1154 /////////////////////////////////////////////////////
1158 Cache::recvTimingResp(PacketPtr pkt
)
1160 assert(pkt
->isResponse());
1162 // all header delay should be paid for by the crossbar, unless
1163 // this is a prefetch response from above
1164 panic_if(pkt
->headerDelay
!= 0 && pkt
->cmd
!= MemCmd::HardPFResp
,
1165 "%s saw a non-zero packet delay\n", name());
1167 MSHR
*mshr
= dynamic_cast<MSHR
*>(pkt
->senderState
);
1168 bool is_error
= pkt
->isError();
1173 DPRINTF(Cache
, "Cache received packet with error for addr %#llx (%s), "
1174 "cmd: %s\n", pkt
->getAddr(), pkt
->isSecure() ? "s" : "ns",
1178 DPRINTF(Cache
, "Handling response %s for addr %#llx size %d (%s)\n",
1179 pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize(),
1180 pkt
->isSecure() ? "s" : "ns");
1182 MSHRQueue
*mq
= mshr
->queue
;
1183 bool wasFull
= mq
->isFull();
1185 if (mshr
== noTargetMSHR
) {
1186 // we always clear at least one target
1187 clearBlocked(Blocked_NoTargets
);
1188 noTargetMSHR
= NULL
;
1191 // Initial target is used just for stats
1192 MSHR::Target
*initial_tgt
= mshr
->getTarget();
1193 int stats_cmd_idx
= initial_tgt
->pkt
->cmdToIndex();
1194 Tick miss_latency
= curTick() - initial_tgt
->recvTime
;
1195 PacketList writebacks
;
1196 // We need forward_time here because we have a call of
1197 // allocateWriteBuffer() that need this parameter to specify the
1198 // time to request the bus. In this case we use forward latency
1199 // because there is a writeback. We pay also here for headerDelay
1200 // that is charged of bus latencies if the packet comes from the
1202 Tick forward_time
= clockEdge(forwardLatency
) + pkt
->headerDelay
;
1204 if (pkt
->req
->isUncacheable()) {
1205 assert(pkt
->req
->masterId() < system
->maxMasters());
1206 mshr_uncacheable_lat
[stats_cmd_idx
][pkt
->req
->masterId()] +=
1209 assert(pkt
->req
->masterId() < system
->maxMasters());
1210 mshr_miss_latency
[stats_cmd_idx
][pkt
->req
->masterId()] +=
1214 // upgrade deferred targets if we got exclusive
1215 if (!pkt
->sharedAsserted()) {
1216 mshr
->promoteExclusive();
1219 bool is_fill
= !mshr
->isForward
&&
1220 (pkt
->isRead() || pkt
->cmd
== MemCmd::UpgradeResp
);
1222 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), pkt
->isSecure());
1224 if (is_fill
&& !is_error
) {
1225 DPRINTF(Cache
, "Block for addr %#llx being updated in Cache\n",
1228 blk
= handleFill(pkt
, blk
, writebacks
);
1229 assert(blk
!= NULL
);
1232 // allow invalidation responses originating from write-line
1233 // requests to be discarded
1234 bool is_invalidate
= pkt
->isInvalidate();
1236 // First offset for critical word first calculations
1237 int initial_offset
= initial_tgt
->pkt
->getOffset(blkSize
);
1239 while (mshr
->hasTargets()) {
1240 MSHR::Target
*target
= mshr
->getTarget();
1241 Packet
*tgt_pkt
= target
->pkt
;
1243 switch (target
->source
) {
1244 case MSHR::Target::FromCPU
:
1245 Tick completion_time
;
1246 // Here we charge on completion_time the delay of the xbar if the
1247 // packet comes from it, charged on headerDelay.
1248 completion_time
= pkt
->headerDelay
;
1250 // Software prefetch handling for cache closest to core
1251 if (tgt_pkt
->cmd
.isSWPrefetch()) {
1252 // a software prefetch would have already been ack'd immediately
1253 // with dummy data so the core would be able to retire it.
1254 // this request completes right here, so we deallocate it.
1255 delete tgt_pkt
->req
;
1257 break; // skip response
1260 // unlike the other packet flows, where data is found in other
1261 // caches or memory and brought back, write-line requests always
1262 // have the data right away, so the above check for "is fill?"
1263 // cannot actually be determined until examining the stored MSHR
1264 // state. We "catch up" with that logic here, which is duplicated
1266 if (tgt_pkt
->cmd
== MemCmd::WriteLineReq
) {
1268 // we got the block in exclusive state, so promote any
1269 // deferred targets if possible
1270 mshr
->promoteExclusive();
1271 // NB: we use the original packet here and not the response!
1272 blk
= handleFill(tgt_pkt
, blk
, writebacks
);
1273 assert(blk
!= NULL
);
1275 // treat as a fill, and discard the invalidation
1278 is_invalidate
= false;
1282 satisfyCpuSideRequest(tgt_pkt
, blk
,
1283 true, mshr
->hasPostDowngrade());
1285 // How many bytes past the first request is this one
1286 int transfer_offset
=
1287 tgt_pkt
->getOffset(blkSize
) - initial_offset
;
1288 if (transfer_offset
< 0) {
1289 transfer_offset
+= blkSize
;
1292 // If not critical word (offset) return payloadDelay.
1293 // responseLatency is the latency of the return path
1294 // from lower level caches/memory to an upper level cache or
1296 completion_time
+= clockEdge(responseLatency
) +
1297 (transfer_offset
? pkt
->payloadDelay
: 0);
1299 assert(!tgt_pkt
->req
->isUncacheable());
1301 assert(tgt_pkt
->req
->masterId() < system
->maxMasters());
1302 missLatency
[tgt_pkt
->cmdToIndex()][tgt_pkt
->req
->masterId()] +=
1303 completion_time
- target
->recvTime
;
1304 } else if (pkt
->cmd
== MemCmd::UpgradeFailResp
) {
1305 // failed StoreCond upgrade
1306 assert(tgt_pkt
->cmd
== MemCmd::StoreCondReq
||
1307 tgt_pkt
->cmd
== MemCmd::StoreCondFailReq
||
1308 tgt_pkt
->cmd
== MemCmd::SCUpgradeFailReq
);
1309 // responseLatency is the latency of the return path
1310 // from lower level caches/memory to an upper level cache or
1312 completion_time
+= clockEdge(responseLatency
) +
1314 tgt_pkt
->req
->setExtraData(0);
1316 // not a cache fill, just forwarding response
1317 // responseLatency is the latency of the return path
1318 // from lower level cahces/memory to the core.
1319 completion_time
+= clockEdge(responseLatency
) +
1321 if (pkt
->isRead() && !is_error
) {
1323 assert(pkt
->getAddr() == tgt_pkt
->getAddr());
1324 assert(pkt
->getSize() >= tgt_pkt
->getSize());
1326 tgt_pkt
->setData(pkt
->getConstPtr
<uint8_t>());
1329 tgt_pkt
->makeTimingResponse();
1330 // if this packet is an error copy that to the new packet
1332 tgt_pkt
->copyError(pkt
);
1333 if (tgt_pkt
->cmd
== MemCmd::ReadResp
&&
1334 (is_invalidate
|| mshr
->hasPostInvalidate())) {
1335 // If intermediate cache got ReadRespWithInvalidate,
1336 // propagate that. Response should not have
1337 // isInvalidate() set otherwise.
1338 tgt_pkt
->cmd
= MemCmd::ReadRespWithInvalidate
;
1339 DPRINTF(Cache
, "%s updated cmd to %s for addr %#llx\n",
1340 __func__
, tgt_pkt
->cmdString(), tgt_pkt
->getAddr());
1342 // Reset the bus additional time as it is now accounted for
1343 tgt_pkt
->headerDelay
= tgt_pkt
->payloadDelay
= 0;
1344 cpuSidePort
->schedTimingResp(tgt_pkt
, completion_time
);
1347 case MSHR::Target::FromPrefetcher
:
1348 assert(tgt_pkt
->cmd
== MemCmd::HardPFReq
);
1350 blk
->status
|= BlkHWPrefetched
;
1351 delete tgt_pkt
->req
;
1355 case MSHR::Target::FromSnoop
:
1356 // I don't believe that a snoop can be in an error state
1358 // response to snoop request
1359 DPRINTF(Cache
, "processing deferred snoop...\n");
1360 assert(!(is_invalidate
&& !mshr
->hasPostInvalidate()));
1361 handleSnoop(tgt_pkt
, blk
, true, true, mshr
->hasPostInvalidate());
1365 panic("Illegal target->source enum %d\n", target
->source
);
1371 if (blk
&& blk
->isValid()) {
1372 // an invalidate response stemming from a write line request
1373 // should not invalidate the block, so check if the
1374 // invalidation should be discarded
1375 if (is_invalidate
|| mshr
->hasPostInvalidate()) {
1376 assert(blk
!= tempBlock
);
1377 tags
->invalidate(blk
);
1379 } else if (mshr
->hasPostDowngrade()) {
1380 blk
->status
&= ~BlkWritable
;
1384 if (mshr
->promoteDeferredTargets()) {
1385 // avoid later read getting stale data while write miss is
1386 // outstanding.. see comment in timingAccess()
1388 blk
->status
&= ~BlkReadable
;
1391 mq
->markPending(mshr
);
1392 schedMemSideSendEvent(clockEdge() + pkt
->payloadDelay
);
1394 mq
->deallocate(mshr
);
1395 if (wasFull
&& !mq
->isFull()) {
1396 clearBlocked((BlockedCause
)mq
->index
);
1399 // Request the bus for a prefetch if this deallocation freed enough
1400 // MSHRs for a prefetch to take place
1401 if (prefetcher
&& mq
== &mshrQueue
&& mshrQueue
.canPrefetch()) {
1402 Tick next_pf_time
= std::max(prefetcher
->nextPrefetchReadyTime(),
1404 if (next_pf_time
!= MaxTick
)
1405 schedMemSideSendEvent(next_pf_time
);
1408 // reset the xbar additional timinig as it is now accounted for
1409 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
1411 // copy writebacks to write buffer
1412 doWritebacks(writebacks
, forward_time
);
1414 // if we used temp block, check to see if its valid and then clear it out
1415 if (blk
== tempBlock
&& tempBlock
->isValid()) {
1416 // We use forwardLatency here because we are copying
1417 // Writebacks/CleanEvicts to write buffer. It specifies the latency to
1418 // allocate an internal buffer and to schedule an event to the
1420 if (blk
->isDirty()) {
1421 PacketPtr wbPkt
= writebackBlk(blk
);
1422 allocateWriteBuffer(wbPkt
, forward_time
);
1423 // Set BLOCK_CACHED flag if cached above.
1424 if (isCachedAbove(wbPkt
))
1425 wbPkt
->setBlockCached();
1427 PacketPtr wcPkt
= cleanEvictBlk(blk
);
1428 // Check to see if block is cached above. If not allocate
1430 if (isCachedAbove(wcPkt
))
1433 allocateWriteBuffer(wcPkt
, forward_time
);
1438 DPRINTF(Cache
, "Leaving %s with %s for addr %#llx\n", __func__
,
1439 pkt
->cmdString(), pkt
->getAddr());
1444 Cache::writebackBlk(CacheBlk
*blk
)
1446 chatty_assert(!isReadOnly
, "Writeback from read-only cache");
1447 assert(blk
&& blk
->isValid() && blk
->isDirty());
1449 writebacks
[Request::wbMasterId
]++;
1451 Request
*writebackReq
=
1452 new Request(tags
->regenerateBlkAddr(blk
->tag
, blk
->set
), blkSize
, 0,
1453 Request::wbMasterId
);
1454 if (blk
->isSecure())
1455 writebackReq
->setFlags(Request::SECURE
);
1457 writebackReq
->taskId(blk
->task_id
);
1458 blk
->task_id
= ContextSwitchTaskId::Unknown
;
1459 blk
->tickInserted
= curTick();
1461 PacketPtr writeback
= new Packet(writebackReq
, MemCmd::Writeback
);
1462 if (blk
->isWritable()) {
1463 // not asserting shared means we pass the block in modified
1464 // state, mark our own block non-writeable
1465 blk
->status
&= ~BlkWritable
;
1467 // we are in the owned state, tell the receiver
1468 writeback
->assertShared();
1471 writeback
->allocate();
1472 std::memcpy(writeback
->getPtr
<uint8_t>(), blk
->data
, blkSize
);
1474 blk
->status
&= ~BlkDirty
;
1479 Cache::cleanEvictBlk(CacheBlk
*blk
)
1481 assert(blk
&& blk
->isValid() && !blk
->isDirty());
1482 // Creating a zero sized write, a message to the snoop filter
1484 new Request(tags
->regenerateBlkAddr(blk
->tag
, blk
->set
), blkSize
, 0,
1485 Request::wbMasterId
);
1486 if (blk
->isSecure())
1487 req
->setFlags(Request::SECURE
);
1489 req
->taskId(blk
->task_id
);
1490 blk
->task_id
= ContextSwitchTaskId::Unknown
;
1491 blk
->tickInserted
= curTick();
1493 PacketPtr pkt
= new Packet(req
, MemCmd::CleanEvict
);
1495 DPRINTF(Cache
, "%s%s %x Create CleanEvict\n", pkt
->cmdString(),
1496 pkt
->req
->isInstFetch() ? " (ifetch)" : "",
1503 Cache::memWriteback()
1505 CacheBlkVisitorWrapper
visitor(*this, &Cache::writebackVisitor
);
1506 tags
->forEachBlk(visitor
);
1510 Cache::memInvalidate()
1512 CacheBlkVisitorWrapper
visitor(*this, &Cache::invalidateVisitor
);
1513 tags
->forEachBlk(visitor
);
1517 Cache::isDirty() const
1519 CacheBlkIsDirtyVisitor visitor
;
1520 tags
->forEachBlk(visitor
);
1522 return visitor
.isDirty();
1526 Cache::writebackVisitor(CacheBlk
&blk
)
1528 if (blk
.isDirty()) {
1529 assert(blk
.isValid());
1531 Request
request(tags
->regenerateBlkAddr(blk
.tag
, blk
.set
),
1532 blkSize
, 0, Request::funcMasterId
);
1533 request
.taskId(blk
.task_id
);
1535 Packet
packet(&request
, MemCmd::WriteReq
);
1536 packet
.dataStatic(blk
.data
);
1538 memSidePort
->sendFunctional(&packet
);
1540 blk
.status
&= ~BlkDirty
;
1547 Cache::invalidateVisitor(CacheBlk
&blk
)
1551 warn_once("Invalidating dirty cache lines. Expect things to break.\n");
1553 if (blk
.isValid()) {
1554 assert(!blk
.isDirty());
1555 tags
->invalidate(&blk
);
1563 Cache::allocateBlock(Addr addr
, bool is_secure
, PacketList
&writebacks
)
1565 CacheBlk
*blk
= tags
->findVictim(addr
);
1567 // It is valid to return NULL if there is no victim
1571 if (blk
->isValid()) {
1572 Addr repl_addr
= tags
->regenerateBlkAddr(blk
->tag
, blk
->set
);
1573 MSHR
*repl_mshr
= mshrQueue
.findMatch(repl_addr
, blk
->isSecure());
1575 // must be an outstanding upgrade request
1576 // on a block we're about to replace...
1577 assert(!blk
->isWritable() || blk
->isDirty());
1578 assert(repl_mshr
->needsExclusive());
1579 // too hard to replace block with transient state
1580 // allocation failed, block not inserted
1583 DPRINTF(Cache
, "replacement: replacing %#llx (%s) with %#llx (%s): %s\n",
1584 repl_addr
, blk
->isSecure() ? "s" : "ns",
1585 addr
, is_secure
? "s" : "ns",
1586 blk
->isDirty() ? "writeback" : "clean");
1588 // Will send up Writeback/CleanEvict snoops via isCachedAbove
1589 // when pushing this writeback list into the write buffer.
1590 if (blk
->isDirty()) {
1591 // Save writeback packet for handling by caller
1592 writebacks
.push_back(writebackBlk(blk
));
1594 writebacks
.push_back(cleanEvictBlk(blk
));
1603 // Note that the reason we return a list of writebacks rather than
1604 // inserting them directly in the write buffer is that this function
1605 // is called by both atomic and timing-mode accesses, and in atomic
1606 // mode we don't mess with the write buffer (we just perform the
1607 // writebacks atomically once the original request is complete).
1609 Cache::handleFill(PacketPtr pkt
, CacheBlk
*blk
, PacketList
&writebacks
)
1611 assert(pkt
->isResponse() || pkt
->cmd
== MemCmd::WriteLineReq
);
1612 Addr addr
= pkt
->getAddr();
1613 bool is_secure
= pkt
->isSecure();
1615 CacheBlk::State old_state
= blk
? blk
->status
: 0;
1618 // When handling a fill, discard any CleanEvicts for the
1619 // same address in write buffer.
1620 Addr M5_VAR_USED blk_addr
= blockAlign(pkt
->getAddr());
1621 std::vector
<MSHR
*> M5_VAR_USED wbs
;
1622 assert (!writeBuffer
.findMatches(blk_addr
, is_secure
, wbs
));
1625 // better have read new data...
1626 assert(pkt
->hasData());
1628 // only read responses and write-line requests have data;
1629 // note that we don't write the data here for write-line - that
1630 // happens in the subsequent satisfyCpuSideRequest.
1631 assert(pkt
->isRead() || pkt
->cmd
== MemCmd::WriteLineReq
);
1633 // need to do a replacement
1634 blk
= allocateBlock(addr
, is_secure
, writebacks
);
1636 // No replaceable block... just use temporary storage to
1637 // complete the current request and then get rid of it
1638 assert(!tempBlock
->isValid());
1640 tempBlock
->set
= tags
->extractSet(addr
);
1641 tempBlock
->tag
= tags
->extractTag(addr
);
1642 // @todo: set security state as well...
1643 DPRINTF(Cache
, "using temp block for %#llx (%s)\n", addr
,
1644 is_secure
? "s" : "ns");
1646 tags
->insertBlock(pkt
, blk
);
1649 // we should never be overwriting a valid block
1650 assert(!blk
->isValid());
1652 // existing block... probably an upgrade
1653 assert(blk
->tag
== tags
->extractTag(addr
));
1654 // either we're getting new data or the block should already be valid
1655 assert(pkt
->hasData() || blk
->isValid());
1656 // don't clear block status... if block is already dirty we
1657 // don't want to lose that
1661 blk
->status
|= BlkSecure
;
1662 blk
->status
|= BlkValid
| BlkReadable
;
1664 // sanity check for whole-line writes, which should always be
1665 // marked as writable as part of the fill, and then later marked
1666 // dirty as part of satisfyCpuSideRequest
1667 if (pkt
->cmd
== MemCmd::WriteLineReq
) {
1668 assert(!pkt
->sharedAsserted());
1669 // at the moment other caches do not respond to the
1670 // invalidation requests corresponding to a whole-line write
1671 assert(!pkt
->memInhibitAsserted());
1674 if (!pkt
->sharedAsserted()) {
1675 // we could get non-shared responses from memory (rather than
1676 // a cache) even in a read-only cache, note that we set this
1677 // bit even for a read-only cache as we use it to represent
1678 // the exclusive state
1679 blk
->status
|= BlkWritable
;
1681 // If we got this via cache-to-cache transfer (i.e., from a
1682 // cache that was an owner) and took away that owner's copy,
1683 // then we need to write it back. Normally this happens
1684 // anyway as a side effect of getting a copy to write it, but
1685 // there are cases (such as failed store conditionals or
1686 // compare-and-swaps) where we'll demand an exclusive copy but
1687 // end up not writing it.
1688 if (pkt
->memInhibitAsserted()) {
1689 blk
->status
|= BlkDirty
;
1691 chatty_assert(!isReadOnly
, "Should never see dirty snoop response "
1692 "in read-only cache %s\n", name());
1696 DPRINTF(Cache
, "Block addr %#llx (%s) moving from state %x to %s\n",
1697 addr
, is_secure
? "s" : "ns", old_state
, blk
->print());
1699 // if we got new data, copy it in (checking for a read response
1700 // and a response that has data is the same in the end)
1701 if (pkt
->isRead()) {
1703 assert(pkt
->hasData());
1704 assert(pkt
->getSize() == blkSize
);
1706 std::memcpy(blk
->data
, pkt
->getConstPtr
<uint8_t>(), blkSize
);
1708 // We pay for fillLatency here.
1709 blk
->whenReady
= clockEdge() + fillLatency
* clockPeriod() +
1716 /////////////////////////////////////////////////////
1718 // Snoop path: requests coming in from the memory side
1720 /////////////////////////////////////////////////////
1723 Cache::doTimingSupplyResponse(PacketPtr req_pkt
, const uint8_t *blk_data
,
1724 bool already_copied
, bool pending_inval
)
1727 assert(req_pkt
->isRequest());
1728 assert(req_pkt
->needsResponse());
1730 DPRINTF(Cache
, "%s for %s addr %#llx size %d\n", __func__
,
1731 req_pkt
->cmdString(), req_pkt
->getAddr(), req_pkt
->getSize());
1732 // timing-mode snoop responses require a new packet, unless we
1733 // already made a copy...
1734 PacketPtr pkt
= req_pkt
;
1735 if (!already_copied
)
1736 // do not clear flags, and allocate space for data if the
1737 // packet needs it (the only packets that carry data are read
1739 pkt
= new Packet(req_pkt
, false, req_pkt
->isRead());
1741 assert(req_pkt
->req
->isUncacheable() || req_pkt
->isInvalidate() ||
1742 pkt
->sharedAsserted());
1743 pkt
->makeTimingResponse();
1744 if (pkt
->isRead()) {
1745 pkt
->setDataFromBlock(blk_data
, blkSize
);
1747 if (pkt
->cmd
== MemCmd::ReadResp
&& pending_inval
) {
1748 // Assume we defer a response to a read from a far-away cache
1749 // A, then later defer a ReadExcl from a cache B on the same
1750 // bus as us. We'll assert MemInhibit in both cases, but in
1751 // the latter case MemInhibit will keep the invalidation from
1752 // reaching cache A. This special response tells cache A that
1753 // it gets the block to satisfy its read, but must immediately
1755 pkt
->cmd
= MemCmd::ReadRespWithInvalidate
;
1757 // Here we consider forward_time, paying for just forward latency and
1758 // also charging the delay provided by the xbar.
1759 // forward_time is used as send_time in next allocateWriteBuffer().
1760 Tick forward_time
= clockEdge(forwardLatency
) + pkt
->headerDelay
;
1761 // Here we reset the timing of the packet.
1762 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
1763 DPRINTF(Cache
, "%s created response: %s addr %#llx size %d tick: %lu\n",
1764 __func__
, pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize(),
1766 memSidePort
->schedTimingSnoopResp(pkt
, forward_time
, true);
1770 Cache::handleSnoop(PacketPtr pkt
, CacheBlk
*blk
, bool is_timing
,
1771 bool is_deferred
, bool pending_inval
)
1773 DPRINTF(Cache
, "%s for %s addr %#llx size %d\n", __func__
,
1774 pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize());
1775 // deferred snoops can only happen in timing mode
1776 assert(!(is_deferred
&& !is_timing
));
1777 // pending_inval only makes sense on deferred snoops
1778 assert(!(pending_inval
&& !is_deferred
));
1779 assert(pkt
->isRequest());
1781 // the packet may get modified if we or a forwarded snooper
1782 // responds in atomic mode, so remember a few things about the
1783 // original packet up front
1784 bool invalidate
= pkt
->isInvalidate();
1785 bool M5_VAR_USED needs_exclusive
= pkt
->needsExclusive();
1787 uint32_t snoop_delay
= 0;
1789 if (forwardSnoops
) {
1790 // first propagate snoop upward to see if anyone above us wants to
1791 // handle it. save & restore packet src since it will get
1792 // rewritten to be relative to cpu-side bus (if any)
1793 bool alreadyResponded
= pkt
->memInhibitAsserted();
1795 // copy the packet so that we can clear any flags before
1796 // forwarding it upwards, we also allocate data (passing
1797 // the pointer along in case of static data), in case
1798 // there is a snoop hit in upper levels
1799 Packet
snoopPkt(pkt
, true, true);
1800 snoopPkt
.setExpressSnoop();
1801 snoopPkt
.pushSenderState(new ForwardResponseRecord());
1802 // the snoop packet does not need to wait any additional
1804 snoopPkt
.headerDelay
= snoopPkt
.payloadDelay
= 0;
1805 cpuSidePort
->sendTimingSnoopReq(&snoopPkt
);
1807 // add the header delay (including crossbar and snoop
1808 // delays) of the upward snoop to the snoop delay for this
1810 snoop_delay
+= snoopPkt
.headerDelay
;
1812 if (snoopPkt
.memInhibitAsserted()) {
1813 // cache-to-cache response from some upper cache
1814 assert(!alreadyResponded
);
1815 pkt
->assertMemInhibit();
1817 // no cache (or anyone else for that matter) will
1818 // respond, so delete the ForwardResponseRecord here
1819 delete snoopPkt
.popSenderState();
1821 if (snoopPkt
.sharedAsserted()) {
1822 pkt
->assertShared();
1824 // If this request is a prefetch or clean evict and an upper level
1825 // signals block present, make sure to propagate the block
1826 // presence to the requester.
1827 if (snoopPkt
.isBlockCached()) {
1828 pkt
->setBlockCached();
1831 cpuSidePort
->sendAtomicSnoop(pkt
);
1832 if (!alreadyResponded
&& pkt
->memInhibitAsserted()) {
1833 // cache-to-cache response from some upper cache:
1834 // forward response to original requester
1835 assert(pkt
->isResponse());
1840 if (!blk
|| !blk
->isValid()) {
1841 DPRINTF(Cache
, "%s snoop miss for %s addr %#llx size %d\n",
1842 __func__
, pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize());
1845 DPRINTF(Cache
, "%s snoop hit for %s for addr %#llx size %d, "
1846 "old state is %s\n", __func__
, pkt
->cmdString(),
1847 pkt
->getAddr(), pkt
->getSize(), blk
->print());
1850 chatty_assert(!(isReadOnly
&& blk
->isDirty()),
1851 "Should never have a dirty block in a read-only cache %s\n",
1854 // We may end up modifying both the block state and the packet (if
1855 // we respond in atomic mode), so just figure out what to do now
1856 // and then do it later. If we find dirty data while snooping for
1857 // an invalidate, we don't need to send a response. The
1858 // invalidation itself is taken care of below.
1859 bool respond
= blk
->isDirty() && pkt
->needsResponse() &&
1860 pkt
->cmd
!= MemCmd::InvalidateReq
;
1861 bool have_exclusive
= blk
->isWritable();
1863 // Invalidate any prefetch's from below that would strip write permissions
1864 // MemCmd::HardPFReq is only observed by upstream caches. After missing
1865 // above and in it's own cache, a new MemCmd::ReadReq is created that
1866 // downstream caches observe.
1867 if (pkt
->mustCheckAbove()) {
1868 DPRINTF(Cache
, "Found addr %#llx in upper level cache for snoop %s from"
1869 " lower cache\n", pkt
->getAddr(), pkt
->cmdString());
1870 pkt
->setBlockCached();
1874 if (!pkt
->req
->isUncacheable() && pkt
->isRead() && !invalidate
) {
1875 // reading non-exclusive shared data, note that we retain
1876 // the block in owned state if it is dirty, with the response
1877 // taken care of below, and otherwhise simply downgrade to
1879 assert(!needs_exclusive
);
1880 pkt
->assertShared();
1881 blk
->status
&= ~BlkWritable
;
1885 // prevent anyone else from responding, cache as well as
1886 // memory, and also prevent any memory from even seeing the
1887 // request (with current inhibited semantics), note that this
1888 // applies both to reads and writes and that for writes it
1889 // works thanks to the fact that we still have dirty data and
1890 // will write it back at a later point
1891 pkt
->assertMemInhibit();
1892 if (have_exclusive
) {
1893 // in the case of an uncacheable request there is no point
1894 // in setting the exclusive flag, but since the recipient
1895 // does not care there is no harm in doing so, in any case
1896 // it is just a hint
1897 pkt
->setSupplyExclusive();
1900 doTimingSupplyResponse(pkt
, blk
->data
, is_deferred
, pending_inval
);
1902 pkt
->makeAtomicResponse();
1903 pkt
->setDataFromBlock(blk
->data
, blkSize
);
1907 if (!respond
&& is_timing
&& is_deferred
) {
1908 // if it's a deferred timing snoop then we've made a copy of
1909 // both the request and the packet, and so if we're not using
1910 // those copies to respond and delete them here
1911 DPRINTF(Cache
, "Deleting pkt %p and request %p for cmd %s addr: %p\n",
1912 pkt
, pkt
->req
, pkt
->cmdString(), pkt
->getAddr());
1914 // the packets needs a response (just not from us), so we also
1915 // need to delete the request and not rely on the packet
1917 assert(pkt
->needsResponse());
1922 // Do this last in case it deallocates block data or something
1925 if (blk
!= tempBlock
)
1926 tags
->invalidate(blk
);
1930 DPRINTF(Cache
, "new state is %s\n", blk
->print());
1937 Cache::recvTimingSnoopReq(PacketPtr pkt
)
1939 DPRINTF(Cache
, "%s for %s addr %#llx size %d\n", __func__
,
1940 pkt
->cmdString(), pkt
->getAddr(), pkt
->getSize());
1942 // Snoops shouldn't happen when bypassing caches
1943 assert(!system
->bypassCaches());
1945 // no need to snoop requests that are not in range
1946 if (!inRange(pkt
->getAddr())) {
1950 bool is_secure
= pkt
->isSecure();
1951 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), is_secure
);
1953 Addr blk_addr
= blockAlign(pkt
->getAddr());
1954 MSHR
*mshr
= mshrQueue
.findMatch(blk_addr
, is_secure
);
1956 // Update the latency cost of the snoop so that the crossbar can
1957 // account for it. Do not overwrite what other neighbouring caches
1958 // have already done, rather take the maximum. The update is
1959 // tentative, for cases where we return before an upward snoop
1961 pkt
->snoopDelay
= std::max
<uint32_t>(pkt
->snoopDelay
,
1962 lookupLatency
* clockPeriod());
1964 // Inform request(Prefetch, CleanEvict or Writeback) from below of
1965 // MSHR hit, set setBlockCached.
1966 if (mshr
&& pkt
->mustCheckAbove()) {
1967 DPRINTF(Cache
, "Setting block cached for %s from"
1968 "lower cache on mshr hit %#x\n",
1969 pkt
->cmdString(), pkt
->getAddr());
1970 pkt
->setBlockCached();
1974 // Let the MSHR itself track the snoop and decide whether we want
1975 // to go ahead and do the regular cache snoop
1976 if (mshr
&& mshr
->handleSnoop(pkt
, order
++)) {
1977 DPRINTF(Cache
, "Deferring snoop on in-service MSHR to blk %#llx (%s)."
1978 "mshrs: %s\n", blk_addr
, is_secure
? "s" : "ns",
1981 if (mshr
->getNumTargets() > numTarget
)
1982 warn("allocating bonus target for snoop"); //handle later
1986 //We also need to check the writeback buffers and handle those
1987 std::vector
<MSHR
*> writebacks
;
1988 if (writeBuffer
.findMatches(blk_addr
, is_secure
, writebacks
)) {
1989 DPRINTF(Cache
, "Snoop hit in writeback to addr %#llx (%s)\n",
1990 pkt
->getAddr(), is_secure
? "s" : "ns");
1992 // Look through writebacks for any cachable writes.
1993 // We should only ever find a single match
1994 assert(writebacks
.size() == 1);
1995 MSHR
*wb_entry
= writebacks
[0];
1996 // Expect to see only Writebacks and/or CleanEvicts here, both of
1997 // which should not be generated for uncacheable data.
1998 assert(!wb_entry
->isUncacheable());
1999 // There should only be a single request responsible for generating
2000 // Writebacks/CleanEvicts.
2001 assert(wb_entry
->getNumTargets() == 1);
2002 PacketPtr wb_pkt
= wb_entry
->getTarget()->pkt
;
2003 assert(wb_pkt
->evictingBlock());
2005 if (pkt
->evictingBlock()) {
2006 // if the block is found in the write queue, set the BLOCK_CACHED
2007 // flag for Writeback/CleanEvict snoop. On return the snoop will
2008 // propagate the BLOCK_CACHED flag in Writeback packets and prevent
2009 // any CleanEvicts from travelling down the memory hierarchy.
2010 pkt
->setBlockCached();
2011 DPRINTF(Cache
, "Squashing %s from lower cache on writequeue hit"
2012 " %#x\n", pkt
->cmdString(), pkt
->getAddr());
2016 if (wb_pkt
->cmd
== MemCmd::Writeback
) {
2017 assert(!pkt
->memInhibitAsserted());
2018 pkt
->assertMemInhibit();
2019 if (!pkt
->needsExclusive()) {
2020 pkt
->assertShared();
2021 // the writeback is no longer passing exclusivity (the
2022 // receiving cache should consider the block owned
2023 // rather than modified)
2024 wb_pkt
->assertShared();
2026 // if we're not asserting the shared line, we need to
2027 // invalidate our copy. we'll do that below as long as
2028 // the packet's invalidate flag is set...
2029 assert(pkt
->isInvalidate());
2031 doTimingSupplyResponse(pkt
, wb_pkt
->getConstPtr
<uint8_t>(),
2034 assert(wb_pkt
->cmd
== MemCmd::CleanEvict
);
2035 // The cache technically holds the block until the
2036 // corresponding CleanEvict message reaches the crossbar
2037 // below. Therefore when a snoop encounters a CleanEvict
2038 // message we must set assertShared (just like when it
2039 // encounters a Writeback) to avoid the snoop filter
2040 // prematurely clearing the holder bit in the crossbar
2042 if (!pkt
->needsExclusive())
2043 pkt
->assertShared();
2045 assert(pkt
->isInvalidate());
2048 if (pkt
->isInvalidate()) {
2049 // Invalidation trumps our writeback... discard here
2050 // Note: markInService will remove entry from writeback buffer.
2051 markInService(wb_entry
, false);
2056 // If this was a shared writeback, there may still be
2057 // other shared copies above that require invalidation.
2058 // We could be more selective and return here if the
2059 // request is non-exclusive or if the writeback is
2061 uint32_t snoop_delay
= handleSnoop(pkt
, blk
, true, false, false);
2063 // Override what we did when we first saw the snoop, as we now
2064 // also have the cost of the upwards snoops to account for
2065 pkt
->snoopDelay
= std::max
<uint32_t>(pkt
->snoopDelay
, snoop_delay
+
2066 lookupLatency
* clockPeriod());
2070 Cache::CpuSidePort::recvTimingSnoopResp(PacketPtr pkt
)
2072 // Express snoop responses from master to slave, e.g., from L1 to L2
2073 cache
->recvTimingSnoopResp(pkt
);
2078 Cache::recvAtomicSnoop(PacketPtr pkt
)
2080 // Snoops shouldn't happen when bypassing caches
2081 assert(!system
->bypassCaches());
2083 // no need to snoop requests that are not in range.
2084 if (!inRange(pkt
->getAddr())) {
2088 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), pkt
->isSecure());
2089 uint32_t snoop_delay
= handleSnoop(pkt
, blk
, false, false, false);
2090 return snoop_delay
+ lookupLatency
* clockPeriod();
2095 Cache::getNextMSHR()
2097 // Check both MSHR queue and write buffer for potential requests,
2098 // note that null does not mean there is no request, it could
2099 // simply be that it is not ready
2100 MSHR
*miss_mshr
= mshrQueue
.getNextMSHR();
2101 MSHR
*write_mshr
= writeBuffer
.getNextMSHR();
2103 // If we got a write buffer request ready, first priority is a
2104 // full write buffer, otherwhise we favour the miss requests
2106 ((writeBuffer
.isFull() && writeBuffer
.inServiceEntries
== 0) ||
2108 // need to search MSHR queue for conflicting earlier miss.
2109 MSHR
*conflict_mshr
=
2110 mshrQueue
.findPending(write_mshr
->blkAddr
,
2111 write_mshr
->isSecure
);
2113 if (conflict_mshr
&& conflict_mshr
->order
< write_mshr
->order
) {
2114 // Service misses in order until conflict is cleared.
2115 return conflict_mshr
;
2117 // @todo Note that we ignore the ready time of the conflict here
2120 // No conflicts; issue write
2122 } else if (miss_mshr
) {
2123 // need to check for conflicting earlier writeback
2124 MSHR
*conflict_mshr
=
2125 writeBuffer
.findPending(miss_mshr
->blkAddr
,
2126 miss_mshr
->isSecure
);
2127 if (conflict_mshr
) {
2128 // not sure why we don't check order here... it was in the
2129 // original code but commented out.
2131 // The only way this happens is if we are
2132 // doing a write and we didn't have permissions
2133 // then subsequently saw a writeback (owned got evicted)
2134 // We need to make sure to perform the writeback first
2135 // To preserve the dirty data, then we can issue the write
2137 // should we return write_mshr here instead? I.e. do we
2138 // have to flush writes in order? I don't think so... not
2139 // for Alpha anyway. Maybe for x86?
2140 return conflict_mshr
;
2142 // @todo Note that we ignore the ready time of the conflict here
2145 // No conflicts; issue read
2149 // fall through... no pending requests. Try a prefetch.
2150 assert(!miss_mshr
&& !write_mshr
);
2151 if (prefetcher
&& mshrQueue
.canPrefetch()) {
2152 // If we have a miss queue slot, we can try a prefetch
2153 PacketPtr pkt
= prefetcher
->getPacket();
2155 Addr pf_addr
= blockAlign(pkt
->getAddr());
2156 if (!tags
->findBlock(pf_addr
, pkt
->isSecure()) &&
2157 !mshrQueue
.findMatch(pf_addr
, pkt
->isSecure()) &&
2158 !writeBuffer
.findMatch(pf_addr
, pkt
->isSecure())) {
2159 // Update statistic on number of prefetches issued
2160 // (hwpf_mshr_misses)
2161 assert(pkt
->req
->masterId() < system
->maxMasters());
2162 mshr_misses
[pkt
->cmdToIndex()][pkt
->req
->masterId()]++;
2164 // allocate an MSHR and return it, note
2165 // that we send the packet straight away, so do not
2166 // schedule the send
2167 return allocateMissBuffer(pkt
, curTick(), false);
2169 // free the request and packet
2180 Cache::isCachedAbove(PacketPtr pkt
, bool is_timing
) const
2184 // Mirroring the flow of HardPFReqs, the cache sends CleanEvict and
2185 // Writeback snoops into upper level caches to check for copies of the
2186 // same block. Using the BLOCK_CACHED flag with the Writeback/CleanEvict
2187 // packet, the cache can inform the crossbar below of presence or absence
2190 Packet
snoop_pkt(pkt
, true, false);
2191 snoop_pkt
.setExpressSnoop();
2192 // Assert that packet is either Writeback or CleanEvict and not a
2193 // prefetch request because prefetch requests need an MSHR and may
2194 // generate a snoop response.
2195 assert(pkt
->evictingBlock());
2196 snoop_pkt
.senderState
= NULL
;
2197 cpuSidePort
->sendTimingSnoopReq(&snoop_pkt
);
2198 // Writeback/CleanEvict snoops do not generate a snoop response.
2199 assert(!(snoop_pkt
.memInhibitAsserted()));
2200 return snoop_pkt
.isBlockCached();
2202 cpuSidePort
->sendAtomicSnoop(pkt
);
2203 return pkt
->isBlockCached();
2208 Cache::getTimingPacket()
2210 MSHR
*mshr
= getNextMSHR();
2216 // use request from 1st target
2217 PacketPtr tgt_pkt
= mshr
->getTarget()->pkt
;
2218 PacketPtr pkt
= NULL
;
2220 DPRINTF(CachePort
, "%s %s for addr %#llx size %d\n", __func__
,
2221 tgt_pkt
->cmdString(), tgt_pkt
->getAddr(), tgt_pkt
->getSize());
2223 CacheBlk
*blk
= tags
->findBlock(mshr
->blkAddr
, mshr
->isSecure
);
2225 if (tgt_pkt
->cmd
== MemCmd::HardPFReq
&& forwardSnoops
) {
2226 // We need to check the caches above us to verify that
2227 // they don't have a copy of this block in the dirty state
2228 // at the moment. Without this check we could get a stale
2229 // copy from memory that might get used in place of the
2231 Packet
snoop_pkt(tgt_pkt
, true, false);
2232 snoop_pkt
.setExpressSnoop();
2233 snoop_pkt
.senderState
= mshr
;
2234 cpuSidePort
->sendTimingSnoopReq(&snoop_pkt
);
2236 // Check to see if the prefetch was squashed by an upper cache (to
2237 // prevent us from grabbing the line) or if a Check to see if a
2238 // writeback arrived between the time the prefetch was placed in
2239 // the MSHRs and when it was selected to be sent or if the
2240 // prefetch was squashed by an upper cache.
2242 // It is important to check memInhibitAsserted before
2243 // prefetchSquashed. If another cache has asserted MEM_INGIBIT, it
2244 // will be sending a response which will arrive at the MSHR
2245 // allocated ofr this request. Checking the prefetchSquash first
2246 // may result in the MSHR being prematurely deallocated.
2248 if (snoop_pkt
.memInhibitAsserted()) {
2249 // If we are getting a non-shared response it is dirty
2250 bool pending_dirty_resp
= !snoop_pkt
.sharedAsserted();
2251 markInService(mshr
, pending_dirty_resp
);
2252 DPRINTF(Cache
, "Upward snoop of prefetch for addr"
2254 tgt_pkt
->getAddr(), tgt_pkt
->isSecure()? "s": "ns");
2258 if (snoop_pkt
.isBlockCached() || blk
!= NULL
) {
2259 DPRINTF(Cache
, "Block present, prefetch squashed by cache. "
2260 "Deallocating mshr target %#x.\n",
2263 // Deallocate the mshr target
2264 if (tgt_pkt
->cmd
!= MemCmd::Writeback
) {
2265 if (mshr
->queue
->forceDeallocateTarget(mshr
)) {
2266 // Clear block if this deallocation resulted freed an
2267 // mshr when all had previously been utilized
2268 clearBlocked((BlockedCause
)(mshr
->queue
->index
));
2272 // If this is a Writeback, and the snoops indicate that the blk
2273 // is cached above, set the BLOCK_CACHED flag in the Writeback
2274 // packet, so that it does not reset the bits corresponding to
2275 // this block in the snoop filter below.
2276 tgt_pkt
->setBlockCached();
2281 if (mshr
->isForwardNoResponse()) {
2282 // no response expected, just forward packet as it is
2283 assert(tags
->findBlock(mshr
->blkAddr
, mshr
->isSecure
) == NULL
);
2286 pkt
= getBusPacket(tgt_pkt
, blk
, mshr
->needsExclusive());
2288 mshr
->isForward
= (pkt
== NULL
);
2290 if (mshr
->isForward
) {
2291 // not a cache block request, but a response is expected
2292 // make copy of current packet to forward, keep current
2293 // copy for response handling
2294 pkt
= new Packet(tgt_pkt
, false, true);
2295 if (pkt
->isWrite()) {
2296 pkt
->setData(tgt_pkt
->getConstPtr
<uint8_t>());
2301 assert(pkt
!= NULL
);
2302 pkt
->senderState
= mshr
;
2308 Cache::nextMSHRReadyTime() const
2310 Tick nextReady
= std::min(mshrQueue
.nextMSHRReadyTime(),
2311 writeBuffer
.nextMSHRReadyTime());
2313 // Don't signal prefetch ready time if no MSHRs available
2314 // Will signal once enoguh MSHRs are deallocated
2315 if (prefetcher
&& mshrQueue
.canPrefetch()) {
2316 nextReady
= std::min(nextReady
,
2317 prefetcher
->nextPrefetchReadyTime());
2324 Cache::serialize(CheckpointOut
&cp
) const
2326 bool dirty(isDirty());
2329 warn("*** The cache still contains dirty data. ***\n");
2330 warn(" Make sure to drain the system using the correct flags.\n");
2331 warn(" This checkpoint will not restore correctly and dirty data in "
2332 "the cache will be lost!\n");
2335 // Since we don't checkpoint the data in the cache, any dirty data
2336 // will be lost when restoring from a checkpoint of a system that
2337 // wasn't drained properly. Flag the checkpoint as invalid if the
2338 // cache contains dirty data.
2339 bool bad_checkpoint(dirty
);
2340 SERIALIZE_SCALAR(bad_checkpoint
);
2344 Cache::unserialize(CheckpointIn
&cp
)
2346 bool bad_checkpoint
;
2347 UNSERIALIZE_SCALAR(bad_checkpoint
);
2348 if (bad_checkpoint
) {
2349 fatal("Restoring from checkpoints with dirty caches is not supported "
2350 "in the classic memory system. Please remove any caches or "
2351 " drain them properly before taking checkpoints.\n");
2362 Cache::CpuSidePort::getAddrRanges() const
2364 return cache
->getAddrRanges();
2368 Cache::CpuSidePort::recvTimingReq(PacketPtr pkt
)
2370 assert(!cache
->system
->bypassCaches());
2372 bool success
= false;
2374 // always let inhibited requests through, even if blocked,
2375 // ultimately we should check if this is an express snoop, but at
2376 // the moment that flag is only set in the cache itself
2377 if (pkt
->memInhibitAsserted()) {
2378 // do not change the current retry state
2379 bool M5_VAR_USED bypass_success
= cache
->recvTimingReq(pkt
);
2380 assert(bypass_success
);
2382 } else if (blocked
|| mustSendRetry
) {
2383 // either already committed to send a retry, or blocked
2386 // pass it on to the cache, and let the cache decide if we
2387 // have to retry or not
2388 success
= cache
->recvTimingReq(pkt
);
2391 // remember if we have to retry
2392 mustSendRetry
= !success
;
2397 Cache::CpuSidePort::recvAtomic(PacketPtr pkt
)
2399 return cache
->recvAtomic(pkt
);
2403 Cache::CpuSidePort::recvFunctional(PacketPtr pkt
)
2405 // functional request
2406 cache
->functionalAccess(pkt
, true);
2410 CpuSidePort::CpuSidePort(const std::string
&_name
, Cache
*_cache
,
2411 const std::string
&_label
)
2412 : BaseCache::CacheSlavePort(_name
, _cache
, _label
), cache(_cache
)
2417 CacheParams::create()
2421 return new Cache(this);
2430 Cache::MemSidePort::recvTimingResp(PacketPtr pkt
)
2432 cache
->recvTimingResp(pkt
);
2436 // Express snooping requests to memside port
2438 Cache::MemSidePort::recvTimingSnoopReq(PacketPtr pkt
)
2440 // handle snooping requests
2441 cache
->recvTimingSnoopReq(pkt
);
2445 Cache::MemSidePort::recvAtomicSnoop(PacketPtr pkt
)
2447 return cache
->recvAtomicSnoop(pkt
);
2451 Cache::MemSidePort::recvFunctionalSnoop(PacketPtr pkt
)
2453 // functional snoop (note that in contrast to atomic we don't have
2454 // a specific functionalSnoop method, as they have the same
2455 // behaviour regardless)
2456 cache
->functionalAccess(pkt
, false);
2460 Cache::CacheReqPacketQueue::sendDeferredPacket()
2463 assert(!waitingOnRetry
);
2465 // there should never be any deferred request packets in the
2466 // queue, instead we resly on the cache to provide the packets
2467 // from the MSHR queue or write queue
2468 assert(deferredPacketReadyTime() == MaxTick
);
2470 // check for request packets (requests & writebacks)
2471 PacketPtr pkt
= cache
.getTimingPacket();
2473 // can happen if e.g. we attempt a writeback and fail, but
2474 // before the retry, the writeback is eliminated because
2475 // we snoop another cache's ReadEx.
2477 MSHR
*mshr
= dynamic_cast<MSHR
*>(pkt
->senderState
);
2478 // in most cases getTimingPacket allocates a new packet, and
2479 // we must delete it unless it is successfully sent
2480 bool delete_pkt
= !mshr
->isForwardNoResponse();
2482 // let our snoop responses go first if there are responses to
2483 // the same addresses we are about to writeback, note that
2484 // this creates a dependency between requests and snoop
2485 // responses, but that should not be a problem since there is
2486 // a chain already and the key is that the snoop responses can
2487 // sink unconditionally
2488 if (snoopRespQueue
.hasAddr(pkt
->getAddr())) {
2489 DPRINTF(CachePort
, "Waiting for snoop response to be sent\n");
2490 Tick when
= snoopRespQueue
.deferredPacketReadyTime();
2491 schedSendEvent(when
);
2500 waitingOnRetry
= !masterPort
.sendTimingReq(pkt
);
2502 if (waitingOnRetry
) {
2503 DPRINTF(CachePort
, "now waiting on a retry\n");
2505 // we are awaiting a retry, but we
2506 // delete the packet and will be creating a new packet
2507 // when we get the opportunity
2510 // note that we have now masked any requestBus and
2511 // schedSendEvent (we will wait for a retry before
2512 // doing anything), and this is so even if we do not
2513 // care about this packet and might override it before
2516 // As part of the call to sendTimingReq the packet is
2517 // forwarded to all neighbouring caches (and any
2518 // caches above them) as a snoop. The packet is also
2519 // sent to any potential cache below as the
2520 // interconnect is not allowed to buffer the
2521 // packet. Thus at this point we know if any of the
2522 // neighbouring, or the downstream cache is
2523 // responding, and if so, if it is with a dirty line
2525 bool pending_dirty_resp
= !pkt
->sharedAsserted() &&
2526 pkt
->memInhibitAsserted();
2528 cache
.markInService(mshr
, pending_dirty_resp
);
2532 // if we succeeded and are not waiting for a retry, schedule the
2533 // next send considering when the next MSHR is ready, note that
2534 // snoop responses have their own packet queue and thus schedule
2536 if (!waitingOnRetry
) {
2537 schedSendEvent(cache
.nextMSHRReadyTime());
2542 MemSidePort::MemSidePort(const std::string
&_name
, Cache
*_cache
,
2543 const std::string
&_label
)
2544 : BaseCache::CacheMasterPort(_name
, _cache
, _reqQueue
, _snoopRespQueue
),
2545 _reqQueue(*_cache
, *this, _snoopRespQueue
, _label
),
2546 _snoopRespQueue(*_cache
, *this, _label
), cache(_cache
)