base.hh revision 13746:723109f11d56
12SN/A/*
29608Sandreas.hansson@arm.com * Copyright (c) 2012-2013, 2015-2016, 2018 ARM Limited
38707Sandreas.hansson@arm.com * All rights reserved.
48707Sandreas.hansson@arm.com *
58707Sandreas.hansson@arm.com * The license below extends only to copyright in the software and shall
68707Sandreas.hansson@arm.com * not be construed as granting a license to any other intellectual
78707Sandreas.hansson@arm.com * property including but not limited to intellectual property relating
88707Sandreas.hansson@arm.com * to a hardware implementation of the functionality of the software
98707Sandreas.hansson@arm.com * licensed hereunder.  You may use the software subject to the license
108707Sandreas.hansson@arm.com * terms below provided that you ensure that this notice is replicated
118707Sandreas.hansson@arm.com * unmodified and in its entirety in all distributions of the software,
128707Sandreas.hansson@arm.com * modified or unmodified, in source code or in binary form.
138707Sandreas.hansson@arm.com *
141762SN/A * Copyright (c) 2003-2005 The Regents of The University of Michigan
157897Shestness@cs.utexas.edu * All rights reserved.
162SN/A *
172SN/A * Redistribution and use in source and binary forms, with or without
182SN/A * modification, are permitted provided that the following conditions are
192SN/A * met: redistributions of source code must retain the above copyright
202SN/A * notice, this list of conditions and the following disclaimer;
212SN/A * redistributions in binary form must reproduce the above copyright
222SN/A * notice, this list of conditions and the following disclaimer in the
232SN/A * documentation and/or other materials provided with the distribution;
242SN/A * neither the name of the copyright holders nor the names of its
252SN/A * contributors may be used to endorse or promote products derived from
262SN/A * this software without specific prior written permission.
272SN/A *
282SN/A * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
292SN/A * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
302SN/A * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
312SN/A * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
322SN/A * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
332SN/A * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
342SN/A * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
352SN/A * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
362SN/A * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
372SN/A * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
382SN/A * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
392SN/A *
402665Ssaidi@eecs.umich.edu * Authors: Erik Hallnor
412665Ssaidi@eecs.umich.edu *          Steve Reinhardt
422665Ssaidi@eecs.umich.edu *          Ron Dreslinski
437897Shestness@cs.utexas.edu *          Andreas Hansson
442SN/A *          Nikos Nikoleris
452SN/A */
461717SN/A
471717SN/A/**
482SN/A * @file
492SN/A * Declares a basic cache interface BaseCache.
502SN/A */
519850Sandreas.hansson@arm.com
529850Sandreas.hansson@arm.com#ifndef __MEM_CACHE_BASE_HH__
539850Sandreas.hansson@arm.com#define __MEM_CACHE_BASE_HH__
549850Sandreas.hansson@arm.com
559850Sandreas.hansson@arm.com#include <cassert>
569850Sandreas.hansson@arm.com#include <cstdint>
578745Sgblack@eecs.umich.edu#include <string>
584182Sgblack@eecs.umich.edu
595664Sgblack@eecs.umich.edu#include "base/addr_range.hh"
60707SN/A#include "base/statistics.hh"
618229Snate@binkert.org#include "base/trace.hh"
6256SN/A#include "base/types.hh"
638779Sgblack@eecs.umich.edu#include "debug/Cache.hh"
644776Sgblack@eecs.umich.edu#include "debug/CachePort.hh"
6510464SAndreas.Sandberg@ARM.com#include "enums/Clusivity.hh"
669814Sandreas.hansson@arm.com#include "mem/cache/cache_blk.hh"
6710529Smorr@cs.wisc.edu#include "mem/cache/mshr_queue.hh"
682SN/A#include "mem/cache/tags/base.hh"
6910529Smorr@cs.wisc.edu#include "mem/cache/write_queue.hh"
708901Sandreas.hansson@arm.com#include "mem/cache/write_queue_entry.hh"
712315SN/A#include "mem/mem_object.hh"
722680Sktlim@umich.edu#include "mem/packet.hh"
732SN/A#include "mem/packet_queue.hh"
7410529Smorr@cs.wisc.edu#include "mem/qport.hh"
7510529Smorr@cs.wisc.edu#include "mem/request.hh"
7610529Smorr@cs.wisc.edu#include "params/WriteAllocator.hh"
7710529Smorr@cs.wisc.edu#include "sim/eventq.hh"
7810529Smorr@cs.wisc.edu#include "sim/probe/probe.hh"
7910529Smorr@cs.wisc.edu#include "sim/serialize.hh"
8010529Smorr@cs.wisc.edu#include "sim/sim_exit.hh"
8110529Smorr@cs.wisc.edu#include "sim/system.hh"
8210529Smorr@cs.wisc.edu
8310529Smorr@cs.wisc.educlass BaseMasterPort;
8410529Smorr@cs.wisc.educlass BasePrefetcher;
8510529Smorr@cs.wisc.educlass BaseSlavePort;
8610529Smorr@cs.wisc.educlass MSHR;
872356SN/Aclass MasterPort;
882356SN/Aclass QueueEntry;
892356SN/Astruct BaseCacheParams;
906144Sksewell@umich.edu
912356SN/A/**
922356SN/A * A basic cache interface. Implements some common functions for speed.
936144Sksewell@umich.edu */
942356SN/Aclass BaseCache : public MemObject
952356SN/A{
966144Sksewell@umich.edu  protected:
972356SN/A    /**
982356SN/A     * Indexes to enumerate the MSHR queues.
992356SN/A     */
1006144Sksewell@umich.edu    enum MSHRQueueIndex {
1016144Sksewell@umich.edu        MSHRQueue_MSHRs,
1026144Sksewell@umich.edu        MSHRQueue_WriteBuffer
1036144Sksewell@umich.edu    };
1046144Sksewell@umich.edu
1055336Shines@cs.fsu.edu  public:
1062356SN/A    /**
1072356SN/A     * Reasons for caches to be blocked.
1082856Srdreslin@umich.edu     */
1092SN/A    enum BlockedCause {
1101634SN/A        Blocked_NoMSHRs = MSHRQueue_MSHRs,
1119157Sandreas.hansson@arm.com        Blocked_NoWBBuffers = MSHRQueue_WriteBuffer,
11210662SAli.Saidi@ARM.com        Blocked_NoTargets,
11310662SAli.Saidi@ARM.com        NUM_BLOCKED_CAUSES
1143814Ssaidi@eecs.umich.edu    };
11510662SAli.Saidi@ARM.com
1165712Shsul@eecs.umich.edu  protected:
1175712Shsul@eecs.umich.edu
1185715Shsul@eecs.umich.edu    /**
1195712Shsul@eecs.umich.edu     * A cache master port is used for the memory-side port of the
1205712Shsul@eecs.umich.edu     * cache, and in addition to the basic timing port that only sends
1211634SN/A     * response packets through a transmit list, it also offers the
12210190Sakash.bagdia@arm.com     * ability to schedule and send request packets (requests &
12310190Sakash.bagdia@arm.com     * writebacks). The send event is scheduled through schedSendEvent,
12410190Sakash.bagdia@arm.com     * and the sendDeferredPacket of the timing port is modified to
12510190Sakash.bagdia@arm.com     * consider both the transmit list and the requests from the MSHR.
12610190Sakash.bagdia@arm.com     */
12710190Sakash.bagdia@arm.com    class CacheMasterPort : public QueuedMasterPort
12810190Sakash.bagdia@arm.com    {
1298832SAli.Saidi@ARM.com
1308832SAli.Saidi@ARM.com      public:
1318832SAli.Saidi@ARM.com
1328832SAli.Saidi@ARM.com        /**
1338832SAli.Saidi@ARM.com         * Schedule a send of a request packet (from the MSHR). Note
1348832SAli.Saidi@ARM.com         * that we could already have a retry outstanding.
1359332Sdam.sunwoo@arm.com         */
1369332Sdam.sunwoo@arm.com        void schedSendEvent(Tick time)
1379332Sdam.sunwoo@arm.com        {
1389332Sdam.sunwoo@arm.com            DPRINTF(CachePort, "Scheduling send event at %llu\n", time);
1399332Sdam.sunwoo@arm.com            reqQueue.schedSendEvent(time);
1409332Sdam.sunwoo@arm.com        }
1419332Sdam.sunwoo@arm.com
1429332Sdam.sunwoo@arm.com      protected:
1439332Sdam.sunwoo@arm.com
1449332Sdam.sunwoo@arm.com        CacheMasterPort(const std::string &_name, BaseCache *_cache,
1459332Sdam.sunwoo@arm.com                        ReqPacketQueue &_reqQueue,
1469430SAndreas.Sandberg@ARM.com                        SnoopRespPacketQueue &_snoopRespQueue) :
1479430SAndreas.Sandberg@ARM.com            QueuedMasterPort(_name, _cache, _reqQueue, _snoopRespQueue)
1489430SAndreas.Sandberg@ARM.com        { }
1499814Sandreas.hansson@arm.com
1509814Sandreas.hansson@arm.com        /**
1519814Sandreas.hansson@arm.com         * Memory-side port always snoops.
1521634SN/A         *
1538850Sandreas.hansson@arm.com         * @return always true
1548850Sandreas.hansson@arm.com         */
1558850Sandreas.hansson@arm.com        virtual bool isSnooping() const { return true; }
1568850Sandreas.hansson@arm.com    };
1578850Sandreas.hansson@arm.com
1588850Sandreas.hansson@arm.com    /**
1598850Sandreas.hansson@arm.com     * Override the default behaviour of sendDeferredPacket to enable
1609608Sandreas.hansson@arm.com     * the memory-side cache port to also send requests based on the
1618850Sandreas.hansson@arm.com     * current MSHR status. This queue has a pointer to our specific
1628850Sandreas.hansson@arm.com     * cache implementation and is used by the MemSidePort.
1638850Sandreas.hansson@arm.com     */
1648850Sandreas.hansson@arm.com    class CacheReqPacketQueue : public ReqPacketQueue
1658850Sandreas.hansson@arm.com    {
1668850Sandreas.hansson@arm.com
1678850Sandreas.hansson@arm.com      protected:
1689608Sandreas.hansson@arm.com
1698850Sandreas.hansson@arm.com        BaseCache &cache;
1705712Shsul@eecs.umich.edu        SnoopRespPacketQueue &snoopRespQueue;
17110110Sandreas.hansson@arm.com
1725712Shsul@eecs.umich.edu      public:
17310190Sakash.bagdia@arm.com
17410190Sakash.bagdia@arm.com        CacheReqPacketQueue(BaseCache &cache, MasterPort &port,
17510190Sakash.bagdia@arm.com                            SnoopRespPacketQueue &snoop_resp_queue,
1768832SAli.Saidi@ARM.com                            const std::string &label) :
1778832SAli.Saidi@ARM.com            ReqPacketQueue(cache, port, label), cache(cache),
1788832SAli.Saidi@ARM.com            snoopRespQueue(snoop_resp_queue) { }
1798832SAli.Saidi@ARM.com
1808832SAli.Saidi@ARM.com        /**
1818850Sandreas.hansson@arm.com         * Override the normal sendDeferredPacket and do not only
1828926Sandreas.hansson@arm.com         * consider the transmit list (used for responses), but also
1838926Sandreas.hansson@arm.com         * requests.
1848926Sandreas.hansson@arm.com         */
1858850Sandreas.hansson@arm.com        virtual void sendDeferredPacket();
1868850Sandreas.hansson@arm.com
1878850Sandreas.hansson@arm.com        /**
1888850Sandreas.hansson@arm.com         * Check if there is a conflicting snoop response about to be
1898922Swilliam.wang@arm.com         * send out, and if so simply stall any requests, and schedule
1908850Sandreas.hansson@arm.com         * a send event at the same time as the next snoop response is
1919294Sandreas.hansson@arm.com         * being sent out.
19211169Sandreas.hansson@arm.com         */
1938850Sandreas.hansson@arm.com        bool checkConflictingSnoop(Addr addr)
1949332Sdam.sunwoo@arm.com        {
1959332Sdam.sunwoo@arm.com            if (snoopRespQueue.hasAddr(addr)) {
1969332Sdam.sunwoo@arm.com                DPRINTF(CachePort, "Waiting for snoop response to be "
1979332Sdam.sunwoo@arm.com                        "sent\n");
1989332Sdam.sunwoo@arm.com                Tick when = snoopRespQueue.deferredPacketReadyTime();
1999332Sdam.sunwoo@arm.com                schedSendEvent(when);
2009332Sdam.sunwoo@arm.com                return true;
2019332Sdam.sunwoo@arm.com            }
2027914SBrad.Beckmann@amd.com            return false;
2037914SBrad.Beckmann@amd.com        }
2043814Ssaidi@eecs.umich.edu    };
2053814Ssaidi@eecs.umich.edu
2061634SN/A
2075664Sgblack@eecs.umich.edu    /**
2085664Sgblack@eecs.umich.edu     * The memory-side port extends the base cache master port with
2092SN/A     * access functions for functional, atomic and timing snoops.
21011150Smitch.hayenga@arm.com     */
2112SN/A    class MemSidePort : public CacheMasterPort
2122SN/A    {
2135645Sgblack@eecs.umich.edu      private:
21411150Smitch.hayenga@arm.com
2155645Sgblack@eecs.umich.edu        /** The cache-specific queue. */
21611150Smitch.hayenga@arm.com        CacheReqPacketQueue _reqQueue;
21711150Smitch.hayenga@arm.com
21811150Smitch.hayenga@arm.com        SnoopRespPacketQueue _snoopRespQueue;
21911150Smitch.hayenga@arm.com
22011150Smitch.hayenga@arm.com        // a pointer to our specific cache implementation
2215645Sgblack@eecs.umich.edu        BaseCache *cache;
2225645Sgblack@eecs.umich.edu
22311151Smitch.hayenga@arm.com      protected:
2245807Snate@binkert.org
2255807Snate@binkert.org        virtual void recvTimingSnoopReq(PacketPtr pkt);
22611150Smitch.hayenga@arm.com
2275807Snate@binkert.org        virtual bool recvTimingResp(PacketPtr pkt);
22811150Smitch.hayenga@arm.com
2298779Sgblack@eecs.umich.edu        virtual Tick recvAtomicSnoop(PacketPtr pkt);
23011151Smitch.hayenga@arm.com
2315807Snate@binkert.org        virtual void recvFunctionalSnoop(PacketPtr pkt);
2325807Snate@binkert.org
2335807Snate@binkert.org      public:
23411150Smitch.hayenga@arm.com
2355807Snate@binkert.org        MemSidePort(const std::string &_name, BaseCache *_cache,
23611150Smitch.hayenga@arm.com                    const std::string &_label);
2375807Snate@binkert.org    };
2385807Snate@binkert.org
2395807Snate@binkert.org    /**
24011150Smitch.hayenga@arm.com     * A cache slave port is used for the CPU-side port of the cache,
2415807Snate@binkert.org     * and it is basically a simple timing port that uses a transmit
24211150Smitch.hayenga@arm.com     * list for responses to the CPU (or connected master). In
2435807Snate@binkert.org     * addition, it has the functionality to block the port for
2442SN/A     * incoming requests. If blocked, the port will issue a retry once
2455704Snate@binkert.org     * unblocked.
2465704Snate@binkert.org     */
2475704Snate@binkert.org    class CacheSlavePort : public QueuedSlavePort
24811150Smitch.hayenga@arm.com    {
2495704Snate@binkert.org
2501917SN/A      public:
2511917SN/A
2521917SN/A        /** Do not accept any new requests. */
2531917SN/A        void setBlocked();
2541917SN/A
2555536Srstrong@hp.com        /** Return to normal operation and accept new requests. */
2561917SN/A        void clearBlocked();
2571917SN/A
2585536Srstrong@hp.com        bool isBlocked() const { return blocked; }
2591917SN/A
2601917SN/A      protected:
2611917SN/A
2622SN/A        CacheSlavePort(const std::string &_name, BaseCache *_cache,
2632SN/A                       const std::string &_label);
2642680Sktlim@umich.edu
2652SN/A        /** A normal packet queue used to store responses. */
2664776Sgblack@eecs.umich.edu        RespPacketQueue queue;
2674776Sgblack@eecs.umich.edu
2682SN/A        bool blocked;
269393SN/A
27011050Sandreas.hansson@arm.com        bool mustSendRetry;
27111050Sandreas.hansson@arm.com
27211050Sandreas.hansson@arm.com      private:
27311050Sandreas.hansson@arm.com
27411050Sandreas.hansson@arm.com        void processSendRetry();
2757764Sgblack@eecs.umich.edu
2767764Sgblack@eecs.umich.edu        EventFunctionWrapper sendRetryEvent;
2777764Sgblack@eecs.umich.edu
2784776Sgblack@eecs.umich.edu    };
2794776Sgblack@eecs.umich.edu
2804776Sgblack@eecs.umich.edu    /**
28110407Smitch.hayenga@arm.com     * The CPU-side port extends the base cache slave port with access
28211526Sdavid.guillen@arm.com     * functions for functional, atomic and timing requests.
283393SN/A     */
284393SN/A    class CpuSidePort : public CacheSlavePort
28511526Sdavid.guillen@arm.com    {
28611526Sdavid.guillen@arm.com      private:
287393SN/A
288393SN/A        // a pointer to our specific cache implementation
2898737Skoansin.tan@gmail.com        BaseCache *cache;
2902SN/A
2914000Ssaidi@eecs.umich.edu      protected:
2924000Ssaidi@eecs.umich.edu        virtual bool recvTimingSnoopResp(PacketPtr pkt) override;
2934000Ssaidi@eecs.umich.edu
2944000Ssaidi@eecs.umich.edu        virtual bool tryTiming(PacketPtr pkt) override;
2959652SAndreas.Sandberg@ARM.com
2964000Ssaidi@eecs.umich.edu        virtual bool recvTimingReq(PacketPtr pkt) override;
29710030SAli.Saidi@ARM.com
29810030SAli.Saidi@ARM.com        virtual Tick recvAtomic(PacketPtr pkt) override;
29910030SAli.Saidi@ARM.com
30011435Smitch.hayenga@arm.com        virtual void recvFunctional(PacketPtr pkt) override;
30111435Smitch.hayenga@arm.com
30211435Smitch.hayenga@arm.com        virtual AddrRangeList getAddrRanges() const override;
30311435Smitch.hayenga@arm.com
3042SN/A      public:
3055529Snate@binkert.org
3065529Snate@binkert.org        CpuSidePort(const std::string &_name, BaseCache *_cache,
3075529Snate@binkert.org                    const std::string &_label);
3088876Sandreas.hansson@arm.com
3091191SN/A    };
3102SN/A
31111169Sandreas.hansson@arm.com    CpuSidePort cpuSidePort;
31211169Sandreas.hansson@arm.com    MemSidePort memSidePort;
31311169Sandreas.hansson@arm.com
3142SN/A  protected:
31511168Sandreas.hansson@arm.com
31610464SAndreas.Sandberg@ARM.com    /** Miss status registers */
3172680Sktlim@umich.edu    MSHRQueue mshrQueue;
318180SN/A
3199254SAndreas.Sandberg@arm.com    /** Write/writeback buffer */
3209254SAndreas.Sandberg@arm.com    WriteQueue writeBuffer;
3219254SAndreas.Sandberg@arm.com
3229254SAndreas.Sandberg@arm.com    /** Tag and data Storage */
3239254SAndreas.Sandberg@arm.com    BaseTags *tags;
3249254SAndreas.Sandberg@arm.com
3259254SAndreas.Sandberg@arm.com    /** Prefetcher */
3262798Sktlim@umich.edu    BasePrefetcher *prefetcher;
327180SN/A
3289254SAndreas.Sandberg@arm.com    /** To probe when a cache hit occurs */
3299254SAndreas.Sandberg@arm.com    ProbePointArg<PacketPtr> *ppHit;
3309254SAndreas.Sandberg@arm.com
3319254SAndreas.Sandberg@arm.com    /** To probe when a cache miss occurs */
3329254SAndreas.Sandberg@arm.com    ProbePointArg<PacketPtr> *ppMiss;
3339254SAndreas.Sandberg@arm.com
3349254SAndreas.Sandberg@arm.com    /** To probe when a cache fill occurs */
3359254SAndreas.Sandberg@arm.com    ProbePointArg<PacketPtr> *ppFill;
3369254SAndreas.Sandberg@arm.com
3379254SAndreas.Sandberg@arm.com    /**
3389254SAndreas.Sandberg@arm.com     * The writeAllocator drive optimizations for streaming writes.
3399254SAndreas.Sandberg@arm.com     * It first determines whether a WriteReq MSHR should be delayed,
340180SN/A     * thus ensuring that we wait longer in cases when we are write
341124SN/A     * coalescing and allowing all the bytes of the line to be written
3429446SAndreas.Sandberg@ARM.com     * before the MSHR packet is sent downstream. This works in unison
3439446SAndreas.Sandberg@ARM.com     * with the tracking in the MSHR to check if the entire line is
3449446SAndreas.Sandberg@ARM.com     * written. The write mode also affects the behaviour on filling
3459446SAndreas.Sandberg@ARM.com     * any whole-line writes. Normally the cache allocates the line
3469446SAndreas.Sandberg@ARM.com     * when receiving the InvalidateResp, but after seeing enough
3479446SAndreas.Sandberg@ARM.com     * consecutive lines we switch to using the tempBlock, and thus
3489446SAndreas.Sandberg@ARM.com     * end up not allocating the line, and instead turning the
3499446SAndreas.Sandberg@ARM.com     * whole-line write into a writeback straight away.
3509446SAndreas.Sandberg@ARM.com     */
3519446SAndreas.Sandberg@ARM.com    WriteAllocator * const writeAllocator;
3529446SAndreas.Sandberg@ARM.com
3539430SAndreas.Sandberg@ARM.com    /**
3549430SAndreas.Sandberg@ARM.com     * Temporary cache block for occasional transitory use.  We use
3559430SAndreas.Sandberg@ARM.com     * the tempBlock to fill when allocation fails (e.g., when there
3569430SAndreas.Sandberg@ARM.com     * is an outstanding request that accesses the victim block) or
3579430SAndreas.Sandberg@ARM.com     * when we want to avoid allocation (e.g., exclusive caches)
3589430SAndreas.Sandberg@ARM.com     */
3599430SAndreas.Sandberg@ARM.com    TempCacheBlk *tempBlock;
3609523SAndreas.Sandberg@ARM.com
3619523SAndreas.Sandberg@ARM.com    /**
3629523SAndreas.Sandberg@ARM.com     * Upstream caches need this packet until true is returned, so
3639523SAndreas.Sandberg@ARM.com     * hold it for deletion until a subsequent call
3649523SAndreas.Sandberg@ARM.com     */
3659523SAndreas.Sandberg@ARM.com    std::unique_ptr<Packet> pendingDelete;
3669523SAndreas.Sandberg@ARM.com
3679523SAndreas.Sandberg@ARM.com    /**
3689523SAndreas.Sandberg@ARM.com     * Mark a request as in service (sent downstream in the memory
3699523SAndreas.Sandberg@ARM.com     * system), effectively making this MSHR the ordering point.
3709523SAndreas.Sandberg@ARM.com     */
371124SN/A    void markInService(MSHR *mshr, bool pending_modified_resp)
372124SN/A    {
373124SN/A        bool wasFull = mshrQueue.isFull();
3746221Snate@binkert.org        mshrQueue.markInService(mshr, pending_modified_resp);
3752SN/A
376124SN/A        if (wasFull && !mshrQueue.isFull()) {
377124SN/A            clearBlocked(Blocked_NoMSHRs);
378124SN/A        }
379124SN/A    }
380124SN/A
381503SN/A    void markInService(WriteQueueEntry *entry)
3822SN/A    {
383124SN/A        bool wasFull = writeBuffer.isFull();
384124SN/A        writeBuffer.markInService(entry);
385124SN/A
386124SN/A        if (wasFull && !writeBuffer.isFull()) {
387124SN/A            clearBlocked(Blocked_NoWBBuffers);
388124SN/A        }
389124SN/A    }
3902SN/A
391921SN/A    /**
392921SN/A     * Determine whether we should allocate on a fill or not. If this
3939814Sandreas.hansson@arm.com     * cache is mostly inclusive with regards to the upstream cache(s)
3949814Sandreas.hansson@arm.com     * we always allocate (for any non-forwarded and cacheable
3959814Sandreas.hansson@arm.com     * requests). In the case of a mostly exclusive cache, we allocate
3969814Sandreas.hansson@arm.com     * on fill if the packet did not come from a cache, thus if we:
3979814Sandreas.hansson@arm.com     * are dealing with a whole-line write (the latter behaves much
398921SN/A     * like a writeback), the original target packet came from a
3999448SAndreas.Sandberg@ARM.com     * non-caching source, or if we are performing a prefetch or LLSC.
4009448SAndreas.Sandberg@ARM.com     *
4019448SAndreas.Sandberg@ARM.com     * @param cmd Command of the incoming requesting packet
4029448SAndreas.Sandberg@ARM.com     * @return Whether we should allocate on the fill
4039448SAndreas.Sandberg@ARM.com     */
4049448SAndreas.Sandberg@ARM.com    inline bool allocOnFill(MemCmd cmd) const
405921SN/A    {
406921SN/A        return clusivity == Enums::mostly_incl ||
40711168Sandreas.hansson@arm.com            cmd == MemCmd::WriteLineReq ||
408921SN/A            cmd == MemCmd::ReadReq ||
409921SN/A            cmd == MemCmd::WriteReq ||
410921SN/A            cmd.isPrefetch() ||
4119448SAndreas.Sandberg@ARM.com            cmd.isLLSC();
4129448SAndreas.Sandberg@ARM.com    }
4139448SAndreas.Sandberg@ARM.com
4149448SAndreas.Sandberg@ARM.com    /**
4159448SAndreas.Sandberg@ARM.com     * Regenerate block address using tags.
4169448SAndreas.Sandberg@ARM.com     * Block address regeneration depends on whether we're using a temporary
417921SN/A     * block or not.
4189448SAndreas.Sandberg@ARM.com     *
419921SN/A     * @param blk The block to regenerate address.
42011168Sandreas.hansson@arm.com     * @return The block's address.
421921SN/A     */
422124SN/A    Addr regenerateBlkAddr(CacheBlk* blk);
4239448SAndreas.Sandberg@ARM.com
4249448SAndreas.Sandberg@ARM.com    /**
4259448SAndreas.Sandberg@ARM.com     * Calculate access latency in ticks given a tag lookup latency, and
4269448SAndreas.Sandberg@ARM.com     * whether access was a hit or miss.
4279448SAndreas.Sandberg@ARM.com     *
42810905Sandreas.sandberg@arm.com     * @param blk The cache block that was accessed.
4299448SAndreas.Sandberg@ARM.com     * @param delay The delay until the packet's metadata is present.
4309448SAndreas.Sandberg@ARM.com     * @param lookup_lat Latency of the respective tag lookup.
4319448SAndreas.Sandberg@ARM.com     * @return The number of ticks that pass due to a block access.
4329448SAndreas.Sandberg@ARM.com     */
4339448SAndreas.Sandberg@ARM.com    Cycles calculateAccessLatency(const CacheBlk* blk, const uint32_t delay,
4349448SAndreas.Sandberg@ARM.com                                  const Cycles lookup_lat) const;
4359448SAndreas.Sandberg@ARM.com
4369448SAndreas.Sandberg@ARM.com    /**
43710905Sandreas.sandberg@arm.com     * Does all the processing necessary to perform the provided request.
4389448SAndreas.Sandberg@ARM.com     * @param pkt The memory request to perform.
4398834Satgutier@umich.edu     * @param blk The cache block to be updated.
4408834Satgutier@umich.edu     * @param lat The latency of the access.
4418834Satgutier@umich.edu     * @param writebacks List for any writebacks that need to be performed.
442707SN/A     * @return Boolean indicating whether the request was satisfied.
4439749Sandreas@sandberg.pp.se     */
4449749Sandreas@sandberg.pp.se    virtual bool access(PacketPtr pkt, CacheBlk *&blk, Cycles &lat,
4459749Sandreas@sandberg.pp.se                        PacketList &writebacks);
4469749Sandreas@sandberg.pp.se
4479749Sandreas@sandberg.pp.se    /*
4489749Sandreas@sandberg.pp.se     * Handle a timing request that hit in the cache
4499749Sandreas@sandberg.pp.se     *
4509749Sandreas@sandberg.pp.se     * @param ptk The request packet
4519749Sandreas@sandberg.pp.se     * @param blk The referenced block
4529749Sandreas@sandberg.pp.se     * @param request_time The tick at which the block lookup is compete
4539749Sandreas@sandberg.pp.se     */
4549749Sandreas@sandberg.pp.se    virtual void handleTimingReqHit(PacketPtr pkt, CacheBlk *blk,
4559749Sandreas@sandberg.pp.se                                    Tick request_time);
4569749Sandreas@sandberg.pp.se
4579749Sandreas@sandberg.pp.se    /*
4589749Sandreas@sandberg.pp.se     * Handle a timing request that missed in the cache
4599749Sandreas@sandberg.pp.se     *
4609749Sandreas@sandberg.pp.se     * Implementation specific handling for different cache
4619749Sandreas@sandberg.pp.se     * implementations
4629749Sandreas@sandberg.pp.se     *
4639749Sandreas@sandberg.pp.se     * @param ptk The request packet
4649749Sandreas@sandberg.pp.se     * @param blk The referenced block
4659749Sandreas@sandberg.pp.se     * @param forward_time The tick at which we can process dependent requests
4669749Sandreas@sandberg.pp.se     * @param request_time The tick at which the block lookup is compete
4679749Sandreas@sandberg.pp.se     */
4689749Sandreas@sandberg.pp.se    virtual void handleTimingReqMiss(PacketPtr pkt, CacheBlk *blk,
4699749Sandreas@sandberg.pp.se                                     Tick forward_time,
4709749Sandreas@sandberg.pp.se                                     Tick request_time) = 0;
4719749Sandreas@sandberg.pp.se
4729749Sandreas@sandberg.pp.se    /*
47311415SGeoffrey.Blake@arm.com     * Handle a timing request that missed in the cache
47411415SGeoffrey.Blake@arm.com     *
47511415SGeoffrey.Blake@arm.com     * Common functionality across different cache implementations
47611415SGeoffrey.Blake@arm.com     *
47711415SGeoffrey.Blake@arm.com     * @param ptk The request packet
47811415SGeoffrey.Blake@arm.com     * @param blk The referenced block
47911415SGeoffrey.Blake@arm.com     * @param mshr Any existing mshr for the referenced cache block
48011415SGeoffrey.Blake@arm.com     * @param forward_time The tick at which we can process dependent requests
48111415SGeoffrey.Blake@arm.com     * @param request_time The tick at which the block lookup is compete
48210464SAndreas.Sandberg@ARM.com     */
48310464SAndreas.Sandberg@ARM.com    void handleTimingReqMiss(PacketPtr pkt, MSHR *mshr, CacheBlk *blk,
48410464SAndreas.Sandberg@ARM.com                             Tick forward_time, Tick request_time);
48510464SAndreas.Sandberg@ARM.com
48610464SAndreas.Sandberg@ARM.com    /**
48710464SAndreas.Sandberg@ARM.com     * Performs the access specified by the request.
48810464SAndreas.Sandberg@ARM.com     * @param pkt The request to perform.
48910464SAndreas.Sandberg@ARM.com     */
49010464SAndreas.Sandberg@ARM.com    virtual void recvTimingReq(PacketPtr pkt);
49110464SAndreas.Sandberg@ARM.com
49210464SAndreas.Sandberg@ARM.com    /**
49310464SAndreas.Sandberg@ARM.com     * Handling the special case of uncacheable write responses to
49410464SAndreas.Sandberg@ARM.com     * make recvTimingResp less cluttered.
49510464SAndreas.Sandberg@ARM.com     */
49610464SAndreas.Sandberg@ARM.com    void handleUncacheableWriteResp(PacketPtr pkt);
49710464SAndreas.Sandberg@ARM.com
49810464SAndreas.Sandberg@ARM.com    /**
49910464SAndreas.Sandberg@ARM.com     * Service non-deferred MSHR targets using the received response
50010464SAndreas.Sandberg@ARM.com     *
50110464SAndreas.Sandberg@ARM.com     * Iterates through the list of targets that can be serviced with
50210464SAndreas.Sandberg@ARM.com     * the current response.
50310464SAndreas.Sandberg@ARM.com     *
50410464SAndreas.Sandberg@ARM.com     * @param mshr The MSHR that corresponds to the reponse
50510464SAndreas.Sandberg@ARM.com     * @param pkt The response packet
50610464SAndreas.Sandberg@ARM.com     * @param blk The reference block
50710464SAndreas.Sandberg@ARM.com     */
50810464SAndreas.Sandberg@ARM.com    virtual void serviceMSHRTargets(MSHR *mshr, const PacketPtr pkt,
50910464SAndreas.Sandberg@ARM.com                                    CacheBlk *blk) = 0;
51010464SAndreas.Sandberg@ARM.com
51110464SAndreas.Sandberg@ARM.com    /**
51210464SAndreas.Sandberg@ARM.com     * Handles a response (cache line fill/write ack) from the bus.
51310464SAndreas.Sandberg@ARM.com     * @param pkt The response packet
51410464SAndreas.Sandberg@ARM.com     */
51510464SAndreas.Sandberg@ARM.com    virtual void recvTimingResp(PacketPtr pkt);
51610464SAndreas.Sandberg@ARM.com
51710464SAndreas.Sandberg@ARM.com    /**
51810464SAndreas.Sandberg@ARM.com     * Snoops bus transactions to maintain coherence.
51910464SAndreas.Sandberg@ARM.com     * @param pkt The current bus transaction.
52010464SAndreas.Sandberg@ARM.com     */
52110464SAndreas.Sandberg@ARM.com    virtual void recvTimingSnoopReq(PacketPtr pkt) = 0;
52210464SAndreas.Sandberg@ARM.com
52310464SAndreas.Sandberg@ARM.com    /**
52410464SAndreas.Sandberg@ARM.com     * Handle a snoop response.
52510464SAndreas.Sandberg@ARM.com     * @param pkt Snoop response packet
52610464SAndreas.Sandberg@ARM.com     */
52710464SAndreas.Sandberg@ARM.com    virtual void recvTimingSnoopResp(PacketPtr pkt) = 0;
52810464SAndreas.Sandberg@ARM.com
52910464SAndreas.Sandberg@ARM.com    /**
5301191SN/A     * Handle a request in atomic mode that missed in this cache
5311191SN/A     *
5321191SN/A     * Creates a downstream request, sends it to the memory below and
5331191SN/A     * handles the response. As we are in atomic mode all operations
5341191SN/A     * are performed immediately.
5351191SN/A     *
5361191SN/A     * @param pkt The packet with the requests
5371191SN/A     * @param blk The referenced block
5381191SN/A     * @param writebacks A list with packets for any performed writebacks
5391191SN/A     * @return Cycles for handling the request
5408662SAli.Saidi@ARM.com     */
5418662SAli.Saidi@ARM.com    virtual Cycles handleAtomicReqMiss(PacketPtr pkt, CacheBlk *&blk,
5428662SAli.Saidi@ARM.com                                       PacketList &writebacks) = 0;
5438662SAli.Saidi@ARM.com
5441191SN/A    /**
5451191SN/A     * Performs the access specified by the request.
5461191SN/A     * @param pkt The request to perform.
5471191SN/A     * @return The number of ticks required for the access.
5481191SN/A     */
5491191SN/A    virtual Tick recvAtomic(PacketPtr pkt);
5502SN/A
5518834Satgutier@umich.edu    /**
552707SN/A     * Snoop for the provided request in the cache and return the estimated
553707SN/A     * time taken.
554707SN/A     * @param pkt The memory request to snoop
555707SN/A     * @return The number of ticks required for the snoop.
556707SN/A     */
5578834Satgutier@umich.edu    virtual Tick recvAtomicSnoop(PacketPtr pkt) = 0;
5588834Satgutier@umich.edu
5598834Satgutier@umich.edu    /**
5608834Satgutier@umich.edu     * Performs the access specified by the request.
5618834Satgutier@umich.edu     *
5628834Satgutier@umich.edu     * @param pkt The request to perform.
5638834Satgutier@umich.edu     * @param fromCpuSide from the CPU side port or the memory side port
5648834Satgutier@umich.edu     */
5658834Satgutier@umich.edu    virtual void functionalAccess(PacketPtr pkt, bool from_cpu_side);
5668834Satgutier@umich.edu
5678834Satgutier@umich.edu    /**
5688834Satgutier@umich.edu     * Handle doing the Compare and Swap function for SPARC.
569707SN/A     */
570707SN/A    void cmpAndSwap(CacheBlk *blk, PacketPtr pkt);
571707SN/A
572707SN/A    /**
573707SN/A     * Return the next queue entry to service, either a pending miss
574707SN/A     * from the MSHR queue, a buffered write from the write buffer, or
5755999Snate@binkert.org     * something from the prefetcher. This function is responsible
5767914SBrad.Beckmann@amd.com     * for prioritizing among those sources on the fly.
5777914SBrad.Beckmann@amd.com     */
57810529Smorr@cs.wisc.edu    QueueEntry* getNextQueueEntry();
57910529Smorr@cs.wisc.edu
58011148Smitch.hayenga@arm.com    /**
58110529Smorr@cs.wisc.edu     * Insert writebacks into the write buffer
58210529Smorr@cs.wisc.edu     */
58311148Smitch.hayenga@arm.com    virtual void doWritebacks(PacketList& writebacks, Tick forward_time) = 0;
58411148Smitch.hayenga@arm.com
58511148Smitch.hayenga@arm.com    /**
58611148Smitch.hayenga@arm.com     * Send writebacks down the memory hierarchy in atomic mode
58711148Smitch.hayenga@arm.com     */
58811148Smitch.hayenga@arm.com    virtual void doWritebacksAtomic(PacketList& writebacks) = 0;
58911148Smitch.hayenga@arm.com
59011148Smitch.hayenga@arm.com    /**
59111877Sbrandon.potter@amd.com     * Create an appropriate downstream bus request packet.
59212122Sjose.marinho@arm.com     *
59312122Sjose.marinho@arm.com     * Creates a new packet with the request to be send to the memory
59411877Sbrandon.potter@amd.com     * below, or nullptr if the current request in cpu_pkt should just
5952SN/A     * be forwarded on.
5962SN/A     *
5979850Sandreas.hansson@arm.com     * @param cpu_pkt The miss packet that needs to be satisfied.
5989850Sandreas.hansson@arm.com     * @param blk The referenced block, can be nullptr.
5991717SN/A     * @param needs_writable Indicates that the block must be writable
600     * even if the request in cpu_pkt doesn't indicate that.
601     * @param is_whole_line_write True if there are writes for the
602     * whole line
603     * @return A packet send to the memory below
604     */
605    virtual PacketPtr createMissPacket(PacketPtr cpu_pkt, CacheBlk *blk,
606                                       bool needs_writable,
607                                       bool is_whole_line_write) const = 0;
608
609    /**
610     * Determine if clean lines should be written back or not. In
611     * cases where a downstream cache is mostly inclusive we likely
612     * want it to act as a victim cache also for lines that have not
613     * been modified. Hence, we cannot simply drop the line (or send a
614     * clean evict), but rather need to send the actual data.
615     */
616    const bool writebackClean;
617
618    /**
619     * Writebacks from the tempBlock, resulting on the response path
620     * in atomic mode, must happen after the call to recvAtomic has
621     * finished (for the right ordering of the packets). We therefore
622     * need to hold on to the packets, and have a method and an event
623     * to send them.
624     */
625    PacketPtr tempBlockWriteback;
626
627    /**
628     * Send the outstanding tempBlock writeback. To be called after
629     * recvAtomic finishes in cases where the block we filled is in
630     * fact the tempBlock, and now needs to be written back.
631     */
632    void writebackTempBlockAtomic() {
633        assert(tempBlockWriteback != nullptr);
634        PacketList writebacks{tempBlockWriteback};
635        doWritebacksAtomic(writebacks);
636        tempBlockWriteback = nullptr;
637    }
638
639    /**
640     * An event to writeback the tempBlock after recvAtomic
641     * finishes. To avoid other calls to recvAtomic getting in
642     * between, we create this event with a higher priority.
643     */
644    EventFunctionWrapper writebackTempBlockAtomicEvent;
645
646    /**
647     * Perform any necessary updates to the block and perform any data
648     * exchange between the packet and the block. The flags of the
649     * packet are also set accordingly.
650     *
651     * @param pkt Request packet from upstream that hit a block
652     * @param blk Cache block that the packet hit
653     * @param deferred_response Whether this request originally missed
654     * @param pending_downgrade Whether the writable flag is to be removed
655     */
656    virtual void satisfyRequest(PacketPtr pkt, CacheBlk *blk,
657                                bool deferred_response = false,
658                                bool pending_downgrade = false);
659
660    /**
661     * Maintain the clusivity of this cache by potentially
662     * invalidating a block. This method works in conjunction with
663     * satisfyRequest, but is separate to allow us to handle all MSHR
664     * targets before potentially dropping a block.
665     *
666     * @param from_cache Whether we have dealt with a packet from a cache
667     * @param blk The block that should potentially be dropped
668     */
669    void maintainClusivity(bool from_cache, CacheBlk *blk);
670
671    /**
672     * Handle a fill operation caused by a received packet.
673     *
674     * Populates a cache block and handles all outstanding requests for the
675     * satisfied fill request. This version takes two memory requests. One
676     * contains the fill data, the other is an optional target to satisfy.
677     * Note that the reason we return a list of writebacks rather than
678     * inserting them directly in the write buffer is that this function
679     * is called by both atomic and timing-mode accesses, and in atomic
680     * mode we don't mess with the write buffer (we just perform the
681     * writebacks atomically once the original request is complete).
682     *
683     * @param pkt The memory request with the fill data.
684     * @param blk The cache block if it already exists.
685     * @param writebacks List for any writebacks that need to be performed.
686     * @param allocate Whether to allocate a block or use the temp block
687     * @return Pointer to the new cache block.
688     */
689    CacheBlk *handleFill(PacketPtr pkt, CacheBlk *blk,
690                         PacketList &writebacks, bool allocate);
691
692    /**
693     * Allocate a new block and perform any necessary writebacks
694     *
695     * Find a victim block and if necessary prepare writebacks for any
696     * existing data. May return nullptr if there are no replaceable
697     * blocks. If a replaceable block is found, it inserts the new block in
698     * its place. The new block, however, is not set as valid yet.
699     *
700     * @param pkt Packet holding the address to update
701     * @param writebacks A list of writeback packets for the evicted blocks
702     * @return the allocated block
703     */
704    CacheBlk *allocateBlock(const PacketPtr pkt, PacketList &writebacks);
705    /**
706     * Evict a cache block.
707     *
708     * Performs a writeback if necesssary and invalidates the block
709     *
710     * @param blk Block to invalidate
711     * @return A packet with the writeback, can be nullptr
712     */
713    M5_NODISCARD virtual PacketPtr evictBlock(CacheBlk *blk) = 0;
714
715    /**
716     * Evict a cache block.
717     *
718     * Performs a writeback if necesssary and invalidates the block
719     *
720     * @param blk Block to invalidate
721     * @param writebacks Return a list of packets with writebacks
722     */
723    void evictBlock(CacheBlk *blk, PacketList &writebacks);
724
725    /**
726     * Invalidate a cache block.
727     *
728     * @param blk Block to invalidate
729     */
730    void invalidateBlock(CacheBlk *blk);
731
732    /**
733     * Create a writeback request for the given block.
734     *
735     * @param blk The block to writeback.
736     * @return The writeback request for the block.
737     */
738    PacketPtr writebackBlk(CacheBlk *blk);
739
740    /**
741     * Create a writeclean request for the given block.
742     *
743     * Creates a request that writes the block to the cache below
744     * without evicting the block from the current cache.
745     *
746     * @param blk The block to write clean.
747     * @param dest The destination of the write clean operation.
748     * @param id Use the given packet id for the write clean operation.
749     * @return The generated write clean packet.
750     */
751    PacketPtr writecleanBlk(CacheBlk *blk, Request::Flags dest, PacketId id);
752
753    /**
754     * Write back dirty blocks in the cache using functional accesses.
755     */
756    virtual void memWriteback() override;
757
758    /**
759     * Invalidates all blocks in the cache.
760     *
761     * @warn Dirty cache lines will not be written back to
762     * memory. Make sure to call functionalWriteback() first if you
763     * want the to write them to memory.
764     */
765    virtual void memInvalidate() override;
766
767    /**
768     * Determine if there are any dirty blocks in the cache.
769     *
770     * @return true if at least one block is dirty, false otherwise.
771     */
772    bool isDirty() const;
773
774    /**
775     * Determine if an address is in the ranges covered by this
776     * cache. This is useful to filter snoops.
777     *
778     * @param addr Address to check against
779     *
780     * @return If the address in question is in range
781     */
782    bool inRange(Addr addr) const;
783
784    /**
785     * Find next request ready time from among possible sources.
786     */
787    Tick nextQueueReadyTime() const;
788
789    /** Block size of this cache */
790    const unsigned blkSize;
791
792    /**
793     * The latency of tag lookup of a cache. It occurs when there is
794     * an access to the cache.
795     */
796    const Cycles lookupLatency;
797
798    /**
799     * The latency of data access of a cache. It occurs when there is
800     * an access to the cache.
801     */
802    const Cycles dataLatency;
803
804    /**
805     * This is the forward latency of the cache. It occurs when there
806     * is a cache miss and a request is forwarded downstream, in
807     * particular an outbound miss.
808     */
809    const Cycles forwardLatency;
810
811    /** The latency to fill a cache block */
812    const Cycles fillLatency;
813
814    /**
815     * The latency of sending reponse to its upper level cache/core on
816     * a linefill. The responseLatency parameter captures this
817     * latency.
818     */
819    const Cycles responseLatency;
820
821    /**
822     * Whether tags and data are accessed sequentially.
823     */
824    const bool sequentialAccess;
825
826    /** The number of targets for each MSHR. */
827    const int numTarget;
828
829    /** Do we forward snoops from mem side port through to cpu side port? */
830    bool forwardSnoops;
831
832    /**
833     * Clusivity with respect to the upstream cache, determining if we
834     * fill into both this cache and the cache above on a miss. Note
835     * that we currently do not support strict clusivity policies.
836     */
837    const Enums::Clusivity clusivity;
838
839    /**
840     * Is this cache read only, for example the instruction cache, or
841     * table-walker cache. A cache that is read only should never see
842     * any writes, and should never get any dirty data (and hence
843     * never have to do any writebacks).
844     */
845    const bool isReadOnly;
846
847    /**
848     * Bit vector of the blocking reasons for the access path.
849     * @sa #BlockedCause
850     */
851    uint8_t blocked;
852
853    /** Increasing order number assigned to each incoming request. */
854    uint64_t order;
855
856    /** Stores time the cache blocked for statistics. */
857    Cycles blockedCycle;
858
859    /** Pointer to the MSHR that has no targets. */
860    MSHR *noTargetMSHR;
861
862    /** The number of misses to trigger an exit event. */
863    Counter missCount;
864
865    /**
866     * The address range to which the cache responds on the CPU side.
867     * Normally this is all possible memory addresses. */
868    const AddrRangeList addrRanges;
869
870  public:
871    /** System we are currently operating in. */
872    System *system;
873
874    // Statistics
875    /**
876     * @addtogroup CacheStatistics
877     * @{
878     */
879
880    /** Number of hits per thread for each type of command.
881        @sa Packet::Command */
882    Stats::Vector hits[MemCmd::NUM_MEM_CMDS];
883    /** Number of hits for demand accesses. */
884    Stats::Formula demandHits;
885    /** Number of hit for all accesses. */
886    Stats::Formula overallHits;
887
888    /** Number of misses per thread for each type of command.
889        @sa Packet::Command */
890    Stats::Vector misses[MemCmd::NUM_MEM_CMDS];
891    /** Number of misses for demand accesses. */
892    Stats::Formula demandMisses;
893    /** Number of misses for all accesses. */
894    Stats::Formula overallMisses;
895
896    /**
897     * Total number of cycles per thread/command spent waiting for a miss.
898     * Used to calculate the average miss latency.
899     */
900    Stats::Vector missLatency[MemCmd::NUM_MEM_CMDS];
901    /** Total number of cycles spent waiting for demand misses. */
902    Stats::Formula demandMissLatency;
903    /** Total number of cycles spent waiting for all misses. */
904    Stats::Formula overallMissLatency;
905
906    /** The number of accesses per command and thread. */
907    Stats::Formula accesses[MemCmd::NUM_MEM_CMDS];
908    /** The number of demand accesses. */
909    Stats::Formula demandAccesses;
910    /** The number of overall accesses. */
911    Stats::Formula overallAccesses;
912
913    /** The miss rate per command and thread. */
914    Stats::Formula missRate[MemCmd::NUM_MEM_CMDS];
915    /** The miss rate of all demand accesses. */
916    Stats::Formula demandMissRate;
917    /** The miss rate for all accesses. */
918    Stats::Formula overallMissRate;
919
920    /** The average miss latency per command and thread. */
921    Stats::Formula avgMissLatency[MemCmd::NUM_MEM_CMDS];
922    /** The average miss latency for demand misses. */
923    Stats::Formula demandAvgMissLatency;
924    /** The average miss latency for all misses. */
925    Stats::Formula overallAvgMissLatency;
926
927    /** The total number of cycles blocked for each blocked cause. */
928    Stats::Vector blocked_cycles;
929    /** The number of times this cache blocked for each blocked cause. */
930    Stats::Vector blocked_causes;
931
932    /** The average number of cycles blocked for each blocked cause. */
933    Stats::Formula avg_blocked;
934
935    /** The number of times a HW-prefetched block is evicted w/o reference. */
936    Stats::Scalar unusedPrefetches;
937
938    /** Number of blocks written back per thread. */
939    Stats::Vector writebacks;
940
941    /** Number of misses that hit in the MSHRs per command and thread. */
942    Stats::Vector mshr_hits[MemCmd::NUM_MEM_CMDS];
943    /** Demand misses that hit in the MSHRs. */
944    Stats::Formula demandMshrHits;
945    /** Total number of misses that hit in the MSHRs. */
946    Stats::Formula overallMshrHits;
947
948    /** Number of misses that miss in the MSHRs, per command and thread. */
949    Stats::Vector mshr_misses[MemCmd::NUM_MEM_CMDS];
950    /** Demand misses that miss in the MSHRs. */
951    Stats::Formula demandMshrMisses;
952    /** Total number of misses that miss in the MSHRs. */
953    Stats::Formula overallMshrMisses;
954
955    /** Number of misses that miss in the MSHRs, per command and thread. */
956    Stats::Vector mshr_uncacheable[MemCmd::NUM_MEM_CMDS];
957    /** Total number of misses that miss in the MSHRs. */
958    Stats::Formula overallMshrUncacheable;
959
960    /** Total cycle latency of each MSHR miss, per command and thread. */
961    Stats::Vector mshr_miss_latency[MemCmd::NUM_MEM_CMDS];
962    /** Total cycle latency of demand MSHR misses. */
963    Stats::Formula demandMshrMissLatency;
964    /** Total cycle latency of overall MSHR misses. */
965    Stats::Formula overallMshrMissLatency;
966
967    /** Total cycle latency of each MSHR miss, per command and thread. */
968    Stats::Vector mshr_uncacheable_lat[MemCmd::NUM_MEM_CMDS];
969    /** Total cycle latency of overall MSHR misses. */
970    Stats::Formula overallMshrUncacheableLatency;
971
972#if 0
973    /** The total number of MSHR accesses per command and thread. */
974    Stats::Formula mshrAccesses[MemCmd::NUM_MEM_CMDS];
975    /** The total number of demand MSHR accesses. */
976    Stats::Formula demandMshrAccesses;
977    /** The total number of MSHR accesses. */
978    Stats::Formula overallMshrAccesses;
979#endif
980
981    /** The miss rate in the MSHRs pre command and thread. */
982    Stats::Formula mshrMissRate[MemCmd::NUM_MEM_CMDS];
983    /** The demand miss rate in the MSHRs. */
984    Stats::Formula demandMshrMissRate;
985    /** The overall miss rate in the MSHRs. */
986    Stats::Formula overallMshrMissRate;
987
988    /** The average latency of an MSHR miss, per command and thread. */
989    Stats::Formula avgMshrMissLatency[MemCmd::NUM_MEM_CMDS];
990    /** The average latency of a demand MSHR miss. */
991    Stats::Formula demandAvgMshrMissLatency;
992    /** The average overall latency of an MSHR miss. */
993    Stats::Formula overallAvgMshrMissLatency;
994
995    /** The average latency of an MSHR miss, per command and thread. */
996    Stats::Formula avgMshrUncacheableLatency[MemCmd::NUM_MEM_CMDS];
997    /** The average overall latency of an MSHR miss. */
998    Stats::Formula overallAvgMshrUncacheableLatency;
999
1000    /** Number of replacements of valid blocks. */
1001    Stats::Scalar replacements;
1002
1003    /**
1004     * @}
1005     */
1006
1007    /**
1008     * Register stats for this object.
1009     */
1010    void regStats() override;
1011
1012    /** Registers probes. */
1013    void regProbePoints() override;
1014
1015  public:
1016    BaseCache(const BaseCacheParams *p, unsigned blk_size);
1017    ~BaseCache();
1018
1019    void init() override;
1020
1021    BaseMasterPort &getMasterPort(const std::string &if_name,
1022                                  PortID idx = InvalidPortID) override;
1023    BaseSlavePort &getSlavePort(const std::string &if_name,
1024                                PortID idx = InvalidPortID) override;
1025
1026    /**
1027     * Query block size of a cache.
1028     * @return  The block size
1029     */
1030    unsigned
1031    getBlockSize() const
1032    {
1033        return blkSize;
1034    }
1035
1036    const AddrRangeList &getAddrRanges() const { return addrRanges; }
1037
1038    MSHR *allocateMissBuffer(PacketPtr pkt, Tick time, bool sched_send = true)
1039    {
1040        MSHR *mshr = mshrQueue.allocate(pkt->getBlockAddr(blkSize), blkSize,
1041                                        pkt, time, order++,
1042                                        allocOnFill(pkt->cmd));
1043
1044        if (mshrQueue.isFull()) {
1045            setBlocked((BlockedCause)MSHRQueue_MSHRs);
1046        }
1047
1048        if (sched_send) {
1049            // schedule the send
1050            schedMemSideSendEvent(time);
1051        }
1052
1053        return mshr;
1054    }
1055
1056    void allocateWriteBuffer(PacketPtr pkt, Tick time)
1057    {
1058        // should only see writes or clean evicts here
1059        assert(pkt->isWrite() || pkt->cmd == MemCmd::CleanEvict);
1060
1061        Addr blk_addr = pkt->getBlockAddr(blkSize);
1062
1063        WriteQueueEntry *wq_entry =
1064            writeBuffer.findMatch(blk_addr, pkt->isSecure());
1065        if (wq_entry && !wq_entry->inService) {
1066            DPRINTF(Cache, "Potential to merge writeback %s", pkt->print());
1067        }
1068
1069        writeBuffer.allocate(blk_addr, blkSize, pkt, time, order++);
1070
1071        if (writeBuffer.isFull()) {
1072            setBlocked((BlockedCause)MSHRQueue_WriteBuffer);
1073        }
1074
1075        // schedule the send
1076        schedMemSideSendEvent(time);
1077    }
1078
1079    /**
1080     * Returns true if the cache is blocked for accesses.
1081     */
1082    bool isBlocked() const
1083    {
1084        return blocked != 0;
1085    }
1086
1087    /**
1088     * Marks the access path of the cache as blocked for the given cause. This
1089     * also sets the blocked flag in the slave interface.
1090     * @param cause The reason for the cache blocking.
1091     */
1092    void setBlocked(BlockedCause cause)
1093    {
1094        uint8_t flag = 1 << cause;
1095        if (blocked == 0) {
1096            blocked_causes[cause]++;
1097            blockedCycle = curCycle();
1098            cpuSidePort.setBlocked();
1099        }
1100        blocked |= flag;
1101        DPRINTF(Cache,"Blocking for cause %d, mask=%d\n", cause, blocked);
1102    }
1103
1104    /**
1105     * Marks the cache as unblocked for the given cause. This also clears the
1106     * blocked flags in the appropriate interfaces.
1107     * @param cause The newly unblocked cause.
1108     * @warning Calling this function can cause a blocked request on the bus to
1109     * access the cache. The cache must be in a state to handle that request.
1110     */
1111    void clearBlocked(BlockedCause cause)
1112    {
1113        uint8_t flag = 1 << cause;
1114        blocked &= ~flag;
1115        DPRINTF(Cache,"Unblocking for cause %d, mask=%d\n", cause, blocked);
1116        if (blocked == 0) {
1117            blocked_cycles[cause] += curCycle() - blockedCycle;
1118            cpuSidePort.clearBlocked();
1119        }
1120    }
1121
1122    /**
1123     * Schedule a send event for the memory-side port. If already
1124     * scheduled, this may reschedule the event at an earlier
1125     * time. When the specified time is reached, the port is free to
1126     * send either a response, a request, or a prefetch request.
1127     *
1128     * @param time The time when to attempt sending a packet.
1129     */
1130    void schedMemSideSendEvent(Tick time)
1131    {
1132        memSidePort.schedSendEvent(time);
1133    }
1134
1135    bool inCache(Addr addr, bool is_secure) const {
1136        return tags->findBlock(addr, is_secure);
1137    }
1138
1139    bool hasBeenPrefetched(Addr addr, bool is_secure) const {
1140        CacheBlk *block = tags->findBlock(addr, is_secure);
1141        if (block) {
1142            return block->wasPrefetched();
1143        } else {
1144            return false;
1145        }
1146    }
1147
1148    bool inMissQueue(Addr addr, bool is_secure) const {
1149        return mshrQueue.findMatch(addr, is_secure);
1150    }
1151
1152    void incMissCount(PacketPtr pkt)
1153    {
1154        assert(pkt->req->masterId() < system->maxMasters());
1155        misses[pkt->cmdToIndex()][pkt->req->masterId()]++;
1156        pkt->req->incAccessDepth();
1157        if (missCount) {
1158            --missCount;
1159            if (missCount == 0)
1160                exitSimLoop("A cache reached the maximum miss count");
1161        }
1162    }
1163    void incHitCount(PacketPtr pkt)
1164    {
1165        assert(pkt->req->masterId() < system->maxMasters());
1166        hits[pkt->cmdToIndex()][pkt->req->masterId()]++;
1167
1168    }
1169
1170    /**
1171     * Checks if the cache is coalescing writes
1172     *
1173     * @return True if the cache is coalescing writes
1174     */
1175    bool coalesce() const;
1176
1177
1178    /**
1179     * Cache block visitor that writes back dirty cache blocks using
1180     * functional writes.
1181     */
1182    void writebackVisitor(CacheBlk &blk);
1183
1184    /**
1185     * Cache block visitor that invalidates all blocks in the cache.
1186     *
1187     * @warn Dirty cache lines will not be written back to memory.
1188     */
1189    void invalidateVisitor(CacheBlk &blk);
1190
1191    /**
1192     * Take an MSHR, turn it into a suitable downstream packet, and
1193     * send it out. This construct allows a queue entry to choose a suitable
1194     * approach based on its type.
1195     *
1196     * @param mshr The MSHR to turn into a packet and send
1197     * @return True if the port is waiting for a retry
1198     */
1199    virtual bool sendMSHRQueuePacket(MSHR* mshr);
1200
1201    /**
1202     * Similar to sendMSHR, but for a write-queue entry
1203     * instead. Create the packet, and send it, and if successful also
1204     * mark the entry in service.
1205     *
1206     * @param wq_entry The write-queue entry to turn into a packet and send
1207     * @return True if the port is waiting for a retry
1208     */
1209    bool sendWriteQueuePacket(WriteQueueEntry* wq_entry);
1210
1211    /**
1212     * Serialize the state of the caches
1213     *
1214     * We currently don't support checkpointing cache state, so this panics.
1215     */
1216    void serialize(CheckpointOut &cp) const override;
1217    void unserialize(CheckpointIn &cp) override;
1218};
1219
1220/**
1221 * The write allocator inspects write packets and detects streaming
1222 * patterns. The write allocator supports a single stream where writes
1223 * are expected to access consecutive locations and keeps track of
1224 * size of the area covered by the concecutive writes in byteCount.
1225 *
1226 * 1) When byteCount has surpassed the coallesceLimit the mode
1227 * switches from ALLOCATE to COALESCE where writes should be delayed
1228 * until the whole block is written at which point a single packet
1229 * (whole line write) can service them.
1230 *
1231 * 2) When byteCount has also exceeded the noAllocateLimit (whole
1232 * line) we switch to NO_ALLOCATE when writes should not allocate in
1233 * the cache but rather send a whole line write to the memory below.
1234 */
1235class WriteAllocator : public SimObject {
1236  public:
1237    WriteAllocator(const WriteAllocatorParams *p) :
1238        SimObject(p),
1239        coalesceLimit(p->coalesce_limit * p->block_size),
1240        noAllocateLimit(p->no_allocate_limit * p->block_size),
1241        delayThreshold(p->delay_threshold)
1242    {
1243        reset();
1244    }
1245
1246    /**
1247     * Should writes be coalesced? This is true if the mode is set to
1248     * NO_ALLOCATE.
1249     *
1250     * @return return true if the cache should coalesce writes.
1251     */
1252    bool coalesce() const {
1253        return mode != WriteMode::ALLOCATE;
1254    }
1255
1256    /**
1257     * Should writes allocate?
1258     *
1259     * @return return true if the cache should not allocate for writes.
1260     */
1261    bool allocate() const {
1262        return mode != WriteMode::NO_ALLOCATE;
1263    }
1264
1265    /**
1266     * Reset the write allocator state, meaning that it allocates for
1267     * writes and has not recorded any information about qualifying
1268     * writes that might trigger a switch to coalescing and later no
1269     * allocation.
1270     */
1271    void reset() {
1272        mode = WriteMode::ALLOCATE;
1273        byteCount = 0;
1274        nextAddr = 0;
1275    }
1276
1277    /**
1278     * Access whether we need to delay the current write.
1279     *
1280     * @param blk_addr The block address the packet writes to
1281     * @return true if the current packet should be delayed
1282     */
1283    bool delay(Addr blk_addr) {
1284        if (delayCtr[blk_addr] > 0) {
1285            --delayCtr[blk_addr];
1286            return true;
1287        } else {
1288            return false;
1289        }
1290    }
1291
1292    /**
1293     * Clear delay counter for the input block
1294     *
1295     * @param blk_addr The accessed cache block
1296     */
1297    void resetDelay(Addr blk_addr) {
1298        delayCtr.erase(blk_addr);
1299    }
1300
1301    /**
1302     * Update the write mode based on the current write
1303     * packet. This method compares the packet's address with any
1304     * current stream, and updates the tracking and the mode
1305     * accordingly.
1306     *
1307     * @param write_addr Start address of the write request
1308     * @param write_size Size of the write request
1309     * @param blk_addr The block address that this packet writes to
1310     */
1311    void updateMode(Addr write_addr, unsigned write_size, Addr blk_addr);
1312
1313  private:
1314    /**
1315     * The current mode for write coalescing and allocation, either
1316     * normal operation (ALLOCATE), write coalescing (COALESCE), or
1317     * write coalescing without allocation (NO_ALLOCATE).
1318     */
1319    enum class WriteMode : char {
1320        ALLOCATE,
1321        COALESCE,
1322        NO_ALLOCATE,
1323    };
1324    WriteMode mode;
1325
1326    /** Address to match writes against to detect streams. */
1327    Addr nextAddr;
1328
1329    /**
1330     * Bytes written contiguously. Saturating once we no longer
1331     * allocate.
1332     */
1333    uint32_t byteCount;
1334
1335    /**
1336     * Limits for when to switch between the different write modes.
1337     */
1338    const uint32_t coalesceLimit;
1339    const uint32_t noAllocateLimit;
1340    /**
1341     * The number of times the allocator will delay an WriteReq MSHR.
1342     */
1343    const uint32_t delayThreshold;
1344
1345    /**
1346     * Keep track of the number of times the allocator has delayed an
1347     * WriteReq MSHR.
1348     */
1349    std::unordered_map<Addr, Counter> delayCtr;
1350};
1351
1352#endif //__MEM_CACHE_BASE_HH__
1353