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