2 * Copyright (c) 2012-2013, 2018-2019 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) 2003-2005 The Regents of The University of Michigan
15 * All rights reserved.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions are
19 * met: redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer;
21 * redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution;
24 * neither the name of the copyright holders nor the names of its
25 * contributors may be used to endorse or promote products derived from
26 * this software without specific prior written permission.
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43 * Definition of BaseCache functions.
46 #include "mem/cache/base.hh"
48 #include "base/compiler.hh"
49 #include "base/logging.hh"
50 #include "debug/Cache.hh"
51 #include "debug/CacheComp.hh"
52 #include "debug/CachePort.hh"
53 #include "debug/CacheRepl.hh"
54 #include "debug/CacheVerbose.hh"
55 #include "mem/cache/compressors/base.hh"
56 #include "mem/cache/mshr.hh"
57 #include "mem/cache/prefetch/base.hh"
58 #include "mem/cache/queue_entry.hh"
59 #include "mem/cache/tags/super_blk.hh"
60 #include "params/BaseCache.hh"
61 #include "params/WriteAllocator.hh"
62 #include "sim/core.hh"
66 BaseCache::CacheSlavePort::CacheSlavePort(const std::string
&_name
,
68 const std::string
&_label
)
69 : QueuedSlavePort(_name
, _cache
, queue
),
70 queue(*_cache
, *this, true, _label
),
71 blocked(false), mustSendRetry(false),
72 sendRetryEvent([this]{ processSendRetry(); }, _name
)
76 BaseCache::BaseCache(const BaseCacheParams
*p
, unsigned blk_size
)
78 cpuSidePort (p
->name
+ ".cpu_side", this, "CpuSidePort"),
79 memSidePort(p
->name
+ ".mem_side", this, "MemSidePort"),
80 mshrQueue("MSHRs", p
->mshrs
, 0, p
->demand_mshr_reserve
), // see below
81 writeBuffer("write buffer", p
->write_buffers
, p
->mshrs
), // see below
83 compressor(p
->compressor
),
84 prefetcher(p
->prefetcher
),
85 writeAllocator(p
->write_allocator
),
86 writebackClean(p
->writeback_clean
),
87 tempBlockWriteback(nullptr),
88 writebackTempBlockAtomicEvent([this]{ writebackTempBlockAtomic(); },
90 EventBase::Delayed_Writeback_Pri
),
92 lookupLatency(p
->tag_latency
),
93 dataLatency(p
->data_latency
),
94 forwardLatency(p
->tag_latency
),
95 fillLatency(p
->data_latency
),
96 responseLatency(p
->response_latency
),
97 sequentialAccess(p
->sequential_access
),
98 numTarget(p
->tgts_per_mshr
),
100 clusivity(p
->clusivity
),
101 isReadOnly(p
->is_read_only
),
104 noTargetMSHR(nullptr),
105 missCount(p
->max_miss_count
),
106 addrRanges(p
->addr_ranges
.begin(), p
->addr_ranges
.end()),
110 // the MSHR queue has no reserve entries as we check the MSHR
111 // queue on every single allocation, whereas the write queue has
112 // as many reserve entries as we have MSHRs, since every MSHR may
113 // eventually require a writeback, and we do not check the write
114 // buffer before committing to an MSHR
116 // forward snoops is overridden in init() once we can query
117 // whether the connected master is actually snooping or not
119 tempBlock
= new TempCacheBlk(blkSize
);
123 prefetcher
->setCache(this);
126 BaseCache::~BaseCache()
132 BaseCache::CacheSlavePort::setBlocked()
135 DPRINTF(CachePort
, "Port is blocking new requests\n");
137 // if we already scheduled a retry in this cycle, but it has not yet
138 // happened, cancel it
139 if (sendRetryEvent
.scheduled()) {
140 owner
.deschedule(sendRetryEvent
);
141 DPRINTF(CachePort
, "Port descheduled retry\n");
142 mustSendRetry
= true;
147 BaseCache::CacheSlavePort::clearBlocked()
150 DPRINTF(CachePort
, "Port is accepting new requests\n");
153 // @TODO: need to find a better time (next cycle?)
154 owner
.schedule(sendRetryEvent
, curTick() + 1);
159 BaseCache::CacheSlavePort::processSendRetry()
161 DPRINTF(CachePort
, "Port is sending retry\n");
163 // reset the flag and call retry
164 mustSendRetry
= false;
169 BaseCache::regenerateBlkAddr(CacheBlk
* blk
)
171 if (blk
!= tempBlock
) {
172 return tags
->regenerateBlkAddr(blk
);
174 return tempBlock
->getAddr();
181 if (!cpuSidePort
.isConnected() || !memSidePort
.isConnected())
182 fatal("Cache ports on %s are not connected\n", name());
183 cpuSidePort
.sendRangeChange();
184 forwardSnoops
= cpuSidePort
.isSnooping();
188 BaseCache::getPort(const std::string
&if_name
, PortID idx
)
190 if (if_name
== "mem_side") {
192 } else if (if_name
== "cpu_side") {
195 return ClockedObject::getPort(if_name
, idx
);
200 BaseCache::inRange(Addr addr
) const
202 for (const auto& r
: addrRanges
) {
203 if (r
.contains(addr
)) {
211 BaseCache::handleTimingReqHit(PacketPtr pkt
, CacheBlk
*blk
, Tick request_time
)
213 if (pkt
->needsResponse()) {
214 // These delays should have been consumed by now
215 assert(pkt
->headerDelay
== 0);
216 assert(pkt
->payloadDelay
== 0);
218 pkt
->makeTimingResponse();
220 // In this case we are considering request_time that takes
221 // into account the delay of the xbar, if any, and just
222 // lat, neglecting responseLatency, modelling hit latency
223 // just as the value of lat overriden by access(), which calls
224 // the calculateAccessLatency() function.
225 cpuSidePort
.schedTimingResp(pkt
, request_time
);
227 DPRINTF(Cache
, "%s satisfied %s, no response needed\n", __func__
,
230 // queue the packet for deletion, as the sending cache is
231 // still relying on it; if the block is found in access(),
232 // CleanEvict and Writeback messages will be deleted
234 pendingDelete
.reset(pkt
);
239 BaseCache::handleTimingReqMiss(PacketPtr pkt
, MSHR
*mshr
, CacheBlk
*blk
,
240 Tick forward_time
, Tick request_time
)
242 if (writeAllocator
&&
243 pkt
&& pkt
->isWrite() && !pkt
->req
->isUncacheable()) {
244 writeAllocator
->updateMode(pkt
->getAddr(), pkt
->getSize(),
245 pkt
->getBlockAddr(blkSize
));
250 /// @note writebacks will be checked in getNextMSHR()
251 /// for any conflicting requests to the same block
253 //@todo remove hw_pf here
255 // Coalesce unless it was a software prefetch (see above).
257 assert(!pkt
->isWriteback());
258 // CleanEvicts corresponding to blocks which have
259 // outstanding requests in MSHRs are simply sunk here
260 if (pkt
->cmd
== MemCmd::CleanEvict
) {
261 pendingDelete
.reset(pkt
);
262 } else if (pkt
->cmd
== MemCmd::WriteClean
) {
263 // A WriteClean should never coalesce with any
264 // outstanding cache maintenance requests.
266 // We use forward_time here because there is an
267 // uncached memory write, forwarded to WriteBuffer.
268 allocateWriteBuffer(pkt
, forward_time
);
270 DPRINTF(Cache
, "%s coalescing MSHR for %s\n", __func__
,
273 assert(pkt
->req
->masterId() < system
->maxMasters());
274 stats
.cmdStats(pkt
).mshr_hits
[pkt
->req
->masterId()]++;
276 // We use forward_time here because it is the same
277 // considering new targets. We have multiple
278 // requests for the same address here. It
279 // specifies the latency to allocate an internal
280 // buffer and to schedule an event to the queued
281 // port and also takes into account the additional
282 // delay of the xbar.
283 mshr
->allocateTarget(pkt
, forward_time
, order
++,
284 allocOnFill(pkt
->cmd
));
285 if (mshr
->getNumTargets() == numTarget
) {
287 setBlocked(Blocked_NoTargets
);
288 // need to be careful with this... if this mshr isn't
289 // ready yet (i.e. time > curTick()), we don't want to
290 // move it ahead of mshrs that are ready
291 // mshrQueue.moveToFront(mshr);
297 assert(pkt
->req
->masterId() < system
->maxMasters());
298 stats
.cmdStats(pkt
).mshr_misses
[pkt
->req
->masterId()]++;
300 if (pkt
->isEviction() || pkt
->cmd
== MemCmd::WriteClean
) {
301 // We use forward_time here because there is an
302 // writeback or writeclean, forwarded to WriteBuffer.
303 allocateWriteBuffer(pkt
, forward_time
);
305 if (blk
&& blk
->isValid()) {
306 // If we have a write miss to a valid block, we
307 // need to mark the block non-readable. Otherwise
308 // if we allow reads while there's an outstanding
309 // write miss, the read could return stale data
310 // out of the cache block... a more aggressive
311 // system could detect the overlap (if any) and
312 // forward data out of the MSHRs, but we don't do
313 // that yet. Note that we do need to leave the
314 // block valid so that it stays in the cache, in
315 // case we get an upgrade response (and hence no
316 // new data) when the write miss completes.
317 // As long as CPUs do proper store/load forwarding
318 // internally, and have a sufficiently weak memory
319 // model, this is probably unnecessary, but at some
320 // point it must have seemed like we needed it...
321 assert((pkt
->needsWritable() && !blk
->isWritable()) ||
322 pkt
->req
->isCacheMaintenance());
323 blk
->status
&= ~BlkReadable
;
325 // Here we are using forward_time, modelling the latency of
326 // a miss (outbound) just as forwardLatency, neglecting the
327 // lookupLatency component.
328 allocateMissBuffer(pkt
, forward_time
);
334 BaseCache::recvTimingReq(PacketPtr pkt
)
336 // anything that is merely forwarded pays for the forward latency and
337 // the delay provided by the crossbar
338 Tick forward_time
= clockEdge(forwardLatency
) + pkt
->headerDelay
;
341 CacheBlk
*blk
= nullptr;
342 bool satisfied
= false;
344 PacketList writebacks
;
345 // Note that lat is passed by reference here. The function
346 // access() will set the lat value.
347 satisfied
= access(pkt
, blk
, lat
, writebacks
);
349 // After the evicted blocks are selected, they must be forwarded
350 // to the write buffer to ensure they logically precede anything
352 doWritebacks(writebacks
, clockEdge(lat
+ forwardLatency
));
355 // Here we charge the headerDelay that takes into account the latencies
356 // of the bus, if the packet comes from it.
357 // The latency charged is just the value set by the access() function.
358 // In case of a hit we are neglecting response latency.
359 // In case of a miss we are neglecting forward latency.
360 Tick request_time
= clockEdge(lat
);
361 // Here we reset the timing of the packet.
362 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
365 // notify before anything else as later handleTimingReqHit might turn
366 // the packet in a response
369 if (prefetcher
&& blk
&& blk
->wasPrefetched()) {
370 blk
->status
&= ~BlkHWPrefetched
;
373 handleTimingReqHit(pkt
, blk
, request_time
);
375 handleTimingReqMiss(pkt
, blk
, forward_time
, request_time
);
381 // track time of availability of next prefetch, if any
382 Tick next_pf_time
= prefetcher
->nextPrefetchReadyTime();
383 if (next_pf_time
!= MaxTick
) {
384 schedMemSideSendEvent(next_pf_time
);
390 BaseCache::handleUncacheableWriteResp(PacketPtr pkt
)
392 Tick completion_time
= clockEdge(responseLatency
) +
393 pkt
->headerDelay
+ pkt
->payloadDelay
;
395 // Reset the bus additional time as it is now accounted for
396 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
398 cpuSidePort
.schedTimingResp(pkt
, completion_time
);
402 BaseCache::recvTimingResp(PacketPtr pkt
)
404 assert(pkt
->isResponse());
406 // all header delay should be paid for by the crossbar, unless
407 // this is a prefetch response from above
408 panic_if(pkt
->headerDelay
!= 0 && pkt
->cmd
!= MemCmd::HardPFResp
,
409 "%s saw a non-zero packet delay\n", name());
411 const bool is_error
= pkt
->isError();
414 DPRINTF(Cache
, "%s: Cache received %s with error\n", __func__
,
418 DPRINTF(Cache
, "%s: Handling response %s\n", __func__
,
421 // if this is a write, we should be looking at an uncacheable
423 if (pkt
->isWrite()) {
424 assert(pkt
->req
->isUncacheable());
425 handleUncacheableWriteResp(pkt
);
429 // we have dealt with any (uncacheable) writes above, from here on
430 // we know we are dealing with an MSHR due to a miss or a prefetch
431 MSHR
*mshr
= dynamic_cast<MSHR
*>(pkt
->popSenderState());
434 if (mshr
== noTargetMSHR
) {
435 // we always clear at least one target
436 clearBlocked(Blocked_NoTargets
);
437 noTargetMSHR
= nullptr;
440 // Initial target is used just for stats
441 const QueueEntry::Target
*initial_tgt
= mshr
->getTarget();
442 const Tick miss_latency
= curTick() - initial_tgt
->recvTime
;
443 if (pkt
->req
->isUncacheable()) {
444 assert(pkt
->req
->masterId() < system
->maxMasters());
445 stats
.cmdStats(initial_tgt
->pkt
)
446 .mshr_uncacheable_lat
[pkt
->req
->masterId()] += miss_latency
;
448 assert(pkt
->req
->masterId() < system
->maxMasters());
449 stats
.cmdStats(initial_tgt
->pkt
)
450 .mshr_miss_latency
[pkt
->req
->masterId()] += miss_latency
;
453 PacketList writebacks
;
455 bool is_fill
= !mshr
->isForward
&&
456 (pkt
->isRead() || pkt
->cmd
== MemCmd::UpgradeResp
||
457 mshr
->wasWholeLineWrite
);
459 // make sure that if the mshr was due to a whole line write then
460 // the response is an invalidation
461 assert(!mshr
->wasWholeLineWrite
|| pkt
->isInvalidate());
463 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), pkt
->isSecure());
465 if (is_fill
&& !is_error
) {
466 DPRINTF(Cache
, "Block for addr %#llx being updated in Cache\n",
469 const bool allocate
= (writeAllocator
&& mshr
->wasWholeLineWrite
) ?
470 writeAllocator
->allocate() : mshr
->allocOnFill();
471 blk
= handleFill(pkt
, blk
, writebacks
, allocate
);
472 assert(blk
!= nullptr);
476 if (blk
&& blk
->isValid() && pkt
->isClean() && !pkt
->isInvalidate()) {
477 // The block was marked not readable while there was a pending
478 // cache maintenance operation, restore its flag.
479 blk
->status
|= BlkReadable
;
481 // This was a cache clean operation (without invalidate)
482 // and we have a copy of the block already. Since there
483 // is no invalidation, we can promote targets that don't
484 // require a writable copy
485 mshr
->promoteReadable();
488 if (blk
&& blk
->isWritable() && !pkt
->req
->isCacheInvalidate()) {
489 // If at this point the referenced block is writable and the
490 // response is not a cache invalidate, we promote targets that
491 // were deferred as we couldn't guarrantee a writable copy
492 mshr
->promoteWritable();
495 serviceMSHRTargets(mshr
, pkt
, blk
);
497 if (mshr
->promoteDeferredTargets()) {
498 // avoid later read getting stale data while write miss is
499 // outstanding.. see comment in timingAccess()
501 blk
->status
&= ~BlkReadable
;
503 mshrQueue
.markPending(mshr
);
504 schedMemSideSendEvent(clockEdge() + pkt
->payloadDelay
);
506 // while we deallocate an mshr from the queue we still have to
507 // check the isFull condition before and after as we might
508 // have been using the reserved entries already
509 const bool was_full
= mshrQueue
.isFull();
510 mshrQueue
.deallocate(mshr
);
511 if (was_full
&& !mshrQueue
.isFull()) {
512 clearBlocked(Blocked_NoMSHRs
);
515 // Request the bus for a prefetch if this deallocation freed enough
516 // MSHRs for a prefetch to take place
517 if (prefetcher
&& mshrQueue
.canPrefetch()) {
518 Tick next_pf_time
= std::max(prefetcher
->nextPrefetchReadyTime(),
520 if (next_pf_time
!= MaxTick
)
521 schedMemSideSendEvent(next_pf_time
);
525 // if we used temp block, check to see if its valid and then clear it out
526 if (blk
== tempBlock
&& tempBlock
->isValid()) {
527 evictBlock(blk
, writebacks
);
530 const Tick forward_time
= clockEdge(forwardLatency
) + pkt
->headerDelay
;
531 // copy writebacks to write buffer
532 doWritebacks(writebacks
, forward_time
);
534 DPRINTF(CacheVerbose
, "%s: Leaving with %s\n", __func__
, pkt
->print());
540 BaseCache::recvAtomic(PacketPtr pkt
)
542 // should assert here that there are no outstanding MSHRs or
543 // writebacks... that would mean that someone used an atomic
544 // access in timing mode
546 // We use lookupLatency here because it is used to specify the latency
548 Cycles lat
= lookupLatency
;
550 CacheBlk
*blk
= nullptr;
551 PacketList writebacks
;
552 bool satisfied
= access(pkt
, blk
, lat
, writebacks
);
554 if (pkt
->isClean() && blk
&& blk
->isDirty()) {
555 // A cache clean opearation is looking for a dirty
556 // block. If a dirty block is encountered a WriteClean
557 // will update any copies to the path to the memory
558 // until the point of reference.
559 DPRINTF(CacheVerbose
, "%s: packet %s found block: %s\n",
560 __func__
, pkt
->print(), blk
->print());
561 PacketPtr wb_pkt
= writecleanBlk(blk
, pkt
->req
->getDest(), pkt
->id
);
562 writebacks
.push_back(wb_pkt
);
566 // handle writebacks resulting from the access here to ensure they
567 // logically precede anything happening below
568 doWritebacksAtomic(writebacks
);
569 assert(writebacks
.empty());
572 lat
+= handleAtomicReqMiss(pkt
, blk
, writebacks
);
575 // Note that we don't invoke the prefetcher at all in atomic mode.
576 // It's not clear how to do it properly, particularly for
577 // prefetchers that aggressively generate prefetch candidates and
578 // rely on bandwidth contention to throttle them; these will tend
579 // to pollute the cache in atomic mode since there is no bandwidth
580 // contention. If we ever do want to enable prefetching in atomic
581 // mode, though, this is the place to do it... see timingAccess()
582 // for an example (though we'd want to issue the prefetch(es)
583 // immediately rather than calling requestMemSideBus() as we do
586 // do any writebacks resulting from the response handling
587 doWritebacksAtomic(writebacks
);
589 // if we used temp block, check to see if its valid and if so
590 // clear it out, but only do so after the call to recvAtomic is
591 // finished so that any downstream observers (such as a snoop
592 // filter), first see the fill, and only then see the eviction
593 if (blk
== tempBlock
&& tempBlock
->isValid()) {
594 // the atomic CPU calls recvAtomic for fetch and load/store
595 // sequentuially, and we may already have a tempBlock
596 // writeback from the fetch that we have not yet sent
597 if (tempBlockWriteback
) {
598 // if that is the case, write the prevoius one back, and
599 // do not schedule any new event
600 writebackTempBlockAtomic();
602 // the writeback/clean eviction happens after the call to
603 // recvAtomic has finished (but before any successive
604 // calls), so that the response handling from the fill is
605 // allowed to happen first
606 schedule(writebackTempBlockAtomicEvent
, curTick());
609 tempBlockWriteback
= evictBlock(blk
);
612 if (pkt
->needsResponse()) {
613 pkt
->makeAtomicResponse();
616 return lat
* clockPeriod();
620 BaseCache::functionalAccess(PacketPtr pkt
, bool from_cpu_side
)
622 Addr blk_addr
= pkt
->getBlockAddr(blkSize
);
623 bool is_secure
= pkt
->isSecure();
624 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), is_secure
);
625 MSHR
*mshr
= mshrQueue
.findMatch(blk_addr
, is_secure
);
627 pkt
->pushLabel(name());
629 CacheBlkPrintWrapper
cbpw(blk
);
631 // Note that just because an L2/L3 has valid data doesn't mean an
632 // L1 doesn't have a more up-to-date modified copy that still
633 // needs to be found. As a result we always update the request if
634 // we have it, but only declare it satisfied if we are the owner.
636 // see if we have data at all (owned or otherwise)
637 bool have_data
= blk
&& blk
->isValid()
638 && pkt
->trySatisfyFunctional(&cbpw
, blk_addr
, is_secure
, blkSize
,
641 // data we have is dirty if marked as such or if we have an
642 // in-service MSHR that is pending a modified line
644 have_data
&& (blk
->isDirty() ||
645 (mshr
&& mshr
->inService
&& mshr
->isPendingModified()));
647 bool done
= have_dirty
||
648 cpuSidePort
.trySatisfyFunctional(pkt
) ||
649 mshrQueue
.trySatisfyFunctional(pkt
) ||
650 writeBuffer
.trySatisfyFunctional(pkt
) ||
651 memSidePort
.trySatisfyFunctional(pkt
);
653 DPRINTF(CacheVerbose
, "%s: %s %s%s%s\n", __func__
, pkt
->print(),
654 (blk
&& blk
->isValid()) ? "valid " : "",
655 have_data
? "data " : "", done
? "done " : "");
657 // We're leaving the cache, so pop cache->name() label
663 // if it came as a request from the CPU side then make sure it
664 // continues towards the memory side
666 memSidePort
.sendFunctional(pkt
);
667 } else if (cpuSidePort
.isSnooping()) {
668 // if it came from the memory side, it must be a snoop request
669 // and we should only forward it if we are forwarding snoops
670 cpuSidePort
.sendFunctionalSnoop(pkt
);
677 BaseCache::cmpAndSwap(CacheBlk
*blk
, PacketPtr pkt
)
679 assert(pkt
->isRequest());
681 uint64_t overwrite_val
;
683 uint64_t condition_val64
;
684 uint32_t condition_val32
;
686 int offset
= pkt
->getOffset(blkSize
);
687 uint8_t *blk_data
= blk
->data
+ offset
;
689 assert(sizeof(uint64_t) >= pkt
->getSize());
691 overwrite_mem
= true;
692 // keep a copy of our possible write value, and copy what is at the
693 // memory address into the packet
694 pkt
->writeData((uint8_t *)&overwrite_val
);
695 pkt
->setData(blk_data
);
697 if (pkt
->req
->isCondSwap()) {
698 if (pkt
->getSize() == sizeof(uint64_t)) {
699 condition_val64
= pkt
->req
->getExtraData();
700 overwrite_mem
= !std::memcmp(&condition_val64
, blk_data
,
702 } else if (pkt
->getSize() == sizeof(uint32_t)) {
703 condition_val32
= (uint32_t)pkt
->req
->getExtraData();
704 overwrite_mem
= !std::memcmp(&condition_val32
, blk_data
,
707 panic("Invalid size for conditional read/write\n");
711 std::memcpy(blk_data
, &overwrite_val
, pkt
->getSize());
712 blk
->status
|= BlkDirty
;
717 BaseCache::getNextQueueEntry()
719 // Check both MSHR queue and write buffer for potential requests,
720 // note that null does not mean there is no request, it could
721 // simply be that it is not ready
722 MSHR
*miss_mshr
= mshrQueue
.getNext();
723 WriteQueueEntry
*wq_entry
= writeBuffer
.getNext();
725 // If we got a write buffer request ready, first priority is a
726 // full write buffer, otherwise we favour the miss requests
727 if (wq_entry
&& (writeBuffer
.isFull() || !miss_mshr
)) {
728 // need to search MSHR queue for conflicting earlier miss.
729 MSHR
*conflict_mshr
= mshrQueue
.findPending(wq_entry
);
731 if (conflict_mshr
&& conflict_mshr
->order
< wq_entry
->order
) {
732 // Service misses in order until conflict is cleared.
733 return conflict_mshr
;
735 // @todo Note that we ignore the ready time of the conflict here
738 // No conflicts; issue write
740 } else if (miss_mshr
) {
741 // need to check for conflicting earlier writeback
742 WriteQueueEntry
*conflict_mshr
= writeBuffer
.findPending(miss_mshr
);
744 // not sure why we don't check order here... it was in the
745 // original code but commented out.
747 // The only way this happens is if we are
748 // doing a write and we didn't have permissions
749 // then subsequently saw a writeback (owned got evicted)
750 // We need to make sure to perform the writeback first
751 // To preserve the dirty data, then we can issue the write
753 // should we return wq_entry here instead? I.e. do we
754 // have to flush writes in order? I don't think so... not
755 // for Alpha anyway. Maybe for x86?
756 return conflict_mshr
;
758 // @todo Note that we ignore the ready time of the conflict here
761 // No conflicts; issue read
765 // fall through... no pending requests. Try a prefetch.
766 assert(!miss_mshr
&& !wq_entry
);
767 if (prefetcher
&& mshrQueue
.canPrefetch()) {
768 // If we have a miss queue slot, we can try a prefetch
769 PacketPtr pkt
= prefetcher
->getPacket();
771 Addr pf_addr
= pkt
->getBlockAddr(blkSize
);
772 if (!tags
->findBlock(pf_addr
, pkt
->isSecure()) &&
773 !mshrQueue
.findMatch(pf_addr
, pkt
->isSecure()) &&
774 !writeBuffer
.findMatch(pf_addr
, pkt
->isSecure())) {
775 // Update statistic on number of prefetches issued
776 // (hwpf_mshr_misses)
777 assert(pkt
->req
->masterId() < system
->maxMasters());
778 stats
.cmdStats(pkt
).mshr_misses
[pkt
->req
->masterId()]++;
780 // allocate an MSHR and return it, note
781 // that we send the packet straight away, so do not
783 return allocateMissBuffer(pkt
, curTick(), false);
785 // free the request and packet
795 BaseCache::handleEvictions(std::vector
<CacheBlk
*> &evict_blks
,
796 PacketList
&writebacks
)
798 bool replacement
= false;
799 for (const auto& blk
: evict_blks
) {
800 if (blk
->isValid()) {
804 mshrQueue
.findMatch(regenerateBlkAddr(blk
), blk
->isSecure());
806 // Must be an outstanding upgrade or clean request on a block
807 // we're about to replace
808 assert((!blk
->isWritable() && mshr
->needsWritable()) ||
815 // The victim will be replaced by a new entry, so increase the replacement
816 // counter if a valid block is being replaced
818 stats
.replacements
++;
820 // Evict valid blocks associated to this victim block
821 for (auto& blk
: evict_blks
) {
822 if (blk
->isValid()) {
823 evictBlock(blk
, writebacks
);
832 BaseCache::updateCompressionData(CacheBlk
*blk
, const uint64_t* data
,
833 PacketList
&writebacks
)
835 // tempBlock does not exist in the tags, so don't do anything for it.
836 if (blk
== tempBlock
) {
840 // Get superblock of the given block
841 CompressionBlk
* compression_blk
= static_cast<CompressionBlk
*>(blk
);
842 const SuperBlk
* superblock
= static_cast<const SuperBlk
*>(
843 compression_blk
->getSectorBlock());
845 // The compressor is called to compress the updated data, so that its
846 // metadata can be updated.
847 std::size_t compression_size
= 0;
848 Cycles compression_lat
= Cycles(0);
849 Cycles decompression_lat
= Cycles(0);
850 compressor
->compress(data
, compression_lat
, decompression_lat
,
853 // If block's compression factor increased, it may not be co-allocatable
854 // anymore. If so, some blocks might need to be evicted to make room for
857 // Get previous compressed size
858 const std::size_t M5_VAR_USED prev_size
= compression_blk
->getSizeBits();
860 // Check if new data is co-allocatable
861 const bool is_co_allocatable
= superblock
->isCompressed(compression_blk
) &&
862 superblock
->canCoAllocate(compression_size
);
864 // If block was compressed, possibly co-allocated with other blocks, and
865 // cannot be co-allocated anymore, one or more blocks must be evicted to
866 // make room for the expanded block. As of now we decide to evict the co-
867 // allocated blocks to make room for the expansion, but other approaches
868 // that take the replacement data of the superblock into account may
869 // generate better results
870 const bool was_compressed
= compression_blk
->isCompressed();
871 if (was_compressed
&& !is_co_allocatable
) {
872 std::vector
<CacheBlk
*> evict_blks
;
873 for (const auto& sub_blk
: superblock
->blks
) {
874 if (sub_blk
->isValid() && (compression_blk
!= sub_blk
)) {
875 evict_blks
.push_back(sub_blk
);
879 // Try to evict blocks; if it fails, give up on update
880 if (!handleEvictions(evict_blks
, writebacks
)) {
884 // Update the number of data expansions
885 stats
.dataExpansions
++;
887 DPRINTF(CacheComp
, "Data expansion: expanding [%s] from %d to %d bits"
888 "\n", blk
->print(), prev_size
, compression_size
);
891 // We always store compressed blocks when possible
892 if (is_co_allocatable
) {
893 compression_blk
->setCompressed();
895 compression_blk
->setUncompressed();
897 compression_blk
->setSizeBits(compression_size
);
898 compression_blk
->setDecompressionLatency(decompression_lat
);
904 BaseCache::satisfyRequest(PacketPtr pkt
, CacheBlk
*blk
, bool, bool)
906 assert(pkt
->isRequest());
908 assert(blk
&& blk
->isValid());
909 // Occasionally this is not true... if we are a lower-level cache
910 // satisfying a string of Read and ReadEx requests from
911 // upper-level caches, a Read will mark the block as shared but we
912 // can satisfy a following ReadEx anyway since we can rely on the
913 // Read requester(s) to have buffered the ReadEx snoop and to
914 // invalidate their blocks after receiving them.
915 // assert(!pkt->needsWritable() || blk->isWritable());
916 assert(pkt
->getOffset(blkSize
) + pkt
->getSize() <= blkSize
);
918 // Check RMW operations first since both isRead() and
919 // isWrite() will be true for them
920 if (pkt
->cmd
== MemCmd::SwapReq
) {
921 if (pkt
->isAtomicOp()) {
922 // extract data from cache and save it into the data field in
923 // the packet as a return value from this atomic op
924 int offset
= tags
->extractBlkOffset(pkt
->getAddr());
925 uint8_t *blk_data
= blk
->data
+ offset
;
926 pkt
->setData(blk_data
);
928 // execute AMO operation
929 (*(pkt
->getAtomicOp()))(blk_data
);
931 // set block status to dirty
932 blk
->status
|= BlkDirty
;
934 cmpAndSwap(blk
, pkt
);
936 } else if (pkt
->isWrite()) {
937 // we have the block in a writable state and can go ahead,
938 // note that the line may be also be considered writable in
939 // downstream caches along the path to memory, but always
940 // Exclusive, and never Modified
941 assert(blk
->isWritable());
942 // Write or WriteLine at the first cache with block in writable state
943 if (blk
->checkWrite(pkt
)) {
944 pkt
->writeDataToBlock(blk
->data
, blkSize
);
946 // Always mark the line as dirty (and thus transition to the
947 // Modified state) even if we are a failed StoreCond so we
948 // supply data to any snoops that have appended themselves to
949 // this cache before knowing the store will fail.
950 blk
->status
|= BlkDirty
;
951 DPRINTF(CacheVerbose
, "%s for %s (write)\n", __func__
, pkt
->print());
952 } else if (pkt
->isRead()) {
954 blk
->trackLoadLocked(pkt
);
957 // all read responses have a data payload
958 assert(pkt
->hasRespData());
959 pkt
->setDataFromBlock(blk
->data
, blkSize
);
960 } else if (pkt
->isUpgrade()) {
962 assert(!pkt
->hasSharers());
964 if (blk
->isDirty()) {
965 // we were in the Owned state, and a cache above us that
966 // has the line in Shared state needs to be made aware
967 // that the data it already has is in fact dirty
968 pkt
->setCacheResponding();
969 blk
->status
&= ~BlkDirty
;
971 } else if (pkt
->isClean()) {
972 blk
->status
&= ~BlkDirty
;
974 assert(pkt
->isInvalidate());
975 invalidateBlock(blk
);
976 DPRINTF(CacheVerbose
, "%s for %s (invalidation)\n", __func__
,
981 /////////////////////////////////////////////////////
983 // Access path: requests coming in from the CPU side
985 /////////////////////////////////////////////////////
987 BaseCache::calculateTagOnlyLatency(const uint32_t delay
,
988 const Cycles lookup_lat
) const
990 // A tag-only access has to wait for the packet to arrive in order to
991 // perform the tag lookup.
992 return ticksToCycles(delay
) + lookup_lat
;
996 BaseCache::calculateAccessLatency(const CacheBlk
* blk
, const uint32_t delay
,
997 const Cycles lookup_lat
) const
1001 if (blk
!= nullptr) {
1002 // As soon as the access arrives, for sequential accesses first access
1003 // tags, then the data entry. In the case of parallel accesses the
1004 // latency is dictated by the slowest of tag and data latencies.
1005 if (sequentialAccess
) {
1006 lat
= ticksToCycles(delay
) + lookup_lat
+ dataLatency
;
1008 lat
= ticksToCycles(delay
) + std::max(lookup_lat
, dataLatency
);
1011 // Check if the block to be accessed is available. If not, apply the
1012 // access latency on top of when the block is ready to be accessed.
1013 const Tick tick
= curTick() + delay
;
1014 const Tick when_ready
= blk
->getWhenReady();
1015 if (when_ready
> tick
&&
1016 ticksToCycles(when_ready
- tick
) > lat
) {
1017 lat
+= ticksToCycles(when_ready
- tick
);
1020 // In case of a miss, we neglect the data access in a parallel
1021 // configuration (i.e., the data access will be stopped as soon as
1022 // we find out it is a miss), and use the tag-only latency.
1023 lat
= calculateTagOnlyLatency(delay
, lookup_lat
);
1030 BaseCache::access(PacketPtr pkt
, CacheBlk
*&blk
, Cycles
&lat
,
1031 PacketList
&writebacks
)
1034 assert(pkt
->isRequest());
1036 chatty_assert(!(isReadOnly
&& pkt
->isWrite()),
1037 "Should never see a write in a read-only cache %s\n",
1040 // Access block in the tags
1041 Cycles
tag_latency(0);
1042 blk
= tags
->accessBlock(pkt
->getAddr(), pkt
->isSecure(), tag_latency
);
1044 DPRINTF(Cache
, "%s for %s %s\n", __func__
, pkt
->print(),
1045 blk
? "hit " + blk
->print() : "miss");
1047 if (pkt
->req
->isCacheMaintenance()) {
1048 // A cache maintenance operation is always forwarded to the
1049 // memory below even if the block is found in dirty state.
1051 // We defer any changes to the state of the block until we
1052 // create and mark as in service the mshr for the downstream
1055 // Calculate access latency on top of when the packet arrives. This
1056 // takes into account the bus delay.
1057 lat
= calculateTagOnlyLatency(pkt
->headerDelay
, tag_latency
);
1062 if (pkt
->isEviction()) {
1063 // We check for presence of block in above caches before issuing
1064 // Writeback or CleanEvict to write buffer. Therefore the only
1065 // possible cases can be of a CleanEvict packet coming from above
1066 // encountering a Writeback generated in this cache peer cache and
1067 // waiting in the write buffer. Cases of upper level peer caches
1068 // generating CleanEvict and Writeback or simply CleanEvict and
1069 // CleanEvict almost simultaneously will be caught by snoops sent out
1071 WriteQueueEntry
*wb_entry
= writeBuffer
.findMatch(pkt
->getAddr(),
1074 assert(wb_entry
->getNumTargets() == 1);
1075 PacketPtr wbPkt
= wb_entry
->getTarget()->pkt
;
1076 assert(wbPkt
->isWriteback());
1078 if (pkt
->isCleanEviction()) {
1079 // The CleanEvict and WritebackClean snoops into other
1080 // peer caches of the same level while traversing the
1081 // crossbar. If a copy of the block is found, the
1082 // packet is deleted in the crossbar. Hence, none of
1083 // the other upper level caches connected to this
1084 // cache have the block, so we can clear the
1085 // BLOCK_CACHED flag in the Writeback if set and
1086 // discard the CleanEvict by returning true.
1087 wbPkt
->clearBlockCached();
1089 // A clean evict does not need to access the data array
1090 lat
= calculateTagOnlyLatency(pkt
->headerDelay
, tag_latency
);
1094 assert(pkt
->cmd
== MemCmd::WritebackDirty
);
1095 // Dirty writeback from above trumps our clean
1096 // writeback... discard here
1097 // Note: markInService will remove entry from writeback buffer.
1098 markInService(wb_entry
);
1104 // The critical latency part of a write depends only on the tag access
1105 if (pkt
->isWrite()) {
1106 lat
= calculateTagOnlyLatency(pkt
->headerDelay
, tag_latency
);
1109 // Writeback handling is special case. We can write the block into
1110 // the cache without having a writeable copy (or any copy at all).
1111 if (pkt
->isWriteback()) {
1112 assert(blkSize
== pkt
->getSize());
1114 // we could get a clean writeback while we are having
1115 // outstanding accesses to a block, do the simple thing for
1116 // now and drop the clean writeback so that we do not upset
1117 // any ordering/decisions about ownership already taken
1118 if (pkt
->cmd
== MemCmd::WritebackClean
&&
1119 mshrQueue
.findMatch(pkt
->getAddr(), pkt
->isSecure())) {
1120 DPRINTF(Cache
, "Clean writeback %#llx to block with MSHR, "
1121 "dropping\n", pkt
->getAddr());
1123 // A writeback searches for the block, then writes the data.
1124 // As the writeback is being dropped, the data is not touched,
1125 // and we just had to wait for the time to find a match in the
1126 // MSHR. As of now assume a mshr queue search takes as long as
1127 // a tag lookup for simplicity.
1132 // need to do a replacement
1133 blk
= allocateBlock(pkt
, writebacks
);
1135 // no replaceable block available: give up, fwd to next level.
1140 blk
->status
|= BlkReadable
;
1141 } else if (compressor
) {
1142 // This is an overwrite to an existing block, therefore we need
1143 // to check for data expansion (i.e., block was compressed with
1144 // a smaller size, and now it doesn't fit the entry anymore).
1145 // If that is the case we might need to evict blocks.
1146 if (!updateCompressionData(blk
, pkt
->getConstPtr
<uint64_t>(),
1148 invalidateBlock(blk
);
1153 // only mark the block dirty if we got a writeback command,
1154 // and leave it as is for a clean writeback
1155 if (pkt
->cmd
== MemCmd::WritebackDirty
) {
1156 // TODO: the coherent cache can assert(!blk->isDirty());
1157 blk
->status
|= BlkDirty
;
1159 // if the packet does not have sharers, it is passing
1160 // writable, and we got the writeback in Modified or Exclusive
1161 // state, if not we are in the Owned or Shared state
1162 if (!pkt
->hasSharers()) {
1163 blk
->status
|= BlkWritable
;
1165 // nothing else to do; writeback doesn't expect response
1166 assert(!pkt
->needsResponse());
1167 pkt
->writeDataToBlock(blk
->data
, blkSize
);
1168 DPRINTF(Cache
, "%s new state is %s\n", __func__
, blk
->print());
1171 // When the packet metadata arrives, the tag lookup will be done while
1172 // the payload is arriving. Then the block will be ready to access as
1173 // soon as the fill is done
1174 blk
->setWhenReady(clockEdge(fillLatency
) + pkt
->headerDelay
+
1175 std::max(cyclesToTicks(tag_latency
), (uint64_t)pkt
->payloadDelay
));
1178 } else if (pkt
->cmd
== MemCmd::CleanEvict
) {
1179 // A CleanEvict does not need to access the data array
1180 lat
= calculateTagOnlyLatency(pkt
->headerDelay
, tag_latency
);
1183 // Found the block in the tags, need to stop CleanEvict from
1184 // propagating further down the hierarchy. Returning true will
1185 // treat the CleanEvict like a satisfied write request and delete
1189 // We didn't find the block here, propagate the CleanEvict further
1190 // down the memory hierarchy. Returning false will treat the CleanEvict
1191 // like a Writeback which could not find a replaceable block so has to
1192 // go to next level.
1194 } else if (pkt
->cmd
== MemCmd::WriteClean
) {
1195 // WriteClean handling is a special case. We can allocate a
1196 // block directly if it doesn't exist and we can update the
1197 // block immediately. The WriteClean transfers the ownership
1198 // of the block as well.
1199 assert(blkSize
== pkt
->getSize());
1202 if (pkt
->writeThrough()) {
1203 // if this is a write through packet, we don't try to
1204 // allocate if the block is not present
1207 // a writeback that misses needs to allocate a new block
1208 blk
= allocateBlock(pkt
, writebacks
);
1210 // no replaceable block available: give up, fwd to
1216 blk
->status
|= BlkReadable
;
1218 } else if (compressor
) {
1219 // This is an overwrite to an existing block, therefore we need
1220 // to check for data expansion (i.e., block was compressed with
1221 // a smaller size, and now it doesn't fit the entry anymore).
1222 // If that is the case we might need to evict blocks.
1223 if (!updateCompressionData(blk
, pkt
->getConstPtr
<uint64_t>(),
1225 invalidateBlock(blk
);
1230 // at this point either this is a writeback or a write-through
1231 // write clean operation and the block is already in this
1232 // cache, we need to update the data and the block flags
1234 // TODO: the coherent cache can assert(!blk->isDirty());
1235 if (!pkt
->writeThrough()) {
1236 blk
->status
|= BlkDirty
;
1238 // nothing else to do; writeback doesn't expect response
1239 assert(!pkt
->needsResponse());
1240 pkt
->writeDataToBlock(blk
->data
, blkSize
);
1241 DPRINTF(Cache
, "%s new state is %s\n", __func__
, blk
->print());
1245 // When the packet metadata arrives, the tag lookup will be done while
1246 // the payload is arriving. Then the block will be ready to access as
1247 // soon as the fill is done
1248 blk
->setWhenReady(clockEdge(fillLatency
) + pkt
->headerDelay
+
1249 std::max(cyclesToTicks(tag_latency
), (uint64_t)pkt
->payloadDelay
));
1251 // If this a write-through packet it will be sent to cache below
1252 return !pkt
->writeThrough();
1253 } else if (blk
&& (pkt
->needsWritable() ? blk
->isWritable() :
1254 blk
->isReadable())) {
1255 // OK to satisfy access
1258 // Calculate access latency based on the need to access the data array
1259 if (pkt
->isRead()) {
1260 lat
= calculateAccessLatency(blk
, pkt
->headerDelay
, tag_latency
);
1262 // When a block is compressed, it must first be decompressed
1263 // before being read. This adds to the access latency.
1265 lat
+= compressor
->getDecompressionLatency(blk
);
1268 lat
= calculateTagOnlyLatency(pkt
->headerDelay
, tag_latency
);
1271 satisfyRequest(pkt
, blk
);
1272 maintainClusivity(pkt
->fromCache(), blk
);
1277 // Can't satisfy access normally... either no block (blk == nullptr)
1278 // or have block but need writable
1282 lat
= calculateAccessLatency(blk
, pkt
->headerDelay
, tag_latency
);
1284 if (!blk
&& pkt
->isLLSC() && pkt
->isWrite()) {
1285 // complete miss on store conditional... just give up now
1286 pkt
->req
->setExtraData(0);
1294 BaseCache::maintainClusivity(bool from_cache
, CacheBlk
*blk
)
1296 if (from_cache
&& blk
&& blk
->isValid() && !blk
->isDirty() &&
1297 clusivity
== Enums::mostly_excl
) {
1298 // if we have responded to a cache, and our block is still
1299 // valid, but not dirty, and this cache is mostly exclusive
1300 // with respect to the cache above, drop the block
1301 invalidateBlock(blk
);
1306 BaseCache::handleFill(PacketPtr pkt
, CacheBlk
*blk
, PacketList
&writebacks
,
1309 assert(pkt
->isResponse());
1310 Addr addr
= pkt
->getAddr();
1311 bool is_secure
= pkt
->isSecure();
1313 CacheBlk::State old_state
= blk
? blk
->status
: 0;
1316 // When handling a fill, we should have no writes to this line.
1317 assert(addr
== pkt
->getBlockAddr(blkSize
));
1318 assert(!writeBuffer
.findMatch(addr
, is_secure
));
1321 // better have read new data...
1322 assert(pkt
->hasData() || pkt
->cmd
== MemCmd::InvalidateResp
);
1324 // need to do a replacement if allocating, otherwise we stick
1325 // with the temporary storage
1326 blk
= allocate
? allocateBlock(pkt
, writebacks
) : nullptr;
1329 // No replaceable block or a mostly exclusive
1330 // cache... just use temporary storage to complete the
1331 // current request and then get rid of it
1333 tempBlock
->insert(addr
, is_secure
);
1334 DPRINTF(Cache
, "using temp block for %#llx (%s)\n", addr
,
1335 is_secure
? "s" : "ns");
1338 // existing block... probably an upgrade
1339 // don't clear block status... if block is already dirty we
1340 // don't want to lose that
1343 // Block is guaranteed to be valid at this point
1344 assert(blk
->isValid());
1345 assert(blk
->isSecure() == is_secure
);
1346 assert(regenerateBlkAddr(blk
) == addr
);
1348 blk
->status
|= BlkReadable
;
1350 // sanity check for whole-line writes, which should always be
1351 // marked as writable as part of the fill, and then later marked
1352 // dirty as part of satisfyRequest
1353 if (pkt
->cmd
== MemCmd::InvalidateResp
) {
1354 assert(!pkt
->hasSharers());
1357 // here we deal with setting the appropriate state of the line,
1358 // and we start by looking at the hasSharers flag, and ignore the
1359 // cacheResponding flag (normally signalling dirty data) if the
1360 // packet has sharers, thus the line is never allocated as Owned
1361 // (dirty but not writable), and always ends up being either
1362 // Shared, Exclusive or Modified, see Packet::setCacheResponding
1364 if (!pkt
->hasSharers()) {
1365 // we could get a writable line from memory (rather than a
1366 // cache) even in a read-only cache, note that we set this bit
1367 // even for a read-only cache, possibly revisit this decision
1368 blk
->status
|= BlkWritable
;
1370 // check if we got this via cache-to-cache transfer (i.e., from a
1371 // cache that had the block in Modified or Owned state)
1372 if (pkt
->cacheResponding()) {
1373 // we got the block in Modified state, and invalidated the
1375 blk
->status
|= BlkDirty
;
1377 chatty_assert(!isReadOnly
, "Should never see dirty snoop response "
1378 "in read-only cache %s\n", name());
1383 DPRINTF(Cache
, "Block addr %#llx (%s) moving from state %x to %s\n",
1384 addr
, is_secure
? "s" : "ns", old_state
, blk
->print());
1386 // if we got new data, copy it in (checking for a read response
1387 // and a response that has data is the same in the end)
1388 if (pkt
->isRead()) {
1390 assert(pkt
->hasData());
1391 assert(pkt
->getSize() == blkSize
);
1393 pkt
->writeDataToBlock(blk
->data
, blkSize
);
1395 // The block will be ready when the payload arrives and the fill is done
1396 blk
->setWhenReady(clockEdge(fillLatency
) + pkt
->headerDelay
+
1403 BaseCache::allocateBlock(const PacketPtr pkt
, PacketList
&writebacks
)
1406 const Addr addr
= pkt
->getAddr();
1409 const bool is_secure
= pkt
->isSecure();
1411 // Block size and compression related access latency. Only relevant if
1412 // using a compressor, otherwise there is no extra delay, and the block
1414 std::size_t blk_size_bits
= blkSize
*8;
1415 Cycles compression_lat
= Cycles(0);
1416 Cycles decompression_lat
= Cycles(0);
1418 // If a compressor is being used, it is called to compress data before
1419 // insertion. Although in Gem5 the data is stored uncompressed, even if a
1420 // compressor is used, the compression/decompression methods are called to
1421 // calculate the amount of extra cycles needed to read or write compressed
1423 if (compressor
&& pkt
->hasData()) {
1424 compressor
->compress(pkt
->getConstPtr
<uint64_t>(), compression_lat
,
1425 decompression_lat
, blk_size_bits
);
1428 // Find replacement victim
1429 std::vector
<CacheBlk
*> evict_blks
;
1430 CacheBlk
*victim
= tags
->findVictim(addr
, is_secure
, blk_size_bits
,
1433 // It is valid to return nullptr if there is no victim
1437 // Print victim block's information
1438 DPRINTF(CacheRepl
, "Replacement victim: %s\n", victim
->print());
1440 // Try to evict blocks; if it fails, give up on allocation
1441 if (!handleEvictions(evict_blks
, writebacks
)) {
1445 // If using a compressor, set compression data. This must be done before
1446 // block insertion, as compressed tags use this information.
1448 compressor
->setSizeBits(victim
, blk_size_bits
);
1449 compressor
->setDecompressionLatency(victim
, decompression_lat
);
1452 // Insert new block at victimized entry
1453 tags
->insertBlock(pkt
, victim
);
1459 BaseCache::invalidateBlock(CacheBlk
*blk
)
1461 // If block is still marked as prefetched, then it hasn't been used
1462 if (blk
->wasPrefetched()) {
1463 stats
.unusedPrefetches
++;
1466 // If handling a block present in the Tags, let it do its invalidation
1467 // process, which will update stats and invalidate the block itself
1468 if (blk
!= tempBlock
) {
1469 tags
->invalidate(blk
);
1471 tempBlock
->invalidate();
1476 BaseCache::evictBlock(CacheBlk
*blk
, PacketList
&writebacks
)
1478 PacketPtr pkt
= evictBlock(blk
);
1480 writebacks
.push_back(pkt
);
1485 BaseCache::writebackBlk(CacheBlk
*blk
)
1487 chatty_assert(!isReadOnly
|| writebackClean
,
1488 "Writeback from read-only cache");
1489 assert(blk
&& blk
->isValid() && (blk
->isDirty() || writebackClean
));
1491 stats
.writebacks
[Request::wbMasterId
]++;
1493 RequestPtr req
= std::make_shared
<Request
>(
1494 regenerateBlkAddr(blk
), blkSize
, 0, Request::wbMasterId
);
1496 if (blk
->isSecure())
1497 req
->setFlags(Request::SECURE
);
1499 req
->taskId(blk
->task_id
);
1502 new Packet(req
, blk
->isDirty() ?
1503 MemCmd::WritebackDirty
: MemCmd::WritebackClean
);
1505 DPRINTF(Cache
, "Create Writeback %s writable: %d, dirty: %d\n",
1506 pkt
->print(), blk
->isWritable(), blk
->isDirty());
1508 if (blk
->isWritable()) {
1509 // not asserting shared means we pass the block in modified
1510 // state, mark our own block non-writeable
1511 blk
->status
&= ~BlkWritable
;
1513 // we are in the Owned state, tell the receiver
1514 pkt
->setHasSharers();
1517 // make sure the block is not marked dirty
1518 blk
->status
&= ~BlkDirty
;
1521 pkt
->setDataFromBlock(blk
->data
, blkSize
);
1523 // When a block is compressed, it must first be decompressed before being
1524 // sent for writeback.
1526 pkt
->payloadDelay
= compressor
->getDecompressionLatency(blk
);
1533 BaseCache::writecleanBlk(CacheBlk
*blk
, Request::Flags dest
, PacketId id
)
1535 RequestPtr req
= std::make_shared
<Request
>(
1536 regenerateBlkAddr(blk
), blkSize
, 0, Request::wbMasterId
);
1538 if (blk
->isSecure()) {
1539 req
->setFlags(Request::SECURE
);
1541 req
->taskId(blk
->task_id
);
1543 PacketPtr pkt
= new Packet(req
, MemCmd::WriteClean
, blkSize
, id
);
1546 req
->setFlags(dest
);
1547 pkt
->setWriteThrough();
1550 DPRINTF(Cache
, "Create %s writable: %d, dirty: %d\n", pkt
->print(),
1551 blk
->isWritable(), blk
->isDirty());
1553 if (blk
->isWritable()) {
1554 // not asserting shared means we pass the block in modified
1555 // state, mark our own block non-writeable
1556 blk
->status
&= ~BlkWritable
;
1558 // we are in the Owned state, tell the receiver
1559 pkt
->setHasSharers();
1562 // make sure the block is not marked dirty
1563 blk
->status
&= ~BlkDirty
;
1566 pkt
->setDataFromBlock(blk
->data
, blkSize
);
1568 // When a block is compressed, it must first be decompressed before being
1569 // sent for writeback.
1571 pkt
->payloadDelay
= compressor
->getDecompressionLatency(blk
);
1579 BaseCache::memWriteback()
1581 tags
->forEachBlk([this](CacheBlk
&blk
) { writebackVisitor(blk
); });
1585 BaseCache::memInvalidate()
1587 tags
->forEachBlk([this](CacheBlk
&blk
) { invalidateVisitor(blk
); });
1591 BaseCache::isDirty() const
1593 return tags
->anyBlk([](CacheBlk
&blk
) { return blk
.isDirty(); });
1597 BaseCache::coalesce() const
1599 return writeAllocator
&& writeAllocator
->coalesce();
1603 BaseCache::writebackVisitor(CacheBlk
&blk
)
1605 if (blk
.isDirty()) {
1606 assert(blk
.isValid());
1608 RequestPtr request
= std::make_shared
<Request
>(
1609 regenerateBlkAddr(&blk
), blkSize
, 0, Request::funcMasterId
);
1611 request
->taskId(blk
.task_id
);
1612 if (blk
.isSecure()) {
1613 request
->setFlags(Request::SECURE
);
1616 Packet
packet(request
, MemCmd::WriteReq
);
1617 packet
.dataStatic(blk
.data
);
1619 memSidePort
.sendFunctional(&packet
);
1621 blk
.status
&= ~BlkDirty
;
1626 BaseCache::invalidateVisitor(CacheBlk
&blk
)
1629 warn_once("Invalidating dirty cache lines. " \
1630 "Expect things to break.\n");
1632 if (blk
.isValid()) {
1633 assert(!blk
.isDirty());
1634 invalidateBlock(&blk
);
1639 BaseCache::nextQueueReadyTime() const
1641 Tick nextReady
= std::min(mshrQueue
.nextReadyTime(),
1642 writeBuffer
.nextReadyTime());
1644 // Don't signal prefetch ready time if no MSHRs available
1645 // Will signal once enoguh MSHRs are deallocated
1646 if (prefetcher
&& mshrQueue
.canPrefetch()) {
1647 nextReady
= std::min(nextReady
,
1648 prefetcher
->nextPrefetchReadyTime());
1656 BaseCache::sendMSHRQueuePacket(MSHR
* mshr
)
1660 // use request from 1st target
1661 PacketPtr tgt_pkt
= mshr
->getTarget()->pkt
;
1663 DPRINTF(Cache
, "%s: MSHR %s\n", __func__
, tgt_pkt
->print());
1665 // if the cache is in write coalescing mode or (additionally) in
1666 // no allocation mode, and we have a write packet with an MSHR
1667 // that is not a whole-line write (due to incompatible flags etc),
1668 // then reset the write mode
1669 if (writeAllocator
&& writeAllocator
->coalesce() && tgt_pkt
->isWrite()) {
1670 if (!mshr
->isWholeLineWrite()) {
1671 // if we are currently write coalescing, hold on the
1672 // MSHR as many cycles extra as we need to completely
1673 // write a cache line
1674 if (writeAllocator
->delay(mshr
->blkAddr
)) {
1675 Tick delay
= blkSize
/ tgt_pkt
->getSize() * clockPeriod();
1676 DPRINTF(CacheVerbose
, "Delaying pkt %s %llu ticks to allow "
1677 "for write coalescing\n", tgt_pkt
->print(), delay
);
1678 mshrQueue
.delay(mshr
, delay
);
1681 writeAllocator
->reset();
1684 writeAllocator
->resetDelay(mshr
->blkAddr
);
1688 CacheBlk
*blk
= tags
->findBlock(mshr
->blkAddr
, mshr
->isSecure
);
1690 // either a prefetch that is not present upstream, or a normal
1691 // MSHR request, proceed to get the packet to send downstream
1692 PacketPtr pkt
= createMissPacket(tgt_pkt
, blk
, mshr
->needsWritable(),
1693 mshr
->isWholeLineWrite());
1695 mshr
->isForward
= (pkt
== nullptr);
1697 if (mshr
->isForward
) {
1698 // not a cache block request, but a response is expected
1699 // make copy of current packet to forward, keep current
1700 // copy for response handling
1701 pkt
= new Packet(tgt_pkt
, false, true);
1702 assert(!pkt
->isWrite());
1705 // play it safe and append (rather than set) the sender state,
1706 // as forwarded packets may already have existing state
1707 pkt
->pushSenderState(mshr
);
1709 if (pkt
->isClean() && blk
&& blk
->isDirty()) {
1710 // A cache clean opearation is looking for a dirty block. Mark
1711 // the packet so that the destination xbar can determine that
1712 // there will be a follow-up write packet as well.
1713 pkt
->setSatisfied();
1716 if (!memSidePort
.sendTimingReq(pkt
)) {
1717 // we are awaiting a retry, but we
1718 // delete the packet and will be creating a new packet
1719 // when we get the opportunity
1722 // note that we have now masked any requestBus and
1723 // schedSendEvent (we will wait for a retry before
1724 // doing anything), and this is so even if we do not
1725 // care about this packet and might override it before
1729 // As part of the call to sendTimingReq the packet is
1730 // forwarded to all neighbouring caches (and any caches
1731 // above them) as a snoop. Thus at this point we know if
1732 // any of the neighbouring caches are responding, and if
1733 // so, we know it is dirty, and we can determine if it is
1734 // being passed as Modified, making our MSHR the ordering
1736 bool pending_modified_resp
= !pkt
->hasSharers() &&
1737 pkt
->cacheResponding();
1738 markInService(mshr
, pending_modified_resp
);
1740 if (pkt
->isClean() && blk
&& blk
->isDirty()) {
1741 // A cache clean opearation is looking for a dirty
1742 // block. If a dirty block is encountered a WriteClean
1743 // will update any copies to the path to the memory
1744 // until the point of reference.
1745 DPRINTF(CacheVerbose
, "%s: packet %s found block: %s\n",
1746 __func__
, pkt
->print(), blk
->print());
1747 PacketPtr wb_pkt
= writecleanBlk(blk
, pkt
->req
->getDest(),
1749 PacketList writebacks
;
1750 writebacks
.push_back(wb_pkt
);
1751 doWritebacks(writebacks
, 0);
1759 BaseCache::sendWriteQueuePacket(WriteQueueEntry
* wq_entry
)
1763 // always a single target for write queue entries
1764 PacketPtr tgt_pkt
= wq_entry
->getTarget()->pkt
;
1766 DPRINTF(Cache
, "%s: write %s\n", __func__
, tgt_pkt
->print());
1768 // forward as is, both for evictions and uncacheable writes
1769 if (!memSidePort
.sendTimingReq(tgt_pkt
)) {
1770 // note that we have now masked any requestBus and
1771 // schedSendEvent (we will wait for a retry before
1772 // doing anything), and this is so even if we do not
1773 // care about this packet and might override it before
1777 markInService(wq_entry
);
1783 BaseCache::serialize(CheckpointOut
&cp
) const
1785 bool dirty(isDirty());
1788 warn("*** The cache still contains dirty data. ***\n");
1789 warn(" Make sure to drain the system using the correct flags.\n");
1790 warn(" This checkpoint will not restore correctly " \
1791 "and dirty data in the cache will be lost!\n");
1794 // Since we don't checkpoint the data in the cache, any dirty data
1795 // will be lost when restoring from a checkpoint of a system that
1796 // wasn't drained properly. Flag the checkpoint as invalid if the
1797 // cache contains dirty data.
1798 bool bad_checkpoint(dirty
);
1799 SERIALIZE_SCALAR(bad_checkpoint
);
1803 BaseCache::unserialize(CheckpointIn
&cp
)
1805 bool bad_checkpoint
;
1806 UNSERIALIZE_SCALAR(bad_checkpoint
);
1807 if (bad_checkpoint
) {
1808 fatal("Restoring from checkpoints with dirty caches is not "
1809 "supported in the classic memory system. Please remove any "
1810 "caches or drain them properly before taking checkpoints.\n");
1815 BaseCache::CacheCmdStats::CacheCmdStats(BaseCache
&c
,
1816 const std::string
&name
)
1817 : Stats::Group(&c
), cache(c
),
1820 this, (name
+ "_hits").c_str(),
1821 ("number of " + name
+ " hits").c_str()),
1823 this, (name
+ "_misses").c_str(),
1824 ("number of " + name
+ " misses").c_str()),
1826 this, (name
+ "_miss_latency").c_str(),
1827 ("number of " + name
+ " miss cycles").c_str()),
1829 this, (name
+ "_accesses").c_str(),
1830 ("number of " + name
+ " accesses(hits+misses)").c_str()),
1832 this, (name
+ "_miss_rate").c_str(),
1833 ("miss rate for " + name
+ " accesses").c_str()),
1835 this, (name
+ "_avg_miss_latency").c_str(),
1836 ("average " + name
+ " miss latency").c_str()),
1838 this, (name
+ "_mshr_hits").c_str(),
1839 ("number of " + name
+ " MSHR hits").c_str()),
1841 this, (name
+ "_mshr_misses").c_str(),
1842 ("number of " + name
+ " MSHR misses").c_str()),
1844 this, (name
+ "_mshr_uncacheable").c_str(),
1845 ("number of " + name
+ " MSHR uncacheable").c_str()),
1847 this, (name
+ "_mshr_miss_latency").c_str(),
1848 ("number of " + name
+ " MSHR miss cycles").c_str()),
1849 mshr_uncacheable_lat(
1850 this, (name
+ "_mshr_uncacheable_latency").c_str(),
1851 ("number of " + name
+ " MSHR uncacheable cycles").c_str()),
1853 this, (name
+ "_mshr_miss_rate").c_str(),
1854 ("mshr miss rate for " + name
+ " accesses").c_str()),
1856 this, (name
+ "_avg_mshr_miss_latency").c_str(),
1857 ("average " + name
+ " mshr miss latency").c_str()),
1858 avgMshrUncacheableLatency(
1859 this, (name
+ "_avg_mshr_uncacheable_latency").c_str(),
1860 ("average " + name
+ " mshr uncacheable latency").c_str())
1865 BaseCache::CacheCmdStats::regStatsFromParent()
1867 using namespace Stats
;
1869 Stats::Group::regStats();
1870 System
*system
= cache
.system
;
1871 const auto max_masters
= system
->maxMasters();
1875 .flags(total
| nozero
| nonan
)
1877 for (int i
= 0; i
< max_masters
; i
++) {
1878 hits
.subname(i
, system
->getMasterName(i
));
1884 .flags(total
| nozero
| nonan
)
1886 for (int i
= 0; i
< max_masters
; i
++) {
1887 misses
.subname(i
, system
->getMasterName(i
));
1890 // Miss latency statistics
1893 .flags(total
| nozero
| nonan
)
1895 for (int i
= 0; i
< max_masters
; i
++) {
1896 missLatency
.subname(i
, system
->getMasterName(i
));
1900 accesses
.flags(total
| nozero
| nonan
);
1901 accesses
= hits
+ misses
;
1902 for (int i
= 0; i
< max_masters
; i
++) {
1903 accesses
.subname(i
, system
->getMasterName(i
));
1906 // miss rate formulas
1907 missRate
.flags(total
| nozero
| nonan
);
1908 missRate
= misses
/ accesses
;
1909 for (int i
= 0; i
< max_masters
; i
++) {
1910 missRate
.subname(i
, system
->getMasterName(i
));
1913 // miss latency formulas
1914 avgMissLatency
.flags(total
| nozero
| nonan
);
1915 avgMissLatency
= missLatency
/ misses
;
1916 for (int i
= 0; i
< max_masters
; i
++) {
1917 avgMissLatency
.subname(i
, system
->getMasterName(i
));
1921 // MSHR hit statistics
1924 .flags(total
| nozero
| nonan
)
1926 for (int i
= 0; i
< max_masters
; i
++) {
1927 mshr_hits
.subname(i
, system
->getMasterName(i
));
1930 // MSHR miss statistics
1933 .flags(total
| nozero
| nonan
)
1935 for (int i
= 0; i
< max_masters
; i
++) {
1936 mshr_misses
.subname(i
, system
->getMasterName(i
));
1939 // MSHR miss latency statistics
1942 .flags(total
| nozero
| nonan
)
1944 for (int i
= 0; i
< max_masters
; i
++) {
1945 mshr_miss_latency
.subname(i
, system
->getMasterName(i
));
1948 // MSHR uncacheable statistics
1951 .flags(total
| nozero
| nonan
)
1953 for (int i
= 0; i
< max_masters
; i
++) {
1954 mshr_uncacheable
.subname(i
, system
->getMasterName(i
));
1957 // MSHR miss latency statistics
1958 mshr_uncacheable_lat
1960 .flags(total
| nozero
| nonan
)
1962 for (int i
= 0; i
< max_masters
; i
++) {
1963 mshr_uncacheable_lat
.subname(i
, system
->getMasterName(i
));
1966 // MSHR miss rate formulas
1967 mshrMissRate
.flags(total
| nozero
| nonan
);
1968 mshrMissRate
= mshr_misses
/ accesses
;
1970 for (int i
= 0; i
< max_masters
; i
++) {
1971 mshrMissRate
.subname(i
, system
->getMasterName(i
));
1974 // mshrMiss latency formulas
1975 avgMshrMissLatency
.flags(total
| nozero
| nonan
);
1976 avgMshrMissLatency
= mshr_miss_latency
/ mshr_misses
;
1977 for (int i
= 0; i
< max_masters
; i
++) {
1978 avgMshrMissLatency
.subname(i
, system
->getMasterName(i
));
1981 // mshrUncacheable latency formulas
1982 avgMshrUncacheableLatency
.flags(total
| nozero
| nonan
);
1983 avgMshrUncacheableLatency
= mshr_uncacheable_lat
/ mshr_uncacheable
;
1984 for (int i
= 0; i
< max_masters
; i
++) {
1985 avgMshrUncacheableLatency
.subname(i
, system
->getMasterName(i
));
1989 BaseCache::CacheStats::CacheStats(BaseCache
&c
)
1990 : Stats::Group(&c
), cache(c
),
1992 demandHits(this, "demand_hits", "number of demand (read+write) hits"),
1994 overallHits(this, "overall_hits", "number of overall hits"),
1995 demandMisses(this, "demand_misses",
1996 "number of demand (read+write) misses"),
1997 overallMisses(this, "overall_misses", "number of overall misses"),
1998 demandMissLatency(this, "demand_miss_latency",
1999 "number of demand (read+write) miss cycles"),
2000 overallMissLatency(this, "overall_miss_latency",
2001 "number of overall miss cycles"),
2002 demandAccesses(this, "demand_accesses",
2003 "number of demand (read+write) accesses"),
2004 overallAccesses(this, "overall_accesses",
2005 "number of overall (read+write) accesses"),
2006 demandMissRate(this, "demand_miss_rate",
2007 "miss rate for demand accesses"),
2008 overallMissRate(this, "overall_miss_rate",
2009 "miss rate for overall accesses"),
2010 demandAvgMissLatency(this, "demand_avg_miss_latency",
2011 "average overall miss latency"),
2012 overallAvgMissLatency(this, "overall_avg_miss_latency",
2013 "average overall miss latency"),
2014 blocked_cycles(this, "blocked_cycles",
2015 "number of cycles access was blocked"),
2016 blocked_causes(this, "blocked", "number of cycles access was blocked"),
2017 avg_blocked(this, "avg_blocked_cycles",
2018 "average number of cycles each access was blocked"),
2019 unusedPrefetches(this, "unused_prefetches",
2020 "number of HardPF blocks evicted w/o reference"),
2021 writebacks(this, "writebacks", "number of writebacks"),
2022 demandMshrHits(this, "demand_mshr_hits",
2023 "number of demand (read+write) MSHR hits"),
2024 overallMshrHits(this, "overall_mshr_hits",
2025 "number of overall MSHR hits"),
2026 demandMshrMisses(this, "demand_mshr_misses",
2027 "number of demand (read+write) MSHR misses"),
2028 overallMshrMisses(this, "overall_mshr_misses",
2029 "number of overall MSHR misses"),
2030 overallMshrUncacheable(this, "overall_mshr_uncacheable_misses",
2031 "number of overall MSHR uncacheable misses"),
2032 demandMshrMissLatency(this, "demand_mshr_miss_latency",
2033 "number of demand (read+write) MSHR miss cycles"),
2034 overallMshrMissLatency(this, "overall_mshr_miss_latency",
2035 "number of overall MSHR miss cycles"),
2036 overallMshrUncacheableLatency(this, "overall_mshr_uncacheable_latency",
2037 "number of overall MSHR uncacheable cycles"),
2038 demandMshrMissRate(this, "demand_mshr_miss_rate",
2039 "mshr miss rate for demand accesses"),
2040 overallMshrMissRate(this, "overall_mshr_miss_rate",
2041 "mshr miss rate for overall accesses"),
2042 demandAvgMshrMissLatency(this, "demand_avg_mshr_miss_latency",
2043 "average overall mshr miss latency"),
2044 overallAvgMshrMissLatency(this, "overall_avg_mshr_miss_latency",
2045 "average overall mshr miss latency"),
2046 overallAvgMshrUncacheableLatency(
2047 this, "overall_avg_mshr_uncacheable_latency",
2048 "average overall mshr uncacheable latency"),
2049 replacements(this, "replacements", "number of replacements"),
2051 dataExpansions(this, "data_expansions", "number of data expansions"),
2052 cmd(MemCmd::NUM_MEM_CMDS
)
2054 for (int idx
= 0; idx
< MemCmd::NUM_MEM_CMDS
; ++idx
)
2055 cmd
[idx
].reset(new CacheCmdStats(c
, MemCmd(idx
).toString()));
2059 BaseCache::CacheStats::regStats()
2061 using namespace Stats
;
2063 Stats::Group::regStats();
2065 System
*system
= cache
.system
;
2066 const auto max_masters
= system
->maxMasters();
2068 for (auto &cs
: cmd
)
2069 cs
->regStatsFromParent();
2071 // These macros make it easier to sum the right subset of commands and
2072 // to change the subset of commands that are considered "demand" vs
2074 #define SUM_DEMAND(s) \
2075 (cmd[MemCmd::ReadReq]->s + cmd[MemCmd::WriteReq]->s + \
2076 cmd[MemCmd::WriteLineReq]->s + cmd[MemCmd::ReadExReq]->s + \
2077 cmd[MemCmd::ReadCleanReq]->s + cmd[MemCmd::ReadSharedReq]->s)
2079 // should writebacks be included here? prior code was inconsistent...
2080 #define SUM_NON_DEMAND(s) \
2081 (cmd[MemCmd::SoftPFReq]->s + cmd[MemCmd::HardPFReq]->s + \
2082 cmd[MemCmd::SoftPFExReq]->s)
2084 demandHits
.flags(total
| nozero
| nonan
);
2085 demandHits
= SUM_DEMAND(hits
);
2086 for (int i
= 0; i
< max_masters
; i
++) {
2087 demandHits
.subname(i
, system
->getMasterName(i
));
2090 overallHits
.flags(total
| nozero
| nonan
);
2091 overallHits
= demandHits
+ SUM_NON_DEMAND(hits
);
2092 for (int i
= 0; i
< max_masters
; i
++) {
2093 overallHits
.subname(i
, system
->getMasterName(i
));
2096 demandMisses
.flags(total
| nozero
| nonan
);
2097 demandMisses
= SUM_DEMAND(misses
);
2098 for (int i
= 0; i
< max_masters
; i
++) {
2099 demandMisses
.subname(i
, system
->getMasterName(i
));
2102 overallMisses
.flags(total
| nozero
| nonan
);
2103 overallMisses
= demandMisses
+ SUM_NON_DEMAND(misses
);
2104 for (int i
= 0; i
< max_masters
; i
++) {
2105 overallMisses
.subname(i
, system
->getMasterName(i
));
2108 demandMissLatency
.flags(total
| nozero
| nonan
);
2109 demandMissLatency
= SUM_DEMAND(missLatency
);
2110 for (int i
= 0; i
< max_masters
; i
++) {
2111 demandMissLatency
.subname(i
, system
->getMasterName(i
));
2114 overallMissLatency
.flags(total
| nozero
| nonan
);
2115 overallMissLatency
= demandMissLatency
+ SUM_NON_DEMAND(missLatency
);
2116 for (int i
= 0; i
< max_masters
; i
++) {
2117 overallMissLatency
.subname(i
, system
->getMasterName(i
));
2120 demandAccesses
.flags(total
| nozero
| nonan
);
2121 demandAccesses
= demandHits
+ demandMisses
;
2122 for (int i
= 0; i
< max_masters
; i
++) {
2123 demandAccesses
.subname(i
, system
->getMasterName(i
));
2126 overallAccesses
.flags(total
| nozero
| nonan
);
2127 overallAccesses
= overallHits
+ overallMisses
;
2128 for (int i
= 0; i
< max_masters
; i
++) {
2129 overallAccesses
.subname(i
, system
->getMasterName(i
));
2132 demandMissRate
.flags(total
| nozero
| nonan
);
2133 demandMissRate
= demandMisses
/ demandAccesses
;
2134 for (int i
= 0; i
< max_masters
; i
++) {
2135 demandMissRate
.subname(i
, system
->getMasterName(i
));
2138 overallMissRate
.flags(total
| nozero
| nonan
);
2139 overallMissRate
= overallMisses
/ overallAccesses
;
2140 for (int i
= 0; i
< max_masters
; i
++) {
2141 overallMissRate
.subname(i
, system
->getMasterName(i
));
2144 demandAvgMissLatency
.flags(total
| nozero
| nonan
);
2145 demandAvgMissLatency
= demandMissLatency
/ demandMisses
;
2146 for (int i
= 0; i
< max_masters
; i
++) {
2147 demandAvgMissLatency
.subname(i
, system
->getMasterName(i
));
2150 overallAvgMissLatency
.flags(total
| nozero
| nonan
);
2151 overallAvgMissLatency
= overallMissLatency
/ overallMisses
;
2152 for (int i
= 0; i
< max_masters
; i
++) {
2153 overallAvgMissLatency
.subname(i
, system
->getMasterName(i
));
2156 blocked_cycles
.init(NUM_BLOCKED_CAUSES
);
2158 .subname(Blocked_NoMSHRs
, "no_mshrs")
2159 .subname(Blocked_NoTargets
, "no_targets")
2163 blocked_causes
.init(NUM_BLOCKED_CAUSES
);
2165 .subname(Blocked_NoMSHRs
, "no_mshrs")
2166 .subname(Blocked_NoTargets
, "no_targets")
2170 .subname(Blocked_NoMSHRs
, "no_mshrs")
2171 .subname(Blocked_NoTargets
, "no_targets")
2173 avg_blocked
= blocked_cycles
/ blocked_causes
;
2175 unusedPrefetches
.flags(nozero
);
2179 .flags(total
| nozero
| nonan
)
2181 for (int i
= 0; i
< max_masters
; i
++) {
2182 writebacks
.subname(i
, system
->getMasterName(i
));
2185 demandMshrHits
.flags(total
| nozero
| nonan
);
2186 demandMshrHits
= SUM_DEMAND(mshr_hits
);
2187 for (int i
= 0; i
< max_masters
; i
++) {
2188 demandMshrHits
.subname(i
, system
->getMasterName(i
));
2191 overallMshrHits
.flags(total
| nozero
| nonan
);
2192 overallMshrHits
= demandMshrHits
+ SUM_NON_DEMAND(mshr_hits
);
2193 for (int i
= 0; i
< max_masters
; i
++) {
2194 overallMshrHits
.subname(i
, system
->getMasterName(i
));
2197 demandMshrMisses
.flags(total
| nozero
| nonan
);
2198 demandMshrMisses
= SUM_DEMAND(mshr_misses
);
2199 for (int i
= 0; i
< max_masters
; i
++) {
2200 demandMshrMisses
.subname(i
, system
->getMasterName(i
));
2203 overallMshrMisses
.flags(total
| nozero
| nonan
);
2204 overallMshrMisses
= demandMshrMisses
+ SUM_NON_DEMAND(mshr_misses
);
2205 for (int i
= 0; i
< max_masters
; i
++) {
2206 overallMshrMisses
.subname(i
, system
->getMasterName(i
));
2209 demandMshrMissLatency
.flags(total
| nozero
| nonan
);
2210 demandMshrMissLatency
= SUM_DEMAND(mshr_miss_latency
);
2211 for (int i
= 0; i
< max_masters
; i
++) {
2212 demandMshrMissLatency
.subname(i
, system
->getMasterName(i
));
2215 overallMshrMissLatency
.flags(total
| nozero
| nonan
);
2216 overallMshrMissLatency
=
2217 demandMshrMissLatency
+ SUM_NON_DEMAND(mshr_miss_latency
);
2218 for (int i
= 0; i
< max_masters
; i
++) {
2219 overallMshrMissLatency
.subname(i
, system
->getMasterName(i
));
2222 overallMshrUncacheable
.flags(total
| nozero
| nonan
);
2223 overallMshrUncacheable
=
2224 SUM_DEMAND(mshr_uncacheable
) + SUM_NON_DEMAND(mshr_uncacheable
);
2225 for (int i
= 0; i
< max_masters
; i
++) {
2226 overallMshrUncacheable
.subname(i
, system
->getMasterName(i
));
2230 overallMshrUncacheableLatency
.flags(total
| nozero
| nonan
);
2231 overallMshrUncacheableLatency
=
2232 SUM_DEMAND(mshr_uncacheable_lat
) +
2233 SUM_NON_DEMAND(mshr_uncacheable_lat
);
2234 for (int i
= 0; i
< max_masters
; i
++) {
2235 overallMshrUncacheableLatency
.subname(i
, system
->getMasterName(i
));
2238 demandMshrMissRate
.flags(total
| nozero
| nonan
);
2239 demandMshrMissRate
= demandMshrMisses
/ demandAccesses
;
2240 for (int i
= 0; i
< max_masters
; i
++) {
2241 demandMshrMissRate
.subname(i
, system
->getMasterName(i
));
2244 overallMshrMissRate
.flags(total
| nozero
| nonan
);
2245 overallMshrMissRate
= overallMshrMisses
/ overallAccesses
;
2246 for (int i
= 0; i
< max_masters
; i
++) {
2247 overallMshrMissRate
.subname(i
, system
->getMasterName(i
));
2250 demandAvgMshrMissLatency
.flags(total
| nozero
| nonan
);
2251 demandAvgMshrMissLatency
= demandMshrMissLatency
/ demandMshrMisses
;
2252 for (int i
= 0; i
< max_masters
; i
++) {
2253 demandAvgMshrMissLatency
.subname(i
, system
->getMasterName(i
));
2256 overallAvgMshrMissLatency
.flags(total
| nozero
| nonan
);
2257 overallAvgMshrMissLatency
= overallMshrMissLatency
/ overallMshrMisses
;
2258 for (int i
= 0; i
< max_masters
; i
++) {
2259 overallAvgMshrMissLatency
.subname(i
, system
->getMasterName(i
));
2262 overallAvgMshrUncacheableLatency
.flags(total
| nozero
| nonan
);
2263 overallAvgMshrUncacheableLatency
=
2264 overallMshrUncacheableLatency
/ overallMshrUncacheable
;
2265 for (int i
= 0; i
< max_masters
; i
++) {
2266 overallAvgMshrUncacheableLatency
.subname(i
, system
->getMasterName(i
));
2269 dataExpansions
.flags(nozero
| nonan
);
2273 BaseCache::regProbePoints()
2275 ppHit
= new ProbePointArg
<PacketPtr
>(this->getProbeManager(), "Hit");
2276 ppMiss
= new ProbePointArg
<PacketPtr
>(this->getProbeManager(), "Miss");
2277 ppFill
= new ProbePointArg
<PacketPtr
>(this->getProbeManager(), "Fill");
2286 BaseCache::CpuSidePort::recvTimingSnoopResp(PacketPtr pkt
)
2288 // Snoops shouldn't happen when bypassing caches
2289 assert(!cache
->system
->bypassCaches());
2291 assert(pkt
->isResponse());
2293 // Express snoop responses from master to slave, e.g., from L1 to L2
2294 cache
->recvTimingSnoopResp(pkt
);
2300 BaseCache::CpuSidePort::tryTiming(PacketPtr pkt
)
2302 if (cache
->system
->bypassCaches() || pkt
->isExpressSnoop()) {
2303 // always let express snoop packets through even if blocked
2305 } else if (blocked
|| mustSendRetry
) {
2306 // either already committed to send a retry, or blocked
2307 mustSendRetry
= true;
2310 mustSendRetry
= false;
2315 BaseCache::CpuSidePort::recvTimingReq(PacketPtr pkt
)
2317 assert(pkt
->isRequest());
2319 if (cache
->system
->bypassCaches()) {
2320 // Just forward the packet if caches are disabled.
2321 // @todo This should really enqueue the packet rather
2322 bool M5_VAR_USED success
= cache
->memSidePort
.sendTimingReq(pkt
);
2325 } else if (tryTiming(pkt
)) {
2326 cache
->recvTimingReq(pkt
);
2333 BaseCache::CpuSidePort::recvAtomic(PacketPtr pkt
)
2335 if (cache
->system
->bypassCaches()) {
2336 // Forward the request if the system is in cache bypass mode.
2337 return cache
->memSidePort
.sendAtomic(pkt
);
2339 return cache
->recvAtomic(pkt
);
2344 BaseCache::CpuSidePort::recvFunctional(PacketPtr pkt
)
2346 if (cache
->system
->bypassCaches()) {
2347 // The cache should be flushed if we are in cache bypass mode,
2348 // so we don't need to check if we need to update anything.
2349 cache
->memSidePort
.sendFunctional(pkt
);
2353 // functional request
2354 cache
->functionalAccess(pkt
, true);
2358 BaseCache::CpuSidePort::getAddrRanges() const
2360 return cache
->getAddrRanges();
2365 CpuSidePort::CpuSidePort(const std::string
&_name
, BaseCache
*_cache
,
2366 const std::string
&_label
)
2367 : CacheSlavePort(_name
, _cache
, _label
), cache(_cache
)
2377 BaseCache::MemSidePort::recvTimingResp(PacketPtr pkt
)
2379 cache
->recvTimingResp(pkt
);
2383 // Express snooping requests to memside port
2385 BaseCache::MemSidePort::recvTimingSnoopReq(PacketPtr pkt
)
2387 // Snoops shouldn't happen when bypassing caches
2388 assert(!cache
->system
->bypassCaches());
2390 // handle snooping requests
2391 cache
->recvTimingSnoopReq(pkt
);
2395 BaseCache::MemSidePort::recvAtomicSnoop(PacketPtr pkt
)
2397 // Snoops shouldn't happen when bypassing caches
2398 assert(!cache
->system
->bypassCaches());
2400 return cache
->recvAtomicSnoop(pkt
);
2404 BaseCache::MemSidePort::recvFunctionalSnoop(PacketPtr pkt
)
2406 // Snoops shouldn't happen when bypassing caches
2407 assert(!cache
->system
->bypassCaches());
2409 // functional snoop (note that in contrast to atomic we don't have
2410 // a specific functionalSnoop method, as they have the same
2411 // behaviour regardless)
2412 cache
->functionalAccess(pkt
, false);
2416 BaseCache::CacheReqPacketQueue::sendDeferredPacket()
2419 assert(!waitingOnRetry
);
2421 // there should never be any deferred request packets in the
2422 // queue, instead we resly on the cache to provide the packets
2423 // from the MSHR queue or write queue
2424 assert(deferredPacketReadyTime() == MaxTick
);
2426 // check for request packets (requests & writebacks)
2427 QueueEntry
* entry
= cache
.getNextQueueEntry();
2430 // can happen if e.g. we attempt a writeback and fail, but
2431 // before the retry, the writeback is eliminated because
2432 // we snoop another cache's ReadEx.
2434 // let our snoop responses go first if there are responses to
2435 // the same addresses
2436 if (checkConflictingSnoop(entry
->getTarget()->pkt
)) {
2439 waitingOnRetry
= entry
->sendPacket(cache
);
2442 // if we succeeded and are not waiting for a retry, schedule the
2443 // next send considering when the next queue is ready, note that
2444 // snoop responses have their own packet queue and thus schedule
2446 if (!waitingOnRetry
) {
2447 schedSendEvent(cache
.nextQueueReadyTime());
2451 BaseCache::MemSidePort::MemSidePort(const std::string
&_name
,
2453 const std::string
&_label
)
2454 : CacheMasterPort(_name
, _cache
, _reqQueue
, _snoopRespQueue
),
2455 _reqQueue(*_cache
, *this, _snoopRespQueue
, _label
),
2456 _snoopRespQueue(*_cache
, *this, true, _label
), cache(_cache
)
2461 WriteAllocator::updateMode(Addr write_addr
, unsigned write_size
,
2464 // check if we are continuing where the last write ended
2465 if (nextAddr
== write_addr
) {
2466 delayCtr
[blk_addr
] = delayThreshold
;
2467 // stop if we have already saturated
2468 if (mode
!= WriteMode::NO_ALLOCATE
) {
2469 byteCount
+= write_size
;
2470 // switch to streaming mode if we have passed the lower
2472 if (mode
== WriteMode::ALLOCATE
&&
2473 byteCount
> coalesceLimit
) {
2474 mode
= WriteMode::COALESCE
;
2475 DPRINTF(Cache
, "Switched to write coalescing\n");
2476 } else if (mode
== WriteMode::COALESCE
&&
2477 byteCount
> noAllocateLimit
) {
2478 // and continue and switch to non-allocating mode if we
2479 // pass the upper threshold
2480 mode
= WriteMode::NO_ALLOCATE
;
2481 DPRINTF(Cache
, "Switched to write-no-allocate\n");
2485 // we did not see a write matching the previous one, start
2487 byteCount
= write_size
;
2488 mode
= WriteMode::ALLOCATE
;
2489 resetDelay(blk_addr
);
2491 nextAddr
= write_addr
+ write_size
;
2495 WriteAllocatorParams::create()
2497 return new WriteAllocator(this);