mem-cache: Add a repeated value pattern to compressors
[gem5.git] / src / mem / cache / base.cc
1 /*
2 * Copyright (c) 2012-2013, 2018-2019 ARM Limited
3 * All rights reserved.
4 *
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.
13 *
14 * Copyright (c) 2003-2005 The Regents of The University of Michigan
15 * All rights reserved.
16 *
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.
27 *
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.
39 *
40 * Authors: Erik Hallnor
41 * Nikos Nikoleris
42 */
43
44 /**
45 * @file
46 * Definition of BaseCache functions.
47 */
48
49 #include "mem/cache/base.hh"
50
51 #include "base/compiler.hh"
52 #include "base/logging.hh"
53 #include "debug/Cache.hh"
54 #include "debug/CacheComp.hh"
55 #include "debug/CachePort.hh"
56 #include "debug/CacheRepl.hh"
57 #include "debug/CacheVerbose.hh"
58 #include "mem/cache/compressors/base.hh"
59 #include "mem/cache/mshr.hh"
60 #include "mem/cache/prefetch/base.hh"
61 #include "mem/cache/queue_entry.hh"
62 #include "mem/cache/tags/super_blk.hh"
63 #include "params/BaseCache.hh"
64 #include "params/WriteAllocator.hh"
65 #include "sim/core.hh"
66
67 using namespace std;
68
69 BaseCache::CacheSlavePort::CacheSlavePort(const std::string &_name,
70 BaseCache *_cache,
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)
76 {
77 }
78
79 BaseCache::BaseCache(const BaseCacheParams *p, unsigned blk_size)
80 : ClockedObject(p),
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
85 tags(p->tags),
86 compressor(p->compressor),
87 prefetcher(p->prefetcher),
88 writeAllocator(p->write_allocator),
89 writebackClean(p->writeback_clean),
90 tempBlockWriteback(nullptr),
91 writebackTempBlockAtomicEvent([this]{ writebackTempBlockAtomic(); },
92 name(), false,
93 EventBase::Delayed_Writeback_Pri),
94 blkSize(blk_size),
95 lookupLatency(p->tag_latency),
96 dataLatency(p->data_latency),
97 forwardLatency(p->tag_latency),
98 fillLatency(p->data_latency),
99 responseLatency(p->response_latency),
100 sequentialAccess(p->sequential_access),
101 numTarget(p->tgts_per_mshr),
102 forwardSnoops(true),
103 clusivity(p->clusivity),
104 isReadOnly(p->is_read_only),
105 blocked(0),
106 order(0),
107 noTargetMSHR(nullptr),
108 missCount(p->max_miss_count),
109 addrRanges(p->addr_ranges.begin(), p->addr_ranges.end()),
110 system(p->system),
111 stats(*this)
112 {
113 // the MSHR queue has no reserve entries as we check the MSHR
114 // queue on every single allocation, whereas the write queue has
115 // as many reserve entries as we have MSHRs, since every MSHR may
116 // eventually require a writeback, and we do not check the write
117 // buffer before committing to an MSHR
118
119 // forward snoops is overridden in init() once we can query
120 // whether the connected master is actually snooping or not
121
122 tempBlock = new TempCacheBlk(blkSize);
123
124 tags->tagsInit();
125 if (prefetcher)
126 prefetcher->setCache(this);
127 }
128
129 BaseCache::~BaseCache()
130 {
131 delete tempBlock;
132 }
133
134 void
135 BaseCache::CacheSlavePort::setBlocked()
136 {
137 assert(!blocked);
138 DPRINTF(CachePort, "Port is blocking new requests\n");
139 blocked = true;
140 // if we already scheduled a retry in this cycle, but it has not yet
141 // happened, cancel it
142 if (sendRetryEvent.scheduled()) {
143 owner.deschedule(sendRetryEvent);
144 DPRINTF(CachePort, "Port descheduled retry\n");
145 mustSendRetry = true;
146 }
147 }
148
149 void
150 BaseCache::CacheSlavePort::clearBlocked()
151 {
152 assert(blocked);
153 DPRINTF(CachePort, "Port is accepting new requests\n");
154 blocked = false;
155 if (mustSendRetry) {
156 // @TODO: need to find a better time (next cycle?)
157 owner.schedule(sendRetryEvent, curTick() + 1);
158 }
159 }
160
161 void
162 BaseCache::CacheSlavePort::processSendRetry()
163 {
164 DPRINTF(CachePort, "Port is sending retry\n");
165
166 // reset the flag and call retry
167 mustSendRetry = false;
168 sendRetryReq();
169 }
170
171 Addr
172 BaseCache::regenerateBlkAddr(CacheBlk* blk)
173 {
174 if (blk != tempBlock) {
175 return tags->regenerateBlkAddr(blk);
176 } else {
177 return tempBlock->getAddr();
178 }
179 }
180
181 void
182 BaseCache::init()
183 {
184 if (!cpuSidePort.isConnected() || !memSidePort.isConnected())
185 fatal("Cache ports on %s are not connected\n", name());
186 cpuSidePort.sendRangeChange();
187 forwardSnoops = cpuSidePort.isSnooping();
188 }
189
190 Port &
191 BaseCache::getPort(const std::string &if_name, PortID idx)
192 {
193 if (if_name == "mem_side") {
194 return memSidePort;
195 } else if (if_name == "cpu_side") {
196 return cpuSidePort;
197 } else {
198 return ClockedObject::getPort(if_name, idx);
199 }
200 }
201
202 bool
203 BaseCache::inRange(Addr addr) const
204 {
205 for (const auto& r : addrRanges) {
206 if (r.contains(addr)) {
207 return true;
208 }
209 }
210 return false;
211 }
212
213 void
214 BaseCache::handleTimingReqHit(PacketPtr pkt, CacheBlk *blk, Tick request_time)
215 {
216 if (pkt->needsResponse()) {
217 // These delays should have been consumed by now
218 assert(pkt->headerDelay == 0);
219 assert(pkt->payloadDelay == 0);
220
221 pkt->makeTimingResponse();
222
223 // In this case we are considering request_time that takes
224 // into account the delay of the xbar, if any, and just
225 // lat, neglecting responseLatency, modelling hit latency
226 // just as the value of lat overriden by access(), which calls
227 // the calculateAccessLatency() function.
228 cpuSidePort.schedTimingResp(pkt, request_time);
229 } else {
230 DPRINTF(Cache, "%s satisfied %s, no response needed\n", __func__,
231 pkt->print());
232
233 // queue the packet for deletion, as the sending cache is
234 // still relying on it; if the block is found in access(),
235 // CleanEvict and Writeback messages will be deleted
236 // here as well
237 pendingDelete.reset(pkt);
238 }
239 }
240
241 void
242 BaseCache::handleTimingReqMiss(PacketPtr pkt, MSHR *mshr, CacheBlk *blk,
243 Tick forward_time, Tick request_time)
244 {
245 if (writeAllocator &&
246 pkt && pkt->isWrite() && !pkt->req->isUncacheable()) {
247 writeAllocator->updateMode(pkt->getAddr(), pkt->getSize(),
248 pkt->getBlockAddr(blkSize));
249 }
250
251 if (mshr) {
252 /// MSHR hit
253 /// @note writebacks will be checked in getNextMSHR()
254 /// for any conflicting requests to the same block
255
256 //@todo remove hw_pf here
257
258 // Coalesce unless it was a software prefetch (see above).
259 if (pkt) {
260 assert(!pkt->isWriteback());
261 // CleanEvicts corresponding to blocks which have
262 // outstanding requests in MSHRs are simply sunk here
263 if (pkt->cmd == MemCmd::CleanEvict) {
264 pendingDelete.reset(pkt);
265 } else if (pkt->cmd == MemCmd::WriteClean) {
266 // A WriteClean should never coalesce with any
267 // outstanding cache maintenance requests.
268
269 // We use forward_time here because there is an
270 // uncached memory write, forwarded to WriteBuffer.
271 allocateWriteBuffer(pkt, forward_time);
272 } else {
273 DPRINTF(Cache, "%s coalescing MSHR for %s\n", __func__,
274 pkt->print());
275
276 assert(pkt->req->masterId() < system->maxMasters());
277 stats.cmdStats(pkt).mshr_hits[pkt->req->masterId()]++;
278
279 // We use forward_time here because it is the same
280 // considering new targets. We have multiple
281 // requests for the same address here. It
282 // specifies the latency to allocate an internal
283 // buffer and to schedule an event to the queued
284 // port and also takes into account the additional
285 // delay of the xbar.
286 mshr->allocateTarget(pkt, forward_time, order++,
287 allocOnFill(pkt->cmd));
288 if (mshr->getNumTargets() == numTarget) {
289 noTargetMSHR = mshr;
290 setBlocked(Blocked_NoTargets);
291 // need to be careful with this... if this mshr isn't
292 // ready yet (i.e. time > curTick()), we don't want to
293 // move it ahead of mshrs that are ready
294 // mshrQueue.moveToFront(mshr);
295 }
296 }
297 }
298 } else {
299 // no MSHR
300 assert(pkt->req->masterId() < system->maxMasters());
301 stats.cmdStats(pkt).mshr_misses[pkt->req->masterId()]++;
302
303 if (pkt->isEviction() || pkt->cmd == MemCmd::WriteClean) {
304 // We use forward_time here because there is an
305 // writeback or writeclean, forwarded to WriteBuffer.
306 allocateWriteBuffer(pkt, forward_time);
307 } else {
308 if (blk && blk->isValid()) {
309 // If we have a write miss to a valid block, we
310 // need to mark the block non-readable. Otherwise
311 // if we allow reads while there's an outstanding
312 // write miss, the read could return stale data
313 // out of the cache block... a more aggressive
314 // system could detect the overlap (if any) and
315 // forward data out of the MSHRs, but we don't do
316 // that yet. Note that we do need to leave the
317 // block valid so that it stays in the cache, in
318 // case we get an upgrade response (and hence no
319 // new data) when the write miss completes.
320 // As long as CPUs do proper store/load forwarding
321 // internally, and have a sufficiently weak memory
322 // model, this is probably unnecessary, but at some
323 // point it must have seemed like we needed it...
324 assert((pkt->needsWritable() && !blk->isWritable()) ||
325 pkt->req->isCacheMaintenance());
326 blk->status &= ~BlkReadable;
327 }
328 // Here we are using forward_time, modelling the latency of
329 // a miss (outbound) just as forwardLatency, neglecting the
330 // lookupLatency component.
331 allocateMissBuffer(pkt, forward_time);
332 }
333 }
334 }
335
336 void
337 BaseCache::recvTimingReq(PacketPtr pkt)
338 {
339 // anything that is merely forwarded pays for the forward latency and
340 // the delay provided by the crossbar
341 Tick forward_time = clockEdge(forwardLatency) + pkt->headerDelay;
342
343 Cycles lat;
344 CacheBlk *blk = nullptr;
345 bool satisfied = false;
346 {
347 PacketList writebacks;
348 // Note that lat is passed by reference here. The function
349 // access() will set the lat value.
350 satisfied = access(pkt, blk, lat, writebacks);
351
352 // After the evicted blocks are selected, they must be forwarded
353 // to the write buffer to ensure they logically precede anything
354 // happening below
355 doWritebacks(writebacks, clockEdge(lat + forwardLatency));
356 }
357
358 // Here we charge the headerDelay that takes into account the latencies
359 // of the bus, if the packet comes from it.
360 // The latency charged is just the value set by the access() function.
361 // In case of a hit we are neglecting response latency.
362 // In case of a miss we are neglecting forward latency.
363 Tick request_time = clockEdge(lat);
364 // Here we reset the timing of the packet.
365 pkt->headerDelay = pkt->payloadDelay = 0;
366
367 if (satisfied) {
368 // notify before anything else as later handleTimingReqHit might turn
369 // the packet in a response
370 ppHit->notify(pkt);
371
372 if (prefetcher && blk && blk->wasPrefetched()) {
373 blk->status &= ~BlkHWPrefetched;
374 }
375
376 handleTimingReqHit(pkt, blk, request_time);
377 } else {
378 handleTimingReqMiss(pkt, blk, forward_time, request_time);
379
380 ppMiss->notify(pkt);
381 }
382
383 if (prefetcher) {
384 // track time of availability of next prefetch, if any
385 Tick next_pf_time = prefetcher->nextPrefetchReadyTime();
386 if (next_pf_time != MaxTick) {
387 schedMemSideSendEvent(next_pf_time);
388 }
389 }
390 }
391
392 void
393 BaseCache::handleUncacheableWriteResp(PacketPtr pkt)
394 {
395 Tick completion_time = clockEdge(responseLatency) +
396 pkt->headerDelay + pkt->payloadDelay;
397
398 // Reset the bus additional time as it is now accounted for
399 pkt->headerDelay = pkt->payloadDelay = 0;
400
401 cpuSidePort.schedTimingResp(pkt, completion_time);
402 }
403
404 void
405 BaseCache::recvTimingResp(PacketPtr pkt)
406 {
407 assert(pkt->isResponse());
408
409 // all header delay should be paid for by the crossbar, unless
410 // this is a prefetch response from above
411 panic_if(pkt->headerDelay != 0 && pkt->cmd != MemCmd::HardPFResp,
412 "%s saw a non-zero packet delay\n", name());
413
414 const bool is_error = pkt->isError();
415
416 if (is_error) {
417 DPRINTF(Cache, "%s: Cache received %s with error\n", __func__,
418 pkt->print());
419 }
420
421 DPRINTF(Cache, "%s: Handling response %s\n", __func__,
422 pkt->print());
423
424 // if this is a write, we should be looking at an uncacheable
425 // write
426 if (pkt->isWrite()) {
427 assert(pkt->req->isUncacheable());
428 handleUncacheableWriteResp(pkt);
429 return;
430 }
431
432 // we have dealt with any (uncacheable) writes above, from here on
433 // we know we are dealing with an MSHR due to a miss or a prefetch
434 MSHR *mshr = dynamic_cast<MSHR*>(pkt->popSenderState());
435 assert(mshr);
436
437 if (mshr == noTargetMSHR) {
438 // we always clear at least one target
439 clearBlocked(Blocked_NoTargets);
440 noTargetMSHR = nullptr;
441 }
442
443 // Initial target is used just for stats
444 const QueueEntry::Target *initial_tgt = mshr->getTarget();
445 const Tick miss_latency = curTick() - initial_tgt->recvTime;
446 if (pkt->req->isUncacheable()) {
447 assert(pkt->req->masterId() < system->maxMasters());
448 stats.cmdStats(initial_tgt->pkt)
449 .mshr_uncacheable_lat[pkt->req->masterId()] += miss_latency;
450 } else {
451 assert(pkt->req->masterId() < system->maxMasters());
452 stats.cmdStats(initial_tgt->pkt)
453 .mshr_miss_latency[pkt->req->masterId()] += miss_latency;
454 }
455
456 PacketList writebacks;
457
458 bool is_fill = !mshr->isForward &&
459 (pkt->isRead() || pkt->cmd == MemCmd::UpgradeResp ||
460 mshr->wasWholeLineWrite);
461
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());
465
466 CacheBlk *blk = tags->findBlock(pkt->getAddr(), pkt->isSecure());
467
468 if (is_fill && !is_error) {
469 DPRINTF(Cache, "Block for addr %#llx being updated in Cache\n",
470 pkt->getAddr());
471
472 const bool allocate = (writeAllocator && mshr->wasWholeLineWrite) ?
473 writeAllocator->allocate() : mshr->allocOnFill();
474 blk = handleFill(pkt, blk, writebacks, allocate);
475 assert(blk != nullptr);
476 ppFill->notify(pkt);
477 }
478
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;
483
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();
489 }
490
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();
496 }
497
498 serviceMSHRTargets(mshr, pkt, blk);
499
500 if (mshr->promoteDeferredTargets()) {
501 // avoid later read getting stale data while write miss is
502 // outstanding.. see comment in timingAccess()
503 if (blk) {
504 blk->status &= ~BlkReadable;
505 }
506 mshrQueue.markPending(mshr);
507 schedMemSideSendEvent(clockEdge() + pkt->payloadDelay);
508 } else {
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);
516 }
517
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(),
522 clockEdge());
523 if (next_pf_time != MaxTick)
524 schedMemSideSendEvent(next_pf_time);
525 }
526 }
527
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);
531 }
532
533 const Tick forward_time = clockEdge(forwardLatency) + pkt->headerDelay;
534 // copy writebacks to write buffer
535 doWritebacks(writebacks, forward_time);
536
537 DPRINTF(CacheVerbose, "%s: Leaving with %s\n", __func__, pkt->print());
538 delete pkt;
539 }
540
541
542 Tick
543 BaseCache::recvAtomic(PacketPtr pkt)
544 {
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
548
549 // We use lookupLatency here because it is used to specify the latency
550 // to access.
551 Cycles lat = lookupLatency;
552
553 CacheBlk *blk = nullptr;
554 PacketList writebacks;
555 bool satisfied = access(pkt, blk, lat, writebacks);
556
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);
566 pkt->setSatisfied();
567 }
568
569 // handle writebacks resulting from the access here to ensure they
570 // logically precede anything happening below
571 doWritebacksAtomic(writebacks);
572 assert(writebacks.empty());
573
574 if (!satisfied) {
575 lat += handleAtomicReqMiss(pkt, blk, writebacks);
576 }
577
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
587 // there).
588
589 // do any writebacks resulting from the response handling
590 doWritebacksAtomic(writebacks);
591
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();
604 } else {
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());
610 }
611
612 tempBlockWriteback = evictBlock(blk);
613 }
614
615 if (pkt->needsResponse()) {
616 pkt->makeAtomicResponse();
617 }
618
619 return lat * clockPeriod();
620 }
621
622 void
623 BaseCache::functionalAccess(PacketPtr pkt, bool from_cpu_side)
624 {
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);
629
630 pkt->pushLabel(name());
631
632 CacheBlkPrintWrapper cbpw(blk);
633
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.
638
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,
642 blk->data);
643
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
646 bool have_dirty =
647 have_data && (blk->isDirty() ||
648 (mshr && mshr->inService && mshr->isPendingModified()));
649
650 bool done = have_dirty ||
651 cpuSidePort.trySatisfyFunctional(pkt) ||
652 mshrQueue.trySatisfyFunctional(pkt) ||
653 writeBuffer.trySatisfyFunctional(pkt) ||
654 memSidePort.trySatisfyFunctional(pkt);
655
656 DPRINTF(CacheVerbose, "%s: %s %s%s%s\n", __func__, pkt->print(),
657 (blk && blk->isValid()) ? "valid " : "",
658 have_data ? "data " : "", done ? "done " : "");
659
660 // We're leaving the cache, so pop cache->name() label
661 pkt->popLabel();
662
663 if (done) {
664 pkt->makeResponse();
665 } else {
666 // if it came as a request from the CPU side then make sure it
667 // continues towards the memory side
668 if (from_cpu_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);
674 }
675 }
676 }
677
678
679 void
680 BaseCache::cmpAndSwap(CacheBlk *blk, PacketPtr pkt)
681 {
682 assert(pkt->isRequest());
683
684 uint64_t overwrite_val;
685 bool overwrite_mem;
686 uint64_t condition_val64;
687 uint32_t condition_val32;
688
689 int offset = pkt->getOffset(blkSize);
690 uint8_t *blk_data = blk->data + offset;
691
692 assert(sizeof(uint64_t) >= pkt->getSize());
693
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);
699
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,
704 sizeof(uint64_t));
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,
708 sizeof(uint32_t));
709 } else
710 panic("Invalid size for conditional read/write\n");
711 }
712
713 if (overwrite_mem) {
714 std::memcpy(blk_data, &overwrite_val, pkt->getSize());
715 blk->status |= BlkDirty;
716 }
717 }
718
719 QueueEntry*
720 BaseCache::getNextQueueEntry()
721 {
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();
727
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 = mshrQueue.findPending(wq_entry);
733
734 if (conflict_mshr && conflict_mshr->order < wq_entry->order) {
735 // Service misses in order until conflict is cleared.
736 return conflict_mshr;
737
738 // @todo Note that we ignore the ready time of the conflict here
739 }
740
741 // No conflicts; issue write
742 return wq_entry;
743 } else if (miss_mshr) {
744 // need to check for conflicting earlier writeback
745 WriteQueueEntry *conflict_mshr = writeBuffer.findPending(miss_mshr);
746 if (conflict_mshr) {
747 // not sure why we don't check order here... it was in the
748 // original code but commented out.
749
750 // The only way this happens is if we are
751 // doing a write and we didn't have permissions
752 // then subsequently saw a writeback (owned got evicted)
753 // We need to make sure to perform the writeback first
754 // To preserve the dirty data, then we can issue the write
755
756 // should we return wq_entry here instead? I.e. do we
757 // have to flush writes in order? I don't think so... not
758 // for Alpha anyway. Maybe for x86?
759 return conflict_mshr;
760
761 // @todo Note that we ignore the ready time of the conflict here
762 }
763
764 // No conflicts; issue read
765 return miss_mshr;
766 }
767
768 // fall through... no pending requests. Try a prefetch.
769 assert(!miss_mshr && !wq_entry);
770 if (prefetcher && mshrQueue.canPrefetch()) {
771 // If we have a miss queue slot, we can try a prefetch
772 PacketPtr pkt = prefetcher->getPacket();
773 if (pkt) {
774 Addr pf_addr = pkt->getBlockAddr(blkSize);
775 if (!tags->findBlock(pf_addr, pkt->isSecure()) &&
776 !mshrQueue.findMatch(pf_addr, pkt->isSecure()) &&
777 !writeBuffer.findMatch(pf_addr, pkt->isSecure())) {
778 // Update statistic on number of prefetches issued
779 // (hwpf_mshr_misses)
780 assert(pkt->req->masterId() < system->maxMasters());
781 stats.cmdStats(pkt).mshr_misses[pkt->req->masterId()]++;
782
783 // allocate an MSHR and return it, note
784 // that we send the packet straight away, so do not
785 // schedule the send
786 return allocateMissBuffer(pkt, curTick(), false);
787 } else {
788 // free the request and packet
789 delete pkt;
790 }
791 }
792 }
793
794 return nullptr;
795 }
796
797 bool
798 BaseCache::updateCompressionData(CacheBlk *blk, const uint64_t* data,
799 PacketList &writebacks)
800 {
801 // tempBlock does not exist in the tags, so don't do anything for it.
802 if (blk == tempBlock) {
803 return true;
804 }
805
806 // Get superblock of the given block
807 CompressionBlk* compression_blk = static_cast<CompressionBlk*>(blk);
808 const SuperBlk* superblock = static_cast<const SuperBlk*>(
809 compression_blk->getSectorBlock());
810
811 // The compressor is called to compress the updated data, so that its
812 // metadata can be updated.
813 std::size_t compression_size = 0;
814 Cycles compression_lat = Cycles(0);
815 Cycles decompression_lat = Cycles(0);
816 compressor->compress(data, compression_lat, decompression_lat,
817 compression_size);
818
819 // If block's compression factor increased, it may not be co-allocatable
820 // anymore. If so, some blocks might need to be evicted to make room for
821 // the bigger block
822
823 // Get previous compressed size
824 const std::size_t M5_VAR_USED prev_size = compression_blk->getSizeBits();
825
826 // Check if new data is co-allocatable
827 const bool is_co_allocatable = superblock->isCompressed(compression_blk) &&
828 superblock->canCoAllocate(compression_size);
829
830 // If block was compressed, possibly co-allocated with other blocks, and
831 // cannot be co-allocated anymore, one or more blocks must be evicted to
832 // make room for the expanded block. As of now we decide to evict the co-
833 // allocated blocks to make room for the expansion, but other approaches
834 // that take the replacement data of the superblock into account may
835 // generate better results
836 std::vector<CacheBlk*> evict_blks;
837 const bool was_compressed = compression_blk->isCompressed();
838 if (was_compressed && !is_co_allocatable) {
839 // Get all co-allocated blocks
840 for (const auto& sub_blk : superblock->blks) {
841 if (sub_blk->isValid() && (compression_blk != sub_blk)) {
842 // Check for transient state allocations. If any of the
843 // entries listed for eviction has a transient state, the
844 // allocation fails
845 const Addr repl_addr = regenerateBlkAddr(sub_blk);
846 const MSHR *repl_mshr =
847 mshrQueue.findMatch(repl_addr, sub_blk->isSecure());
848 if (repl_mshr) {
849 DPRINTF(CacheRepl, "Aborting data expansion of %s due " \
850 "to replacement of block in transient state: %s\n",
851 compression_blk->print(), sub_blk->print());
852 // Too hard to replace block with transient state, so it
853 // cannot be evicted. Mark the update as failed and expect
854 // the caller to evict this block. Since this is called
855 // only when writebacks arrive, and packets do not contain
856 // compressed data, there is no need to decompress
857 compression_blk->setSizeBits(blkSize * 8);
858 compression_blk->setDecompressionLatency(Cycles(0));
859 compression_blk->setUncompressed();
860 return false;
861 }
862
863 evict_blks.push_back(sub_blk);
864 }
865 }
866
867 // Update the number of data expansions
868 stats.dataExpansions++;
869
870 DPRINTF(CacheComp, "Data expansion: expanding [%s] from %d to %d bits"
871 "\n", blk->print(), prev_size, compression_size);
872 }
873
874 // We always store compressed blocks when possible
875 if (is_co_allocatable) {
876 compression_blk->setCompressed();
877 } else {
878 compression_blk->setUncompressed();
879 }
880 compression_blk->setSizeBits(compression_size);
881 compression_blk->setDecompressionLatency(decompression_lat);
882
883 // Evict valid blocks
884 for (const auto& evict_blk : evict_blks) {
885 if (evict_blk->isValid()) {
886 if (evict_blk->wasPrefetched()) {
887 stats.unusedPrefetches++;
888 }
889 evictBlock(evict_blk, writebacks);
890 }
891 }
892
893 return true;
894 }
895
896 void
897 BaseCache::satisfyRequest(PacketPtr pkt, CacheBlk *blk, bool, bool)
898 {
899 assert(pkt->isRequest());
900
901 assert(blk && blk->isValid());
902 // Occasionally this is not true... if we are a lower-level cache
903 // satisfying a string of Read and ReadEx requests from
904 // upper-level caches, a Read will mark the block as shared but we
905 // can satisfy a following ReadEx anyway since we can rely on the
906 // Read requester(s) to have buffered the ReadEx snoop and to
907 // invalidate their blocks after receiving them.
908 // assert(!pkt->needsWritable() || blk->isWritable());
909 assert(pkt->getOffset(blkSize) + pkt->getSize() <= blkSize);
910
911 // Check RMW operations first since both isRead() and
912 // isWrite() will be true for them
913 if (pkt->cmd == MemCmd::SwapReq) {
914 if (pkt->isAtomicOp()) {
915 // extract data from cache and save it into the data field in
916 // the packet as a return value from this atomic op
917 int offset = tags->extractBlkOffset(pkt->getAddr());
918 uint8_t *blk_data = blk->data + offset;
919 pkt->setData(blk_data);
920
921 // execute AMO operation
922 (*(pkt->getAtomicOp()))(blk_data);
923
924 // set block status to dirty
925 blk->status |= BlkDirty;
926 } else {
927 cmpAndSwap(blk, pkt);
928 }
929 } else if (pkt->isWrite()) {
930 // we have the block in a writable state and can go ahead,
931 // note that the line may be also be considered writable in
932 // downstream caches along the path to memory, but always
933 // Exclusive, and never Modified
934 assert(blk->isWritable());
935 // Write or WriteLine at the first cache with block in writable state
936 if (blk->checkWrite(pkt)) {
937 pkt->writeDataToBlock(blk->data, blkSize);
938 }
939 // Always mark the line as dirty (and thus transition to the
940 // Modified state) even if we are a failed StoreCond so we
941 // supply data to any snoops that have appended themselves to
942 // this cache before knowing the store will fail.
943 blk->status |= BlkDirty;
944 DPRINTF(CacheVerbose, "%s for %s (write)\n", __func__, pkt->print());
945 } else if (pkt->isRead()) {
946 if (pkt->isLLSC()) {
947 blk->trackLoadLocked(pkt);
948 }
949
950 // all read responses have a data payload
951 assert(pkt->hasRespData());
952 pkt->setDataFromBlock(blk->data, blkSize);
953 } else if (pkt->isUpgrade()) {
954 // sanity check
955 assert(!pkt->hasSharers());
956
957 if (blk->isDirty()) {
958 // we were in the Owned state, and a cache above us that
959 // has the line in Shared state needs to be made aware
960 // that the data it already has is in fact dirty
961 pkt->setCacheResponding();
962 blk->status &= ~BlkDirty;
963 }
964 } else if (pkt->isClean()) {
965 blk->status &= ~BlkDirty;
966 } else {
967 assert(pkt->isInvalidate());
968 invalidateBlock(blk);
969 DPRINTF(CacheVerbose, "%s for %s (invalidation)\n", __func__,
970 pkt->print());
971 }
972 }
973
974 /////////////////////////////////////////////////////
975 //
976 // Access path: requests coming in from the CPU side
977 //
978 /////////////////////////////////////////////////////
979 Cycles
980 BaseCache::calculateTagOnlyLatency(const uint32_t delay,
981 const Cycles lookup_lat) const
982 {
983 // A tag-only access has to wait for the packet to arrive in order to
984 // perform the tag lookup.
985 return ticksToCycles(delay) + lookup_lat;
986 }
987
988 Cycles
989 BaseCache::calculateAccessLatency(const CacheBlk* blk, const uint32_t delay,
990 const Cycles lookup_lat) const
991 {
992 Cycles lat(0);
993
994 if (blk != nullptr) {
995 // As soon as the access arrives, for sequential accesses first access
996 // tags, then the data entry. In the case of parallel accesses the
997 // latency is dictated by the slowest of tag and data latencies.
998 if (sequentialAccess) {
999 lat = ticksToCycles(delay) + lookup_lat + dataLatency;
1000 } else {
1001 lat = ticksToCycles(delay) + std::max(lookup_lat, dataLatency);
1002 }
1003
1004 // Check if the block to be accessed is available. If not, apply the
1005 // access latency on top of when the block is ready to be accessed.
1006 const Tick tick = curTick() + delay;
1007 const Tick when_ready = blk->getWhenReady();
1008 if (when_ready > tick &&
1009 ticksToCycles(when_ready - tick) > lat) {
1010 lat += ticksToCycles(when_ready - tick);
1011 }
1012 } else {
1013 // In case of a miss, we neglect the data access in a parallel
1014 // configuration (i.e., the data access will be stopped as soon as
1015 // we find out it is a miss), and use the tag-only latency.
1016 lat = calculateTagOnlyLatency(delay, lookup_lat);
1017 }
1018
1019 return lat;
1020 }
1021
1022 bool
1023 BaseCache::access(PacketPtr pkt, CacheBlk *&blk, Cycles &lat,
1024 PacketList &writebacks)
1025 {
1026 // sanity check
1027 assert(pkt->isRequest());
1028
1029 chatty_assert(!(isReadOnly && pkt->isWrite()),
1030 "Should never see a write in a read-only cache %s\n",
1031 name());
1032
1033 // Access block in the tags
1034 Cycles tag_latency(0);
1035 blk = tags->accessBlock(pkt->getAddr(), pkt->isSecure(), tag_latency);
1036
1037 DPRINTF(Cache, "%s for %s %s\n", __func__, pkt->print(),
1038 blk ? "hit " + blk->print() : "miss");
1039
1040 if (pkt->req->isCacheMaintenance()) {
1041 // A cache maintenance operation is always forwarded to the
1042 // memory below even if the block is found in dirty state.
1043
1044 // We defer any changes to the state of the block until we
1045 // create and mark as in service the mshr for the downstream
1046 // packet.
1047
1048 // Calculate access latency on top of when the packet arrives. This
1049 // takes into account the bus delay.
1050 lat = calculateTagOnlyLatency(pkt->headerDelay, tag_latency);
1051
1052 return false;
1053 }
1054
1055 if (pkt->isEviction()) {
1056 // We check for presence of block in above caches before issuing
1057 // Writeback or CleanEvict to write buffer. Therefore the only
1058 // possible cases can be of a CleanEvict packet coming from above
1059 // encountering a Writeback generated in this cache peer cache and
1060 // waiting in the write buffer. Cases of upper level peer caches
1061 // generating CleanEvict and Writeback or simply CleanEvict and
1062 // CleanEvict almost simultaneously will be caught by snoops sent out
1063 // by crossbar.
1064 WriteQueueEntry *wb_entry = writeBuffer.findMatch(pkt->getAddr(),
1065 pkt->isSecure());
1066 if (wb_entry) {
1067 assert(wb_entry->getNumTargets() == 1);
1068 PacketPtr wbPkt = wb_entry->getTarget()->pkt;
1069 assert(wbPkt->isWriteback());
1070
1071 if (pkt->isCleanEviction()) {
1072 // The CleanEvict and WritebackClean snoops into other
1073 // peer caches of the same level while traversing the
1074 // crossbar. If a copy of the block is found, the
1075 // packet is deleted in the crossbar. Hence, none of
1076 // the other upper level caches connected to this
1077 // cache have the block, so we can clear the
1078 // BLOCK_CACHED flag in the Writeback if set and
1079 // discard the CleanEvict by returning true.
1080 wbPkt->clearBlockCached();
1081
1082 // A clean evict does not need to access the data array
1083 lat = calculateTagOnlyLatency(pkt->headerDelay, tag_latency);
1084
1085 return true;
1086 } else {
1087 assert(pkt->cmd == MemCmd::WritebackDirty);
1088 // Dirty writeback from above trumps our clean
1089 // writeback... discard here
1090 // Note: markInService will remove entry from writeback buffer.
1091 markInService(wb_entry);
1092 delete wbPkt;
1093 }
1094 }
1095 }
1096
1097 // The critical latency part of a write depends only on the tag access
1098 if (pkt->isWrite()) {
1099 lat = calculateTagOnlyLatency(pkt->headerDelay, tag_latency);
1100 }
1101
1102 // Writeback handling is special case. We can write the block into
1103 // the cache without having a writeable copy (or any copy at all).
1104 if (pkt->isWriteback()) {
1105 assert(blkSize == pkt->getSize());
1106
1107 // we could get a clean writeback while we are having
1108 // outstanding accesses to a block, do the simple thing for
1109 // now and drop the clean writeback so that we do not upset
1110 // any ordering/decisions about ownership already taken
1111 if (pkt->cmd == MemCmd::WritebackClean &&
1112 mshrQueue.findMatch(pkt->getAddr(), pkt->isSecure())) {
1113 DPRINTF(Cache, "Clean writeback %#llx to block with MSHR, "
1114 "dropping\n", pkt->getAddr());
1115
1116 // A writeback searches for the block, then writes the data.
1117 // As the writeback is being dropped, the data is not touched,
1118 // and we just had to wait for the time to find a match in the
1119 // MSHR. As of now assume a mshr queue search takes as long as
1120 // a tag lookup for simplicity.
1121 return true;
1122 }
1123
1124 if (!blk) {
1125 // need to do a replacement
1126 blk = allocateBlock(pkt, writebacks);
1127 if (!blk) {
1128 // no replaceable block available: give up, fwd to next level.
1129 incMissCount(pkt);
1130 return false;
1131 }
1132
1133 blk->status |= BlkReadable;
1134 } else if (compressor) {
1135 // This is an overwrite to an existing block, therefore we need
1136 // to check for data expansion (i.e., block was compressed with
1137 // a smaller size, and now it doesn't fit the entry anymore).
1138 // If that is the case we might need to evict blocks.
1139 if (!updateCompressionData(blk, pkt->getConstPtr<uint64_t>(),
1140 writebacks)) {
1141 invalidateBlock(blk);
1142 return false;
1143 }
1144 }
1145
1146 // only mark the block dirty if we got a writeback command,
1147 // and leave it as is for a clean writeback
1148 if (pkt->cmd == MemCmd::WritebackDirty) {
1149 // TODO: the coherent cache can assert(!blk->isDirty());
1150 blk->status |= BlkDirty;
1151 }
1152 // if the packet does not have sharers, it is passing
1153 // writable, and we got the writeback in Modified or Exclusive
1154 // state, if not we are in the Owned or Shared state
1155 if (!pkt->hasSharers()) {
1156 blk->status |= BlkWritable;
1157 }
1158 // nothing else to do; writeback doesn't expect response
1159 assert(!pkt->needsResponse());
1160 pkt->writeDataToBlock(blk->data, blkSize);
1161 DPRINTF(Cache, "%s new state is %s\n", __func__, blk->print());
1162 incHitCount(pkt);
1163
1164 // When the packet metadata arrives, the tag lookup will be done while
1165 // the payload is arriving. Then the block will be ready to access as
1166 // soon as the fill is done
1167 blk->setWhenReady(clockEdge(fillLatency) + pkt->headerDelay +
1168 std::max(cyclesToTicks(tag_latency), (uint64_t)pkt->payloadDelay));
1169
1170 return true;
1171 } else if (pkt->cmd == MemCmd::CleanEvict) {
1172 // A CleanEvict does not need to access the data array
1173 lat = calculateTagOnlyLatency(pkt->headerDelay, tag_latency);
1174
1175 if (blk) {
1176 // Found the block in the tags, need to stop CleanEvict from
1177 // propagating further down the hierarchy. Returning true will
1178 // treat the CleanEvict like a satisfied write request and delete
1179 // it.
1180 return true;
1181 }
1182 // We didn't find the block here, propagate the CleanEvict further
1183 // down the memory hierarchy. Returning false will treat the CleanEvict
1184 // like a Writeback which could not find a replaceable block so has to
1185 // go to next level.
1186 return false;
1187 } else if (pkt->cmd == MemCmd::WriteClean) {
1188 // WriteClean handling is a special case. We can allocate a
1189 // block directly if it doesn't exist and we can update the
1190 // block immediately. The WriteClean transfers the ownership
1191 // of the block as well.
1192 assert(blkSize == pkt->getSize());
1193
1194 if (!blk) {
1195 if (pkt->writeThrough()) {
1196 // if this is a write through packet, we don't try to
1197 // allocate if the block is not present
1198 return false;
1199 } else {
1200 // a writeback that misses needs to allocate a new block
1201 blk = allocateBlock(pkt, writebacks);
1202 if (!blk) {
1203 // no replaceable block available: give up, fwd to
1204 // next level.
1205 incMissCount(pkt);
1206 return false;
1207 }
1208
1209 blk->status |= BlkReadable;
1210 }
1211 } else if (compressor) {
1212 // This is an overwrite to an existing block, therefore we need
1213 // to check for data expansion (i.e., block was compressed with
1214 // a smaller size, and now it doesn't fit the entry anymore).
1215 // If that is the case we might need to evict blocks.
1216 if (!updateCompressionData(blk, pkt->getConstPtr<uint64_t>(),
1217 writebacks)) {
1218 invalidateBlock(blk);
1219 return false;
1220 }
1221 }
1222
1223 // at this point either this is a writeback or a write-through
1224 // write clean operation and the block is already in this
1225 // cache, we need to update the data and the block flags
1226 assert(blk);
1227 // TODO: the coherent cache can assert(!blk->isDirty());
1228 if (!pkt->writeThrough()) {
1229 blk->status |= BlkDirty;
1230 }
1231 // nothing else to do; writeback doesn't expect response
1232 assert(!pkt->needsResponse());
1233 pkt->writeDataToBlock(blk->data, blkSize);
1234 DPRINTF(Cache, "%s new state is %s\n", __func__, blk->print());
1235
1236 incHitCount(pkt);
1237
1238 // When the packet metadata arrives, the tag lookup will be done while
1239 // the payload is arriving. Then the block will be ready to access as
1240 // soon as the fill is done
1241 blk->setWhenReady(clockEdge(fillLatency) + pkt->headerDelay +
1242 std::max(cyclesToTicks(tag_latency), (uint64_t)pkt->payloadDelay));
1243
1244 // If this a write-through packet it will be sent to cache below
1245 return !pkt->writeThrough();
1246 } else if (blk && (pkt->needsWritable() ? blk->isWritable() :
1247 blk->isReadable())) {
1248 // OK to satisfy access
1249 incHitCount(pkt);
1250
1251 // Calculate access latency based on the need to access the data array
1252 if (pkt->isRead()) {
1253 lat = calculateAccessLatency(blk, pkt->headerDelay, tag_latency);
1254
1255 // When a block is compressed, it must first be decompressed
1256 // before being read. This adds to the access latency.
1257 if (compressor) {
1258 lat += compressor->getDecompressionLatency(blk);
1259 }
1260 } else {
1261 lat = calculateTagOnlyLatency(pkt->headerDelay, tag_latency);
1262 }
1263
1264 satisfyRequest(pkt, blk);
1265 maintainClusivity(pkt->fromCache(), blk);
1266
1267 return true;
1268 }
1269
1270 // Can't satisfy access normally... either no block (blk == nullptr)
1271 // or have block but need writable
1272
1273 incMissCount(pkt);
1274
1275 lat = calculateAccessLatency(blk, pkt->headerDelay, tag_latency);
1276
1277 if (!blk && pkt->isLLSC() && pkt->isWrite()) {
1278 // complete miss on store conditional... just give up now
1279 pkt->req->setExtraData(0);
1280 return true;
1281 }
1282
1283 return false;
1284 }
1285
1286 void
1287 BaseCache::maintainClusivity(bool from_cache, CacheBlk *blk)
1288 {
1289 if (from_cache && blk && blk->isValid() && !blk->isDirty() &&
1290 clusivity == Enums::mostly_excl) {
1291 // if we have responded to a cache, and our block is still
1292 // valid, but not dirty, and this cache is mostly exclusive
1293 // with respect to the cache above, drop the block
1294 invalidateBlock(blk);
1295 }
1296 }
1297
1298 CacheBlk*
1299 BaseCache::handleFill(PacketPtr pkt, CacheBlk *blk, PacketList &writebacks,
1300 bool allocate)
1301 {
1302 assert(pkt->isResponse());
1303 Addr addr = pkt->getAddr();
1304 bool is_secure = pkt->isSecure();
1305 #if TRACING_ON
1306 CacheBlk::State old_state = blk ? blk->status : 0;
1307 #endif
1308
1309 // When handling a fill, we should have no writes to this line.
1310 assert(addr == pkt->getBlockAddr(blkSize));
1311 assert(!writeBuffer.findMatch(addr, is_secure));
1312
1313 if (!blk) {
1314 // better have read new data...
1315 assert(pkt->hasData() || pkt->cmd == MemCmd::InvalidateResp);
1316
1317 // need to do a replacement if allocating, otherwise we stick
1318 // with the temporary storage
1319 blk = allocate ? allocateBlock(pkt, writebacks) : nullptr;
1320
1321 if (!blk) {
1322 // No replaceable block or a mostly exclusive
1323 // cache... just use temporary storage to complete the
1324 // current request and then get rid of it
1325 blk = tempBlock;
1326 tempBlock->insert(addr, is_secure);
1327 DPRINTF(Cache, "using temp block for %#llx (%s)\n", addr,
1328 is_secure ? "s" : "ns");
1329 }
1330 } else {
1331 // existing block... probably an upgrade
1332 // don't clear block status... if block is already dirty we
1333 // don't want to lose that
1334 }
1335
1336 // Block is guaranteed to be valid at this point
1337 assert(blk->isValid());
1338 assert(blk->isSecure() == is_secure);
1339 assert(regenerateBlkAddr(blk) == addr);
1340
1341 blk->status |= BlkReadable;
1342
1343 // sanity check for whole-line writes, which should always be
1344 // marked as writable as part of the fill, and then later marked
1345 // dirty as part of satisfyRequest
1346 if (pkt->cmd == MemCmd::InvalidateResp) {
1347 assert(!pkt->hasSharers());
1348 }
1349
1350 // here we deal with setting the appropriate state of the line,
1351 // and we start by looking at the hasSharers flag, and ignore the
1352 // cacheResponding flag (normally signalling dirty data) if the
1353 // packet has sharers, thus the line is never allocated as Owned
1354 // (dirty but not writable), and always ends up being either
1355 // Shared, Exclusive or Modified, see Packet::setCacheResponding
1356 // for more details
1357 if (!pkt->hasSharers()) {
1358 // we could get a writable line from memory (rather than a
1359 // cache) even in a read-only cache, note that we set this bit
1360 // even for a read-only cache, possibly revisit this decision
1361 blk->status |= BlkWritable;
1362
1363 // check if we got this via cache-to-cache transfer (i.e., from a
1364 // cache that had the block in Modified or Owned state)
1365 if (pkt->cacheResponding()) {
1366 // we got the block in Modified state, and invalidated the
1367 // owners copy
1368 blk->status |= BlkDirty;
1369
1370 chatty_assert(!isReadOnly, "Should never see dirty snoop response "
1371 "in read-only cache %s\n", name());
1372
1373 }
1374 }
1375
1376 DPRINTF(Cache, "Block addr %#llx (%s) moving from state %x to %s\n",
1377 addr, is_secure ? "s" : "ns", old_state, blk->print());
1378
1379 // if we got new data, copy it in (checking for a read response
1380 // and a response that has data is the same in the end)
1381 if (pkt->isRead()) {
1382 // sanity checks
1383 assert(pkt->hasData());
1384 assert(pkt->getSize() == blkSize);
1385
1386 pkt->writeDataToBlock(blk->data, blkSize);
1387 }
1388 // The block will be ready when the payload arrives and the fill is done
1389 blk->setWhenReady(clockEdge(fillLatency) + pkt->headerDelay +
1390 pkt->payloadDelay);
1391
1392 return blk;
1393 }
1394
1395 CacheBlk*
1396 BaseCache::allocateBlock(const PacketPtr pkt, PacketList &writebacks)
1397 {
1398 // Get address
1399 const Addr addr = pkt->getAddr();
1400
1401 // Get secure bit
1402 const bool is_secure = pkt->isSecure();
1403
1404 // Block size and compression related access latency. Only relevant if
1405 // using a compressor, otherwise there is no extra delay, and the block
1406 // is fully sized
1407 std::size_t blk_size_bits = blkSize*8;
1408 Cycles compression_lat = Cycles(0);
1409 Cycles decompression_lat = Cycles(0);
1410
1411 // If a compressor is being used, it is called to compress data before
1412 // insertion. Although in Gem5 the data is stored uncompressed, even if a
1413 // compressor is used, the compression/decompression methods are called to
1414 // calculate the amount of extra cycles needed to read or write compressed
1415 // blocks.
1416 if (compressor && pkt->hasData()) {
1417 compressor->compress(pkt->getConstPtr<uint64_t>(), compression_lat,
1418 decompression_lat, blk_size_bits);
1419 }
1420
1421 // Find replacement victim
1422 std::vector<CacheBlk*> evict_blks;
1423 CacheBlk *victim = tags->findVictim(addr, is_secure, blk_size_bits,
1424 evict_blks);
1425
1426 // It is valid to return nullptr if there is no victim
1427 if (!victim)
1428 return nullptr;
1429
1430 // Print victim block's information
1431 DPRINTF(CacheRepl, "Replacement victim: %s\n", victim->print());
1432
1433 // Check for transient state allocations. If any of the entries listed
1434 // for eviction has a transient state, the allocation fails
1435 bool replacement = false;
1436 for (const auto& blk : evict_blks) {
1437 if (blk->isValid()) {
1438 replacement = true;
1439
1440 Addr repl_addr = regenerateBlkAddr(blk);
1441 MSHR *repl_mshr = mshrQueue.findMatch(repl_addr, blk->isSecure());
1442 if (repl_mshr) {
1443 // must be an outstanding upgrade or clean request
1444 // on a block we're about to replace...
1445 assert((!blk->isWritable() && repl_mshr->needsWritable()) ||
1446 repl_mshr->isCleaning());
1447
1448 // too hard to replace block with transient state
1449 // allocation failed, block not inserted
1450 return nullptr;
1451 }
1452 }
1453 }
1454
1455 // The victim will be replaced by a new entry, so increase the replacement
1456 // counter if a valid block is being replaced
1457 if (replacement) {
1458 // Evict valid blocks associated to this victim block
1459 for (const auto& blk : evict_blks) {
1460 if (blk->isValid()) {
1461 DPRINTF(CacheRepl, "Evicting %s (%#llx) to make room for " \
1462 "%#llx (%s)\n", blk->print(), regenerateBlkAddr(blk),
1463 addr, is_secure);
1464
1465 if (blk->wasPrefetched()) {
1466 stats.unusedPrefetches++;
1467 }
1468
1469 evictBlock(blk, writebacks);
1470 }
1471 }
1472
1473 stats.replacements++;
1474 }
1475
1476 // If using a compressor, set compression data. This must be done before
1477 // block insertion, as compressed tags use this information.
1478 if (compressor) {
1479 compressor->setSizeBits(victim, blk_size_bits);
1480 compressor->setDecompressionLatency(victim, decompression_lat);
1481 }
1482
1483 // Insert new block at victimized entry
1484 tags->insertBlock(pkt, victim);
1485
1486 return victim;
1487 }
1488
1489 void
1490 BaseCache::invalidateBlock(CacheBlk *blk)
1491 {
1492 // If handling a block present in the Tags, let it do its invalidation
1493 // process, which will update stats and invalidate the block itself
1494 if (blk != tempBlock) {
1495 tags->invalidate(blk);
1496 } else {
1497 tempBlock->invalidate();
1498 }
1499 }
1500
1501 void
1502 BaseCache::evictBlock(CacheBlk *blk, PacketList &writebacks)
1503 {
1504 PacketPtr pkt = evictBlock(blk);
1505 if (pkt) {
1506 writebacks.push_back(pkt);
1507 }
1508 }
1509
1510 PacketPtr
1511 BaseCache::writebackBlk(CacheBlk *blk)
1512 {
1513 chatty_assert(!isReadOnly || writebackClean,
1514 "Writeback from read-only cache");
1515 assert(blk && blk->isValid() && (blk->isDirty() || writebackClean));
1516
1517 stats.writebacks[Request::wbMasterId]++;
1518
1519 RequestPtr req = std::make_shared<Request>(
1520 regenerateBlkAddr(blk), blkSize, 0, Request::wbMasterId);
1521
1522 if (blk->isSecure())
1523 req->setFlags(Request::SECURE);
1524
1525 req->taskId(blk->task_id);
1526
1527 PacketPtr pkt =
1528 new Packet(req, blk->isDirty() ?
1529 MemCmd::WritebackDirty : MemCmd::WritebackClean);
1530
1531 DPRINTF(Cache, "Create Writeback %s writable: %d, dirty: %d\n",
1532 pkt->print(), blk->isWritable(), blk->isDirty());
1533
1534 if (blk->isWritable()) {
1535 // not asserting shared means we pass the block in modified
1536 // state, mark our own block non-writeable
1537 blk->status &= ~BlkWritable;
1538 } else {
1539 // we are in the Owned state, tell the receiver
1540 pkt->setHasSharers();
1541 }
1542
1543 // make sure the block is not marked dirty
1544 blk->status &= ~BlkDirty;
1545
1546 pkt->allocate();
1547 pkt->setDataFromBlock(blk->data, blkSize);
1548
1549 // When a block is compressed, it must first be decompressed before being
1550 // sent for writeback.
1551 if (compressor) {
1552 pkt->payloadDelay = compressor->getDecompressionLatency(blk);
1553 }
1554
1555 return pkt;
1556 }
1557
1558 PacketPtr
1559 BaseCache::writecleanBlk(CacheBlk *blk, Request::Flags dest, PacketId id)
1560 {
1561 RequestPtr req = std::make_shared<Request>(
1562 regenerateBlkAddr(blk), blkSize, 0, Request::wbMasterId);
1563
1564 if (blk->isSecure()) {
1565 req->setFlags(Request::SECURE);
1566 }
1567 req->taskId(blk->task_id);
1568
1569 PacketPtr pkt = new Packet(req, MemCmd::WriteClean, blkSize, id);
1570
1571 if (dest) {
1572 req->setFlags(dest);
1573 pkt->setWriteThrough();
1574 }
1575
1576 DPRINTF(Cache, "Create %s writable: %d, dirty: %d\n", pkt->print(),
1577 blk->isWritable(), blk->isDirty());
1578
1579 if (blk->isWritable()) {
1580 // not asserting shared means we pass the block in modified
1581 // state, mark our own block non-writeable
1582 blk->status &= ~BlkWritable;
1583 } else {
1584 // we are in the Owned state, tell the receiver
1585 pkt->setHasSharers();
1586 }
1587
1588 // make sure the block is not marked dirty
1589 blk->status &= ~BlkDirty;
1590
1591 pkt->allocate();
1592 pkt->setDataFromBlock(blk->data, blkSize);
1593
1594 // When a block is compressed, it must first be decompressed before being
1595 // sent for writeback.
1596 if (compressor) {
1597 pkt->payloadDelay = compressor->getDecompressionLatency(blk);
1598 }
1599
1600 return pkt;
1601 }
1602
1603
1604 void
1605 BaseCache::memWriteback()
1606 {
1607 tags->forEachBlk([this](CacheBlk &blk) { writebackVisitor(blk); });
1608 }
1609
1610 void
1611 BaseCache::memInvalidate()
1612 {
1613 tags->forEachBlk([this](CacheBlk &blk) { invalidateVisitor(blk); });
1614 }
1615
1616 bool
1617 BaseCache::isDirty() const
1618 {
1619 return tags->anyBlk([](CacheBlk &blk) { return blk.isDirty(); });
1620 }
1621
1622 bool
1623 BaseCache::coalesce() const
1624 {
1625 return writeAllocator && writeAllocator->coalesce();
1626 }
1627
1628 void
1629 BaseCache::writebackVisitor(CacheBlk &blk)
1630 {
1631 if (blk.isDirty()) {
1632 assert(blk.isValid());
1633
1634 RequestPtr request = std::make_shared<Request>(
1635 regenerateBlkAddr(&blk), blkSize, 0, Request::funcMasterId);
1636
1637 request->taskId(blk.task_id);
1638 if (blk.isSecure()) {
1639 request->setFlags(Request::SECURE);
1640 }
1641
1642 Packet packet(request, MemCmd::WriteReq);
1643 packet.dataStatic(blk.data);
1644
1645 memSidePort.sendFunctional(&packet);
1646
1647 blk.status &= ~BlkDirty;
1648 }
1649 }
1650
1651 void
1652 BaseCache::invalidateVisitor(CacheBlk &blk)
1653 {
1654 if (blk.isDirty())
1655 warn_once("Invalidating dirty cache lines. " \
1656 "Expect things to break.\n");
1657
1658 if (blk.isValid()) {
1659 assert(!blk.isDirty());
1660 invalidateBlock(&blk);
1661 }
1662 }
1663
1664 Tick
1665 BaseCache::nextQueueReadyTime() const
1666 {
1667 Tick nextReady = std::min(mshrQueue.nextReadyTime(),
1668 writeBuffer.nextReadyTime());
1669
1670 // Don't signal prefetch ready time if no MSHRs available
1671 // Will signal once enoguh MSHRs are deallocated
1672 if (prefetcher && mshrQueue.canPrefetch()) {
1673 nextReady = std::min(nextReady,
1674 prefetcher->nextPrefetchReadyTime());
1675 }
1676
1677 return nextReady;
1678 }
1679
1680
1681 bool
1682 BaseCache::sendMSHRQueuePacket(MSHR* mshr)
1683 {
1684 assert(mshr);
1685
1686 // use request from 1st target
1687 PacketPtr tgt_pkt = mshr->getTarget()->pkt;
1688
1689 DPRINTF(Cache, "%s: MSHR %s\n", __func__, tgt_pkt->print());
1690
1691 // if the cache is in write coalescing mode or (additionally) in
1692 // no allocation mode, and we have a write packet with an MSHR
1693 // that is not a whole-line write (due to incompatible flags etc),
1694 // then reset the write mode
1695 if (writeAllocator && writeAllocator->coalesce() && tgt_pkt->isWrite()) {
1696 if (!mshr->isWholeLineWrite()) {
1697 // if we are currently write coalescing, hold on the
1698 // MSHR as many cycles extra as we need to completely
1699 // write a cache line
1700 if (writeAllocator->delay(mshr->blkAddr)) {
1701 Tick delay = blkSize / tgt_pkt->getSize() * clockPeriod();
1702 DPRINTF(CacheVerbose, "Delaying pkt %s %llu ticks to allow "
1703 "for write coalescing\n", tgt_pkt->print(), delay);
1704 mshrQueue.delay(mshr, delay);
1705 return false;
1706 } else {
1707 writeAllocator->reset();
1708 }
1709 } else {
1710 writeAllocator->resetDelay(mshr->blkAddr);
1711 }
1712 }
1713
1714 CacheBlk *blk = tags->findBlock(mshr->blkAddr, mshr->isSecure);
1715
1716 // either a prefetch that is not present upstream, or a normal
1717 // MSHR request, proceed to get the packet to send downstream
1718 PacketPtr pkt = createMissPacket(tgt_pkt, blk, mshr->needsWritable(),
1719 mshr->isWholeLineWrite());
1720
1721 mshr->isForward = (pkt == nullptr);
1722
1723 if (mshr->isForward) {
1724 // not a cache block request, but a response is expected
1725 // make copy of current packet to forward, keep current
1726 // copy for response handling
1727 pkt = new Packet(tgt_pkt, false, true);
1728 assert(!pkt->isWrite());
1729 }
1730
1731 // play it safe and append (rather than set) the sender state,
1732 // as forwarded packets may already have existing state
1733 pkt->pushSenderState(mshr);
1734
1735 if (pkt->isClean() && blk && blk->isDirty()) {
1736 // A cache clean opearation is looking for a dirty block. Mark
1737 // the packet so that the destination xbar can determine that
1738 // there will be a follow-up write packet as well.
1739 pkt->setSatisfied();
1740 }
1741
1742 if (!memSidePort.sendTimingReq(pkt)) {
1743 // we are awaiting a retry, but we
1744 // delete the packet and will be creating a new packet
1745 // when we get the opportunity
1746 delete pkt;
1747
1748 // note that we have now masked any requestBus and
1749 // schedSendEvent (we will wait for a retry before
1750 // doing anything), and this is so even if we do not
1751 // care about this packet and might override it before
1752 // it gets retried
1753 return true;
1754 } else {
1755 // As part of the call to sendTimingReq the packet is
1756 // forwarded to all neighbouring caches (and any caches
1757 // above them) as a snoop. Thus at this point we know if
1758 // any of the neighbouring caches are responding, and if
1759 // so, we know it is dirty, and we can determine if it is
1760 // being passed as Modified, making our MSHR the ordering
1761 // point
1762 bool pending_modified_resp = !pkt->hasSharers() &&
1763 pkt->cacheResponding();
1764 markInService(mshr, pending_modified_resp);
1765
1766 if (pkt->isClean() && blk && blk->isDirty()) {
1767 // A cache clean opearation is looking for a dirty
1768 // block. If a dirty block is encountered a WriteClean
1769 // will update any copies to the path to the memory
1770 // until the point of reference.
1771 DPRINTF(CacheVerbose, "%s: packet %s found block: %s\n",
1772 __func__, pkt->print(), blk->print());
1773 PacketPtr wb_pkt = writecleanBlk(blk, pkt->req->getDest(),
1774 pkt->id);
1775 PacketList writebacks;
1776 writebacks.push_back(wb_pkt);
1777 doWritebacks(writebacks, 0);
1778 }
1779
1780 return false;
1781 }
1782 }
1783
1784 bool
1785 BaseCache::sendWriteQueuePacket(WriteQueueEntry* wq_entry)
1786 {
1787 assert(wq_entry);
1788
1789 // always a single target for write queue entries
1790 PacketPtr tgt_pkt = wq_entry->getTarget()->pkt;
1791
1792 DPRINTF(Cache, "%s: write %s\n", __func__, tgt_pkt->print());
1793
1794 // forward as is, both for evictions and uncacheable writes
1795 if (!memSidePort.sendTimingReq(tgt_pkt)) {
1796 // note that we have now masked any requestBus and
1797 // schedSendEvent (we will wait for a retry before
1798 // doing anything), and this is so even if we do not
1799 // care about this packet and might override it before
1800 // it gets retried
1801 return true;
1802 } else {
1803 markInService(wq_entry);
1804 return false;
1805 }
1806 }
1807
1808 void
1809 BaseCache::serialize(CheckpointOut &cp) const
1810 {
1811 bool dirty(isDirty());
1812
1813 if (dirty) {
1814 warn("*** The cache still contains dirty data. ***\n");
1815 warn(" Make sure to drain the system using the correct flags.\n");
1816 warn(" This checkpoint will not restore correctly " \
1817 "and dirty data in the cache will be lost!\n");
1818 }
1819
1820 // Since we don't checkpoint the data in the cache, any dirty data
1821 // will be lost when restoring from a checkpoint of a system that
1822 // wasn't drained properly. Flag the checkpoint as invalid if the
1823 // cache contains dirty data.
1824 bool bad_checkpoint(dirty);
1825 SERIALIZE_SCALAR(bad_checkpoint);
1826 }
1827
1828 void
1829 BaseCache::unserialize(CheckpointIn &cp)
1830 {
1831 bool bad_checkpoint;
1832 UNSERIALIZE_SCALAR(bad_checkpoint);
1833 if (bad_checkpoint) {
1834 fatal("Restoring from checkpoints with dirty caches is not "
1835 "supported in the classic memory system. Please remove any "
1836 "caches or drain them properly before taking checkpoints.\n");
1837 }
1838 }
1839
1840
1841 BaseCache::CacheCmdStats::CacheCmdStats(BaseCache &c,
1842 const std::string &name)
1843 : Stats::Group(&c), cache(c),
1844
1845 hits(
1846 this, (name + "_hits").c_str(),
1847 ("number of " + name + " hits").c_str()),
1848 misses(
1849 this, (name + "_misses").c_str(),
1850 ("number of " + name + " misses").c_str()),
1851 missLatency(
1852 this, (name + "_miss_latency").c_str(),
1853 ("number of " + name + " miss cycles").c_str()),
1854 accesses(
1855 this, (name + "_accesses").c_str(),
1856 ("number of " + name + " accesses(hits+misses)").c_str()),
1857 missRate(
1858 this, (name + "_miss_rate").c_str(),
1859 ("miss rate for " + name + " accesses").c_str()),
1860 avgMissLatency(
1861 this, (name + "_avg_miss_latency").c_str(),
1862 ("average " + name + " miss latency").c_str()),
1863 mshr_hits(
1864 this, (name + "_mshr_hits").c_str(),
1865 ("number of " + name + " MSHR hits").c_str()),
1866 mshr_misses(
1867 this, (name + "_mshr_misses").c_str(),
1868 ("number of " + name + " MSHR misses").c_str()),
1869 mshr_uncacheable(
1870 this, (name + "_mshr_uncacheable").c_str(),
1871 ("number of " + name + " MSHR uncacheable").c_str()),
1872 mshr_miss_latency(
1873 this, (name + "_mshr_miss_latency").c_str(),
1874 ("number of " + name + " MSHR miss cycles").c_str()),
1875 mshr_uncacheable_lat(
1876 this, (name + "_mshr_uncacheable_latency").c_str(),
1877 ("number of " + name + " MSHR uncacheable cycles").c_str()),
1878 mshrMissRate(
1879 this, (name + "_mshr_miss_rate").c_str(),
1880 ("mshr miss rate for " + name + " accesses").c_str()),
1881 avgMshrMissLatency(
1882 this, (name + "_avg_mshr_miss_latency").c_str(),
1883 ("average " + name + " mshr miss latency").c_str()),
1884 avgMshrUncacheableLatency(
1885 this, (name + "_avg_mshr_uncacheable_latency").c_str(),
1886 ("average " + name + " mshr uncacheable latency").c_str())
1887 {
1888 }
1889
1890 void
1891 BaseCache::CacheCmdStats::regStatsFromParent()
1892 {
1893 using namespace Stats;
1894
1895 Stats::Group::regStats();
1896 System *system = cache.system;
1897 const auto max_masters = system->maxMasters();
1898
1899 hits
1900 .init(max_masters)
1901 .flags(total | nozero | nonan)
1902 ;
1903 for (int i = 0; i < max_masters; i++) {
1904 hits.subname(i, system->getMasterName(i));
1905 }
1906
1907 // Miss statistics
1908 misses
1909 .init(max_masters)
1910 .flags(total | nozero | nonan)
1911 ;
1912 for (int i = 0; i < max_masters; i++) {
1913 misses.subname(i, system->getMasterName(i));
1914 }
1915
1916 // Miss latency statistics
1917 missLatency
1918 .init(max_masters)
1919 .flags(total | nozero | nonan)
1920 ;
1921 for (int i = 0; i < max_masters; i++) {
1922 missLatency.subname(i, system->getMasterName(i));
1923 }
1924
1925 // access formulas
1926 accesses.flags(total | nozero | nonan);
1927 accesses = hits + misses;
1928 for (int i = 0; i < max_masters; i++) {
1929 accesses.subname(i, system->getMasterName(i));
1930 }
1931
1932 // miss rate formulas
1933 missRate.flags(total | nozero | nonan);
1934 missRate = misses / accesses;
1935 for (int i = 0; i < max_masters; i++) {
1936 missRate.subname(i, system->getMasterName(i));
1937 }
1938
1939 // miss latency formulas
1940 avgMissLatency.flags(total | nozero | nonan);
1941 avgMissLatency = missLatency / misses;
1942 for (int i = 0; i < max_masters; i++) {
1943 avgMissLatency.subname(i, system->getMasterName(i));
1944 }
1945
1946 // MSHR statistics
1947 // MSHR hit statistics
1948 mshr_hits
1949 .init(max_masters)
1950 .flags(total | nozero | nonan)
1951 ;
1952 for (int i = 0; i < max_masters; i++) {
1953 mshr_hits.subname(i, system->getMasterName(i));
1954 }
1955
1956 // MSHR miss statistics
1957 mshr_misses
1958 .init(max_masters)
1959 .flags(total | nozero | nonan)
1960 ;
1961 for (int i = 0; i < max_masters; i++) {
1962 mshr_misses.subname(i, system->getMasterName(i));
1963 }
1964
1965 // MSHR miss latency statistics
1966 mshr_miss_latency
1967 .init(max_masters)
1968 .flags(total | nozero | nonan)
1969 ;
1970 for (int i = 0; i < max_masters; i++) {
1971 mshr_miss_latency.subname(i, system->getMasterName(i));
1972 }
1973
1974 // MSHR uncacheable statistics
1975 mshr_uncacheable
1976 .init(max_masters)
1977 .flags(total | nozero | nonan)
1978 ;
1979 for (int i = 0; i < max_masters; i++) {
1980 mshr_uncacheable.subname(i, system->getMasterName(i));
1981 }
1982
1983 // MSHR miss latency statistics
1984 mshr_uncacheable_lat
1985 .init(max_masters)
1986 .flags(total | nozero | nonan)
1987 ;
1988 for (int i = 0; i < max_masters; i++) {
1989 mshr_uncacheable_lat.subname(i, system->getMasterName(i));
1990 }
1991
1992 // MSHR miss rate formulas
1993 mshrMissRate.flags(total | nozero | nonan);
1994 mshrMissRate = mshr_misses / accesses;
1995
1996 for (int i = 0; i < max_masters; i++) {
1997 mshrMissRate.subname(i, system->getMasterName(i));
1998 }
1999
2000 // mshrMiss latency formulas
2001 avgMshrMissLatency.flags(total | nozero | nonan);
2002 avgMshrMissLatency = mshr_miss_latency / mshr_misses;
2003 for (int i = 0; i < max_masters; i++) {
2004 avgMshrMissLatency.subname(i, system->getMasterName(i));
2005 }
2006
2007 // mshrUncacheable latency formulas
2008 avgMshrUncacheableLatency.flags(total | nozero | nonan);
2009 avgMshrUncacheableLatency = mshr_uncacheable_lat / mshr_uncacheable;
2010 for (int i = 0; i < max_masters; i++) {
2011 avgMshrUncacheableLatency.subname(i, system->getMasterName(i));
2012 }
2013 }
2014
2015 BaseCache::CacheStats::CacheStats(BaseCache &c)
2016 : Stats::Group(&c), cache(c),
2017
2018 demandHits(this, "demand_hits", "number of demand (read+write) hits"),
2019
2020 overallHits(this, "overall_hits", "number of overall hits"),
2021 demandMisses(this, "demand_misses",
2022 "number of demand (read+write) misses"),
2023 overallMisses(this, "overall_misses", "number of overall misses"),
2024 demandMissLatency(this, "demand_miss_latency",
2025 "number of demand (read+write) miss cycles"),
2026 overallMissLatency(this, "overall_miss_latency",
2027 "number of overall miss cycles"),
2028 demandAccesses(this, "demand_accesses",
2029 "number of demand (read+write) accesses"),
2030 overallAccesses(this, "overall_accesses",
2031 "number of overall (read+write) accesses"),
2032 demandMissRate(this, "demand_miss_rate",
2033 "miss rate for demand accesses"),
2034 overallMissRate(this, "overall_miss_rate",
2035 "miss rate for overall accesses"),
2036 demandAvgMissLatency(this, "demand_avg_miss_latency",
2037 "average overall miss latency"),
2038 overallAvgMissLatency(this, "overall_avg_miss_latency",
2039 "average overall miss latency"),
2040 blocked_cycles(this, "blocked_cycles",
2041 "number of cycles access was blocked"),
2042 blocked_causes(this, "blocked", "number of cycles access was blocked"),
2043 avg_blocked(this, "avg_blocked_cycles",
2044 "average number of cycles each access was blocked"),
2045 unusedPrefetches(this, "unused_prefetches",
2046 "number of HardPF blocks evicted w/o reference"),
2047 writebacks(this, "writebacks", "number of writebacks"),
2048 demandMshrHits(this, "demand_mshr_hits",
2049 "number of demand (read+write) MSHR hits"),
2050 overallMshrHits(this, "overall_mshr_hits",
2051 "number of overall MSHR hits"),
2052 demandMshrMisses(this, "demand_mshr_misses",
2053 "number of demand (read+write) MSHR misses"),
2054 overallMshrMisses(this, "overall_mshr_misses",
2055 "number of overall MSHR misses"),
2056 overallMshrUncacheable(this, "overall_mshr_uncacheable_misses",
2057 "number of overall MSHR uncacheable misses"),
2058 demandMshrMissLatency(this, "demand_mshr_miss_latency",
2059 "number of demand (read+write) MSHR miss cycles"),
2060 overallMshrMissLatency(this, "overall_mshr_miss_latency",
2061 "number of overall MSHR miss cycles"),
2062 overallMshrUncacheableLatency(this, "overall_mshr_uncacheable_latency",
2063 "number of overall MSHR uncacheable cycles"),
2064 demandMshrMissRate(this, "demand_mshr_miss_rate",
2065 "mshr miss rate for demand accesses"),
2066 overallMshrMissRate(this, "overall_mshr_miss_rate",
2067 "mshr miss rate for overall accesses"),
2068 demandAvgMshrMissLatency(this, "demand_avg_mshr_miss_latency",
2069 "average overall mshr miss latency"),
2070 overallAvgMshrMissLatency(this, "overall_avg_mshr_miss_latency",
2071 "average overall mshr miss latency"),
2072 overallAvgMshrUncacheableLatency(
2073 this, "overall_avg_mshr_uncacheable_latency",
2074 "average overall mshr uncacheable latency"),
2075 replacements(this, "replacements", "number of replacements"),
2076
2077 dataExpansions(this, "data_expansions", "number of data expansions"),
2078 cmd(MemCmd::NUM_MEM_CMDS)
2079 {
2080 for (int idx = 0; idx < MemCmd::NUM_MEM_CMDS; ++idx)
2081 cmd[idx].reset(new CacheCmdStats(c, MemCmd(idx).toString()));
2082 }
2083
2084 void
2085 BaseCache::CacheStats::regStats()
2086 {
2087 using namespace Stats;
2088
2089 Stats::Group::regStats();
2090
2091 System *system = cache.system;
2092 const auto max_masters = system->maxMasters();
2093
2094 for (auto &cs : cmd)
2095 cs->regStatsFromParent();
2096
2097 // These macros make it easier to sum the right subset of commands and
2098 // to change the subset of commands that are considered "demand" vs
2099 // "non-demand"
2100 #define SUM_DEMAND(s) \
2101 (cmd[MemCmd::ReadReq]->s + cmd[MemCmd::WriteReq]->s + \
2102 cmd[MemCmd::WriteLineReq]->s + cmd[MemCmd::ReadExReq]->s + \
2103 cmd[MemCmd::ReadCleanReq]->s + cmd[MemCmd::ReadSharedReq]->s)
2104
2105 // should writebacks be included here? prior code was inconsistent...
2106 #define SUM_NON_DEMAND(s) \
2107 (cmd[MemCmd::SoftPFReq]->s + cmd[MemCmd::HardPFReq]->s + \
2108 cmd[MemCmd::SoftPFExReq]->s)
2109
2110 demandHits.flags(total | nozero | nonan);
2111 demandHits = SUM_DEMAND(hits);
2112 for (int i = 0; i < max_masters; i++) {
2113 demandHits.subname(i, system->getMasterName(i));
2114 }
2115
2116 overallHits.flags(total | nozero | nonan);
2117 overallHits = demandHits + SUM_NON_DEMAND(hits);
2118 for (int i = 0; i < max_masters; i++) {
2119 overallHits.subname(i, system->getMasterName(i));
2120 }
2121
2122 demandMisses.flags(total | nozero | nonan);
2123 demandMisses = SUM_DEMAND(misses);
2124 for (int i = 0; i < max_masters; i++) {
2125 demandMisses.subname(i, system->getMasterName(i));
2126 }
2127
2128 overallMisses.flags(total | nozero | nonan);
2129 overallMisses = demandMisses + SUM_NON_DEMAND(misses);
2130 for (int i = 0; i < max_masters; i++) {
2131 overallMisses.subname(i, system->getMasterName(i));
2132 }
2133
2134 demandMissLatency.flags(total | nozero | nonan);
2135 demandMissLatency = SUM_DEMAND(missLatency);
2136 for (int i = 0; i < max_masters; i++) {
2137 demandMissLatency.subname(i, system->getMasterName(i));
2138 }
2139
2140 overallMissLatency.flags(total | nozero | nonan);
2141 overallMissLatency = demandMissLatency + SUM_NON_DEMAND(missLatency);
2142 for (int i = 0; i < max_masters; i++) {
2143 overallMissLatency.subname(i, system->getMasterName(i));
2144 }
2145
2146 demandAccesses.flags(total | nozero | nonan);
2147 demandAccesses = demandHits + demandMisses;
2148 for (int i = 0; i < max_masters; i++) {
2149 demandAccesses.subname(i, system->getMasterName(i));
2150 }
2151
2152 overallAccesses.flags(total | nozero | nonan);
2153 overallAccesses = overallHits + overallMisses;
2154 for (int i = 0; i < max_masters; i++) {
2155 overallAccesses.subname(i, system->getMasterName(i));
2156 }
2157
2158 demandMissRate.flags(total | nozero | nonan);
2159 demandMissRate = demandMisses / demandAccesses;
2160 for (int i = 0; i < max_masters; i++) {
2161 demandMissRate.subname(i, system->getMasterName(i));
2162 }
2163
2164 overallMissRate.flags(total | nozero | nonan);
2165 overallMissRate = overallMisses / overallAccesses;
2166 for (int i = 0; i < max_masters; i++) {
2167 overallMissRate.subname(i, system->getMasterName(i));
2168 }
2169
2170 demandAvgMissLatency.flags(total | nozero | nonan);
2171 demandAvgMissLatency = demandMissLatency / demandMisses;
2172 for (int i = 0; i < max_masters; i++) {
2173 demandAvgMissLatency.subname(i, system->getMasterName(i));
2174 }
2175
2176 overallAvgMissLatency.flags(total | nozero | nonan);
2177 overallAvgMissLatency = overallMissLatency / overallMisses;
2178 for (int i = 0; i < max_masters; i++) {
2179 overallAvgMissLatency.subname(i, system->getMasterName(i));
2180 }
2181
2182 blocked_cycles.init(NUM_BLOCKED_CAUSES);
2183 blocked_cycles
2184 .subname(Blocked_NoMSHRs, "no_mshrs")
2185 .subname(Blocked_NoTargets, "no_targets")
2186 ;
2187
2188
2189 blocked_causes.init(NUM_BLOCKED_CAUSES);
2190 blocked_causes
2191 .subname(Blocked_NoMSHRs, "no_mshrs")
2192 .subname(Blocked_NoTargets, "no_targets")
2193 ;
2194
2195 avg_blocked
2196 .subname(Blocked_NoMSHRs, "no_mshrs")
2197 .subname(Blocked_NoTargets, "no_targets")
2198 ;
2199 avg_blocked = blocked_cycles / blocked_causes;
2200
2201 unusedPrefetches.flags(nozero);
2202
2203 writebacks
2204 .init(max_masters)
2205 .flags(total | nozero | nonan)
2206 ;
2207 for (int i = 0; i < max_masters; i++) {
2208 writebacks.subname(i, system->getMasterName(i));
2209 }
2210
2211 demandMshrHits.flags(total | nozero | nonan);
2212 demandMshrHits = SUM_DEMAND(mshr_hits);
2213 for (int i = 0; i < max_masters; i++) {
2214 demandMshrHits.subname(i, system->getMasterName(i));
2215 }
2216
2217 overallMshrHits.flags(total | nozero | nonan);
2218 overallMshrHits = demandMshrHits + SUM_NON_DEMAND(mshr_hits);
2219 for (int i = 0; i < max_masters; i++) {
2220 overallMshrHits.subname(i, system->getMasterName(i));
2221 }
2222
2223 demandMshrMisses.flags(total | nozero | nonan);
2224 demandMshrMisses = SUM_DEMAND(mshr_misses);
2225 for (int i = 0; i < max_masters; i++) {
2226 demandMshrMisses.subname(i, system->getMasterName(i));
2227 }
2228
2229 overallMshrMisses.flags(total | nozero | nonan);
2230 overallMshrMisses = demandMshrMisses + SUM_NON_DEMAND(mshr_misses);
2231 for (int i = 0; i < max_masters; i++) {
2232 overallMshrMisses.subname(i, system->getMasterName(i));
2233 }
2234
2235 demandMshrMissLatency.flags(total | nozero | nonan);
2236 demandMshrMissLatency = SUM_DEMAND(mshr_miss_latency);
2237 for (int i = 0; i < max_masters; i++) {
2238 demandMshrMissLatency.subname(i, system->getMasterName(i));
2239 }
2240
2241 overallMshrMissLatency.flags(total | nozero | nonan);
2242 overallMshrMissLatency =
2243 demandMshrMissLatency + SUM_NON_DEMAND(mshr_miss_latency);
2244 for (int i = 0; i < max_masters; i++) {
2245 overallMshrMissLatency.subname(i, system->getMasterName(i));
2246 }
2247
2248 overallMshrUncacheable.flags(total | nozero | nonan);
2249 overallMshrUncacheable =
2250 SUM_DEMAND(mshr_uncacheable) + SUM_NON_DEMAND(mshr_uncacheable);
2251 for (int i = 0; i < max_masters; i++) {
2252 overallMshrUncacheable.subname(i, system->getMasterName(i));
2253 }
2254
2255
2256 overallMshrUncacheableLatency.flags(total | nozero | nonan);
2257 overallMshrUncacheableLatency =
2258 SUM_DEMAND(mshr_uncacheable_lat) +
2259 SUM_NON_DEMAND(mshr_uncacheable_lat);
2260 for (int i = 0; i < max_masters; i++) {
2261 overallMshrUncacheableLatency.subname(i, system->getMasterName(i));
2262 }
2263
2264 demandMshrMissRate.flags(total | nozero | nonan);
2265 demandMshrMissRate = demandMshrMisses / demandAccesses;
2266 for (int i = 0; i < max_masters; i++) {
2267 demandMshrMissRate.subname(i, system->getMasterName(i));
2268 }
2269
2270 overallMshrMissRate.flags(total | nozero | nonan);
2271 overallMshrMissRate = overallMshrMisses / overallAccesses;
2272 for (int i = 0; i < max_masters; i++) {
2273 overallMshrMissRate.subname(i, system->getMasterName(i));
2274 }
2275
2276 demandAvgMshrMissLatency.flags(total | nozero | nonan);
2277 demandAvgMshrMissLatency = demandMshrMissLatency / demandMshrMisses;
2278 for (int i = 0; i < max_masters; i++) {
2279 demandAvgMshrMissLatency.subname(i, system->getMasterName(i));
2280 }
2281
2282 overallAvgMshrMissLatency.flags(total | nozero | nonan);
2283 overallAvgMshrMissLatency = overallMshrMissLatency / overallMshrMisses;
2284 for (int i = 0; i < max_masters; i++) {
2285 overallAvgMshrMissLatency.subname(i, system->getMasterName(i));
2286 }
2287
2288 overallAvgMshrUncacheableLatency.flags(total | nozero | nonan);
2289 overallAvgMshrUncacheableLatency =
2290 overallMshrUncacheableLatency / overallMshrUncacheable;
2291 for (int i = 0; i < max_masters; i++) {
2292 overallAvgMshrUncacheableLatency.subname(i, system->getMasterName(i));
2293 }
2294
2295 dataExpansions.flags(nozero | nonan);
2296 }
2297
2298 void
2299 BaseCache::regProbePoints()
2300 {
2301 ppHit = new ProbePointArg<PacketPtr>(this->getProbeManager(), "Hit");
2302 ppMiss = new ProbePointArg<PacketPtr>(this->getProbeManager(), "Miss");
2303 ppFill = new ProbePointArg<PacketPtr>(this->getProbeManager(), "Fill");
2304 }
2305
2306 ///////////////
2307 //
2308 // CpuSidePort
2309 //
2310 ///////////////
2311 bool
2312 BaseCache::CpuSidePort::recvTimingSnoopResp(PacketPtr pkt)
2313 {
2314 // Snoops shouldn't happen when bypassing caches
2315 assert(!cache->system->bypassCaches());
2316
2317 assert(pkt->isResponse());
2318
2319 // Express snoop responses from master to slave, e.g., from L1 to L2
2320 cache->recvTimingSnoopResp(pkt);
2321 return true;
2322 }
2323
2324
2325 bool
2326 BaseCache::CpuSidePort::tryTiming(PacketPtr pkt)
2327 {
2328 if (cache->system->bypassCaches() || pkt->isExpressSnoop()) {
2329 // always let express snoop packets through even if blocked
2330 return true;
2331 } else if (blocked || mustSendRetry) {
2332 // either already committed to send a retry, or blocked
2333 mustSendRetry = true;
2334 return false;
2335 }
2336 mustSendRetry = false;
2337 return true;
2338 }
2339
2340 bool
2341 BaseCache::CpuSidePort::recvTimingReq(PacketPtr pkt)
2342 {
2343 assert(pkt->isRequest());
2344
2345 if (cache->system->bypassCaches()) {
2346 // Just forward the packet if caches are disabled.
2347 // @todo This should really enqueue the packet rather
2348 bool M5_VAR_USED success = cache->memSidePort.sendTimingReq(pkt);
2349 assert(success);
2350 return true;
2351 } else if (tryTiming(pkt)) {
2352 cache->recvTimingReq(pkt);
2353 return true;
2354 }
2355 return false;
2356 }
2357
2358 Tick
2359 BaseCache::CpuSidePort::recvAtomic(PacketPtr pkt)
2360 {
2361 if (cache->system->bypassCaches()) {
2362 // Forward the request if the system is in cache bypass mode.
2363 return cache->memSidePort.sendAtomic(pkt);
2364 } else {
2365 return cache->recvAtomic(pkt);
2366 }
2367 }
2368
2369 void
2370 BaseCache::CpuSidePort::recvFunctional(PacketPtr pkt)
2371 {
2372 if (cache->system->bypassCaches()) {
2373 // The cache should be flushed if we are in cache bypass mode,
2374 // so we don't need to check if we need to update anything.
2375 cache->memSidePort.sendFunctional(pkt);
2376 return;
2377 }
2378
2379 // functional request
2380 cache->functionalAccess(pkt, true);
2381 }
2382
2383 AddrRangeList
2384 BaseCache::CpuSidePort::getAddrRanges() const
2385 {
2386 return cache->getAddrRanges();
2387 }
2388
2389
2390 BaseCache::
2391 CpuSidePort::CpuSidePort(const std::string &_name, BaseCache *_cache,
2392 const std::string &_label)
2393 : CacheSlavePort(_name, _cache, _label), cache(_cache)
2394 {
2395 }
2396
2397 ///////////////
2398 //
2399 // MemSidePort
2400 //
2401 ///////////////
2402 bool
2403 BaseCache::MemSidePort::recvTimingResp(PacketPtr pkt)
2404 {
2405 cache->recvTimingResp(pkt);
2406 return true;
2407 }
2408
2409 // Express snooping requests to memside port
2410 void
2411 BaseCache::MemSidePort::recvTimingSnoopReq(PacketPtr pkt)
2412 {
2413 // Snoops shouldn't happen when bypassing caches
2414 assert(!cache->system->bypassCaches());
2415
2416 // handle snooping requests
2417 cache->recvTimingSnoopReq(pkt);
2418 }
2419
2420 Tick
2421 BaseCache::MemSidePort::recvAtomicSnoop(PacketPtr pkt)
2422 {
2423 // Snoops shouldn't happen when bypassing caches
2424 assert(!cache->system->bypassCaches());
2425
2426 return cache->recvAtomicSnoop(pkt);
2427 }
2428
2429 void
2430 BaseCache::MemSidePort::recvFunctionalSnoop(PacketPtr pkt)
2431 {
2432 // Snoops shouldn't happen when bypassing caches
2433 assert(!cache->system->bypassCaches());
2434
2435 // functional snoop (note that in contrast to atomic we don't have
2436 // a specific functionalSnoop method, as they have the same
2437 // behaviour regardless)
2438 cache->functionalAccess(pkt, false);
2439 }
2440
2441 void
2442 BaseCache::CacheReqPacketQueue::sendDeferredPacket()
2443 {
2444 // sanity check
2445 assert(!waitingOnRetry);
2446
2447 // there should never be any deferred request packets in the
2448 // queue, instead we resly on the cache to provide the packets
2449 // from the MSHR queue or write queue
2450 assert(deferredPacketReadyTime() == MaxTick);
2451
2452 // check for request packets (requests & writebacks)
2453 QueueEntry* entry = cache.getNextQueueEntry();
2454
2455 if (!entry) {
2456 // can happen if e.g. we attempt a writeback and fail, but
2457 // before the retry, the writeback is eliminated because
2458 // we snoop another cache's ReadEx.
2459 } else {
2460 // let our snoop responses go first if there are responses to
2461 // the same addresses
2462 if (checkConflictingSnoop(entry->getTarget()->pkt)) {
2463 return;
2464 }
2465 waitingOnRetry = entry->sendPacket(cache);
2466 }
2467
2468 // if we succeeded and are not waiting for a retry, schedule the
2469 // next send considering when the next queue is ready, note that
2470 // snoop responses have their own packet queue and thus schedule
2471 // their own events
2472 if (!waitingOnRetry) {
2473 schedSendEvent(cache.nextQueueReadyTime());
2474 }
2475 }
2476
2477 BaseCache::MemSidePort::MemSidePort(const std::string &_name,
2478 BaseCache *_cache,
2479 const std::string &_label)
2480 : CacheMasterPort(_name, _cache, _reqQueue, _snoopRespQueue),
2481 _reqQueue(*_cache, *this, _snoopRespQueue, _label),
2482 _snoopRespQueue(*_cache, *this, true, _label), cache(_cache)
2483 {
2484 }
2485
2486 void
2487 WriteAllocator::updateMode(Addr write_addr, unsigned write_size,
2488 Addr blk_addr)
2489 {
2490 // check if we are continuing where the last write ended
2491 if (nextAddr == write_addr) {
2492 delayCtr[blk_addr] = delayThreshold;
2493 // stop if we have already saturated
2494 if (mode != WriteMode::NO_ALLOCATE) {
2495 byteCount += write_size;
2496 // switch to streaming mode if we have passed the lower
2497 // threshold
2498 if (mode == WriteMode::ALLOCATE &&
2499 byteCount > coalesceLimit) {
2500 mode = WriteMode::COALESCE;
2501 DPRINTF(Cache, "Switched to write coalescing\n");
2502 } else if (mode == WriteMode::COALESCE &&
2503 byteCount > noAllocateLimit) {
2504 // and continue and switch to non-allocating mode if we
2505 // pass the upper threshold
2506 mode = WriteMode::NO_ALLOCATE;
2507 DPRINTF(Cache, "Switched to write-no-allocate\n");
2508 }
2509 }
2510 } else {
2511 // we did not see a write matching the previous one, start
2512 // over again
2513 byteCount = write_size;
2514 mode = WriteMode::ALLOCATE;
2515 resetDelay(blk_addr);
2516 }
2517 nextAddr = write_addr + write_size;
2518 }
2519
2520 WriteAllocator*
2521 WriteAllocatorParams::create()
2522 {
2523 return new WriteAllocator(this);
2524 }