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