2 * Copyright (c) 2012-2013, 2018 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.
40 * Authors: Erik Hallnor
46 * Definition of BaseCache functions.
49 #include "mem/cache/base.hh"
51 #include "base/compiler.hh"
52 #include "base/logging.hh"
53 #include "debug/Cache.hh"
54 #include "debug/CachePort.hh"
55 #include "debug/CacheRepl.hh"
56 #include "debug/CacheVerbose.hh"
57 #include "mem/cache/mshr.hh"
58 #include "mem/cache/prefetch/base.hh"
59 #include "mem/cache/queue_entry.hh"
60 #include "params/BaseCache.hh"
61 #include "params/WriteAllocator.hh"
62 #include "sim/core.hh"
69 BaseCache::CacheSlavePort::CacheSlavePort(const std::string
&_name
,
71 const std::string
&_label
)
72 : QueuedSlavePort(_name
, _cache
, queue
),
73 queue(*_cache
, *this, true, _label
),
74 blocked(false), mustSendRetry(false),
75 sendRetryEvent([this]{ processSendRetry(); }, _name
)
79 BaseCache::BaseCache(const BaseCacheParams
*p
, unsigned blk_size
)
81 cpuSidePort (p
->name
+ ".cpu_side", this, "CpuSidePort"),
82 memSidePort(p
->name
+ ".mem_side", this, "MemSidePort"),
83 mshrQueue("MSHRs", p
->mshrs
, 0, p
->demand_mshr_reserve
), // see below
84 writeBuffer("write buffer", p
->write_buffers
, p
->mshrs
), // see below
86 prefetcher(p
->prefetcher
),
87 writeAllocator(p
->write_allocator
),
88 writebackClean(p
->writeback_clean
),
89 tempBlockWriteback(nullptr),
90 writebackTempBlockAtomicEvent([this]{ writebackTempBlockAtomic(); },
92 EventBase::Delayed_Writeback_Pri
),
94 lookupLatency(p
->tag_latency
),
95 dataLatency(p
->data_latency
),
96 forwardLatency(p
->tag_latency
),
97 fillLatency(p
->data_latency
),
98 responseLatency(p
->response_latency
),
99 sequentialAccess(p
->sequential_access
),
100 numTarget(p
->tgts_per_mshr
),
102 clusivity(p
->clusivity
),
103 isReadOnly(p
->is_read_only
),
106 noTargetMSHR(nullptr),
107 missCount(p
->max_miss_count
),
108 addrRanges(p
->addr_ranges
.begin(), p
->addr_ranges
.end()),
111 // the MSHR queue has no reserve entries as we check the MSHR
112 // queue on every single allocation, whereas the write queue has
113 // as many reserve entries as we have MSHRs, since every MSHR may
114 // eventually require a writeback, and we do not check the write
115 // buffer before committing to an MSHR
117 // forward snoops is overridden in init() once we can query
118 // whether the connected master is actually snooping or not
120 tempBlock
= new TempCacheBlk(blkSize
);
124 prefetcher
->setCache(this);
127 BaseCache::~BaseCache()
133 BaseCache::CacheSlavePort::setBlocked()
136 DPRINTF(CachePort
, "Port is blocking new requests\n");
138 // if we already scheduled a retry in this cycle, but it has not yet
139 // happened, cancel it
140 if (sendRetryEvent
.scheduled()) {
141 owner
.deschedule(sendRetryEvent
);
142 DPRINTF(CachePort
, "Port descheduled retry\n");
143 mustSendRetry
= true;
148 BaseCache::CacheSlavePort::clearBlocked()
151 DPRINTF(CachePort
, "Port is accepting new requests\n");
154 // @TODO: need to find a better time (next cycle?)
155 owner
.schedule(sendRetryEvent
, curTick() + 1);
160 BaseCache::CacheSlavePort::processSendRetry()
162 DPRINTF(CachePort
, "Port is sending retry\n");
164 // reset the flag and call retry
165 mustSendRetry
= false;
170 BaseCache::regenerateBlkAddr(CacheBlk
* blk
)
172 if (blk
!= tempBlock
) {
173 return tags
->regenerateBlkAddr(blk
);
175 return tempBlock
->getAddr();
182 if (!cpuSidePort
.isConnected() || !memSidePort
.isConnected())
183 fatal("Cache ports on %s are not connected\n", name());
184 cpuSidePort
.sendRangeChange();
185 forwardSnoops
= cpuSidePort
.isSnooping();
189 BaseCache::getPort(const std::string
&if_name
, PortID idx
)
191 if (if_name
== "mem_side") {
193 } else if (if_name
== "cpu_side") {
196 return MemObject::getPort(if_name
, idx
);
201 BaseCache::inRange(Addr addr
) const
203 for (const auto& r
: addrRanges
) {
204 if (r
.contains(addr
)) {
212 BaseCache::handleTimingReqHit(PacketPtr pkt
, CacheBlk
*blk
, Tick request_time
)
214 if (pkt
->needsResponse()) {
215 // These delays should have been consumed by now
216 assert(pkt
->headerDelay
== 0);
217 assert(pkt
->payloadDelay
== 0);
219 pkt
->makeTimingResponse();
221 // In this case we are considering request_time that takes
222 // into account the delay of the xbar, if any, and just
223 // lat, neglecting responseLatency, modelling hit latency
224 // just as the value of lat overriden by access(), which calls
225 // the calculateAccessLatency() function.
226 cpuSidePort
.schedTimingResp(pkt
, request_time
);
228 DPRINTF(Cache
, "%s satisfied %s, no response needed\n", __func__
,
231 // queue the packet for deletion, as the sending cache is
232 // still relying on it; if the block is found in access(),
233 // CleanEvict and Writeback messages will be deleted
235 pendingDelete
.reset(pkt
);
240 BaseCache::handleTimingReqMiss(PacketPtr pkt
, MSHR
*mshr
, CacheBlk
*blk
,
241 Tick forward_time
, Tick request_time
)
243 if (writeAllocator
&&
244 pkt
&& pkt
->isWrite() && !pkt
->req
->isUncacheable()) {
245 writeAllocator
->updateMode(pkt
->getAddr(), pkt
->getSize(),
246 pkt
->getBlockAddr(blkSize
));
251 /// @note writebacks will be checked in getNextMSHR()
252 /// for any conflicting requests to the same block
254 //@todo remove hw_pf here
256 // Coalesce unless it was a software prefetch (see above).
258 assert(!pkt
->isWriteback());
259 // CleanEvicts corresponding to blocks which have
260 // outstanding requests in MSHRs are simply sunk here
261 if (pkt
->cmd
== MemCmd::CleanEvict
) {
262 pendingDelete
.reset(pkt
);
263 } else if (pkt
->cmd
== MemCmd::WriteClean
) {
264 // A WriteClean should never coalesce with any
265 // outstanding cache maintenance requests.
267 // We use forward_time here because there is an
268 // uncached memory write, forwarded to WriteBuffer.
269 allocateWriteBuffer(pkt
, forward_time
);
271 DPRINTF(Cache
, "%s coalescing MSHR for %s\n", __func__
,
274 assert(pkt
->req
->masterId() < system
->maxMasters());
275 mshr_hits
[pkt
->cmdToIndex()][pkt
->req
->masterId()]++;
277 // We use forward_time here because it is the same
278 // considering new targets. We have multiple
279 // requests for the same address here. It
280 // specifies the latency to allocate an internal
281 // buffer and to schedule an event to the queued
282 // port and also takes into account the additional
283 // delay of the xbar.
284 mshr
->allocateTarget(pkt
, forward_time
, order
++,
285 allocOnFill(pkt
->cmd
));
286 if (mshr
->getNumTargets() == numTarget
) {
288 setBlocked(Blocked_NoTargets
);
289 // need to be careful with this... if this mshr isn't
290 // ready yet (i.e. time > curTick()), we don't want to
291 // move it ahead of mshrs that are ready
292 // mshrQueue.moveToFront(mshr);
298 assert(pkt
->req
->masterId() < system
->maxMasters());
299 mshr_misses
[pkt
->cmdToIndex()][pkt
->req
->masterId()]++;
301 if (pkt
->isEviction() || pkt
->cmd
== MemCmd::WriteClean
) {
302 // We use forward_time here because there is an
303 // writeback or writeclean, forwarded to WriteBuffer.
304 allocateWriteBuffer(pkt
, forward_time
);
306 if (blk
&& blk
->isValid()) {
307 // If we have a write miss to a valid block, we
308 // need to mark the block non-readable. Otherwise
309 // if we allow reads while there's an outstanding
310 // write miss, the read could return stale data
311 // out of the cache block... a more aggressive
312 // system could detect the overlap (if any) and
313 // forward data out of the MSHRs, but we don't do
314 // that yet. Note that we do need to leave the
315 // block valid so that it stays in the cache, in
316 // case we get an upgrade response (and hence no
317 // new data) when the write miss completes.
318 // As long as CPUs do proper store/load forwarding
319 // internally, and have a sufficiently weak memory
320 // model, this is probably unnecessary, but at some
321 // point it must have seemed like we needed it...
322 assert((pkt
->needsWritable() && !blk
->isWritable()) ||
323 pkt
->req
->isCacheMaintenance());
324 blk
->status
&= ~BlkReadable
;
326 // Here we are using forward_time, modelling the latency of
327 // a miss (outbound) just as forwardLatency, neglecting the
328 // lookupLatency component.
329 allocateMissBuffer(pkt
, forward_time
);
335 BaseCache::recvTimingReq(PacketPtr pkt
)
337 // anything that is merely forwarded pays for the forward latency and
338 // the delay provided by the crossbar
339 Tick forward_time
= clockEdge(forwardLatency
) + pkt
->headerDelay
;
342 CacheBlk
*blk
= nullptr;
343 bool satisfied
= false;
345 PacketList writebacks
;
346 // Note that lat is passed by reference here. The function
347 // access() will set the lat value.
348 satisfied
= access(pkt
, blk
, lat
, writebacks
);
350 // After the evicted blocks are selected, they must be forwarded
351 // to the write buffer to ensure they logically precede anything
353 doWritebacks(writebacks
, clockEdge(lat
+ forwardLatency
));
356 // Here we charge the headerDelay that takes into account the latencies
357 // of the bus, if the packet comes from it.
358 // The latency charged is just the value set by the access() function.
359 // In case of a hit we are neglecting response latency.
360 // In case of a miss we are neglecting forward latency.
361 Tick request_time
= clockEdge(lat
);
362 // Here we reset the timing of the packet.
363 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
366 // notify before anything else as later handleTimingReqHit might turn
367 // the packet in a response
370 if (prefetcher
&& blk
&& blk
->wasPrefetched()) {
371 blk
->status
&= ~BlkHWPrefetched
;
374 handleTimingReqHit(pkt
, blk
, request_time
);
376 handleTimingReqMiss(pkt
, blk
, forward_time
, request_time
);
382 // track time of availability of next prefetch, if any
383 Tick next_pf_time
= prefetcher
->nextPrefetchReadyTime();
384 if (next_pf_time
!= MaxTick
) {
385 schedMemSideSendEvent(next_pf_time
);
391 BaseCache::handleUncacheableWriteResp(PacketPtr pkt
)
393 Tick completion_time
= clockEdge(responseLatency
) +
394 pkt
->headerDelay
+ pkt
->payloadDelay
;
396 // Reset the bus additional time as it is now accounted for
397 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
399 cpuSidePort
.schedTimingResp(pkt
, completion_time
);
403 BaseCache::recvTimingResp(PacketPtr pkt
)
405 assert(pkt
->isResponse());
407 // all header delay should be paid for by the crossbar, unless
408 // this is a prefetch response from above
409 panic_if(pkt
->headerDelay
!= 0 && pkt
->cmd
!= MemCmd::HardPFResp
,
410 "%s saw a non-zero packet delay\n", name());
412 const bool is_error
= pkt
->isError();
415 DPRINTF(Cache
, "%s: Cache received %s with error\n", __func__
,
419 DPRINTF(Cache
, "%s: Handling response %s\n", __func__
,
422 // if this is a write, we should be looking at an uncacheable
424 if (pkt
->isWrite()) {
425 assert(pkt
->req
->isUncacheable());
426 handleUncacheableWriteResp(pkt
);
430 // we have dealt with any (uncacheable) writes above, from here on
431 // we know we are dealing with an MSHR due to a miss or a prefetch
432 MSHR
*mshr
= dynamic_cast<MSHR
*>(pkt
->popSenderState());
435 if (mshr
== noTargetMSHR
) {
436 // we always clear at least one target
437 clearBlocked(Blocked_NoTargets
);
438 noTargetMSHR
= nullptr;
441 // Initial target is used just for stats
442 MSHR::Target
*initial_tgt
= mshr
->getTarget();
443 int stats_cmd_idx
= initial_tgt
->pkt
->cmdToIndex();
444 Tick miss_latency
= curTick() - initial_tgt
->recvTime
;
446 if (pkt
->req
->isUncacheable()) {
447 assert(pkt
->req
->masterId() < system
->maxMasters());
448 mshr_uncacheable_lat
[stats_cmd_idx
][pkt
->req
->masterId()] +=
451 assert(pkt
->req
->masterId() < system
->maxMasters());
452 mshr_miss_latency
[stats_cmd_idx
][pkt
->req
->masterId()] +=
456 PacketList writebacks
;
458 bool is_fill
= !mshr
->isForward
&&
459 (pkt
->isRead() || pkt
->cmd
== MemCmd::UpgradeResp
||
460 mshr
->wasWholeLineWrite
);
462 // make sure that if the mshr was due to a whole line write then
463 // the response is an invalidation
464 assert(!mshr
->wasWholeLineWrite
|| pkt
->isInvalidate());
466 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), pkt
->isSecure());
468 if (is_fill
&& !is_error
) {
469 DPRINTF(Cache
, "Block for addr %#llx being updated in Cache\n",
472 const bool allocate
= (writeAllocator
&& mshr
->wasWholeLineWrite
) ?
473 writeAllocator
->allocate() : mshr
->allocOnFill();
474 blk
= handleFill(pkt
, blk
, writebacks
, allocate
);
475 assert(blk
!= nullptr);
479 if (blk
&& blk
->isValid() && pkt
->isClean() && !pkt
->isInvalidate()) {
480 // The block was marked not readable while there was a pending
481 // cache maintenance operation, restore its flag.
482 blk
->status
|= BlkReadable
;
484 // This was a cache clean operation (without invalidate)
485 // and we have a copy of the block already. Since there
486 // is no invalidation, we can promote targets that don't
487 // require a writable copy
488 mshr
->promoteReadable();
491 if (blk
&& blk
->isWritable() && !pkt
->req
->isCacheInvalidate()) {
492 // If at this point the referenced block is writable and the
493 // response is not a cache invalidate, we promote targets that
494 // were deferred as we couldn't guarrantee a writable copy
495 mshr
->promoteWritable();
498 serviceMSHRTargets(mshr
, pkt
, blk
);
500 if (mshr
->promoteDeferredTargets()) {
501 // avoid later read getting stale data while write miss is
502 // outstanding.. see comment in timingAccess()
504 blk
->status
&= ~BlkReadable
;
506 mshrQueue
.markPending(mshr
);
507 schedMemSideSendEvent(clockEdge() + pkt
->payloadDelay
);
509 // while we deallocate an mshr from the queue we still have to
510 // check the isFull condition before and after as we might
511 // have been using the reserved entries already
512 const bool was_full
= mshrQueue
.isFull();
513 mshrQueue
.deallocate(mshr
);
514 if (was_full
&& !mshrQueue
.isFull()) {
515 clearBlocked(Blocked_NoMSHRs
);
518 // Request the bus for a prefetch if this deallocation freed enough
519 // MSHRs for a prefetch to take place
520 if (prefetcher
&& mshrQueue
.canPrefetch()) {
521 Tick next_pf_time
= std::max(prefetcher
->nextPrefetchReadyTime(),
523 if (next_pf_time
!= MaxTick
)
524 schedMemSideSendEvent(next_pf_time
);
528 // if we used temp block, check to see if its valid and then clear it out
529 if (blk
== tempBlock
&& tempBlock
->isValid()) {
530 evictBlock(blk
, writebacks
);
533 const Tick forward_time
= clockEdge(forwardLatency
) + pkt
->headerDelay
;
534 // copy writebacks to write buffer
535 doWritebacks(writebacks
, forward_time
);
537 DPRINTF(CacheVerbose
, "%s: Leaving with %s\n", __func__
, pkt
->print());
543 BaseCache::recvAtomic(PacketPtr pkt
)
545 // should assert here that there are no outstanding MSHRs or
546 // writebacks... that would mean that someone used an atomic
547 // access in timing mode
549 // We use lookupLatency here because it is used to specify the latency
551 Cycles lat
= lookupLatency
;
553 CacheBlk
*blk
= nullptr;
554 PacketList writebacks
;
555 bool satisfied
= access(pkt
, blk
, lat
, writebacks
);
557 if (pkt
->isClean() && blk
&& blk
->isDirty()) {
558 // A cache clean opearation is looking for a dirty
559 // block. If a dirty block is encountered a WriteClean
560 // will update any copies to the path to the memory
561 // until the point of reference.
562 DPRINTF(CacheVerbose
, "%s: packet %s found block: %s\n",
563 __func__
, pkt
->print(), blk
->print());
564 PacketPtr wb_pkt
= writecleanBlk(blk
, pkt
->req
->getDest(), pkt
->id
);
565 writebacks
.push_back(wb_pkt
);
569 // handle writebacks resulting from the access here to ensure they
570 // logically precede anything happening below
571 doWritebacksAtomic(writebacks
);
572 assert(writebacks
.empty());
575 lat
+= handleAtomicReqMiss(pkt
, blk
, writebacks
);
578 // Note that we don't invoke the prefetcher at all in atomic mode.
579 // It's not clear how to do it properly, particularly for
580 // prefetchers that aggressively generate prefetch candidates and
581 // rely on bandwidth contention to throttle them; these will tend
582 // to pollute the cache in atomic mode since there is no bandwidth
583 // contention. If we ever do want to enable prefetching in atomic
584 // mode, though, this is the place to do it... see timingAccess()
585 // for an example (though we'd want to issue the prefetch(es)
586 // immediately rather than calling requestMemSideBus() as we do
589 // do any writebacks resulting from the response handling
590 doWritebacksAtomic(writebacks
);
592 // if we used temp block, check to see if its valid and if so
593 // clear it out, but only do so after the call to recvAtomic is
594 // finished so that any downstream observers (such as a snoop
595 // filter), first see the fill, and only then see the eviction
596 if (blk
== tempBlock
&& tempBlock
->isValid()) {
597 // the atomic CPU calls recvAtomic for fetch and load/store
598 // sequentuially, and we may already have a tempBlock
599 // writeback from the fetch that we have not yet sent
600 if (tempBlockWriteback
) {
601 // if that is the case, write the prevoius one back, and
602 // do not schedule any new event
603 writebackTempBlockAtomic();
605 // the writeback/clean eviction happens after the call to
606 // recvAtomic has finished (but before any successive
607 // calls), so that the response handling from the fill is
608 // allowed to happen first
609 schedule(writebackTempBlockAtomicEvent
, curTick());
612 tempBlockWriteback
= evictBlock(blk
);
615 if (pkt
->needsResponse()) {
616 pkt
->makeAtomicResponse();
619 return lat
* clockPeriod();
623 BaseCache::functionalAccess(PacketPtr pkt
, bool from_cpu_side
)
625 Addr blk_addr
= pkt
->getBlockAddr(blkSize
);
626 bool is_secure
= pkt
->isSecure();
627 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), is_secure
);
628 MSHR
*mshr
= mshrQueue
.findMatch(blk_addr
, is_secure
);
630 pkt
->pushLabel(name());
632 CacheBlkPrintWrapper
cbpw(blk
);
634 // Note that just because an L2/L3 has valid data doesn't mean an
635 // L1 doesn't have a more up-to-date modified copy that still
636 // needs to be found. As a result we always update the request if
637 // we have it, but only declare it satisfied if we are the owner.
639 // see if we have data at all (owned or otherwise)
640 bool have_data
= blk
&& blk
->isValid()
641 && pkt
->trySatisfyFunctional(&cbpw
, blk_addr
, is_secure
, blkSize
,
644 // data we have is dirty if marked as such or if we have an
645 // in-service MSHR that is pending a modified line
647 have_data
&& (blk
->isDirty() ||
648 (mshr
&& mshr
->inService
&& mshr
->isPendingModified()));
650 bool done
= have_dirty
||
651 cpuSidePort
.trySatisfyFunctional(pkt
) ||
652 mshrQueue
.trySatisfyFunctional(pkt
, blk_addr
) ||
653 writeBuffer
.trySatisfyFunctional(pkt
, blk_addr
) ||
654 memSidePort
.trySatisfyFunctional(pkt
);
656 DPRINTF(CacheVerbose
, "%s: %s %s%s%s\n", __func__
, pkt
->print(),
657 (blk
&& blk
->isValid()) ? "valid " : "",
658 have_data
? "data " : "", done
? "done " : "");
660 // We're leaving the cache, so pop cache->name() label
666 // if it came as a request from the CPU side then make sure it
667 // continues towards the memory side
669 memSidePort
.sendFunctional(pkt
);
670 } else if (cpuSidePort
.isSnooping()) {
671 // if it came from the memory side, it must be a snoop request
672 // and we should only forward it if we are forwarding snoops
673 cpuSidePort
.sendFunctionalSnoop(pkt
);
680 BaseCache::cmpAndSwap(CacheBlk
*blk
, PacketPtr pkt
)
682 assert(pkt
->isRequest());
684 uint64_t overwrite_val
;
686 uint64_t condition_val64
;
687 uint32_t condition_val32
;
689 int offset
= pkt
->getOffset(blkSize
);
690 uint8_t *blk_data
= blk
->data
+ offset
;
692 assert(sizeof(uint64_t) >= pkt
->getSize());
694 overwrite_mem
= true;
695 // keep a copy of our possible write value, and copy what is at the
696 // memory address into the packet
697 pkt
->writeData((uint8_t *)&overwrite_val
);
698 pkt
->setData(blk_data
);
700 if (pkt
->req
->isCondSwap()) {
701 if (pkt
->getSize() == sizeof(uint64_t)) {
702 condition_val64
= pkt
->req
->getExtraData();
703 overwrite_mem
= !std::memcmp(&condition_val64
, blk_data
,
705 } else if (pkt
->getSize() == sizeof(uint32_t)) {
706 condition_val32
= (uint32_t)pkt
->req
->getExtraData();
707 overwrite_mem
= !std::memcmp(&condition_val32
, blk_data
,
710 panic("Invalid size for conditional read/write\n");
714 std::memcpy(blk_data
, &overwrite_val
, pkt
->getSize());
715 blk
->status
|= BlkDirty
;
720 BaseCache::getNextQueueEntry()
722 // Check both MSHR queue and write buffer for potential requests,
723 // note that null does not mean there is no request, it could
724 // simply be that it is not ready
725 MSHR
*miss_mshr
= mshrQueue
.getNext();
726 WriteQueueEntry
*wq_entry
= writeBuffer
.getNext();
728 // If we got a write buffer request ready, first priority is a
729 // full write buffer, otherwise we favour the miss requests
730 if (wq_entry
&& (writeBuffer
.isFull() || !miss_mshr
)) {
731 // need to search MSHR queue for conflicting earlier miss.
732 MSHR
*conflict_mshr
=
733 mshrQueue
.findPending(wq_entry
->blkAddr
,
736 if (conflict_mshr
&& conflict_mshr
->order
< wq_entry
->order
) {
737 // Service misses in order until conflict is cleared.
738 return conflict_mshr
;
740 // @todo Note that we ignore the ready time of the conflict here
743 // No conflicts; issue write
745 } else if (miss_mshr
) {
746 // need to check for conflicting earlier writeback
747 WriteQueueEntry
*conflict_mshr
=
748 writeBuffer
.findPending(miss_mshr
->blkAddr
,
749 miss_mshr
->isSecure
);
751 // not sure why we don't check order here... it was in the
752 // original code but commented out.
754 // The only way this happens is if we are
755 // doing a write and we didn't have permissions
756 // then subsequently saw a writeback (owned got evicted)
757 // We need to make sure to perform the writeback first
758 // To preserve the dirty data, then we can issue the write
760 // should we return wq_entry here instead? I.e. do we
761 // have to flush writes in order? I don't think so... not
762 // for Alpha anyway. Maybe for x86?
763 return conflict_mshr
;
765 // @todo Note that we ignore the ready time of the conflict here
768 // No conflicts; issue read
772 // fall through... no pending requests. Try a prefetch.
773 assert(!miss_mshr
&& !wq_entry
);
774 if (prefetcher
&& mshrQueue
.canPrefetch()) {
775 // If we have a miss queue slot, we can try a prefetch
776 PacketPtr pkt
= prefetcher
->getPacket();
778 Addr pf_addr
= pkt
->getBlockAddr(blkSize
);
779 if (!tags
->findBlock(pf_addr
, pkt
->isSecure()) &&
780 !mshrQueue
.findMatch(pf_addr
, pkt
->isSecure()) &&
781 !writeBuffer
.findMatch(pf_addr
, pkt
->isSecure())) {
782 // Update statistic on number of prefetches issued
783 // (hwpf_mshr_misses)
784 assert(pkt
->req
->masterId() < system
->maxMasters());
785 mshr_misses
[pkt
->cmdToIndex()][pkt
->req
->masterId()]++;
787 // allocate an MSHR and return it, note
788 // that we send the packet straight away, so do not
790 return allocateMissBuffer(pkt
, curTick(), false);
792 // free the request and packet
802 BaseCache::satisfyRequest(PacketPtr pkt
, CacheBlk
*blk
, bool, bool)
804 assert(pkt
->isRequest());
806 assert(blk
&& blk
->isValid());
807 // Occasionally this is not true... if we are a lower-level cache
808 // satisfying a string of Read and ReadEx requests from
809 // upper-level caches, a Read will mark the block as shared but we
810 // can satisfy a following ReadEx anyway since we can rely on the
811 // Read requester(s) to have buffered the ReadEx snoop and to
812 // invalidate their blocks after receiving them.
813 // assert(!pkt->needsWritable() || blk->isWritable());
814 assert(pkt
->getOffset(blkSize
) + pkt
->getSize() <= blkSize
);
816 // Check RMW operations first since both isRead() and
817 // isWrite() will be true for them
818 if (pkt
->cmd
== MemCmd::SwapReq
) {
819 if (pkt
->isAtomicOp()) {
820 // extract data from cache and save it into the data field in
821 // the packet as a return value from this atomic op
822 int offset
= tags
->extractBlkOffset(pkt
->getAddr());
823 uint8_t *blk_data
= blk
->data
+ offset
;
824 pkt
->setData(blk_data
);
826 // execute AMO operation
827 (*(pkt
->getAtomicOp()))(blk_data
);
829 // set block status to dirty
830 blk
->status
|= BlkDirty
;
832 cmpAndSwap(blk
, pkt
);
834 } else if (pkt
->isWrite()) {
835 // we have the block in a writable state and can go ahead,
836 // note that the line may be also be considered writable in
837 // downstream caches along the path to memory, but always
838 // Exclusive, and never Modified
839 assert(blk
->isWritable());
840 // Write or WriteLine at the first cache with block in writable state
841 if (blk
->checkWrite(pkt
)) {
842 pkt
->writeDataToBlock(blk
->data
, blkSize
);
844 // Always mark the line as dirty (and thus transition to the
845 // Modified state) even if we are a failed StoreCond so we
846 // supply data to any snoops that have appended themselves to
847 // this cache before knowing the store will fail.
848 blk
->status
|= BlkDirty
;
849 DPRINTF(CacheVerbose
, "%s for %s (write)\n", __func__
, pkt
->print());
850 } else if (pkt
->isRead()) {
852 blk
->trackLoadLocked(pkt
);
855 // all read responses have a data payload
856 assert(pkt
->hasRespData());
857 pkt
->setDataFromBlock(blk
->data
, blkSize
);
858 } else if (pkt
->isUpgrade()) {
860 assert(!pkt
->hasSharers());
862 if (blk
->isDirty()) {
863 // we were in the Owned state, and a cache above us that
864 // has the line in Shared state needs to be made aware
865 // that the data it already has is in fact dirty
866 pkt
->setCacheResponding();
867 blk
->status
&= ~BlkDirty
;
869 } else if (pkt
->isClean()) {
870 blk
->status
&= ~BlkDirty
;
872 assert(pkt
->isInvalidate());
873 invalidateBlock(blk
);
874 DPRINTF(CacheVerbose
, "%s for %s (invalidation)\n", __func__
,
879 /////////////////////////////////////////////////////
881 // Access path: requests coming in from the CPU side
883 /////////////////////////////////////////////////////
885 BaseCache::calculateTagOnlyLatency(const uint32_t delay
,
886 const Cycles lookup_lat
) const
888 // A tag-only access has to wait for the packet to arrive in order to
889 // perform the tag lookup.
890 return ticksToCycles(delay
) + lookup_lat
;
894 BaseCache::calculateAccessLatency(const CacheBlk
* blk
, const uint32_t delay
,
895 const Cycles lookup_lat
) const
899 if (blk
!= nullptr) {
900 // As soon as the access arrives, for sequential accesses first access
901 // tags, then the data entry. In the case of parallel accesses the
902 // latency is dictated by the slowest of tag and data latencies.
903 if (sequentialAccess
) {
904 lat
= ticksToCycles(delay
) + lookup_lat
+ dataLatency
;
906 lat
= ticksToCycles(delay
) + std::max(lookup_lat
, dataLatency
);
909 // Check if the block to be accessed is available. If not, apply the
910 // access latency on top of when the block is ready to be accessed.
911 const Tick tick
= curTick() + delay
;
912 const Tick when_ready
= blk
->getWhenReady();
913 if (when_ready
> tick
&&
914 ticksToCycles(when_ready
- tick
) > lat
) {
915 lat
+= ticksToCycles(when_ready
- tick
);
918 // In case of a miss, we neglect the data access in a parallel
919 // configuration (i.e., the data access will be stopped as soon as
920 // we find out it is a miss), and use the tag-only latency.
921 lat
= calculateTagOnlyLatency(delay
, lookup_lat
);
928 BaseCache::access(PacketPtr pkt
, CacheBlk
*&blk
, Cycles
&lat
,
929 PacketList
&writebacks
)
932 assert(pkt
->isRequest());
934 chatty_assert(!(isReadOnly
&& pkt
->isWrite()),
935 "Should never see a write in a read-only cache %s\n",
938 // Access block in the tags
939 Cycles
tag_latency(0);
940 blk
= tags
->accessBlock(pkt
->getAddr(), pkt
->isSecure(), tag_latency
);
942 DPRINTF(Cache
, "%s for %s %s\n", __func__
, pkt
->print(),
943 blk
? "hit " + blk
->print() : "miss");
945 if (pkt
->req
->isCacheMaintenance()) {
946 // A cache maintenance operation is always forwarded to the
947 // memory below even if the block is found in dirty state.
949 // We defer any changes to the state of the block until we
950 // create and mark as in service the mshr for the downstream
953 // Calculate access latency on top of when the packet arrives. This
954 // takes into account the bus delay.
955 lat
= calculateTagOnlyLatency(pkt
->headerDelay
, tag_latency
);
960 if (pkt
->isEviction()) {
961 // We check for presence of block in above caches before issuing
962 // Writeback or CleanEvict to write buffer. Therefore the only
963 // possible cases can be of a CleanEvict packet coming from above
964 // encountering a Writeback generated in this cache peer cache and
965 // waiting in the write buffer. Cases of upper level peer caches
966 // generating CleanEvict and Writeback or simply CleanEvict and
967 // CleanEvict almost simultaneously will be caught by snoops sent out
969 WriteQueueEntry
*wb_entry
= writeBuffer
.findMatch(pkt
->getAddr(),
972 assert(wb_entry
->getNumTargets() == 1);
973 PacketPtr wbPkt
= wb_entry
->getTarget()->pkt
;
974 assert(wbPkt
->isWriteback());
976 if (pkt
->isCleanEviction()) {
977 // The CleanEvict and WritebackClean snoops into other
978 // peer caches of the same level while traversing the
979 // crossbar. If a copy of the block is found, the
980 // packet is deleted in the crossbar. Hence, none of
981 // the other upper level caches connected to this
982 // cache have the block, so we can clear the
983 // BLOCK_CACHED flag in the Writeback if set and
984 // discard the CleanEvict by returning true.
985 wbPkt
->clearBlockCached();
987 // A clean evict does not need to access the data array
988 lat
= calculateTagOnlyLatency(pkt
->headerDelay
, tag_latency
);
992 assert(pkt
->cmd
== MemCmd::WritebackDirty
);
993 // Dirty writeback from above trumps our clean
994 // writeback... discard here
995 // Note: markInService will remove entry from writeback buffer.
996 markInService(wb_entry
);
1002 // Writeback handling is special case. We can write the block into
1003 // the cache without having a writeable copy (or any copy at all).
1004 if (pkt
->isWriteback()) {
1005 assert(blkSize
== pkt
->getSize());
1007 // we could get a clean writeback while we are having
1008 // outstanding accesses to a block, do the simple thing for
1009 // now and drop the clean writeback so that we do not upset
1010 // any ordering/decisions about ownership already taken
1011 if (pkt
->cmd
== MemCmd::WritebackClean
&&
1012 mshrQueue
.findMatch(pkt
->getAddr(), pkt
->isSecure())) {
1013 DPRINTF(Cache
, "Clean writeback %#llx to block with MSHR, "
1014 "dropping\n", pkt
->getAddr());
1016 // A writeback searches for the block, then writes the data.
1017 // As the writeback is being dropped, the data is not touched,
1018 // and we just had to wait for the time to find a match in the
1019 // MSHR. As of now assume a mshr queue search takes as long as
1020 // a tag lookup for simplicity.
1021 lat
= calculateTagOnlyLatency(pkt
->headerDelay
, tag_latency
);
1027 // need to do a replacement
1028 blk
= allocateBlock(pkt
, writebacks
);
1030 // no replaceable block available: give up, fwd to next level.
1033 // A writeback searches for the block, then writes the data.
1034 // As the block could not be found, it was a tag-only access.
1035 lat
= calculateTagOnlyLatency(pkt
->headerDelay
, tag_latency
);
1040 blk
->status
|= BlkReadable
;
1042 // only mark the block dirty if we got a writeback command,
1043 // and leave it as is for a clean writeback
1044 if (pkt
->cmd
== MemCmd::WritebackDirty
) {
1045 // TODO: the coherent cache can assert(!blk->isDirty());
1046 blk
->status
|= BlkDirty
;
1048 // if the packet does not have sharers, it is passing
1049 // writable, and we got the writeback in Modified or Exclusive
1050 // state, if not we are in the Owned or Shared state
1051 if (!pkt
->hasSharers()) {
1052 blk
->status
|= BlkWritable
;
1054 // nothing else to do; writeback doesn't expect response
1055 assert(!pkt
->needsResponse());
1056 pkt
->writeDataToBlock(blk
->data
, blkSize
);
1057 DPRINTF(Cache
, "%s new state is %s\n", __func__
, blk
->print());
1060 // A writeback searches for the block, then writes the data
1061 lat
= calculateAccessLatency(blk
, pkt
->headerDelay
, tag_latency
);
1063 // When the packet metadata arrives, the tag lookup will be done while
1064 // the payload is arriving. Then the block will be ready to access as
1065 // soon as the fill is done
1066 blk
->setWhenReady(clockEdge(fillLatency
) + pkt
->headerDelay
+
1067 std::max(cyclesToTicks(tag_latency
), (uint64_t)pkt
->payloadDelay
));
1070 } else if (pkt
->cmd
== MemCmd::CleanEvict
) {
1071 // A CleanEvict does not need to access the data array
1072 lat
= calculateTagOnlyLatency(pkt
->headerDelay
, tag_latency
);
1075 // Found the block in the tags, need to stop CleanEvict from
1076 // propagating further down the hierarchy. Returning true will
1077 // treat the CleanEvict like a satisfied write request and delete
1081 // We didn't find the block here, propagate the CleanEvict further
1082 // down the memory hierarchy. Returning false will treat the CleanEvict
1083 // like a Writeback which could not find a replaceable block so has to
1084 // go to next level.
1086 } else if (pkt
->cmd
== MemCmd::WriteClean
) {
1087 // WriteClean handling is a special case. We can allocate a
1088 // block directly if it doesn't exist and we can update the
1089 // block immediately. The WriteClean transfers the ownership
1090 // of the block as well.
1091 assert(blkSize
== pkt
->getSize());
1094 if (pkt
->writeThrough()) {
1095 // A writeback searches for the block, then writes the data.
1096 // As the block could not be found, it was a tag-only access.
1097 lat
= calculateTagOnlyLatency(pkt
->headerDelay
, tag_latency
);
1099 // if this is a write through packet, we don't try to
1100 // allocate if the block is not present
1103 // a writeback that misses needs to allocate a new block
1104 blk
= allocateBlock(pkt
, writebacks
);
1106 // no replaceable block available: give up, fwd to
1110 // A writeback searches for the block, then writes the
1111 // data. As the block could not be found, it was a tag-only
1113 lat
= calculateTagOnlyLatency(pkt
->headerDelay
,
1119 blk
->status
|= BlkReadable
;
1123 // at this point either this is a writeback or a write-through
1124 // write clean operation and the block is already in this
1125 // cache, we need to update the data and the block flags
1127 // TODO: the coherent cache can assert(!blk->isDirty());
1128 if (!pkt
->writeThrough()) {
1129 blk
->status
|= BlkDirty
;
1131 // nothing else to do; writeback doesn't expect response
1132 assert(!pkt
->needsResponse());
1133 pkt
->writeDataToBlock(blk
->data
, blkSize
);
1134 DPRINTF(Cache
, "%s new state is %s\n", __func__
, blk
->print());
1138 // A writeback searches for the block, then writes the data
1139 lat
= calculateAccessLatency(blk
, pkt
->headerDelay
, tag_latency
);
1141 // When the packet metadata arrives, the tag lookup will be done while
1142 // the payload is arriving. Then the block will be ready to access as
1143 // soon as the fill is done
1144 blk
->setWhenReady(clockEdge(fillLatency
) + pkt
->headerDelay
+
1145 std::max(cyclesToTicks(tag_latency
), (uint64_t)pkt
->payloadDelay
));
1147 // if this a write-through packet it will be sent to cache
1149 return !pkt
->writeThrough();
1150 } else if (blk
&& (pkt
->needsWritable() ? blk
->isWritable() :
1151 blk
->isReadable())) {
1152 // OK to satisfy access
1155 // Calculate access latency based on the need to access the data array
1156 if (pkt
->isRead() || pkt
->isWrite()) {
1157 lat
= calculateAccessLatency(blk
, pkt
->headerDelay
, tag_latency
);
1159 lat
= calculateTagOnlyLatency(pkt
->headerDelay
, tag_latency
);
1162 satisfyRequest(pkt
, blk
);
1163 maintainClusivity(pkt
->fromCache(), blk
);
1168 // Can't satisfy access normally... either no block (blk == nullptr)
1169 // or have block but need writable
1173 lat
= calculateAccessLatency(blk
, pkt
->headerDelay
, tag_latency
);
1175 if (!blk
&& pkt
->isLLSC() && pkt
->isWrite()) {
1176 // complete miss on store conditional... just give up now
1177 pkt
->req
->setExtraData(0);
1185 BaseCache::maintainClusivity(bool from_cache
, CacheBlk
*blk
)
1187 if (from_cache
&& blk
&& blk
->isValid() && !blk
->isDirty() &&
1188 clusivity
== Enums::mostly_excl
) {
1189 // if we have responded to a cache, and our block is still
1190 // valid, but not dirty, and this cache is mostly exclusive
1191 // with respect to the cache above, drop the block
1192 invalidateBlock(blk
);
1197 BaseCache::handleFill(PacketPtr pkt
, CacheBlk
*blk
, PacketList
&writebacks
,
1200 assert(pkt
->isResponse());
1201 Addr addr
= pkt
->getAddr();
1202 bool is_secure
= pkt
->isSecure();
1204 CacheBlk::State old_state
= blk
? blk
->status
: 0;
1207 // When handling a fill, we should have no writes to this line.
1208 assert(addr
== pkt
->getBlockAddr(blkSize
));
1209 assert(!writeBuffer
.findMatch(addr
, is_secure
));
1212 // better have read new data...
1213 assert(pkt
->hasData() || pkt
->cmd
== MemCmd::InvalidateResp
);
1215 // need to do a replacement if allocating, otherwise we stick
1216 // with the temporary storage
1217 blk
= allocate
? allocateBlock(pkt
, writebacks
) : nullptr;
1220 // No replaceable block or a mostly exclusive
1221 // cache... just use temporary storage to complete the
1222 // current request and then get rid of it
1224 tempBlock
->insert(addr
, is_secure
);
1225 DPRINTF(Cache
, "using temp block for %#llx (%s)\n", addr
,
1226 is_secure
? "s" : "ns");
1229 // existing block... probably an upgrade
1230 // don't clear block status... if block is already dirty we
1231 // don't want to lose that
1234 // Block is guaranteed to be valid at this point
1235 assert(blk
->isValid());
1236 assert(blk
->isSecure() == is_secure
);
1237 assert(regenerateBlkAddr(blk
) == addr
);
1239 blk
->status
|= BlkReadable
;
1241 // sanity check for whole-line writes, which should always be
1242 // marked as writable as part of the fill, and then later marked
1243 // dirty as part of satisfyRequest
1244 if (pkt
->cmd
== MemCmd::InvalidateResp
) {
1245 assert(!pkt
->hasSharers());
1248 // here we deal with setting the appropriate state of the line,
1249 // and we start by looking at the hasSharers flag, and ignore the
1250 // cacheResponding flag (normally signalling dirty data) if the
1251 // packet has sharers, thus the line is never allocated as Owned
1252 // (dirty but not writable), and always ends up being either
1253 // Shared, Exclusive or Modified, see Packet::setCacheResponding
1255 if (!pkt
->hasSharers()) {
1256 // we could get a writable line from memory (rather than a
1257 // cache) even in a read-only cache, note that we set this bit
1258 // even for a read-only cache, possibly revisit this decision
1259 blk
->status
|= BlkWritable
;
1261 // check if we got this via cache-to-cache transfer (i.e., from a
1262 // cache that had the block in Modified or Owned state)
1263 if (pkt
->cacheResponding()) {
1264 // we got the block in Modified state, and invalidated the
1266 blk
->status
|= BlkDirty
;
1268 chatty_assert(!isReadOnly
, "Should never see dirty snoop response "
1269 "in read-only cache %s\n", name());
1273 DPRINTF(Cache
, "Block addr %#llx (%s) moving from state %x to %s\n",
1274 addr
, is_secure
? "s" : "ns", old_state
, blk
->print());
1276 // if we got new data, copy it in (checking for a read response
1277 // and a response that has data is the same in the end)
1278 if (pkt
->isRead()) {
1280 assert(pkt
->hasData());
1281 assert(pkt
->getSize() == blkSize
);
1283 pkt
->writeDataToBlock(blk
->data
, blkSize
);
1285 // The block will be ready when the payload arrives and the fill is done
1286 blk
->setWhenReady(clockEdge(fillLatency
) + pkt
->headerDelay
+
1293 BaseCache::allocateBlock(const PacketPtr pkt
, PacketList
&writebacks
)
1296 const Addr addr
= pkt
->getAddr();
1299 const bool is_secure
= pkt
->isSecure();
1301 // Find replacement victim
1302 std::vector
<CacheBlk
*> evict_blks
;
1303 CacheBlk
*victim
= tags
->findVictim(addr
, is_secure
, evict_blks
);
1305 // It is valid to return nullptr if there is no victim
1309 // Print victim block's information
1310 DPRINTF(CacheRepl
, "Replacement victim: %s\n", victim
->print());
1312 // Check for transient state allocations. If any of the entries listed
1313 // for eviction has a transient state, the allocation fails
1314 for (const auto& blk
: evict_blks
) {
1315 if (blk
->isValid()) {
1316 Addr repl_addr
= regenerateBlkAddr(blk
);
1317 MSHR
*repl_mshr
= mshrQueue
.findMatch(repl_addr
, blk
->isSecure());
1319 // must be an outstanding upgrade or clean request
1320 // on a block we're about to replace...
1321 assert((!blk
->isWritable() && repl_mshr
->needsWritable()) ||
1322 repl_mshr
->isCleaning());
1324 // too hard to replace block with transient state
1325 // allocation failed, block not inserted
1331 // The victim will be replaced by a new entry, so increase the replacement
1332 // counter if a valid block is being replaced
1333 if (victim
->isValid()) {
1334 DPRINTF(Cache
, "replacement: replacing %#llx (%s) with %#llx "
1335 "(%s): %s\n", regenerateBlkAddr(victim
),
1336 victim
->isSecure() ? "s" : "ns",
1337 addr
, is_secure
? "s" : "ns",
1338 victim
->isDirty() ? "writeback" : "clean");
1343 // Evict valid blocks associated to this victim block
1344 for (const auto& blk
: evict_blks
) {
1345 if (blk
->isValid()) {
1346 if (blk
->wasPrefetched()) {
1350 evictBlock(blk
, writebacks
);
1354 // Insert new block at victimized entry
1355 tags
->insertBlock(pkt
, victim
);
1361 BaseCache::invalidateBlock(CacheBlk
*blk
)
1363 // If handling a block present in the Tags, let it do its invalidation
1364 // process, which will update stats and invalidate the block itself
1365 if (blk
!= tempBlock
) {
1366 tags
->invalidate(blk
);
1368 tempBlock
->invalidate();
1373 BaseCache::evictBlock(CacheBlk
*blk
, PacketList
&writebacks
)
1375 PacketPtr pkt
= evictBlock(blk
);
1377 writebacks
.push_back(pkt
);
1382 BaseCache::writebackBlk(CacheBlk
*blk
)
1384 chatty_assert(!isReadOnly
|| writebackClean
,
1385 "Writeback from read-only cache");
1386 assert(blk
&& blk
->isValid() && (blk
->isDirty() || writebackClean
));
1388 writebacks
[Request::wbMasterId
]++;
1390 RequestPtr req
= std::make_shared
<Request
>(
1391 regenerateBlkAddr(blk
), blkSize
, 0, Request::wbMasterId
);
1393 if (blk
->isSecure())
1394 req
->setFlags(Request::SECURE
);
1396 req
->taskId(blk
->task_id
);
1399 new Packet(req
, blk
->isDirty() ?
1400 MemCmd::WritebackDirty
: MemCmd::WritebackClean
);
1402 DPRINTF(Cache
, "Create Writeback %s writable: %d, dirty: %d\n",
1403 pkt
->print(), blk
->isWritable(), blk
->isDirty());
1405 if (blk
->isWritable()) {
1406 // not asserting shared means we pass the block in modified
1407 // state, mark our own block non-writeable
1408 blk
->status
&= ~BlkWritable
;
1410 // we are in the Owned state, tell the receiver
1411 pkt
->setHasSharers();
1414 // make sure the block is not marked dirty
1415 blk
->status
&= ~BlkDirty
;
1418 pkt
->setDataFromBlock(blk
->data
, blkSize
);
1424 BaseCache::writecleanBlk(CacheBlk
*blk
, Request::Flags dest
, PacketId id
)
1426 RequestPtr req
= std::make_shared
<Request
>(
1427 regenerateBlkAddr(blk
), blkSize
, 0, Request::wbMasterId
);
1429 if (blk
->isSecure()) {
1430 req
->setFlags(Request::SECURE
);
1432 req
->taskId(blk
->task_id
);
1434 PacketPtr pkt
= new Packet(req
, MemCmd::WriteClean
, blkSize
, id
);
1437 req
->setFlags(dest
);
1438 pkt
->setWriteThrough();
1441 DPRINTF(Cache
, "Create %s writable: %d, dirty: %d\n", pkt
->print(),
1442 blk
->isWritable(), blk
->isDirty());
1444 if (blk
->isWritable()) {
1445 // not asserting shared means we pass the block in modified
1446 // state, mark our own block non-writeable
1447 blk
->status
&= ~BlkWritable
;
1449 // we are in the Owned state, tell the receiver
1450 pkt
->setHasSharers();
1453 // make sure the block is not marked dirty
1454 blk
->status
&= ~BlkDirty
;
1457 pkt
->setDataFromBlock(blk
->data
, blkSize
);
1464 BaseCache::memWriteback()
1466 tags
->forEachBlk([this](CacheBlk
&blk
) { writebackVisitor(blk
); });
1470 BaseCache::memInvalidate()
1472 tags
->forEachBlk([this](CacheBlk
&blk
) { invalidateVisitor(blk
); });
1476 BaseCache::isDirty() const
1478 return tags
->anyBlk([](CacheBlk
&blk
) { return blk
.isDirty(); });
1482 BaseCache::coalesce() const
1484 return writeAllocator
&& writeAllocator
->coalesce();
1488 BaseCache::writebackVisitor(CacheBlk
&blk
)
1490 if (blk
.isDirty()) {
1491 assert(blk
.isValid());
1493 RequestPtr request
= std::make_shared
<Request
>(
1494 regenerateBlkAddr(&blk
), blkSize
, 0, Request::funcMasterId
);
1496 request
->taskId(blk
.task_id
);
1497 if (blk
.isSecure()) {
1498 request
->setFlags(Request::SECURE
);
1501 Packet
packet(request
, MemCmd::WriteReq
);
1502 packet
.dataStatic(blk
.data
);
1504 memSidePort
.sendFunctional(&packet
);
1506 blk
.status
&= ~BlkDirty
;
1511 BaseCache::invalidateVisitor(CacheBlk
&blk
)
1514 warn_once("Invalidating dirty cache lines. " \
1515 "Expect things to break.\n");
1517 if (blk
.isValid()) {
1518 assert(!blk
.isDirty());
1519 invalidateBlock(&blk
);
1524 BaseCache::nextQueueReadyTime() const
1526 Tick nextReady
= std::min(mshrQueue
.nextReadyTime(),
1527 writeBuffer
.nextReadyTime());
1529 // Don't signal prefetch ready time if no MSHRs available
1530 // Will signal once enoguh MSHRs are deallocated
1531 if (prefetcher
&& mshrQueue
.canPrefetch()) {
1532 nextReady
= std::min(nextReady
,
1533 prefetcher
->nextPrefetchReadyTime());
1541 BaseCache::sendMSHRQueuePacket(MSHR
* mshr
)
1545 // use request from 1st target
1546 PacketPtr tgt_pkt
= mshr
->getTarget()->pkt
;
1548 DPRINTF(Cache
, "%s: MSHR %s\n", __func__
, tgt_pkt
->print());
1550 // if the cache is in write coalescing mode or (additionally) in
1551 // no allocation mode, and we have a write packet with an MSHR
1552 // that is not a whole-line write (due to incompatible flags etc),
1553 // then reset the write mode
1554 if (writeAllocator
&& writeAllocator
->coalesce() && tgt_pkt
->isWrite()) {
1555 if (!mshr
->isWholeLineWrite()) {
1556 // if we are currently write coalescing, hold on the
1557 // MSHR as many cycles extra as we need to completely
1558 // write a cache line
1559 if (writeAllocator
->delay(mshr
->blkAddr
)) {
1560 Tick delay
= blkSize
/ tgt_pkt
->getSize() * clockPeriod();
1561 DPRINTF(CacheVerbose
, "Delaying pkt %s %llu ticks to allow "
1562 "for write coalescing\n", tgt_pkt
->print(), delay
);
1563 mshrQueue
.delay(mshr
, delay
);
1566 writeAllocator
->reset();
1569 writeAllocator
->resetDelay(mshr
->blkAddr
);
1573 CacheBlk
*blk
= tags
->findBlock(mshr
->blkAddr
, mshr
->isSecure
);
1575 // either a prefetch that is not present upstream, or a normal
1576 // MSHR request, proceed to get the packet to send downstream
1577 PacketPtr pkt
= createMissPacket(tgt_pkt
, blk
, mshr
->needsWritable(),
1578 mshr
->isWholeLineWrite());
1580 mshr
->isForward
= (pkt
== nullptr);
1582 if (mshr
->isForward
) {
1583 // not a cache block request, but a response is expected
1584 // make copy of current packet to forward, keep current
1585 // copy for response handling
1586 pkt
= new Packet(tgt_pkt
, false, true);
1587 assert(!pkt
->isWrite());
1590 // play it safe and append (rather than set) the sender state,
1591 // as forwarded packets may already have existing state
1592 pkt
->pushSenderState(mshr
);
1594 if (pkt
->isClean() && blk
&& blk
->isDirty()) {
1595 // A cache clean opearation is looking for a dirty block. Mark
1596 // the packet so that the destination xbar can determine that
1597 // there will be a follow-up write packet as well.
1598 pkt
->setSatisfied();
1601 if (!memSidePort
.sendTimingReq(pkt
)) {
1602 // we are awaiting a retry, but we
1603 // delete the packet and will be creating a new packet
1604 // when we get the opportunity
1607 // note that we have now masked any requestBus and
1608 // schedSendEvent (we will wait for a retry before
1609 // doing anything), and this is so even if we do not
1610 // care about this packet and might override it before
1614 // As part of the call to sendTimingReq the packet is
1615 // forwarded to all neighbouring caches (and any caches
1616 // above them) as a snoop. Thus at this point we know if
1617 // any of the neighbouring caches are responding, and if
1618 // so, we know it is dirty, and we can determine if it is
1619 // being passed as Modified, making our MSHR the ordering
1621 bool pending_modified_resp
= !pkt
->hasSharers() &&
1622 pkt
->cacheResponding();
1623 markInService(mshr
, pending_modified_resp
);
1625 if (pkt
->isClean() && blk
&& blk
->isDirty()) {
1626 // A cache clean opearation is looking for a dirty
1627 // block. If a dirty block is encountered a WriteClean
1628 // will update any copies to the path to the memory
1629 // until the point of reference.
1630 DPRINTF(CacheVerbose
, "%s: packet %s found block: %s\n",
1631 __func__
, pkt
->print(), blk
->print());
1632 PacketPtr wb_pkt
= writecleanBlk(blk
, pkt
->req
->getDest(),
1634 PacketList writebacks
;
1635 writebacks
.push_back(wb_pkt
);
1636 doWritebacks(writebacks
, 0);
1644 BaseCache::sendWriteQueuePacket(WriteQueueEntry
* wq_entry
)
1648 // always a single target for write queue entries
1649 PacketPtr tgt_pkt
= wq_entry
->getTarget()->pkt
;
1651 DPRINTF(Cache
, "%s: write %s\n", __func__
, tgt_pkt
->print());
1653 // forward as is, both for evictions and uncacheable writes
1654 if (!memSidePort
.sendTimingReq(tgt_pkt
)) {
1655 // note that we have now masked any requestBus and
1656 // schedSendEvent (we will wait for a retry before
1657 // doing anything), and this is so even if we do not
1658 // care about this packet and might override it before
1662 markInService(wq_entry
);
1668 BaseCache::serialize(CheckpointOut
&cp
) const
1670 bool dirty(isDirty());
1673 warn("*** The cache still contains dirty data. ***\n");
1674 warn(" Make sure to drain the system using the correct flags.\n");
1675 warn(" This checkpoint will not restore correctly " \
1676 "and dirty data in the cache will be lost!\n");
1679 // Since we don't checkpoint the data in the cache, any dirty data
1680 // will be lost when restoring from a checkpoint of a system that
1681 // wasn't drained properly. Flag the checkpoint as invalid if the
1682 // cache contains dirty data.
1683 bool bad_checkpoint(dirty
);
1684 SERIALIZE_SCALAR(bad_checkpoint
);
1688 BaseCache::unserialize(CheckpointIn
&cp
)
1690 bool bad_checkpoint
;
1691 UNSERIALIZE_SCALAR(bad_checkpoint
);
1692 if (bad_checkpoint
) {
1693 fatal("Restoring from checkpoints with dirty caches is not "
1694 "supported in the classic memory system. Please remove any "
1695 "caches or drain them properly before taking checkpoints.\n");
1700 BaseCache::regStats()
1702 MemObject::regStats();
1704 using namespace Stats
;
1707 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
1708 MemCmd
cmd(access_idx
);
1709 const string
&cstr
= cmd
.toString();
1712 .init(system
->maxMasters())
1713 .name(name() + "." + cstr
+ "_hits")
1714 .desc("number of " + cstr
+ " hits")
1715 .flags(total
| nozero
| nonan
)
1717 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1718 hits
[access_idx
].subname(i
, system
->getMasterName(i
));
1722 // These macros make it easier to sum the right subset of commands and
1723 // to change the subset of commands that are considered "demand" vs
1725 #define SUM_DEMAND(s) \
1726 (s[MemCmd::ReadReq] + s[MemCmd::WriteReq] + s[MemCmd::WriteLineReq] + \
1727 s[MemCmd::ReadExReq] + s[MemCmd::ReadCleanReq] + s[MemCmd::ReadSharedReq])
1729 // should writebacks be included here? prior code was inconsistent...
1730 #define SUM_NON_DEMAND(s) \
1731 (s[MemCmd::SoftPFReq] + s[MemCmd::HardPFReq] + s[MemCmd::SoftPFExReq])
1734 .name(name() + ".demand_hits")
1735 .desc("number of demand (read+write) hits")
1736 .flags(total
| nozero
| nonan
)
1738 demandHits
= SUM_DEMAND(hits
);
1739 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1740 demandHits
.subname(i
, system
->getMasterName(i
));
1744 .name(name() + ".overall_hits")
1745 .desc("number of overall hits")
1746 .flags(total
| nozero
| nonan
)
1748 overallHits
= demandHits
+ SUM_NON_DEMAND(hits
);
1749 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1750 overallHits
.subname(i
, system
->getMasterName(i
));
1754 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
1755 MemCmd
cmd(access_idx
);
1756 const string
&cstr
= cmd
.toString();
1759 .init(system
->maxMasters())
1760 .name(name() + "." + cstr
+ "_misses")
1761 .desc("number of " + cstr
+ " misses")
1762 .flags(total
| nozero
| nonan
)
1764 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1765 misses
[access_idx
].subname(i
, system
->getMasterName(i
));
1770 .name(name() + ".demand_misses")
1771 .desc("number of demand (read+write) misses")
1772 .flags(total
| nozero
| nonan
)
1774 demandMisses
= SUM_DEMAND(misses
);
1775 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1776 demandMisses
.subname(i
, system
->getMasterName(i
));
1780 .name(name() + ".overall_misses")
1781 .desc("number of overall misses")
1782 .flags(total
| nozero
| nonan
)
1784 overallMisses
= demandMisses
+ SUM_NON_DEMAND(misses
);
1785 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1786 overallMisses
.subname(i
, system
->getMasterName(i
));
1789 // Miss latency statistics
1790 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
1791 MemCmd
cmd(access_idx
);
1792 const string
&cstr
= cmd
.toString();
1794 missLatency
[access_idx
]
1795 .init(system
->maxMasters())
1796 .name(name() + "." + cstr
+ "_miss_latency")
1797 .desc("number of " + cstr
+ " miss cycles")
1798 .flags(total
| nozero
| nonan
)
1800 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1801 missLatency
[access_idx
].subname(i
, system
->getMasterName(i
));
1806 .name(name() + ".demand_miss_latency")
1807 .desc("number of demand (read+write) miss cycles")
1808 .flags(total
| nozero
| nonan
)
1810 demandMissLatency
= SUM_DEMAND(missLatency
);
1811 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1812 demandMissLatency
.subname(i
, system
->getMasterName(i
));
1816 .name(name() + ".overall_miss_latency")
1817 .desc("number of overall miss cycles")
1818 .flags(total
| nozero
| nonan
)
1820 overallMissLatency
= demandMissLatency
+ SUM_NON_DEMAND(missLatency
);
1821 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1822 overallMissLatency
.subname(i
, system
->getMasterName(i
));
1826 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
1827 MemCmd
cmd(access_idx
);
1828 const string
&cstr
= cmd
.toString();
1830 accesses
[access_idx
]
1831 .name(name() + "." + cstr
+ "_accesses")
1832 .desc("number of " + cstr
+ " accesses(hits+misses)")
1833 .flags(total
| nozero
| nonan
)
1835 accesses
[access_idx
] = hits
[access_idx
] + misses
[access_idx
];
1837 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1838 accesses
[access_idx
].subname(i
, system
->getMasterName(i
));
1843 .name(name() + ".demand_accesses")
1844 .desc("number of demand (read+write) accesses")
1845 .flags(total
| nozero
| nonan
)
1847 demandAccesses
= demandHits
+ demandMisses
;
1848 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1849 demandAccesses
.subname(i
, system
->getMasterName(i
));
1853 .name(name() + ".overall_accesses")
1854 .desc("number of overall (read+write) accesses")
1855 .flags(total
| nozero
| nonan
)
1857 overallAccesses
= overallHits
+ overallMisses
;
1858 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1859 overallAccesses
.subname(i
, system
->getMasterName(i
));
1862 // miss rate formulas
1863 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
1864 MemCmd
cmd(access_idx
);
1865 const string
&cstr
= cmd
.toString();
1867 missRate
[access_idx
]
1868 .name(name() + "." + cstr
+ "_miss_rate")
1869 .desc("miss rate for " + cstr
+ " accesses")
1870 .flags(total
| nozero
| nonan
)
1872 missRate
[access_idx
] = misses
[access_idx
] / accesses
[access_idx
];
1874 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1875 missRate
[access_idx
].subname(i
, system
->getMasterName(i
));
1880 .name(name() + ".demand_miss_rate")
1881 .desc("miss rate for demand accesses")
1882 .flags(total
| nozero
| nonan
)
1884 demandMissRate
= demandMisses
/ demandAccesses
;
1885 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1886 demandMissRate
.subname(i
, system
->getMasterName(i
));
1890 .name(name() + ".overall_miss_rate")
1891 .desc("miss rate for overall accesses")
1892 .flags(total
| nozero
| nonan
)
1894 overallMissRate
= overallMisses
/ overallAccesses
;
1895 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1896 overallMissRate
.subname(i
, system
->getMasterName(i
));
1899 // miss latency formulas
1900 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
1901 MemCmd
cmd(access_idx
);
1902 const string
&cstr
= cmd
.toString();
1904 avgMissLatency
[access_idx
]
1905 .name(name() + "." + cstr
+ "_avg_miss_latency")
1906 .desc("average " + cstr
+ " miss latency")
1907 .flags(total
| nozero
| nonan
)
1909 avgMissLatency
[access_idx
] =
1910 missLatency
[access_idx
] / misses
[access_idx
];
1912 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1913 avgMissLatency
[access_idx
].subname(i
, system
->getMasterName(i
));
1917 demandAvgMissLatency
1918 .name(name() + ".demand_avg_miss_latency")
1919 .desc("average overall miss latency")
1920 .flags(total
| nozero
| nonan
)
1922 demandAvgMissLatency
= demandMissLatency
/ demandMisses
;
1923 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1924 demandAvgMissLatency
.subname(i
, system
->getMasterName(i
));
1927 overallAvgMissLatency
1928 .name(name() + ".overall_avg_miss_latency")
1929 .desc("average overall miss latency")
1930 .flags(total
| nozero
| nonan
)
1932 overallAvgMissLatency
= overallMissLatency
/ overallMisses
;
1933 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1934 overallAvgMissLatency
.subname(i
, system
->getMasterName(i
));
1937 blocked_cycles
.init(NUM_BLOCKED_CAUSES
);
1939 .name(name() + ".blocked_cycles")
1940 .desc("number of cycles access was blocked")
1941 .subname(Blocked_NoMSHRs
, "no_mshrs")
1942 .subname(Blocked_NoTargets
, "no_targets")
1946 blocked_causes
.init(NUM_BLOCKED_CAUSES
);
1948 .name(name() + ".blocked")
1949 .desc("number of cycles access was blocked")
1950 .subname(Blocked_NoMSHRs
, "no_mshrs")
1951 .subname(Blocked_NoTargets
, "no_targets")
1955 .name(name() + ".avg_blocked_cycles")
1956 .desc("average number of cycles each access was blocked")
1957 .subname(Blocked_NoMSHRs
, "no_mshrs")
1958 .subname(Blocked_NoTargets
, "no_targets")
1961 avg_blocked
= blocked_cycles
/ blocked_causes
;
1964 .name(name() + ".unused_prefetches")
1965 .desc("number of HardPF blocks evicted w/o reference")
1970 .init(system
->maxMasters())
1971 .name(name() + ".writebacks")
1972 .desc("number of writebacks")
1973 .flags(total
| nozero
| nonan
)
1975 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1976 writebacks
.subname(i
, system
->getMasterName(i
));
1980 // MSHR hit statistics
1981 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
1982 MemCmd
cmd(access_idx
);
1983 const string
&cstr
= cmd
.toString();
1985 mshr_hits
[access_idx
]
1986 .init(system
->maxMasters())
1987 .name(name() + "." + cstr
+ "_mshr_hits")
1988 .desc("number of " + cstr
+ " MSHR hits")
1989 .flags(total
| nozero
| nonan
)
1991 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1992 mshr_hits
[access_idx
].subname(i
, system
->getMasterName(i
));
1997 .name(name() + ".demand_mshr_hits")
1998 .desc("number of demand (read+write) MSHR hits")
1999 .flags(total
| nozero
| nonan
)
2001 demandMshrHits
= SUM_DEMAND(mshr_hits
);
2002 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2003 demandMshrHits
.subname(i
, system
->getMasterName(i
));
2007 .name(name() + ".overall_mshr_hits")
2008 .desc("number of overall MSHR hits")
2009 .flags(total
| nozero
| nonan
)
2011 overallMshrHits
= demandMshrHits
+ SUM_NON_DEMAND(mshr_hits
);
2012 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2013 overallMshrHits
.subname(i
, system
->getMasterName(i
));
2016 // MSHR miss statistics
2017 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
2018 MemCmd
cmd(access_idx
);
2019 const string
&cstr
= cmd
.toString();
2021 mshr_misses
[access_idx
]
2022 .init(system
->maxMasters())
2023 .name(name() + "." + cstr
+ "_mshr_misses")
2024 .desc("number of " + cstr
+ " MSHR misses")
2025 .flags(total
| nozero
| nonan
)
2027 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2028 mshr_misses
[access_idx
].subname(i
, system
->getMasterName(i
));
2033 .name(name() + ".demand_mshr_misses")
2034 .desc("number of demand (read+write) MSHR misses")
2035 .flags(total
| nozero
| nonan
)
2037 demandMshrMisses
= SUM_DEMAND(mshr_misses
);
2038 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2039 demandMshrMisses
.subname(i
, system
->getMasterName(i
));
2043 .name(name() + ".overall_mshr_misses")
2044 .desc("number of overall MSHR misses")
2045 .flags(total
| nozero
| nonan
)
2047 overallMshrMisses
= demandMshrMisses
+ SUM_NON_DEMAND(mshr_misses
);
2048 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2049 overallMshrMisses
.subname(i
, system
->getMasterName(i
));
2052 // MSHR miss latency statistics
2053 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
2054 MemCmd
cmd(access_idx
);
2055 const string
&cstr
= cmd
.toString();
2057 mshr_miss_latency
[access_idx
]
2058 .init(system
->maxMasters())
2059 .name(name() + "." + cstr
+ "_mshr_miss_latency")
2060 .desc("number of " + cstr
+ " MSHR miss cycles")
2061 .flags(total
| nozero
| nonan
)
2063 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2064 mshr_miss_latency
[access_idx
].subname(i
, system
->getMasterName(i
));
2068 demandMshrMissLatency
2069 .name(name() + ".demand_mshr_miss_latency")
2070 .desc("number of demand (read+write) MSHR miss cycles")
2071 .flags(total
| nozero
| nonan
)
2073 demandMshrMissLatency
= SUM_DEMAND(mshr_miss_latency
);
2074 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2075 demandMshrMissLatency
.subname(i
, system
->getMasterName(i
));
2078 overallMshrMissLatency
2079 .name(name() + ".overall_mshr_miss_latency")
2080 .desc("number of overall MSHR miss cycles")
2081 .flags(total
| nozero
| nonan
)
2083 overallMshrMissLatency
=
2084 demandMshrMissLatency
+ SUM_NON_DEMAND(mshr_miss_latency
);
2085 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2086 overallMshrMissLatency
.subname(i
, system
->getMasterName(i
));
2089 // MSHR uncacheable statistics
2090 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
2091 MemCmd
cmd(access_idx
);
2092 const string
&cstr
= cmd
.toString();
2094 mshr_uncacheable
[access_idx
]
2095 .init(system
->maxMasters())
2096 .name(name() + "." + cstr
+ "_mshr_uncacheable")
2097 .desc("number of " + cstr
+ " MSHR uncacheable")
2098 .flags(total
| nozero
| nonan
)
2100 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2101 mshr_uncacheable
[access_idx
].subname(i
, system
->getMasterName(i
));
2105 overallMshrUncacheable
2106 .name(name() + ".overall_mshr_uncacheable_misses")
2107 .desc("number of overall MSHR uncacheable misses")
2108 .flags(total
| nozero
| nonan
)
2110 overallMshrUncacheable
=
2111 SUM_DEMAND(mshr_uncacheable
) + SUM_NON_DEMAND(mshr_uncacheable
);
2112 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2113 overallMshrUncacheable
.subname(i
, system
->getMasterName(i
));
2116 // MSHR miss latency statistics
2117 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
2118 MemCmd
cmd(access_idx
);
2119 const string
&cstr
= cmd
.toString();
2121 mshr_uncacheable_lat
[access_idx
]
2122 .init(system
->maxMasters())
2123 .name(name() + "." + cstr
+ "_mshr_uncacheable_latency")
2124 .desc("number of " + cstr
+ " MSHR uncacheable cycles")
2125 .flags(total
| nozero
| nonan
)
2127 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2128 mshr_uncacheable_lat
[access_idx
].subname(
2129 i
, system
->getMasterName(i
));
2133 overallMshrUncacheableLatency
2134 .name(name() + ".overall_mshr_uncacheable_latency")
2135 .desc("number of overall MSHR uncacheable cycles")
2136 .flags(total
| nozero
| nonan
)
2138 overallMshrUncacheableLatency
=
2139 SUM_DEMAND(mshr_uncacheable_lat
) +
2140 SUM_NON_DEMAND(mshr_uncacheable_lat
);
2141 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2142 overallMshrUncacheableLatency
.subname(i
, system
->getMasterName(i
));
2146 // MSHR access formulas
2147 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
2148 MemCmd
cmd(access_idx
);
2149 const string
&cstr
= cmd
.toString();
2151 mshrAccesses
[access_idx
]
2152 .name(name() + "." + cstr
+ "_mshr_accesses")
2153 .desc("number of " + cstr
+ " mshr accesses(hits+misses)")
2154 .flags(total
| nozero
| nonan
)
2156 mshrAccesses
[access_idx
] =
2157 mshr_hits
[access_idx
] + mshr_misses
[access_idx
]
2158 + mshr_uncacheable
[access_idx
];
2162 .name(name() + ".demand_mshr_accesses")
2163 .desc("number of demand (read+write) mshr accesses")
2164 .flags(total
| nozero
| nonan
)
2166 demandMshrAccesses
= demandMshrHits
+ demandMshrMisses
;
2169 .name(name() + ".overall_mshr_accesses")
2170 .desc("number of overall (read+write) mshr accesses")
2171 .flags(total
| nozero
| nonan
)
2173 overallMshrAccesses
= overallMshrHits
+ overallMshrMisses
2174 + overallMshrUncacheable
;
2177 // MSHR miss rate formulas
2178 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
2179 MemCmd
cmd(access_idx
);
2180 const string
&cstr
= cmd
.toString();
2182 mshrMissRate
[access_idx
]
2183 .name(name() + "." + cstr
+ "_mshr_miss_rate")
2184 .desc("mshr miss rate for " + cstr
+ " accesses")
2185 .flags(total
| nozero
| nonan
)
2187 mshrMissRate
[access_idx
] =
2188 mshr_misses
[access_idx
] / accesses
[access_idx
];
2190 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2191 mshrMissRate
[access_idx
].subname(i
, system
->getMasterName(i
));
2196 .name(name() + ".demand_mshr_miss_rate")
2197 .desc("mshr miss rate for demand accesses")
2198 .flags(total
| nozero
| nonan
)
2200 demandMshrMissRate
= demandMshrMisses
/ demandAccesses
;
2201 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2202 demandMshrMissRate
.subname(i
, system
->getMasterName(i
));
2206 .name(name() + ".overall_mshr_miss_rate")
2207 .desc("mshr miss rate for overall accesses")
2208 .flags(total
| nozero
| nonan
)
2210 overallMshrMissRate
= overallMshrMisses
/ overallAccesses
;
2211 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2212 overallMshrMissRate
.subname(i
, system
->getMasterName(i
));
2215 // mshrMiss latency formulas
2216 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
2217 MemCmd
cmd(access_idx
);
2218 const string
&cstr
= cmd
.toString();
2220 avgMshrMissLatency
[access_idx
]
2221 .name(name() + "." + cstr
+ "_avg_mshr_miss_latency")
2222 .desc("average " + cstr
+ " mshr miss latency")
2223 .flags(total
| nozero
| nonan
)
2225 avgMshrMissLatency
[access_idx
] =
2226 mshr_miss_latency
[access_idx
] / mshr_misses
[access_idx
];
2228 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2229 avgMshrMissLatency
[access_idx
].subname(
2230 i
, system
->getMasterName(i
));
2234 demandAvgMshrMissLatency
2235 .name(name() + ".demand_avg_mshr_miss_latency")
2236 .desc("average overall mshr miss latency")
2237 .flags(total
| nozero
| nonan
)
2239 demandAvgMshrMissLatency
= demandMshrMissLatency
/ demandMshrMisses
;
2240 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2241 demandAvgMshrMissLatency
.subname(i
, system
->getMasterName(i
));
2244 overallAvgMshrMissLatency
2245 .name(name() + ".overall_avg_mshr_miss_latency")
2246 .desc("average overall mshr miss latency")
2247 .flags(total
| nozero
| nonan
)
2249 overallAvgMshrMissLatency
= overallMshrMissLatency
/ overallMshrMisses
;
2250 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2251 overallAvgMshrMissLatency
.subname(i
, system
->getMasterName(i
));
2254 // mshrUncacheable latency formulas
2255 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
2256 MemCmd
cmd(access_idx
);
2257 const string
&cstr
= cmd
.toString();
2259 avgMshrUncacheableLatency
[access_idx
]
2260 .name(name() + "." + cstr
+ "_avg_mshr_uncacheable_latency")
2261 .desc("average " + cstr
+ " mshr uncacheable latency")
2262 .flags(total
| nozero
| nonan
)
2264 avgMshrUncacheableLatency
[access_idx
] =
2265 mshr_uncacheable_lat
[access_idx
] / mshr_uncacheable
[access_idx
];
2267 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2268 avgMshrUncacheableLatency
[access_idx
].subname(
2269 i
, system
->getMasterName(i
));
2273 overallAvgMshrUncacheableLatency
2274 .name(name() + ".overall_avg_mshr_uncacheable_latency")
2275 .desc("average overall mshr uncacheable latency")
2276 .flags(total
| nozero
| nonan
)
2278 overallAvgMshrUncacheableLatency
=
2279 overallMshrUncacheableLatency
/ overallMshrUncacheable
;
2280 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2281 overallAvgMshrUncacheableLatency
.subname(i
, system
->getMasterName(i
));
2285 .name(name() + ".replacements")
2286 .desc("number of replacements")
2291 BaseCache::regProbePoints()
2293 ppHit
= new ProbePointArg
<PacketPtr
>(this->getProbeManager(), "Hit");
2294 ppMiss
= new ProbePointArg
<PacketPtr
>(this->getProbeManager(), "Miss");
2295 ppFill
= new ProbePointArg
<PacketPtr
>(this->getProbeManager(), "Fill");
2304 BaseCache::CpuSidePort::recvTimingSnoopResp(PacketPtr pkt
)
2306 // Snoops shouldn't happen when bypassing caches
2307 assert(!cache
->system
->bypassCaches());
2309 assert(pkt
->isResponse());
2311 // Express snoop responses from master to slave, e.g., from L1 to L2
2312 cache
->recvTimingSnoopResp(pkt
);
2318 BaseCache::CpuSidePort::tryTiming(PacketPtr pkt
)
2320 if (cache
->system
->bypassCaches() || pkt
->isExpressSnoop()) {
2321 // always let express snoop packets through even if blocked
2323 } else if (blocked
|| mustSendRetry
) {
2324 // either already committed to send a retry, or blocked
2325 mustSendRetry
= true;
2328 mustSendRetry
= false;
2333 BaseCache::CpuSidePort::recvTimingReq(PacketPtr pkt
)
2335 assert(pkt
->isRequest());
2337 if (cache
->system
->bypassCaches()) {
2338 // Just forward the packet if caches are disabled.
2339 // @todo This should really enqueue the packet rather
2340 bool M5_VAR_USED success
= cache
->memSidePort
.sendTimingReq(pkt
);
2343 } else if (tryTiming(pkt
)) {
2344 cache
->recvTimingReq(pkt
);
2351 BaseCache::CpuSidePort::recvAtomic(PacketPtr pkt
)
2353 if (cache
->system
->bypassCaches()) {
2354 // Forward the request if the system is in cache bypass mode.
2355 return cache
->memSidePort
.sendAtomic(pkt
);
2357 return cache
->recvAtomic(pkt
);
2362 BaseCache::CpuSidePort::recvFunctional(PacketPtr pkt
)
2364 if (cache
->system
->bypassCaches()) {
2365 // The cache should be flushed if we are in cache bypass mode,
2366 // so we don't need to check if we need to update anything.
2367 cache
->memSidePort
.sendFunctional(pkt
);
2371 // functional request
2372 cache
->functionalAccess(pkt
, true);
2376 BaseCache::CpuSidePort::getAddrRanges() const
2378 return cache
->getAddrRanges();
2383 CpuSidePort::CpuSidePort(const std::string
&_name
, BaseCache
*_cache
,
2384 const std::string
&_label
)
2385 : CacheSlavePort(_name
, _cache
, _label
), cache(_cache
)
2395 BaseCache::MemSidePort::recvTimingResp(PacketPtr pkt
)
2397 cache
->recvTimingResp(pkt
);
2401 // Express snooping requests to memside port
2403 BaseCache::MemSidePort::recvTimingSnoopReq(PacketPtr pkt
)
2405 // Snoops shouldn't happen when bypassing caches
2406 assert(!cache
->system
->bypassCaches());
2408 // handle snooping requests
2409 cache
->recvTimingSnoopReq(pkt
);
2413 BaseCache::MemSidePort::recvAtomicSnoop(PacketPtr pkt
)
2415 // Snoops shouldn't happen when bypassing caches
2416 assert(!cache
->system
->bypassCaches());
2418 return cache
->recvAtomicSnoop(pkt
);
2422 BaseCache::MemSidePort::recvFunctionalSnoop(PacketPtr pkt
)
2424 // Snoops shouldn't happen when bypassing caches
2425 assert(!cache
->system
->bypassCaches());
2427 // functional snoop (note that in contrast to atomic we don't have
2428 // a specific functionalSnoop method, as they have the same
2429 // behaviour regardless)
2430 cache
->functionalAccess(pkt
, false);
2434 BaseCache::CacheReqPacketQueue::sendDeferredPacket()
2437 assert(!waitingOnRetry
);
2439 // there should never be any deferred request packets in the
2440 // queue, instead we resly on the cache to provide the packets
2441 // from the MSHR queue or write queue
2442 assert(deferredPacketReadyTime() == MaxTick
);
2444 // check for request packets (requests & writebacks)
2445 QueueEntry
* entry
= cache
.getNextQueueEntry();
2448 // can happen if e.g. we attempt a writeback and fail, but
2449 // before the retry, the writeback is eliminated because
2450 // we snoop another cache's ReadEx.
2452 // let our snoop responses go first if there are responses to
2453 // the same addresses
2454 if (checkConflictingSnoop(entry
->blkAddr
)) {
2457 waitingOnRetry
= entry
->sendPacket(cache
);
2460 // if we succeeded and are not waiting for a retry, schedule the
2461 // next send considering when the next queue is ready, note that
2462 // snoop responses have their own packet queue and thus schedule
2464 if (!waitingOnRetry
) {
2465 schedSendEvent(cache
.nextQueueReadyTime());
2469 BaseCache::MemSidePort::MemSidePort(const std::string
&_name
,
2471 const std::string
&_label
)
2472 : CacheMasterPort(_name
, _cache
, _reqQueue
, _snoopRespQueue
),
2473 _reqQueue(*_cache
, *this, _snoopRespQueue
, _label
),
2474 _snoopRespQueue(*_cache
, *this, true, _label
), cache(_cache
)
2479 WriteAllocator::updateMode(Addr write_addr
, unsigned write_size
,
2482 // check if we are continuing where the last write ended
2483 if (nextAddr
== write_addr
) {
2484 delayCtr
[blk_addr
] = delayThreshold
;
2485 // stop if we have already saturated
2486 if (mode
!= WriteMode::NO_ALLOCATE
) {
2487 byteCount
+= write_size
;
2488 // switch to streaming mode if we have passed the lower
2490 if (mode
== WriteMode::ALLOCATE
&&
2491 byteCount
> coalesceLimit
) {
2492 mode
= WriteMode::COALESCE
;
2493 DPRINTF(Cache
, "Switched to write coalescing\n");
2494 } else if (mode
== WriteMode::COALESCE
&&
2495 byteCount
> noAllocateLimit
) {
2496 // and continue and switch to non-allocating mode if we
2497 // pass the upper threshold
2498 mode
= WriteMode::NO_ALLOCATE
;
2499 DPRINTF(Cache
, "Switched to write-no-allocate\n");
2503 // we did not see a write matching the previous one, start
2505 byteCount
= write_size
;
2506 mode
= WriteMode::ALLOCATE
;
2507 resetDelay(blk_addr
);
2509 nextAddr
= write_addr
+ write_size
;
2513 WriteAllocatorParams::create()
2515 return new WriteAllocator(this);