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