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::getMasterPort(const std::string
&if_name
, PortID idx
)
191 if (if_name
== "mem_side") {
194 return MemObject::getMasterPort(if_name
, idx
);
199 BaseCache::getSlavePort(const std::string
&if_name
, PortID idx
)
201 if (if_name
== "cpu_side") {
204 return MemObject::getSlavePort(if_name
, idx
);
209 BaseCache::inRange(Addr addr
) const
211 for (const auto& r
: addrRanges
) {
212 if (r
.contains(addr
)) {
220 BaseCache::handleTimingReqHit(PacketPtr pkt
, CacheBlk
*blk
, Tick request_time
)
222 if (pkt
->needsResponse()) {
223 // These delays should have been consumed by now
224 assert(pkt
->headerDelay
== 0);
225 assert(pkt
->payloadDelay
== 0);
227 pkt
->makeTimingResponse();
229 // In this case we are considering request_time that takes
230 // into account the delay of the xbar, if any, and just
231 // lat, neglecting responseLatency, modelling hit latency
232 // just as the value of lat overriden by access(), which calls
233 // the calculateAccessLatency() function.
234 cpuSidePort
.schedTimingResp(pkt
, request_time
);
236 DPRINTF(Cache
, "%s satisfied %s, no response needed\n", __func__
,
239 // queue the packet for deletion, as the sending cache is
240 // still relying on it; if the block is found in access(),
241 // CleanEvict and Writeback messages will be deleted
243 pendingDelete
.reset(pkt
);
248 BaseCache::handleTimingReqMiss(PacketPtr pkt
, MSHR
*mshr
, CacheBlk
*blk
,
249 Tick forward_time
, Tick request_time
)
251 if (writeAllocator
&&
252 pkt
&& pkt
->isWrite() && !pkt
->req
->isUncacheable()) {
253 writeAllocator
->updateMode(pkt
->getAddr(), pkt
->getSize(),
254 pkt
->getBlockAddr(blkSize
));
259 /// @note writebacks will be checked in getNextMSHR()
260 /// for any conflicting requests to the same block
262 //@todo remove hw_pf here
264 // Coalesce unless it was a software prefetch (see above).
266 assert(!pkt
->isWriteback());
267 // CleanEvicts corresponding to blocks which have
268 // outstanding requests in MSHRs are simply sunk here
269 if (pkt
->cmd
== MemCmd::CleanEvict
) {
270 pendingDelete
.reset(pkt
);
271 } else if (pkt
->cmd
== MemCmd::WriteClean
) {
272 // A WriteClean should never coalesce with any
273 // outstanding cache maintenance requests.
275 // We use forward_time here because there is an
276 // uncached memory write, forwarded to WriteBuffer.
277 allocateWriteBuffer(pkt
, forward_time
);
279 DPRINTF(Cache
, "%s coalescing MSHR for %s\n", __func__
,
282 assert(pkt
->req
->masterId() < system
->maxMasters());
283 mshr_hits
[pkt
->cmdToIndex()][pkt
->req
->masterId()]++;
285 // We use forward_time here because it is the same
286 // considering new targets. We have multiple
287 // requests for the same address here. It
288 // specifies the latency to allocate an internal
289 // buffer and to schedule an event to the queued
290 // port and also takes into account the additional
291 // delay of the xbar.
292 mshr
->allocateTarget(pkt
, forward_time
, order
++,
293 allocOnFill(pkt
->cmd
));
294 if (mshr
->getNumTargets() == numTarget
) {
296 setBlocked(Blocked_NoTargets
);
297 // need to be careful with this... if this mshr isn't
298 // ready yet (i.e. time > curTick()), we don't want to
299 // move it ahead of mshrs that are ready
300 // mshrQueue.moveToFront(mshr);
306 assert(pkt
->req
->masterId() < system
->maxMasters());
307 mshr_misses
[pkt
->cmdToIndex()][pkt
->req
->masterId()]++;
309 if (pkt
->isEviction() || pkt
->cmd
== MemCmd::WriteClean
) {
310 // We use forward_time here because there is an
311 // writeback or writeclean, forwarded to WriteBuffer.
312 allocateWriteBuffer(pkt
, forward_time
);
314 if (blk
&& blk
->isValid()) {
315 // If we have a write miss to a valid block, we
316 // need to mark the block non-readable. Otherwise
317 // if we allow reads while there's an outstanding
318 // write miss, the read could return stale data
319 // out of the cache block... a more aggressive
320 // system could detect the overlap (if any) and
321 // forward data out of the MSHRs, but we don't do
322 // that yet. Note that we do need to leave the
323 // block valid so that it stays in the cache, in
324 // case we get an upgrade response (and hence no
325 // new data) when the write miss completes.
326 // As long as CPUs do proper store/load forwarding
327 // internally, and have a sufficiently weak memory
328 // model, this is probably unnecessary, but at some
329 // point it must have seemed like we needed it...
330 assert((pkt
->needsWritable() && !blk
->isWritable()) ||
331 pkt
->req
->isCacheMaintenance());
332 blk
->status
&= ~BlkReadable
;
334 // Here we are using forward_time, modelling the latency of
335 // a miss (outbound) just as forwardLatency, neglecting the
336 // lookupLatency component.
337 allocateMissBuffer(pkt
, forward_time
);
343 BaseCache::recvTimingReq(PacketPtr pkt
)
345 // anything that is merely forwarded pays for the forward latency and
346 // the delay provided by the crossbar
347 Tick forward_time
= clockEdge(forwardLatency
) + pkt
->headerDelay
;
350 CacheBlk
*blk
= nullptr;
351 bool satisfied
= false;
353 PacketList writebacks
;
354 // Note that lat is passed by reference here. The function
355 // access() will set the lat value.
356 satisfied
= access(pkt
, blk
, lat
, writebacks
);
358 // After the evicted blocks are selected, they must be forwarded
359 // to the write buffer to ensure they logically precede anything
361 doWritebacks(writebacks
, clockEdge(lat
+ forwardLatency
));
364 // Here we charge the headerDelay that takes into account the latencies
365 // of the bus, if the packet comes from it.
366 // The latency charged is just the value set by the access() function.
367 // In case of a hit we are neglecting response latency.
368 // In case of a miss we are neglecting forward latency.
369 Tick request_time
= clockEdge(lat
);
370 // Here we reset the timing of the packet.
371 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
374 // notify before anything else as later handleTimingReqHit might turn
375 // the packet in a response
378 if (prefetcher
&& blk
&& blk
->wasPrefetched()) {
379 blk
->status
&= ~BlkHWPrefetched
;
382 handleTimingReqHit(pkt
, blk
, request_time
);
384 handleTimingReqMiss(pkt
, blk
, forward_time
, request_time
);
390 // track time of availability of next prefetch, if any
391 Tick next_pf_time
= prefetcher
->nextPrefetchReadyTime();
392 if (next_pf_time
!= MaxTick
) {
393 schedMemSideSendEvent(next_pf_time
);
399 BaseCache::handleUncacheableWriteResp(PacketPtr pkt
)
401 Tick completion_time
= clockEdge(responseLatency
) +
402 pkt
->headerDelay
+ pkt
->payloadDelay
;
404 // Reset the bus additional time as it is now accounted for
405 pkt
->headerDelay
= pkt
->payloadDelay
= 0;
407 cpuSidePort
.schedTimingResp(pkt
, completion_time
);
411 BaseCache::recvTimingResp(PacketPtr pkt
)
413 assert(pkt
->isResponse());
415 // all header delay should be paid for by the crossbar, unless
416 // this is a prefetch response from above
417 panic_if(pkt
->headerDelay
!= 0 && pkt
->cmd
!= MemCmd::HardPFResp
,
418 "%s saw a non-zero packet delay\n", name());
420 const bool is_error
= pkt
->isError();
423 DPRINTF(Cache
, "%s: Cache received %s with error\n", __func__
,
427 DPRINTF(Cache
, "%s: Handling response %s\n", __func__
,
430 // if this is a write, we should be looking at an uncacheable
432 if (pkt
->isWrite()) {
433 assert(pkt
->req
->isUncacheable());
434 handleUncacheableWriteResp(pkt
);
438 // we have dealt with any (uncacheable) writes above, from here on
439 // we know we are dealing with an MSHR due to a miss or a prefetch
440 MSHR
*mshr
= dynamic_cast<MSHR
*>(pkt
->popSenderState());
443 if (mshr
== noTargetMSHR
) {
444 // we always clear at least one target
445 clearBlocked(Blocked_NoTargets
);
446 noTargetMSHR
= nullptr;
449 // Initial target is used just for stats
450 MSHR::Target
*initial_tgt
= mshr
->getTarget();
451 int stats_cmd_idx
= initial_tgt
->pkt
->cmdToIndex();
452 Tick miss_latency
= curTick() - initial_tgt
->recvTime
;
454 if (pkt
->req
->isUncacheable()) {
455 assert(pkt
->req
->masterId() < system
->maxMasters());
456 mshr_uncacheable_lat
[stats_cmd_idx
][pkt
->req
->masterId()] +=
459 assert(pkt
->req
->masterId() < system
->maxMasters());
460 mshr_miss_latency
[stats_cmd_idx
][pkt
->req
->masterId()] +=
464 PacketList writebacks
;
466 bool is_fill
= !mshr
->isForward
&&
467 (pkt
->isRead() || pkt
->cmd
== MemCmd::UpgradeResp
||
468 mshr
->wasWholeLineWrite
);
470 // make sure that if the mshr was due to a whole line write then
471 // the response is an invalidation
472 assert(!mshr
->wasWholeLineWrite
|| pkt
->isInvalidate());
474 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), pkt
->isSecure());
476 if (is_fill
&& !is_error
) {
477 DPRINTF(Cache
, "Block for addr %#llx being updated in Cache\n",
480 const bool allocate
= (writeAllocator
&& mshr
->wasWholeLineWrite
) ?
481 writeAllocator
->allocate() : mshr
->allocOnFill();
482 blk
= handleFill(pkt
, blk
, writebacks
, allocate
);
483 assert(blk
!= nullptr);
487 if (blk
&& blk
->isValid() && pkt
->isClean() && !pkt
->isInvalidate()) {
488 // The block was marked not readable while there was a pending
489 // cache maintenance operation, restore its flag.
490 blk
->status
|= BlkReadable
;
492 // This was a cache clean operation (without invalidate)
493 // and we have a copy of the block already. Since there
494 // is no invalidation, we can promote targets that don't
495 // require a writable copy
496 mshr
->promoteReadable();
499 if (blk
&& blk
->isWritable() && !pkt
->req
->isCacheInvalidate()) {
500 // If at this point the referenced block is writable and the
501 // response is not a cache invalidate, we promote targets that
502 // were deferred as we couldn't guarrantee a writable copy
503 mshr
->promoteWritable();
506 serviceMSHRTargets(mshr
, pkt
, blk
);
508 if (mshr
->promoteDeferredTargets()) {
509 // avoid later read getting stale data while write miss is
510 // outstanding.. see comment in timingAccess()
512 blk
->status
&= ~BlkReadable
;
514 mshrQueue
.markPending(mshr
);
515 schedMemSideSendEvent(clockEdge() + pkt
->payloadDelay
);
517 // while we deallocate an mshr from the queue we still have to
518 // check the isFull condition before and after as we might
519 // have been using the reserved entries already
520 const bool was_full
= mshrQueue
.isFull();
521 mshrQueue
.deallocate(mshr
);
522 if (was_full
&& !mshrQueue
.isFull()) {
523 clearBlocked(Blocked_NoMSHRs
);
526 // Request the bus for a prefetch if this deallocation freed enough
527 // MSHRs for a prefetch to take place
528 if (prefetcher
&& mshrQueue
.canPrefetch()) {
529 Tick next_pf_time
= std::max(prefetcher
->nextPrefetchReadyTime(),
531 if (next_pf_time
!= MaxTick
)
532 schedMemSideSendEvent(next_pf_time
);
536 // if we used temp block, check to see if its valid and then clear it out
537 if (blk
== tempBlock
&& tempBlock
->isValid()) {
538 evictBlock(blk
, writebacks
);
541 const Tick forward_time
= clockEdge(forwardLatency
) + pkt
->headerDelay
;
542 // copy writebacks to write buffer
543 doWritebacks(writebacks
, forward_time
);
545 DPRINTF(CacheVerbose
, "%s: Leaving with %s\n", __func__
, pkt
->print());
551 BaseCache::recvAtomic(PacketPtr pkt
)
553 // should assert here that there are no outstanding MSHRs or
554 // writebacks... that would mean that someone used an atomic
555 // access in timing mode
557 // We use lookupLatency here because it is used to specify the latency
559 Cycles lat
= lookupLatency
;
561 CacheBlk
*blk
= nullptr;
562 PacketList writebacks
;
563 bool satisfied
= access(pkt
, blk
, lat
, writebacks
);
565 if (pkt
->isClean() && blk
&& blk
->isDirty()) {
566 // A cache clean opearation is looking for a dirty
567 // block. If a dirty block is encountered a WriteClean
568 // will update any copies to the path to the memory
569 // until the point of reference.
570 DPRINTF(CacheVerbose
, "%s: packet %s found block: %s\n",
571 __func__
, pkt
->print(), blk
->print());
572 PacketPtr wb_pkt
= writecleanBlk(blk
, pkt
->req
->getDest(), pkt
->id
);
573 writebacks
.push_back(wb_pkt
);
577 // handle writebacks resulting from the access here to ensure they
578 // logically precede anything happening below
579 doWritebacksAtomic(writebacks
);
580 assert(writebacks
.empty());
583 lat
+= handleAtomicReqMiss(pkt
, blk
, writebacks
);
586 // Note that we don't invoke the prefetcher at all in atomic mode.
587 // It's not clear how to do it properly, particularly for
588 // prefetchers that aggressively generate prefetch candidates and
589 // rely on bandwidth contention to throttle them; these will tend
590 // to pollute the cache in atomic mode since there is no bandwidth
591 // contention. If we ever do want to enable prefetching in atomic
592 // mode, though, this is the place to do it... see timingAccess()
593 // for an example (though we'd want to issue the prefetch(es)
594 // immediately rather than calling requestMemSideBus() as we do
597 // do any writebacks resulting from the response handling
598 doWritebacksAtomic(writebacks
);
600 // if we used temp block, check to see if its valid and if so
601 // clear it out, but only do so after the call to recvAtomic is
602 // finished so that any downstream observers (such as a snoop
603 // filter), first see the fill, and only then see the eviction
604 if (blk
== tempBlock
&& tempBlock
->isValid()) {
605 // the atomic CPU calls recvAtomic for fetch and load/store
606 // sequentuially, and we may already have a tempBlock
607 // writeback from the fetch that we have not yet sent
608 if (tempBlockWriteback
) {
609 // if that is the case, write the prevoius one back, and
610 // do not schedule any new event
611 writebackTempBlockAtomic();
613 // the writeback/clean eviction happens after the call to
614 // recvAtomic has finished (but before any successive
615 // calls), so that the response handling from the fill is
616 // allowed to happen first
617 schedule(writebackTempBlockAtomicEvent
, curTick());
620 tempBlockWriteback
= evictBlock(blk
);
623 if (pkt
->needsResponse()) {
624 pkt
->makeAtomicResponse();
627 return lat
* clockPeriod();
631 BaseCache::functionalAccess(PacketPtr pkt
, bool from_cpu_side
)
633 Addr blk_addr
= pkt
->getBlockAddr(blkSize
);
634 bool is_secure
= pkt
->isSecure();
635 CacheBlk
*blk
= tags
->findBlock(pkt
->getAddr(), is_secure
);
636 MSHR
*mshr
= mshrQueue
.findMatch(blk_addr
, is_secure
);
638 pkt
->pushLabel(name());
640 CacheBlkPrintWrapper
cbpw(blk
);
642 // Note that just because an L2/L3 has valid data doesn't mean an
643 // L1 doesn't have a more up-to-date modified copy that still
644 // needs to be found. As a result we always update the request if
645 // we have it, but only declare it satisfied if we are the owner.
647 // see if we have data at all (owned or otherwise)
648 bool have_data
= blk
&& blk
->isValid()
649 && pkt
->trySatisfyFunctional(&cbpw
, blk_addr
, is_secure
, blkSize
,
652 // data we have is dirty if marked as such or if we have an
653 // in-service MSHR that is pending a modified line
655 have_data
&& (blk
->isDirty() ||
656 (mshr
&& mshr
->inService
&& mshr
->isPendingModified()));
658 bool done
= have_dirty
||
659 cpuSidePort
.trySatisfyFunctional(pkt
) ||
660 mshrQueue
.trySatisfyFunctional(pkt
, blk_addr
) ||
661 writeBuffer
.trySatisfyFunctional(pkt
, blk_addr
) ||
662 memSidePort
.trySatisfyFunctional(pkt
);
664 DPRINTF(CacheVerbose
, "%s: %s %s%s%s\n", __func__
, pkt
->print(),
665 (blk
&& blk
->isValid()) ? "valid " : "",
666 have_data
? "data " : "", done
? "done " : "");
668 // We're leaving the cache, so pop cache->name() label
674 // if it came as a request from the CPU side then make sure it
675 // continues towards the memory side
677 memSidePort
.sendFunctional(pkt
);
678 } else if (cpuSidePort
.isSnooping()) {
679 // if it came from the memory side, it must be a snoop request
680 // and we should only forward it if we are forwarding snoops
681 cpuSidePort
.sendFunctionalSnoop(pkt
);
688 BaseCache::cmpAndSwap(CacheBlk
*blk
, PacketPtr pkt
)
690 assert(pkt
->isRequest());
692 uint64_t overwrite_val
;
694 uint64_t condition_val64
;
695 uint32_t condition_val32
;
697 int offset
= pkt
->getOffset(blkSize
);
698 uint8_t *blk_data
= blk
->data
+ offset
;
700 assert(sizeof(uint64_t) >= pkt
->getSize());
702 overwrite_mem
= true;
703 // keep a copy of our possible write value, and copy what is at the
704 // memory address into the packet
705 pkt
->writeData((uint8_t *)&overwrite_val
);
706 pkt
->setData(blk_data
);
708 if (pkt
->req
->isCondSwap()) {
709 if (pkt
->getSize() == sizeof(uint64_t)) {
710 condition_val64
= pkt
->req
->getExtraData();
711 overwrite_mem
= !std::memcmp(&condition_val64
, blk_data
,
713 } else if (pkt
->getSize() == sizeof(uint32_t)) {
714 condition_val32
= (uint32_t)pkt
->req
->getExtraData();
715 overwrite_mem
= !std::memcmp(&condition_val32
, blk_data
,
718 panic("Invalid size for conditional read/write\n");
722 std::memcpy(blk_data
, &overwrite_val
, pkt
->getSize());
723 blk
->status
|= BlkDirty
;
728 BaseCache::getNextQueueEntry()
730 // Check both MSHR queue and write buffer for potential requests,
731 // note that null does not mean there is no request, it could
732 // simply be that it is not ready
733 MSHR
*miss_mshr
= mshrQueue
.getNext();
734 WriteQueueEntry
*wq_entry
= writeBuffer
.getNext();
736 // If we got a write buffer request ready, first priority is a
737 // full write buffer, otherwise we favour the miss requests
738 if (wq_entry
&& (writeBuffer
.isFull() || !miss_mshr
)) {
739 // need to search MSHR queue for conflicting earlier miss.
740 MSHR
*conflict_mshr
=
741 mshrQueue
.findPending(wq_entry
->blkAddr
,
744 if (conflict_mshr
&& conflict_mshr
->order
< wq_entry
->order
) {
745 // Service misses in order until conflict is cleared.
746 return conflict_mshr
;
748 // @todo Note that we ignore the ready time of the conflict here
751 // No conflicts; issue write
753 } else if (miss_mshr
) {
754 // need to check for conflicting earlier writeback
755 WriteQueueEntry
*conflict_mshr
=
756 writeBuffer
.findPending(miss_mshr
->blkAddr
,
757 miss_mshr
->isSecure
);
759 // not sure why we don't check order here... it was in the
760 // original code but commented out.
762 // The only way this happens is if we are
763 // doing a write and we didn't have permissions
764 // then subsequently saw a writeback (owned got evicted)
765 // We need to make sure to perform the writeback first
766 // To preserve the dirty data, then we can issue the write
768 // should we return wq_entry here instead? I.e. do we
769 // have to flush writes in order? I don't think so... not
770 // for Alpha anyway. Maybe for x86?
771 return conflict_mshr
;
773 // @todo Note that we ignore the ready time of the conflict here
776 // No conflicts; issue read
780 // fall through... no pending requests. Try a prefetch.
781 assert(!miss_mshr
&& !wq_entry
);
782 if (prefetcher
&& mshrQueue
.canPrefetch()) {
783 // If we have a miss queue slot, we can try a prefetch
784 PacketPtr pkt
= prefetcher
->getPacket();
786 Addr pf_addr
= pkt
->getBlockAddr(blkSize
);
787 if (!tags
->findBlock(pf_addr
, pkt
->isSecure()) &&
788 !mshrQueue
.findMatch(pf_addr
, pkt
->isSecure()) &&
789 !writeBuffer
.findMatch(pf_addr
, pkt
->isSecure())) {
790 // Update statistic on number of prefetches issued
791 // (hwpf_mshr_misses)
792 assert(pkt
->req
->masterId() < system
->maxMasters());
793 mshr_misses
[pkt
->cmdToIndex()][pkt
->req
->masterId()]++;
795 // allocate an MSHR and return it, note
796 // that we send the packet straight away, so do not
798 return allocateMissBuffer(pkt
, curTick(), false);
800 // free the request and packet
810 BaseCache::satisfyRequest(PacketPtr pkt
, CacheBlk
*blk
, bool, bool)
812 assert(pkt
->isRequest());
814 assert(blk
&& blk
->isValid());
815 // Occasionally this is not true... if we are a lower-level cache
816 // satisfying a string of Read and ReadEx requests from
817 // upper-level caches, a Read will mark the block as shared but we
818 // can satisfy a following ReadEx anyway since we can rely on the
819 // Read requester(s) to have buffered the ReadEx snoop and to
820 // invalidate their blocks after receiving them.
821 // assert(!pkt->needsWritable() || blk->isWritable());
822 assert(pkt
->getOffset(blkSize
) + pkt
->getSize() <= blkSize
);
824 // Check RMW operations first since both isRead() and
825 // isWrite() will be true for them
826 if (pkt
->cmd
== MemCmd::SwapReq
) {
827 if (pkt
->isAtomicOp()) {
828 // extract data from cache and save it into the data field in
829 // the packet as a return value from this atomic op
830 int offset
= tags
->extractBlkOffset(pkt
->getAddr());
831 uint8_t *blk_data
= blk
->data
+ offset
;
832 pkt
->setData(blk_data
);
834 // execute AMO operation
835 (*(pkt
->getAtomicOp()))(blk_data
);
837 // set block status to dirty
838 blk
->status
|= BlkDirty
;
840 cmpAndSwap(blk
, pkt
);
842 } else if (pkt
->isWrite()) {
843 // we have the block in a writable state and can go ahead,
844 // note that the line may be also be considered writable in
845 // downstream caches along the path to memory, but always
846 // Exclusive, and never Modified
847 assert(blk
->isWritable());
848 // Write or WriteLine at the first cache with block in writable state
849 if (blk
->checkWrite(pkt
)) {
850 pkt
->writeDataToBlock(blk
->data
, blkSize
);
852 // Always mark the line as dirty (and thus transition to the
853 // Modified state) even if we are a failed StoreCond so we
854 // supply data to any snoops that have appended themselves to
855 // this cache before knowing the store will fail.
856 blk
->status
|= BlkDirty
;
857 DPRINTF(CacheVerbose
, "%s for %s (write)\n", __func__
, pkt
->print());
858 } else if (pkt
->isRead()) {
860 blk
->trackLoadLocked(pkt
);
863 // all read responses have a data payload
864 assert(pkt
->hasRespData());
865 pkt
->setDataFromBlock(blk
->data
, blkSize
);
866 } else if (pkt
->isUpgrade()) {
868 assert(!pkt
->hasSharers());
870 if (blk
->isDirty()) {
871 // we were in the Owned state, and a cache above us that
872 // has the line in Shared state needs to be made aware
873 // that the data it already has is in fact dirty
874 pkt
->setCacheResponding();
875 blk
->status
&= ~BlkDirty
;
877 } else if (pkt
->isClean()) {
878 blk
->status
&= ~BlkDirty
;
880 assert(pkt
->isInvalidate());
881 invalidateBlock(blk
);
882 DPRINTF(CacheVerbose
, "%s for %s (invalidation)\n", __func__
,
887 /////////////////////////////////////////////////////
889 // Access path: requests coming in from the CPU side
891 /////////////////////////////////////////////////////
893 BaseCache::calculateAccessLatency(const CacheBlk
* blk
, const uint32_t delay
,
894 const Cycles lookup_lat
) const
898 if (blk
!= nullptr) {
899 // As soon as the access arrives, for sequential accesses first access
900 // tags, then the data entry. In the case of parallel accesses the
901 // latency is dictated by the slowest of tag and data latencies.
902 if (sequentialAccess
) {
903 lat
= ticksToCycles(delay
) + lookup_lat
+ dataLatency
;
905 lat
= ticksToCycles(delay
) + std::max(lookup_lat
, dataLatency
);
908 // Check if the block to be accessed is available. If not, apply the
909 // access latency on top of when the block is ready to be accessed.
910 const Tick tick
= curTick() + delay
;
911 const Tick when_ready
= blk
->getWhenReady();
912 if (when_ready
> tick
&&
913 ticksToCycles(when_ready
- tick
) > lat
) {
914 lat
+= ticksToCycles(when_ready
- tick
);
917 // In case of a miss, apply lookup latency on top of the metadata
918 // delay, as the access can only start when it arrives.
919 lat
= ticksToCycles(delay
) + lookup_lat
;
926 BaseCache::access(PacketPtr pkt
, CacheBlk
*&blk
, Cycles
&lat
,
927 PacketList
&writebacks
)
930 assert(pkt
->isRequest());
932 chatty_assert(!(isReadOnly
&& pkt
->isWrite()),
933 "Should never see a write in a read-only cache %s\n",
936 // Access block in the tags
937 Cycles
tag_latency(0);
938 blk
= tags
->accessBlock(pkt
->getAddr(), pkt
->isSecure(), tag_latency
);
940 // Calculate access latency on top of when the packet arrives. This
941 // takes into account the bus delay.
942 lat
= calculateAccessLatency(blk
, pkt
->headerDelay
,
945 DPRINTF(Cache
, "%s for %s %s\n", __func__
, pkt
->print(),
946 blk
? "hit " + blk
->print() : "miss");
948 if (pkt
->req
->isCacheMaintenance()) {
949 // A cache maintenance operation is always forwarded to the
950 // memory below even if the block is found in dirty state.
952 // We defer any changes to the state of the block until we
953 // create and mark as in service the mshr for the downstream
958 if (pkt
->isEviction()) {
959 // We check for presence of block in above caches before issuing
960 // Writeback or CleanEvict to write buffer. Therefore the only
961 // possible cases can be of a CleanEvict packet coming from above
962 // encountering a Writeback generated in this cache peer cache and
963 // waiting in the write buffer. Cases of upper level peer caches
964 // generating CleanEvict and Writeback or simply CleanEvict and
965 // CleanEvict almost simultaneously will be caught by snoops sent out
967 WriteQueueEntry
*wb_entry
= writeBuffer
.findMatch(pkt
->getAddr(),
970 assert(wb_entry
->getNumTargets() == 1);
971 PacketPtr wbPkt
= wb_entry
->getTarget()->pkt
;
972 assert(wbPkt
->isWriteback());
974 if (pkt
->isCleanEviction()) {
975 // The CleanEvict and WritebackClean snoops into other
976 // peer caches of the same level while traversing the
977 // crossbar. If a copy of the block is found, the
978 // packet is deleted in the crossbar. Hence, none of
979 // the other upper level caches connected to this
980 // cache have the block, so we can clear the
981 // BLOCK_CACHED flag in the Writeback if set and
982 // discard the CleanEvict by returning true.
983 wbPkt
->clearBlockCached();
986 assert(pkt
->cmd
== MemCmd::WritebackDirty
);
987 // Dirty writeback from above trumps our clean
988 // writeback... discard here
989 // Note: markInService will remove entry from writeback buffer.
990 markInService(wb_entry
);
996 // Writeback handling is special case. We can write the block into
997 // the cache without having a writeable copy (or any copy at all).
998 if (pkt
->isWriteback()) {
999 assert(blkSize
== pkt
->getSize());
1001 // we could get a clean writeback while we are having
1002 // outstanding accesses to a block, do the simple thing for
1003 // now and drop the clean writeback so that we do not upset
1004 // any ordering/decisions about ownership already taken
1005 if (pkt
->cmd
== MemCmd::WritebackClean
&&
1006 mshrQueue
.findMatch(pkt
->getAddr(), pkt
->isSecure())) {
1007 DPRINTF(Cache
, "Clean writeback %#llx to block with MSHR, "
1008 "dropping\n", pkt
->getAddr());
1013 // need to do a replacement
1014 blk
= allocateBlock(pkt
, writebacks
);
1016 // no replaceable block available: give up, fwd to next level.
1021 blk
->status
|= BlkReadable
;
1023 // only mark the block dirty if we got a writeback command,
1024 // and leave it as is for a clean writeback
1025 if (pkt
->cmd
== MemCmd::WritebackDirty
) {
1026 // TODO: the coherent cache can assert(!blk->isDirty());
1027 blk
->status
|= BlkDirty
;
1029 // if the packet does not have sharers, it is passing
1030 // writable, and we got the writeback in Modified or Exclusive
1031 // state, if not we are in the Owned or Shared state
1032 if (!pkt
->hasSharers()) {
1033 blk
->status
|= BlkWritable
;
1035 // nothing else to do; writeback doesn't expect response
1036 assert(!pkt
->needsResponse());
1037 pkt
->writeDataToBlock(blk
->data
, blkSize
);
1038 DPRINTF(Cache
, "%s new state is %s\n", __func__
, blk
->print());
1040 // populate the time when the block will be ready to access.
1041 blk
->setWhenReady(clockEdge(fillLatency
) + pkt
->headerDelay
+
1044 } else if (pkt
->cmd
== MemCmd::CleanEvict
) {
1046 // Found the block in the tags, need to stop CleanEvict from
1047 // propagating further down the hierarchy. Returning true will
1048 // treat the CleanEvict like a satisfied write request and delete
1052 // We didn't find the block here, propagate the CleanEvict further
1053 // down the memory hierarchy. Returning false will treat the CleanEvict
1054 // like a Writeback which could not find a replaceable block so has to
1055 // go to next level.
1057 } else if (pkt
->cmd
== MemCmd::WriteClean
) {
1058 // WriteClean handling is a special case. We can allocate a
1059 // block directly if it doesn't exist and we can update the
1060 // block immediately. The WriteClean transfers the ownership
1061 // of the block as well.
1062 assert(blkSize
== pkt
->getSize());
1065 if (pkt
->writeThrough()) {
1066 // if this is a write through packet, we don't try to
1067 // allocate if the block is not present
1070 // a writeback that misses needs to allocate a new block
1071 blk
= allocateBlock(pkt
, writebacks
);
1073 // no replaceable block available: give up, fwd to
1079 blk
->status
|= BlkReadable
;
1083 // at this point either this is a writeback or a write-through
1084 // write clean operation and the block is already in this
1085 // cache, we need to update the data and the block flags
1087 // TODO: the coherent cache can assert(!blk->isDirty());
1088 if (!pkt
->writeThrough()) {
1089 blk
->status
|= BlkDirty
;
1091 // nothing else to do; writeback doesn't expect response
1092 assert(!pkt
->needsResponse());
1093 pkt
->writeDataToBlock(blk
->data
, blkSize
);
1094 DPRINTF(Cache
, "%s new state is %s\n", __func__
, blk
->print());
1097 // populate the time when the block will be ready to access.
1098 blk
->setWhenReady(clockEdge(fillLatency
) + pkt
->headerDelay
+
1100 // if this a write-through packet it will be sent to cache
1102 return !pkt
->writeThrough();
1103 } else if (blk
&& (pkt
->needsWritable() ? blk
->isWritable() :
1104 blk
->isReadable())) {
1105 // OK to satisfy access
1107 satisfyRequest(pkt
, blk
);
1108 maintainClusivity(pkt
->fromCache(), blk
);
1113 // Can't satisfy access normally... either no block (blk == nullptr)
1114 // or have block but need writable
1118 if (!blk
&& pkt
->isLLSC() && pkt
->isWrite()) {
1119 // complete miss on store conditional... just give up now
1120 pkt
->req
->setExtraData(0);
1128 BaseCache::maintainClusivity(bool from_cache
, CacheBlk
*blk
)
1130 if (from_cache
&& blk
&& blk
->isValid() && !blk
->isDirty() &&
1131 clusivity
== Enums::mostly_excl
) {
1132 // if we have responded to a cache, and our block is still
1133 // valid, but not dirty, and this cache is mostly exclusive
1134 // with respect to the cache above, drop the block
1135 invalidateBlock(blk
);
1140 BaseCache::handleFill(PacketPtr pkt
, CacheBlk
*blk
, PacketList
&writebacks
,
1143 assert(pkt
->isResponse());
1144 Addr addr
= pkt
->getAddr();
1145 bool is_secure
= pkt
->isSecure();
1147 CacheBlk::State old_state
= blk
? blk
->status
: 0;
1150 // When handling a fill, we should have no writes to this line.
1151 assert(addr
== pkt
->getBlockAddr(blkSize
));
1152 assert(!writeBuffer
.findMatch(addr
, is_secure
));
1155 // better have read new data...
1156 assert(pkt
->hasData() || pkt
->cmd
== MemCmd::InvalidateResp
);
1158 // need to do a replacement if allocating, otherwise we stick
1159 // with the temporary storage
1160 blk
= allocate
? allocateBlock(pkt
, writebacks
) : nullptr;
1163 // No replaceable block or a mostly exclusive
1164 // cache... just use temporary storage to complete the
1165 // current request and then get rid of it
1167 tempBlock
->insert(addr
, is_secure
);
1168 DPRINTF(Cache
, "using temp block for %#llx (%s)\n", addr
,
1169 is_secure
? "s" : "ns");
1172 // existing block... probably an upgrade
1173 // don't clear block status... if block is already dirty we
1174 // don't want to lose that
1177 // Block is guaranteed to be valid at this point
1178 assert(blk
->isValid());
1179 assert(blk
->isSecure() == is_secure
);
1180 assert(regenerateBlkAddr(blk
) == addr
);
1182 blk
->status
|= BlkReadable
;
1184 // sanity check for whole-line writes, which should always be
1185 // marked as writable as part of the fill, and then later marked
1186 // dirty as part of satisfyRequest
1187 if (pkt
->cmd
== MemCmd::InvalidateResp
) {
1188 assert(!pkt
->hasSharers());
1191 // here we deal with setting the appropriate state of the line,
1192 // and we start by looking at the hasSharers flag, and ignore the
1193 // cacheResponding flag (normally signalling dirty data) if the
1194 // packet has sharers, thus the line is never allocated as Owned
1195 // (dirty but not writable), and always ends up being either
1196 // Shared, Exclusive or Modified, see Packet::setCacheResponding
1198 if (!pkt
->hasSharers()) {
1199 // we could get a writable line from memory (rather than a
1200 // cache) even in a read-only cache, note that we set this bit
1201 // even for a read-only cache, possibly revisit this decision
1202 blk
->status
|= BlkWritable
;
1204 // check if we got this via cache-to-cache transfer (i.e., from a
1205 // cache that had the block in Modified or Owned state)
1206 if (pkt
->cacheResponding()) {
1207 // we got the block in Modified state, and invalidated the
1209 blk
->status
|= BlkDirty
;
1211 chatty_assert(!isReadOnly
, "Should never see dirty snoop response "
1212 "in read-only cache %s\n", name());
1216 DPRINTF(Cache
, "Block addr %#llx (%s) moving from state %x to %s\n",
1217 addr
, is_secure
? "s" : "ns", old_state
, blk
->print());
1219 // if we got new data, copy it in (checking for a read response
1220 // and a response that has data is the same in the end)
1221 if (pkt
->isRead()) {
1223 assert(pkt
->hasData());
1224 assert(pkt
->getSize() == blkSize
);
1226 pkt
->writeDataToBlock(blk
->data
, blkSize
);
1228 // We pay for fillLatency here.
1229 blk
->setWhenReady(clockEdge(fillLatency
) + pkt
->payloadDelay
);
1235 BaseCache::allocateBlock(const PacketPtr pkt
, PacketList
&writebacks
)
1238 const Addr addr
= pkt
->getAddr();
1241 const bool is_secure
= pkt
->isSecure();
1243 // Find replacement victim
1244 std::vector
<CacheBlk
*> evict_blks
;
1245 CacheBlk
*victim
= tags
->findVictim(addr
, is_secure
, evict_blks
);
1247 // It is valid to return nullptr if there is no victim
1251 // Print victim block's information
1252 DPRINTF(CacheRepl
, "Replacement victim: %s\n", victim
->print());
1254 // Check for transient state allocations. If any of the entries listed
1255 // for eviction has a transient state, the allocation fails
1256 for (const auto& blk
: evict_blks
) {
1257 if (blk
->isValid()) {
1258 Addr repl_addr
= regenerateBlkAddr(blk
);
1259 MSHR
*repl_mshr
= mshrQueue
.findMatch(repl_addr
, blk
->isSecure());
1261 // must be an outstanding upgrade or clean request
1262 // on a block we're about to replace...
1263 assert((!blk
->isWritable() && repl_mshr
->needsWritable()) ||
1264 repl_mshr
->isCleaning());
1266 // too hard to replace block with transient state
1267 // allocation failed, block not inserted
1273 // The victim will be replaced by a new entry, so increase the replacement
1274 // counter if a valid block is being replaced
1275 if (victim
->isValid()) {
1276 DPRINTF(Cache
, "replacement: replacing %#llx (%s) with %#llx "
1277 "(%s): %s\n", regenerateBlkAddr(victim
),
1278 victim
->isSecure() ? "s" : "ns",
1279 addr
, is_secure
? "s" : "ns",
1280 victim
->isDirty() ? "writeback" : "clean");
1285 // Evict valid blocks associated to this victim block
1286 for (const auto& blk
: evict_blks
) {
1287 if (blk
->isValid()) {
1288 if (blk
->wasPrefetched()) {
1292 evictBlock(blk
, writebacks
);
1296 // Insert new block at victimized entry
1297 tags
->insertBlock(addr
, is_secure
, pkt
->req
->masterId(),
1298 pkt
->req
->taskId(), victim
);
1304 BaseCache::invalidateBlock(CacheBlk
*blk
)
1306 // If handling a block present in the Tags, let it do its invalidation
1307 // process, which will update stats and invalidate the block itself
1308 if (blk
!= tempBlock
) {
1309 tags
->invalidate(blk
);
1311 tempBlock
->invalidate();
1316 BaseCache::evictBlock(CacheBlk
*blk
, PacketList
&writebacks
)
1318 PacketPtr pkt
= evictBlock(blk
);
1320 writebacks
.push_back(pkt
);
1325 BaseCache::writebackBlk(CacheBlk
*blk
)
1327 chatty_assert(!isReadOnly
|| writebackClean
,
1328 "Writeback from read-only cache");
1329 assert(blk
&& blk
->isValid() && (blk
->isDirty() || writebackClean
));
1331 writebacks
[Request::wbMasterId
]++;
1333 RequestPtr req
= std::make_shared
<Request
>(
1334 regenerateBlkAddr(blk
), blkSize
, 0, Request::wbMasterId
);
1336 if (blk
->isSecure())
1337 req
->setFlags(Request::SECURE
);
1339 req
->taskId(blk
->task_id
);
1342 new Packet(req
, blk
->isDirty() ?
1343 MemCmd::WritebackDirty
: MemCmd::WritebackClean
);
1345 DPRINTF(Cache
, "Create Writeback %s writable: %d, dirty: %d\n",
1346 pkt
->print(), blk
->isWritable(), blk
->isDirty());
1348 if (blk
->isWritable()) {
1349 // not asserting shared means we pass the block in modified
1350 // state, mark our own block non-writeable
1351 blk
->status
&= ~BlkWritable
;
1353 // we are in the Owned state, tell the receiver
1354 pkt
->setHasSharers();
1357 // make sure the block is not marked dirty
1358 blk
->status
&= ~BlkDirty
;
1361 pkt
->setDataFromBlock(blk
->data
, blkSize
);
1367 BaseCache::writecleanBlk(CacheBlk
*blk
, Request::Flags dest
, PacketId id
)
1369 RequestPtr req
= std::make_shared
<Request
>(
1370 regenerateBlkAddr(blk
), blkSize
, 0, Request::wbMasterId
);
1372 if (blk
->isSecure()) {
1373 req
->setFlags(Request::SECURE
);
1375 req
->taskId(blk
->task_id
);
1377 PacketPtr pkt
= new Packet(req
, MemCmd::WriteClean
, blkSize
, id
);
1380 req
->setFlags(dest
);
1381 pkt
->setWriteThrough();
1384 DPRINTF(Cache
, "Create %s writable: %d, dirty: %d\n", pkt
->print(),
1385 blk
->isWritable(), blk
->isDirty());
1387 if (blk
->isWritable()) {
1388 // not asserting shared means we pass the block in modified
1389 // state, mark our own block non-writeable
1390 blk
->status
&= ~BlkWritable
;
1392 // we are in the Owned state, tell the receiver
1393 pkt
->setHasSharers();
1396 // make sure the block is not marked dirty
1397 blk
->status
&= ~BlkDirty
;
1400 pkt
->setDataFromBlock(blk
->data
, blkSize
);
1407 BaseCache::memWriteback()
1409 tags
->forEachBlk([this](CacheBlk
&blk
) { writebackVisitor(blk
); });
1413 BaseCache::memInvalidate()
1415 tags
->forEachBlk([this](CacheBlk
&blk
) { invalidateVisitor(blk
); });
1419 BaseCache::isDirty() const
1421 return tags
->anyBlk([](CacheBlk
&blk
) { return blk
.isDirty(); });
1425 BaseCache::coalesce() const
1427 return writeAllocator
&& writeAllocator
->coalesce();
1431 BaseCache::writebackVisitor(CacheBlk
&blk
)
1433 if (blk
.isDirty()) {
1434 assert(blk
.isValid());
1436 RequestPtr request
= std::make_shared
<Request
>(
1437 regenerateBlkAddr(&blk
), blkSize
, 0, Request::funcMasterId
);
1439 request
->taskId(blk
.task_id
);
1440 if (blk
.isSecure()) {
1441 request
->setFlags(Request::SECURE
);
1444 Packet
packet(request
, MemCmd::WriteReq
);
1445 packet
.dataStatic(blk
.data
);
1447 memSidePort
.sendFunctional(&packet
);
1449 blk
.status
&= ~BlkDirty
;
1454 BaseCache::invalidateVisitor(CacheBlk
&blk
)
1457 warn_once("Invalidating dirty cache lines. " \
1458 "Expect things to break.\n");
1460 if (blk
.isValid()) {
1461 assert(!blk
.isDirty());
1462 invalidateBlock(&blk
);
1467 BaseCache::nextQueueReadyTime() const
1469 Tick nextReady
= std::min(mshrQueue
.nextReadyTime(),
1470 writeBuffer
.nextReadyTime());
1472 // Don't signal prefetch ready time if no MSHRs available
1473 // Will signal once enoguh MSHRs are deallocated
1474 if (prefetcher
&& mshrQueue
.canPrefetch()) {
1475 nextReady
= std::min(nextReady
,
1476 prefetcher
->nextPrefetchReadyTime());
1484 BaseCache::sendMSHRQueuePacket(MSHR
* mshr
)
1488 // use request from 1st target
1489 PacketPtr tgt_pkt
= mshr
->getTarget()->pkt
;
1491 DPRINTF(Cache
, "%s: MSHR %s\n", __func__
, tgt_pkt
->print());
1493 // if the cache is in write coalescing mode or (additionally) in
1494 // no allocation mode, and we have a write packet with an MSHR
1495 // that is not a whole-line write (due to incompatible flags etc),
1496 // then reset the write mode
1497 if (writeAllocator
&& writeAllocator
->coalesce() && tgt_pkt
->isWrite()) {
1498 if (!mshr
->isWholeLineWrite()) {
1499 // if we are currently write coalescing, hold on the
1500 // MSHR as many cycles extra as we need to completely
1501 // write a cache line
1502 if (writeAllocator
->delay(mshr
->blkAddr
)) {
1503 Tick delay
= blkSize
/ tgt_pkt
->getSize() * clockPeriod();
1504 DPRINTF(CacheVerbose
, "Delaying pkt %s %llu ticks to allow "
1505 "for write coalescing\n", tgt_pkt
->print(), delay
);
1506 mshrQueue
.delay(mshr
, delay
);
1509 writeAllocator
->reset();
1512 writeAllocator
->resetDelay(mshr
->blkAddr
);
1516 CacheBlk
*blk
= tags
->findBlock(mshr
->blkAddr
, mshr
->isSecure
);
1518 // either a prefetch that is not present upstream, or a normal
1519 // MSHR request, proceed to get the packet to send downstream
1520 PacketPtr pkt
= createMissPacket(tgt_pkt
, blk
, mshr
->needsWritable(),
1521 mshr
->isWholeLineWrite());
1523 mshr
->isForward
= (pkt
== nullptr);
1525 if (mshr
->isForward
) {
1526 // not a cache block request, but a response is expected
1527 // make copy of current packet to forward, keep current
1528 // copy for response handling
1529 pkt
= new Packet(tgt_pkt
, false, true);
1530 assert(!pkt
->isWrite());
1533 // play it safe and append (rather than set) the sender state,
1534 // as forwarded packets may already have existing state
1535 pkt
->pushSenderState(mshr
);
1537 if (pkt
->isClean() && blk
&& blk
->isDirty()) {
1538 // A cache clean opearation is looking for a dirty block. Mark
1539 // the packet so that the destination xbar can determine that
1540 // there will be a follow-up write packet as well.
1541 pkt
->setSatisfied();
1544 if (!memSidePort
.sendTimingReq(pkt
)) {
1545 // we are awaiting a retry, but we
1546 // delete the packet and will be creating a new packet
1547 // when we get the opportunity
1550 // note that we have now masked any requestBus and
1551 // schedSendEvent (we will wait for a retry before
1552 // doing anything), and this is so even if we do not
1553 // care about this packet and might override it before
1557 // As part of the call to sendTimingReq the packet is
1558 // forwarded to all neighbouring caches (and any caches
1559 // above them) as a snoop. Thus at this point we know if
1560 // any of the neighbouring caches are responding, and if
1561 // so, we know it is dirty, and we can determine if it is
1562 // being passed as Modified, making our MSHR the ordering
1564 bool pending_modified_resp
= !pkt
->hasSharers() &&
1565 pkt
->cacheResponding();
1566 markInService(mshr
, pending_modified_resp
);
1568 if (pkt
->isClean() && blk
&& blk
->isDirty()) {
1569 // A cache clean opearation is looking for a dirty
1570 // block. If a dirty block is encountered a WriteClean
1571 // will update any copies to the path to the memory
1572 // until the point of reference.
1573 DPRINTF(CacheVerbose
, "%s: packet %s found block: %s\n",
1574 __func__
, pkt
->print(), blk
->print());
1575 PacketPtr wb_pkt
= writecleanBlk(blk
, pkt
->req
->getDest(),
1577 PacketList writebacks
;
1578 writebacks
.push_back(wb_pkt
);
1579 doWritebacks(writebacks
, 0);
1587 BaseCache::sendWriteQueuePacket(WriteQueueEntry
* wq_entry
)
1591 // always a single target for write queue entries
1592 PacketPtr tgt_pkt
= wq_entry
->getTarget()->pkt
;
1594 DPRINTF(Cache
, "%s: write %s\n", __func__
, tgt_pkt
->print());
1596 // forward as is, both for evictions and uncacheable writes
1597 if (!memSidePort
.sendTimingReq(tgt_pkt
)) {
1598 // note that we have now masked any requestBus and
1599 // schedSendEvent (we will wait for a retry before
1600 // doing anything), and this is so even if we do not
1601 // care about this packet and might override it before
1605 markInService(wq_entry
);
1611 BaseCache::serialize(CheckpointOut
&cp
) const
1613 bool dirty(isDirty());
1616 warn("*** The cache still contains dirty data. ***\n");
1617 warn(" Make sure to drain the system using the correct flags.\n");
1618 warn(" This checkpoint will not restore correctly " \
1619 "and dirty data in the cache will be lost!\n");
1622 // Since we don't checkpoint the data in the cache, any dirty data
1623 // will be lost when restoring from a checkpoint of a system that
1624 // wasn't drained properly. Flag the checkpoint as invalid if the
1625 // cache contains dirty data.
1626 bool bad_checkpoint(dirty
);
1627 SERIALIZE_SCALAR(bad_checkpoint
);
1631 BaseCache::unserialize(CheckpointIn
&cp
)
1633 bool bad_checkpoint
;
1634 UNSERIALIZE_SCALAR(bad_checkpoint
);
1635 if (bad_checkpoint
) {
1636 fatal("Restoring from checkpoints with dirty caches is not "
1637 "supported in the classic memory system. Please remove any "
1638 "caches or drain them properly before taking checkpoints.\n");
1643 BaseCache::regStats()
1645 MemObject::regStats();
1647 using namespace Stats
;
1650 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
1651 MemCmd
cmd(access_idx
);
1652 const string
&cstr
= cmd
.toString();
1655 .init(system
->maxMasters())
1656 .name(name() + "." + cstr
+ "_hits")
1657 .desc("number of " + cstr
+ " hits")
1658 .flags(total
| nozero
| nonan
)
1660 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1661 hits
[access_idx
].subname(i
, system
->getMasterName(i
));
1665 // These macros make it easier to sum the right subset of commands and
1666 // to change the subset of commands that are considered "demand" vs
1668 #define SUM_DEMAND(s) \
1669 (s[MemCmd::ReadReq] + s[MemCmd::WriteReq] + s[MemCmd::WriteLineReq] + \
1670 s[MemCmd::ReadExReq] + s[MemCmd::ReadCleanReq] + s[MemCmd::ReadSharedReq])
1672 // should writebacks be included here? prior code was inconsistent...
1673 #define SUM_NON_DEMAND(s) \
1674 (s[MemCmd::SoftPFReq] + s[MemCmd::HardPFReq] + s[MemCmd::SoftPFExReq])
1677 .name(name() + ".demand_hits")
1678 .desc("number of demand (read+write) hits")
1679 .flags(total
| nozero
| nonan
)
1681 demandHits
= SUM_DEMAND(hits
);
1682 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1683 demandHits
.subname(i
, system
->getMasterName(i
));
1687 .name(name() + ".overall_hits")
1688 .desc("number of overall hits")
1689 .flags(total
| nozero
| nonan
)
1691 overallHits
= demandHits
+ SUM_NON_DEMAND(hits
);
1692 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1693 overallHits
.subname(i
, system
->getMasterName(i
));
1697 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
1698 MemCmd
cmd(access_idx
);
1699 const string
&cstr
= cmd
.toString();
1702 .init(system
->maxMasters())
1703 .name(name() + "." + cstr
+ "_misses")
1704 .desc("number of " + cstr
+ " misses")
1705 .flags(total
| nozero
| nonan
)
1707 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1708 misses
[access_idx
].subname(i
, system
->getMasterName(i
));
1713 .name(name() + ".demand_misses")
1714 .desc("number of demand (read+write) misses")
1715 .flags(total
| nozero
| nonan
)
1717 demandMisses
= SUM_DEMAND(misses
);
1718 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1719 demandMisses
.subname(i
, system
->getMasterName(i
));
1723 .name(name() + ".overall_misses")
1724 .desc("number of overall misses")
1725 .flags(total
| nozero
| nonan
)
1727 overallMisses
= demandMisses
+ SUM_NON_DEMAND(misses
);
1728 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1729 overallMisses
.subname(i
, system
->getMasterName(i
));
1732 // Miss latency statistics
1733 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
1734 MemCmd
cmd(access_idx
);
1735 const string
&cstr
= cmd
.toString();
1737 missLatency
[access_idx
]
1738 .init(system
->maxMasters())
1739 .name(name() + "." + cstr
+ "_miss_latency")
1740 .desc("number of " + cstr
+ " miss cycles")
1741 .flags(total
| nozero
| nonan
)
1743 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1744 missLatency
[access_idx
].subname(i
, system
->getMasterName(i
));
1749 .name(name() + ".demand_miss_latency")
1750 .desc("number of demand (read+write) miss cycles")
1751 .flags(total
| nozero
| nonan
)
1753 demandMissLatency
= SUM_DEMAND(missLatency
);
1754 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1755 demandMissLatency
.subname(i
, system
->getMasterName(i
));
1759 .name(name() + ".overall_miss_latency")
1760 .desc("number of overall miss cycles")
1761 .flags(total
| nozero
| nonan
)
1763 overallMissLatency
= demandMissLatency
+ SUM_NON_DEMAND(missLatency
);
1764 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1765 overallMissLatency
.subname(i
, system
->getMasterName(i
));
1769 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
1770 MemCmd
cmd(access_idx
);
1771 const string
&cstr
= cmd
.toString();
1773 accesses
[access_idx
]
1774 .name(name() + "." + cstr
+ "_accesses")
1775 .desc("number of " + cstr
+ " accesses(hits+misses)")
1776 .flags(total
| nozero
| nonan
)
1778 accesses
[access_idx
] = hits
[access_idx
] + misses
[access_idx
];
1780 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1781 accesses
[access_idx
].subname(i
, system
->getMasterName(i
));
1786 .name(name() + ".demand_accesses")
1787 .desc("number of demand (read+write) accesses")
1788 .flags(total
| nozero
| nonan
)
1790 demandAccesses
= demandHits
+ demandMisses
;
1791 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1792 demandAccesses
.subname(i
, system
->getMasterName(i
));
1796 .name(name() + ".overall_accesses")
1797 .desc("number of overall (read+write) accesses")
1798 .flags(total
| nozero
| nonan
)
1800 overallAccesses
= overallHits
+ overallMisses
;
1801 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1802 overallAccesses
.subname(i
, system
->getMasterName(i
));
1805 // miss rate formulas
1806 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
1807 MemCmd
cmd(access_idx
);
1808 const string
&cstr
= cmd
.toString();
1810 missRate
[access_idx
]
1811 .name(name() + "." + cstr
+ "_miss_rate")
1812 .desc("miss rate for " + cstr
+ " accesses")
1813 .flags(total
| nozero
| nonan
)
1815 missRate
[access_idx
] = misses
[access_idx
] / accesses
[access_idx
];
1817 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1818 missRate
[access_idx
].subname(i
, system
->getMasterName(i
));
1823 .name(name() + ".demand_miss_rate")
1824 .desc("miss rate for demand accesses")
1825 .flags(total
| nozero
| nonan
)
1827 demandMissRate
= demandMisses
/ demandAccesses
;
1828 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1829 demandMissRate
.subname(i
, system
->getMasterName(i
));
1833 .name(name() + ".overall_miss_rate")
1834 .desc("miss rate for overall accesses")
1835 .flags(total
| nozero
| nonan
)
1837 overallMissRate
= overallMisses
/ overallAccesses
;
1838 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1839 overallMissRate
.subname(i
, system
->getMasterName(i
));
1842 // miss latency formulas
1843 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
1844 MemCmd
cmd(access_idx
);
1845 const string
&cstr
= cmd
.toString();
1847 avgMissLatency
[access_idx
]
1848 .name(name() + "." + cstr
+ "_avg_miss_latency")
1849 .desc("average " + cstr
+ " miss latency")
1850 .flags(total
| nozero
| nonan
)
1852 avgMissLatency
[access_idx
] =
1853 missLatency
[access_idx
] / misses
[access_idx
];
1855 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1856 avgMissLatency
[access_idx
].subname(i
, system
->getMasterName(i
));
1860 demandAvgMissLatency
1861 .name(name() + ".demand_avg_miss_latency")
1862 .desc("average overall miss latency")
1863 .flags(total
| nozero
| nonan
)
1865 demandAvgMissLatency
= demandMissLatency
/ demandMisses
;
1866 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1867 demandAvgMissLatency
.subname(i
, system
->getMasterName(i
));
1870 overallAvgMissLatency
1871 .name(name() + ".overall_avg_miss_latency")
1872 .desc("average overall miss latency")
1873 .flags(total
| nozero
| nonan
)
1875 overallAvgMissLatency
= overallMissLatency
/ overallMisses
;
1876 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1877 overallAvgMissLatency
.subname(i
, system
->getMasterName(i
));
1880 blocked_cycles
.init(NUM_BLOCKED_CAUSES
);
1882 .name(name() + ".blocked_cycles")
1883 .desc("number of cycles access was blocked")
1884 .subname(Blocked_NoMSHRs
, "no_mshrs")
1885 .subname(Blocked_NoTargets
, "no_targets")
1889 blocked_causes
.init(NUM_BLOCKED_CAUSES
);
1891 .name(name() + ".blocked")
1892 .desc("number of cycles access was blocked")
1893 .subname(Blocked_NoMSHRs
, "no_mshrs")
1894 .subname(Blocked_NoTargets
, "no_targets")
1898 .name(name() + ".avg_blocked_cycles")
1899 .desc("average number of cycles each access was blocked")
1900 .subname(Blocked_NoMSHRs
, "no_mshrs")
1901 .subname(Blocked_NoTargets
, "no_targets")
1904 avg_blocked
= blocked_cycles
/ blocked_causes
;
1907 .name(name() + ".unused_prefetches")
1908 .desc("number of HardPF blocks evicted w/o reference")
1913 .init(system
->maxMasters())
1914 .name(name() + ".writebacks")
1915 .desc("number of writebacks")
1916 .flags(total
| nozero
| nonan
)
1918 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1919 writebacks
.subname(i
, system
->getMasterName(i
));
1923 // MSHR hit statistics
1924 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
1925 MemCmd
cmd(access_idx
);
1926 const string
&cstr
= cmd
.toString();
1928 mshr_hits
[access_idx
]
1929 .init(system
->maxMasters())
1930 .name(name() + "." + cstr
+ "_mshr_hits")
1931 .desc("number of " + cstr
+ " MSHR hits")
1932 .flags(total
| nozero
| nonan
)
1934 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1935 mshr_hits
[access_idx
].subname(i
, system
->getMasterName(i
));
1940 .name(name() + ".demand_mshr_hits")
1941 .desc("number of demand (read+write) MSHR hits")
1942 .flags(total
| nozero
| nonan
)
1944 demandMshrHits
= SUM_DEMAND(mshr_hits
);
1945 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1946 demandMshrHits
.subname(i
, system
->getMasterName(i
));
1950 .name(name() + ".overall_mshr_hits")
1951 .desc("number of overall MSHR hits")
1952 .flags(total
| nozero
| nonan
)
1954 overallMshrHits
= demandMshrHits
+ SUM_NON_DEMAND(mshr_hits
);
1955 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1956 overallMshrHits
.subname(i
, system
->getMasterName(i
));
1959 // MSHR miss statistics
1960 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
1961 MemCmd
cmd(access_idx
);
1962 const string
&cstr
= cmd
.toString();
1964 mshr_misses
[access_idx
]
1965 .init(system
->maxMasters())
1966 .name(name() + "." + cstr
+ "_mshr_misses")
1967 .desc("number of " + cstr
+ " MSHR misses")
1968 .flags(total
| nozero
| nonan
)
1970 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1971 mshr_misses
[access_idx
].subname(i
, system
->getMasterName(i
));
1976 .name(name() + ".demand_mshr_misses")
1977 .desc("number of demand (read+write) MSHR misses")
1978 .flags(total
| nozero
| nonan
)
1980 demandMshrMisses
= SUM_DEMAND(mshr_misses
);
1981 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1982 demandMshrMisses
.subname(i
, system
->getMasterName(i
));
1986 .name(name() + ".overall_mshr_misses")
1987 .desc("number of overall MSHR misses")
1988 .flags(total
| nozero
| nonan
)
1990 overallMshrMisses
= demandMshrMisses
+ SUM_NON_DEMAND(mshr_misses
);
1991 for (int i
= 0; i
< system
->maxMasters(); i
++) {
1992 overallMshrMisses
.subname(i
, system
->getMasterName(i
));
1995 // MSHR miss latency statistics
1996 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
1997 MemCmd
cmd(access_idx
);
1998 const string
&cstr
= cmd
.toString();
2000 mshr_miss_latency
[access_idx
]
2001 .init(system
->maxMasters())
2002 .name(name() + "." + cstr
+ "_mshr_miss_latency")
2003 .desc("number of " + cstr
+ " MSHR miss cycles")
2004 .flags(total
| nozero
| nonan
)
2006 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2007 mshr_miss_latency
[access_idx
].subname(i
, system
->getMasterName(i
));
2011 demandMshrMissLatency
2012 .name(name() + ".demand_mshr_miss_latency")
2013 .desc("number of demand (read+write) MSHR miss cycles")
2014 .flags(total
| nozero
| nonan
)
2016 demandMshrMissLatency
= SUM_DEMAND(mshr_miss_latency
);
2017 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2018 demandMshrMissLatency
.subname(i
, system
->getMasterName(i
));
2021 overallMshrMissLatency
2022 .name(name() + ".overall_mshr_miss_latency")
2023 .desc("number of overall MSHR miss cycles")
2024 .flags(total
| nozero
| nonan
)
2026 overallMshrMissLatency
=
2027 demandMshrMissLatency
+ SUM_NON_DEMAND(mshr_miss_latency
);
2028 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2029 overallMshrMissLatency
.subname(i
, system
->getMasterName(i
));
2032 // MSHR uncacheable statistics
2033 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
2034 MemCmd
cmd(access_idx
);
2035 const string
&cstr
= cmd
.toString();
2037 mshr_uncacheable
[access_idx
]
2038 .init(system
->maxMasters())
2039 .name(name() + "." + cstr
+ "_mshr_uncacheable")
2040 .desc("number of " + cstr
+ " MSHR uncacheable")
2041 .flags(total
| nozero
| nonan
)
2043 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2044 mshr_uncacheable
[access_idx
].subname(i
, system
->getMasterName(i
));
2048 overallMshrUncacheable
2049 .name(name() + ".overall_mshr_uncacheable_misses")
2050 .desc("number of overall MSHR uncacheable misses")
2051 .flags(total
| nozero
| nonan
)
2053 overallMshrUncacheable
=
2054 SUM_DEMAND(mshr_uncacheable
) + SUM_NON_DEMAND(mshr_uncacheable
);
2055 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2056 overallMshrUncacheable
.subname(i
, system
->getMasterName(i
));
2059 // MSHR miss latency statistics
2060 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
2061 MemCmd
cmd(access_idx
);
2062 const string
&cstr
= cmd
.toString();
2064 mshr_uncacheable_lat
[access_idx
]
2065 .init(system
->maxMasters())
2066 .name(name() + "." + cstr
+ "_mshr_uncacheable_latency")
2067 .desc("number of " + cstr
+ " MSHR uncacheable cycles")
2068 .flags(total
| nozero
| nonan
)
2070 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2071 mshr_uncacheable_lat
[access_idx
].subname(
2072 i
, system
->getMasterName(i
));
2076 overallMshrUncacheableLatency
2077 .name(name() + ".overall_mshr_uncacheable_latency")
2078 .desc("number of overall MSHR uncacheable cycles")
2079 .flags(total
| nozero
| nonan
)
2081 overallMshrUncacheableLatency
=
2082 SUM_DEMAND(mshr_uncacheable_lat
) +
2083 SUM_NON_DEMAND(mshr_uncacheable_lat
);
2084 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2085 overallMshrUncacheableLatency
.subname(i
, system
->getMasterName(i
));
2089 // MSHR access formulas
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 mshrAccesses
[access_idx
]
2095 .name(name() + "." + cstr
+ "_mshr_accesses")
2096 .desc("number of " + cstr
+ " mshr accesses(hits+misses)")
2097 .flags(total
| nozero
| nonan
)
2099 mshrAccesses
[access_idx
] =
2100 mshr_hits
[access_idx
] + mshr_misses
[access_idx
]
2101 + mshr_uncacheable
[access_idx
];
2105 .name(name() + ".demand_mshr_accesses")
2106 .desc("number of demand (read+write) mshr accesses")
2107 .flags(total
| nozero
| nonan
)
2109 demandMshrAccesses
= demandMshrHits
+ demandMshrMisses
;
2112 .name(name() + ".overall_mshr_accesses")
2113 .desc("number of overall (read+write) mshr accesses")
2114 .flags(total
| nozero
| nonan
)
2116 overallMshrAccesses
= overallMshrHits
+ overallMshrMisses
2117 + overallMshrUncacheable
;
2120 // MSHR miss rate formulas
2121 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
2122 MemCmd
cmd(access_idx
);
2123 const string
&cstr
= cmd
.toString();
2125 mshrMissRate
[access_idx
]
2126 .name(name() + "." + cstr
+ "_mshr_miss_rate")
2127 .desc("mshr miss rate for " + cstr
+ " accesses")
2128 .flags(total
| nozero
| nonan
)
2130 mshrMissRate
[access_idx
] =
2131 mshr_misses
[access_idx
] / accesses
[access_idx
];
2133 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2134 mshrMissRate
[access_idx
].subname(i
, system
->getMasterName(i
));
2139 .name(name() + ".demand_mshr_miss_rate")
2140 .desc("mshr miss rate for demand accesses")
2141 .flags(total
| nozero
| nonan
)
2143 demandMshrMissRate
= demandMshrMisses
/ demandAccesses
;
2144 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2145 demandMshrMissRate
.subname(i
, system
->getMasterName(i
));
2149 .name(name() + ".overall_mshr_miss_rate")
2150 .desc("mshr miss rate for overall accesses")
2151 .flags(total
| nozero
| nonan
)
2153 overallMshrMissRate
= overallMshrMisses
/ overallAccesses
;
2154 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2155 overallMshrMissRate
.subname(i
, system
->getMasterName(i
));
2158 // mshrMiss latency formulas
2159 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
2160 MemCmd
cmd(access_idx
);
2161 const string
&cstr
= cmd
.toString();
2163 avgMshrMissLatency
[access_idx
]
2164 .name(name() + "." + cstr
+ "_avg_mshr_miss_latency")
2165 .desc("average " + cstr
+ " mshr miss latency")
2166 .flags(total
| nozero
| nonan
)
2168 avgMshrMissLatency
[access_idx
] =
2169 mshr_miss_latency
[access_idx
] / mshr_misses
[access_idx
];
2171 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2172 avgMshrMissLatency
[access_idx
].subname(
2173 i
, system
->getMasterName(i
));
2177 demandAvgMshrMissLatency
2178 .name(name() + ".demand_avg_mshr_miss_latency")
2179 .desc("average overall mshr miss latency")
2180 .flags(total
| nozero
| nonan
)
2182 demandAvgMshrMissLatency
= demandMshrMissLatency
/ demandMshrMisses
;
2183 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2184 demandAvgMshrMissLatency
.subname(i
, system
->getMasterName(i
));
2187 overallAvgMshrMissLatency
2188 .name(name() + ".overall_avg_mshr_miss_latency")
2189 .desc("average overall mshr miss latency")
2190 .flags(total
| nozero
| nonan
)
2192 overallAvgMshrMissLatency
= overallMshrMissLatency
/ overallMshrMisses
;
2193 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2194 overallAvgMshrMissLatency
.subname(i
, system
->getMasterName(i
));
2197 // mshrUncacheable latency formulas
2198 for (int access_idx
= 0; access_idx
< MemCmd::NUM_MEM_CMDS
; ++access_idx
) {
2199 MemCmd
cmd(access_idx
);
2200 const string
&cstr
= cmd
.toString();
2202 avgMshrUncacheableLatency
[access_idx
]
2203 .name(name() + "." + cstr
+ "_avg_mshr_uncacheable_latency")
2204 .desc("average " + cstr
+ " mshr uncacheable latency")
2205 .flags(total
| nozero
| nonan
)
2207 avgMshrUncacheableLatency
[access_idx
] =
2208 mshr_uncacheable_lat
[access_idx
] / mshr_uncacheable
[access_idx
];
2210 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2211 avgMshrUncacheableLatency
[access_idx
].subname(
2212 i
, system
->getMasterName(i
));
2216 overallAvgMshrUncacheableLatency
2217 .name(name() + ".overall_avg_mshr_uncacheable_latency")
2218 .desc("average overall mshr uncacheable latency")
2219 .flags(total
| nozero
| nonan
)
2221 overallAvgMshrUncacheableLatency
=
2222 overallMshrUncacheableLatency
/ overallMshrUncacheable
;
2223 for (int i
= 0; i
< system
->maxMasters(); i
++) {
2224 overallAvgMshrUncacheableLatency
.subname(i
, system
->getMasterName(i
));
2228 .name(name() + ".replacements")
2229 .desc("number of replacements")
2234 BaseCache::regProbePoints()
2236 ppHit
= new ProbePointArg
<PacketPtr
>(this->getProbeManager(), "Hit");
2237 ppMiss
= new ProbePointArg
<PacketPtr
>(this->getProbeManager(), "Miss");
2238 ppFill
= new ProbePointArg
<PacketPtr
>(this->getProbeManager(), "Fill");
2247 BaseCache::CpuSidePort::recvTimingSnoopResp(PacketPtr pkt
)
2249 // Snoops shouldn't happen when bypassing caches
2250 assert(!cache
->system
->bypassCaches());
2252 assert(pkt
->isResponse());
2254 // Express snoop responses from master to slave, e.g., from L1 to L2
2255 cache
->recvTimingSnoopResp(pkt
);
2261 BaseCache::CpuSidePort::tryTiming(PacketPtr pkt
)
2263 if (cache
->system
->bypassCaches() || pkt
->isExpressSnoop()) {
2264 // always let express snoop packets through even if blocked
2266 } else if (blocked
|| mustSendRetry
) {
2267 // either already committed to send a retry, or blocked
2268 mustSendRetry
= true;
2271 mustSendRetry
= false;
2276 BaseCache::CpuSidePort::recvTimingReq(PacketPtr pkt
)
2278 assert(pkt
->isRequest());
2280 if (cache
->system
->bypassCaches()) {
2281 // Just forward the packet if caches are disabled.
2282 // @todo This should really enqueue the packet rather
2283 bool M5_VAR_USED success
= cache
->memSidePort
.sendTimingReq(pkt
);
2286 } else if (tryTiming(pkt
)) {
2287 cache
->recvTimingReq(pkt
);
2294 BaseCache::CpuSidePort::recvAtomic(PacketPtr pkt
)
2296 if (cache
->system
->bypassCaches()) {
2297 // Forward the request if the system is in cache bypass mode.
2298 return cache
->memSidePort
.sendAtomic(pkt
);
2300 return cache
->recvAtomic(pkt
);
2305 BaseCache::CpuSidePort::recvFunctional(PacketPtr pkt
)
2307 if (cache
->system
->bypassCaches()) {
2308 // The cache should be flushed if we are in cache bypass mode,
2309 // so we don't need to check if we need to update anything.
2310 cache
->memSidePort
.sendFunctional(pkt
);
2314 // functional request
2315 cache
->functionalAccess(pkt
, true);
2319 BaseCache::CpuSidePort::getAddrRanges() const
2321 return cache
->getAddrRanges();
2326 CpuSidePort::CpuSidePort(const std::string
&_name
, BaseCache
*_cache
,
2327 const std::string
&_label
)
2328 : CacheSlavePort(_name
, _cache
, _label
), cache(_cache
)
2338 BaseCache::MemSidePort::recvTimingResp(PacketPtr pkt
)
2340 cache
->recvTimingResp(pkt
);
2344 // Express snooping requests to memside port
2346 BaseCache::MemSidePort::recvTimingSnoopReq(PacketPtr pkt
)
2348 // Snoops shouldn't happen when bypassing caches
2349 assert(!cache
->system
->bypassCaches());
2351 // handle snooping requests
2352 cache
->recvTimingSnoopReq(pkt
);
2356 BaseCache::MemSidePort::recvAtomicSnoop(PacketPtr pkt
)
2358 // Snoops shouldn't happen when bypassing caches
2359 assert(!cache
->system
->bypassCaches());
2361 return cache
->recvAtomicSnoop(pkt
);
2365 BaseCache::MemSidePort::recvFunctionalSnoop(PacketPtr pkt
)
2367 // Snoops shouldn't happen when bypassing caches
2368 assert(!cache
->system
->bypassCaches());
2370 // functional snoop (note that in contrast to atomic we don't have
2371 // a specific functionalSnoop method, as they have the same
2372 // behaviour regardless)
2373 cache
->functionalAccess(pkt
, false);
2377 BaseCache::CacheReqPacketQueue::sendDeferredPacket()
2380 assert(!waitingOnRetry
);
2382 // there should never be any deferred request packets in the
2383 // queue, instead we resly on the cache to provide the packets
2384 // from the MSHR queue or write queue
2385 assert(deferredPacketReadyTime() == MaxTick
);
2387 // check for request packets (requests & writebacks)
2388 QueueEntry
* entry
= cache
.getNextQueueEntry();
2391 // can happen if e.g. we attempt a writeback and fail, but
2392 // before the retry, the writeback is eliminated because
2393 // we snoop another cache's ReadEx.
2395 // let our snoop responses go first if there are responses to
2396 // the same addresses
2397 if (checkConflictingSnoop(entry
->blkAddr
)) {
2400 waitingOnRetry
= entry
->sendPacket(cache
);
2403 // if we succeeded and are not waiting for a retry, schedule the
2404 // next send considering when the next queue is ready, note that
2405 // snoop responses have their own packet queue and thus schedule
2407 if (!waitingOnRetry
) {
2408 schedSendEvent(cache
.nextQueueReadyTime());
2412 BaseCache::MemSidePort::MemSidePort(const std::string
&_name
,
2414 const std::string
&_label
)
2415 : CacheMasterPort(_name
, _cache
, _reqQueue
, _snoopRespQueue
),
2416 _reqQueue(*_cache
, *this, _snoopRespQueue
, _label
),
2417 _snoopRespQueue(*_cache
, *this, true, _label
), cache(_cache
)
2422 WriteAllocator::updateMode(Addr write_addr
, unsigned write_size
,
2425 // check if we are continuing where the last write ended
2426 if (nextAddr
== write_addr
) {
2427 delayCtr
[blk_addr
] = delayThreshold
;
2428 // stop if we have already saturated
2429 if (mode
!= WriteMode::NO_ALLOCATE
) {
2430 byteCount
+= write_size
;
2431 // switch to streaming mode if we have passed the lower
2433 if (mode
== WriteMode::ALLOCATE
&&
2434 byteCount
> coalesceLimit
) {
2435 mode
= WriteMode::COALESCE
;
2436 DPRINTF(Cache
, "Switched to write coalescing\n");
2437 } else if (mode
== WriteMode::COALESCE
&&
2438 byteCount
> noAllocateLimit
) {
2439 // and continue and switch to non-allocating mode if we
2440 // pass the upper threshold
2441 mode
= WriteMode::NO_ALLOCATE
;
2442 DPRINTF(Cache
, "Switched to write-no-allocate\n");
2446 // we did not see a write matching the previous one, start
2448 byteCount
= write_size
;
2449 mode
= WriteMode::ALLOCATE
;
2450 resetDelay(blk_addr
);
2452 nextAddr
= write_addr
+ write_size
;
2456 WriteAllocatorParams::create()
2458 return new WriteAllocator(this);