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