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