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