mem: Add clean evicts to improve snoop filter tracking
[gem5.git] / src / mem / cache / cache.hh
index 41b270030b73684148ea5dc6b635fd05c975ae1f..4c70d3a4040436812c05af586b602663249d0e87 100644 (file)
@@ -1,4 +1,16 @@
 /*
+ * Copyright (c) 2012-2014 ARM Limited
+ * All rights reserved.
+ *
+ * The license below extends only to copyright in the software and shall
+ * not be construed as granting a license to any other intellectual
+ * property including but not limited to intellectual property relating
+ * to a hardware implementation of the functionality of the software
+ * licensed hereunder.  You may use the software subject to the license
+ * terms below provided that you ensure that this notice is replicated
+ * unmodified and in its entirety in all distributions of the software,
+ * modified or unmodified, in source code or in binary form.
+ *
  * Copyright (c) 2002-2005 The Regents of The University of Michigan
  * All rights reserved.
  *
@@ -28,6 +40,8 @@
  * Authors: Erik Hallnor
  *          Dave Greene
  *          Steve Reinhardt
+ *          Ron Dreslinski
+ *          Andreas Hansson
  */
 
 /**
 #define __CACHE_HH__
 
 #include "base/misc.hh" // fatal, panic, and warn
-#include "cpu/smt.hh" // SMT_MAX_THREADS
-
-#include "mem/cache/base_cache.hh"
-#include "mem/cache/prefetch/prefetcher.hh"
+#include "mem/cache/base.hh"
+#include "mem/cache/blk.hh"
+#include "mem/cache/mshr.hh"
+#include "mem/cache/tags/base.hh"
+#include "sim/eventq.hh"
 
 //Forward decleration
-class MSHR;
-
+class BasePrefetcher;
 
 /**
  * A template-policy based cache. The behavior of the cache can be altered by
  * supplying different template policies. TagStore handles all tag and data
- * storage @sa TagStore. Buffering handles all misses and writes/writebacks
- * @sa MissQueue. Coherence handles all coherence policy details @sa
- * UniCoherence, SimpleMultiCoherence.
+ * storage @sa TagStore, \ref gem5MemorySystem "gem5 Memory System"
  */
-template <class TagStore, class Buffering, class Coherence>
 class Cache : public BaseCache
 {
   public:
-    /** Define the type of cache block to use. */
-    typedef typename TagStore::BlkType BlkType;
 
-    bool prefetchAccess;
+    /** A typedef for a list of CacheBlk pointers. */
+    typedef std::list<CacheBlk*> BlkList;
+
   protected:
 
-    /** Tag and data Storage */
-    TagStore *tags;
-    /** Miss and Writeback handler */
-    Buffering *missQueue;
-    /** Coherence protocol. */
-    Coherence *coherence;
+    /**
+     * The CPU-side port extends the base cache slave port with access
+     * functions for functional, atomic and timing requests.
+     */
+    class CpuSidePort : public CacheSlavePort
+    {
+      private:
 
-    /** Prefetcher */
-    Prefetcher<TagStore, Buffering> *prefetcher;
+        // a pointer to our specific cache implementation
+        Cache *cache;
+
+      protected:
+
+        virtual bool recvTimingSnoopResp(PacketPtr pkt);
+
+        virtual bool recvTimingReq(PacketPtr pkt);
+
+        virtual Tick recvAtomic(PacketPtr pkt);
+
+        virtual void recvFunctional(PacketPtr pkt);
+
+        virtual AddrRangeList getAddrRanges() const;
+
+      public:
 
-    /** Do fast copies in this cache. */
-    bool doCopy;
+        CpuSidePort(const std::string &_name, Cache *_cache,
+                    const std::string &_label);
 
-    /** Block on a delayed copy. */
-    bool blockOnCopy;
+    };
 
     /**
-     * The clock ratio of the outgoing bus.
-     * Used for calculating critical word first.
+     * Override the default behaviour of sendDeferredPacket to enable
+     * the memory-side cache port to also send requests based on the
+     * current MSHR status. This queue has a pointer to our specific
+     * cache implementation and is used by the MemSidePort.
      */
-    int busRatio;
+    class CacheReqPacketQueue : public ReqPacketQueue
+    {
+
+      protected:
+
+        Cache &cache;
+        SnoopRespPacketQueue &snoopRespQueue;
+
+      public:
+
+        CacheReqPacketQueue(Cache &cache, MasterPort &port,
+                            SnoopRespPacketQueue &snoop_resp_queue,
+                            const std::string &label) :
+            ReqPacketQueue(cache, port, label), cache(cache),
+            snoopRespQueue(snoop_resp_queue) { }
 
-     /**
-      * The bus width in bytes of the outgoing bus.
-      * Used for calculating critical word first.
-      */
-    int busWidth;
+        /**
+         * Override the normal sendDeferredPacket and do not only
+         * consider the transmit list (used for responses), but also
+         * requests.
+         */
+        virtual void sendDeferredPacket();
+
+    };
 
     /**
-     * The latency of a hit in this device.
+     * The memory-side port extends the base cache master port with
+     * access functions for functional, atomic and timing snoops.
      */
-    int hitLatency;
+    class MemSidePort : public CacheMasterPort
+    {
+      private:
 
-     /**
-      * A permanent mem req to always be used to cause invalidations.
-      * Used to append to target list, to cause an invalidation.
-      */
-    Packet * invalidatePkt;
-    Request *invalidateReq;
+        /** The cache-specific queue. */
+        CacheReqPacketQueue _reqQueue;
+
+        SnoopRespPacketQueue _snoopRespQueue;
+
+        // a pointer to our specific cache implementation
+        Cache *cache;
+
+      protected:
+
+        virtual void recvTimingSnoopReq(PacketPtr pkt);
+
+        virtual bool recvTimingResp(PacketPtr pkt);
+
+        virtual Tick recvAtomicSnoop(PacketPtr pkt);
+
+        virtual void recvFunctionalSnoop(PacketPtr pkt);
+
+      public:
+
+        MemSidePort(const std::string &_name, Cache *_cache,
+                    const std::string &_label);
+    };
+
+    /** Tag and data Storage */
+    BaseTags *tags;
+
+    /** Prefetcher */
+    BasePrefetcher *prefetcher;
+
+    /** Temporary cache block for occasional transitory use */
+    CacheBlk *tempBlock;
 
     /**
-     * Temporarily move a block into a MSHR.
-     * @todo Remove this when LSQ/SB are fixed and implemented in memtest.
+     * This cache should allocate a block on a line-sized write miss.
      */
-    void pseudoFill(Addr addr);
+    const bool doFastWrites;
 
     /**
-     * Temporarily move a block into an existing MSHR.
-     * @todo Remove this when LSQ/SB are fixed and implemented in memtest.
+     * Turn line-sized writes into WriteInvalidate transactions.
      */
-    void pseudoFill(MSHR *mshr);
+    void promoteWholeLineWrites(PacketPtr pkt);
 
-  public:
-
-    class Params
-    {
-      public:
-        TagStore *tags;
-        Buffering *missQueue;
-        Coherence *coherence;
-        bool doCopy;
-        bool blockOnCopy;
-        BaseCache::Params baseParams;
-        Prefetcher<TagStore, Buffering> *prefetcher;
-        bool prefetchAccess;
-        int hitLatency;
-
-        Params(TagStore *_tags, Buffering *mq, Coherence *coh,
-               bool do_copy, BaseCache::Params params,
-               Prefetcher<TagStore, Buffering> *_prefetcher,
-               bool prefetch_access, int hit_latency)
-            : tags(_tags), missQueue(mq), coherence(coh), doCopy(do_copy),
-              blockOnCopy(false), baseParams(params),
-              prefetcher(_prefetcher), prefetchAccess(prefetch_access),
-              hitLatency(hit_latency)
-        {
-        }
-    };
+    /**
+     * Notify the prefetcher on every access, not just misses.
+     */
+    const bool prefetchOnAccess;
 
-    /** Instantiates a basic cache object. */
-    Cache(const std::string &_name, Params &params);
+    /**
+     * @todo this is a temporary workaround until the 4-phase code is committed.
+     * upstream caches need this packet until true is returned, so hold it for
+     * deletion until a subsequent call
+     */
+    std::vector<PacketPtr> pendingDelete;
 
-    virtual bool doTimingAccess(Packet *pkt, CachePort *cachePort,
-                        bool isCpuSide);
+    /**
+     * Does all the processing necessary to perform the provided request.
+     * @param pkt The memory request to perform.
+     * @param blk The cache block to be updated.
+     * @param lat The latency of the access.
+     * @param writebacks List for any writebacks that need to be performed.
+     * @return Boolean indicating whether the request was satisfied.
+     */
+    bool access(PacketPtr pkt, CacheBlk *&blk,
+                Cycles &lat, PacketList &writebacks);
 
-    virtual Tick doAtomicAccess(Packet *pkt, bool isCpuSide);
+    /**
+     *Handle doing the Compare and Swap function for SPARC.
+     */
+    void cmpAndSwap(CacheBlk *blk, PacketPtr pkt);
 
-    virtual void doFunctionalAccess(Packet *pkt, bool isCpuSide);
+    /**
+     * Find a block frame for new block at address addr targeting the
+     * given security space, assuming that the block is not currently
+     * in the cache.  Append writebacks if any to provided packet
+     * list.  Return free block frame.  May return NULL if there are
+     * no replaceable blocks at the moment.
+     */
+    CacheBlk *allocateBlock(Addr addr, bool is_secure, PacketList &writebacks);
 
-    virtual void recvStatusChange(Port::Status status, bool isCpuSide);
+    /**
+     * Populates a cache block and handles all outstanding requests for the
+     * satisfied fill request. This version takes two memory requests. One
+     * contains the fill data, the other is an optional target to satisfy.
+     * @param pkt The memory request with the fill data.
+     * @param blk The cache block if it already exists.
+     * @param writebacks List for any writebacks that need to be performed.
+     * @return Pointer to the new cache block.
+     */
+    CacheBlk *handleFill(PacketPtr pkt, CacheBlk *blk,
+                        PacketList &writebacks);
 
-    void regStats();
 
     /**
      * Performs the access specified by the request.
      * @param pkt The request to perform.
      * @return The result of the access.
      */
-    bool access(Packet * &pkt);
+    bool recvTimingReq(PacketPtr pkt);
 
     /**
-     * Selects a request to send on the bus.
-     * @return The memory request to service.
+     * Insert writebacks into the write buffer
      */
-    virtual Packet * getPacket();
+    void doWritebacks(PacketList& writebacks, Tick forward_time);
 
     /**
-     * Was the request was sent successfully?
-     * @param pkt The request.
-     * @param success True if the request was sent successfully.
+     * Handles a response (cache line fill/write ack) from the bus.
+     * @param pkt The response packet
      */
-    virtual void sendResult(Packet * &pkt, MSHR* mshr, bool success);
+    void recvTimingResp(PacketPtr pkt);
 
     /**
-     * Handles a response (cache line fill/write ack) from the bus.
-     * @param pkt The request being responded to.
+     * Snoops bus transactions to maintain coherence.
+     * @param pkt The current bus transaction.
      */
-    void handleResponse(Packet * &pkt);
+    void recvTimingSnoopReq(PacketPtr pkt);
 
     /**
-     * Start handling a copy transaction.
-     * @param pkt The copy request to perform.
+     * Handle a snoop response.
+     * @param pkt Snoop response packet
      */
-    void startCopy(Packet * &pkt);
+    void recvTimingSnoopResp(PacketPtr pkt);
 
     /**
-     * Handle a delayed copy transaction.
-     * @param pkt The delayed copy request to continue.
-     * @param addr The address being responded to.
-     * @param blk The block of the current response.
-     * @param mshr The mshr being handled.
+     * Performs the access specified by the request.
+     * @param pkt The request to perform.
+     * @return The number of ticks required for the access.
      */
-    void handleCopy(Packet * &pkt, Addr addr, BlkType *blk, MSHR *mshr);
+    Tick recvAtomic(PacketPtr pkt);
 
     /**
-     * Selects a coherence message to forward to lower levels of the hierarchy.
-     * @return The coherence message to forward.
+     * Snoop for the provided request in the cache and return the estimated
+     * time taken.
+     * @param pkt The memory request to snoop
+     * @return The number of ticks required for the snoop.
      */
-    virtual Packet * getCoherencePacket();
+    Tick recvAtomicSnoop(PacketPtr pkt);
 
     /**
-     * Snoops bus transactions to maintain coherence.
-     * @param pkt The current bus transaction.
+     * Performs the access specified by the request.
+     * @param pkt The request to perform.
+     * @param fromCpuSide from the CPU side port or the memory side port
+     */
+    void functionalAccess(PacketPtr pkt, bool fromCpuSide);
+
+    void satisfyCpuSideRequest(PacketPtr pkt, CacheBlk *blk,
+                               bool deferred_response = false,
+                               bool pending_downgrade = false);
+    bool satisfyMSHR(MSHR *mshr, PacketPtr pkt, CacheBlk *blk);
+
+    void doTimingSupplyResponse(PacketPtr req_pkt, const uint8_t *blk_data,
+                                bool already_copied, bool pending_inval);
+
+    /**
+     * Sets the blk to the new state.
+     * @param blk The cache block being snooped.
+     * @param new_state The new coherence state for the block.
      */
-    void snoop(Packet * &pkt);
+    void handleSnoop(PacketPtr ptk, CacheBlk *blk,
+                     bool is_timing, bool is_deferred, bool pending_inval);
 
-    void snoopResponse(Packet * &pkt);
+    /**
+     * Create a writeback request for the given block.
+     * @param blk The block to writeback.
+     * @return The writeback request for the block.
+     */
+    PacketPtr writebackBlk(CacheBlk *blk);
 
     /**
-     * Invalidates the block containing address if found.
-     * @param addr The address to look for.
-     * @param asid The address space ID of the address.
-     * @todo Is this function necessary?
+     * Create a CleanEvict request for the given block.
+     * @param blk The block to evict.
+     * @return The CleanEvict request for the block.
      */
-    void invalidateBlk(Addr addr);
+    PacketPtr cleanEvictBlk(CacheBlk *blk);
+
+
+    void memWriteback();
+    void memInvalidate();
+    bool isDirty() const;
+
+    /**
+     * Cache block visitor that writes back dirty cache blocks using
+     * functional writes.
+     *
+     * \return Always returns true.
+     */
+    bool writebackVisitor(CacheBlk &blk);
+    /**
+     * Cache block visitor that invalidates all blocks in the cache.
+     *
+     * @warn Dirty cache lines will not be written back to memory.
+     *
+     * \return Always returns true.
+     */
+    bool invalidateVisitor(CacheBlk &blk);
 
     /**
      * Squash all requests associated with specified thread.
      * intended for use by I-cache.
      * @param threadNum The thread to squash.
      */
-    void squash(int threadNum)
-    {
-        missQueue->squash(threadNum);
-    }
+    void squash(int threadNum);
 
     /**
-     * Return the number of outstanding misses in a Cache.
-     * Default returns 0.
-     *
-     * @retval unsigned The number of missing still outstanding.
+     * Generate an appropriate downstream bus request packet for the
+     * given parameters.
+     * @param cpu_pkt  The upstream request that needs to be satisfied.
+     * @param blk The block currently in the cache corresponding to
+     * cpu_pkt (NULL if none).
+     * @param needsExclusive  Indicates that an exclusive copy is required
+     * even if the request in cpu_pkt doesn't indicate that.
+     * @return A new Packet containing the request, or NULL if the
+     * current request in cpu_pkt should just be forwarded on.
+     */
+    PacketPtr getBusPacket(PacketPtr cpu_pkt, CacheBlk *blk,
+                           bool needsExclusive) const;
+
+    /**
+     * Return the next MSHR to service, either a pending miss from the
+     * mshrQueue, a buffered write from the write buffer, or something
+     * from the prefetcher.  This function is responsible for
+     * prioritizing among those sources on the fly.
+     */
+    MSHR *getNextMSHR();
+
+    /**
+     * Send up a snoop request and find cached copies. If cached copies are
+     * found, set the BLOCK_CACHED flag in pkt.
+     */
+    bool isCachedAbove(const PacketPtr pkt) const;
+
+    /**
+     * Selects an outstanding request to service.  Called when the
+     * cache gets granted the downstream bus in timing mode.
+     * @return The request to service, NULL if none found.
+     */
+    PacketPtr getTimingPacket();
+
+    /**
+     * Marks a request as in service (sent on the bus). This can have
+     * side effect since storage for no response commands is
+     * deallocated once they are successfully sent. Also remember if
+     * we are expecting a dirty response from another cache,
+     * effectively making this MSHR the ordering point.
      */
-    unsigned outstandingMisses() const
+    void markInService(MSHR *mshr, bool pending_dirty_resp);
+
+    /**
+     * Return whether there are any outstanding misses.
+     */
+    bool outstandingMisses() const
     {
-        return missQueue->getMisses();
+        return mshrQueue.allocated != 0;
+    }
+
+    CacheBlk *findBlock(Addr addr, bool is_secure) const {
+        return tags->findBlock(addr, is_secure);
+    }
+
+    bool inCache(Addr addr, bool is_secure) const {
+        return (tags->findBlock(addr, is_secure) != 0);
+    }
+
+    bool inMissQueue(Addr addr, bool is_secure) const {
+        return (mshrQueue.findMatch(addr, is_secure) != 0);
     }
 
     /**
-     * Perform the access specified in the request and return the estimated
-     * time of completion. This function can either update the hierarchy state
-     * or just perform the access wherever the data is found depending on the
-     * state of the update flag.
-     * @param pkt The memory request to satisfy
-     * @param update If true, update the hierarchy, otherwise just perform the
-     * request.
-     * @return The estimated completion time.
+     * Find next request ready time from among possible sources.
      */
-    Tick probe(Packet * &pkt, bool update, CachePort * otherSidePort);
+    Tick nextMSHRReadyTime() const;
+
+  public:
+    /** Instantiates a basic cache object. */
+    Cache(const Params *p);
+
+    /** Non-default destructor is needed to deallocate memory. */
+    virtual ~Cache();
+
+    void regStats();
+
+    /** serialize the state of the caches
+     * We currently don't support checkpointing cache state, so this panics.
+     */
+    virtual void serialize(std::ostream &os);
+    void unserialize(Checkpoint *cp, const std::string &section);
+};
+
+/**
+ * Wrap a method and present it as a cache block visitor.
+ *
+ * For example the forEachBlk method in the tag arrays expects a
+ * callable object/function as their parameter. This class wraps a
+ * method in an object and presents  callable object that adheres to
+ * the cache block visitor protocol.
+ */
+class CacheBlkVisitorWrapper : public CacheBlkVisitor
+{
+  public:
+    typedef bool (Cache::*VisitorPtr)(CacheBlk &blk);
+
+    CacheBlkVisitorWrapper(Cache &_cache, VisitorPtr _visitor)
+        : cache(_cache), visitor(_visitor) {}
+
+    bool operator()(CacheBlk &blk) M5_ATTR_OVERRIDE {
+        return (cache.*visitor)(blk);
+    }
+
+  private:
+    Cache &cache;
+    VisitorPtr visitor;
+};
+
+/**
+ * Cache block visitor that determines if there are dirty blocks in a
+ * cache.
+ *
+ * Use with the forEachBlk method in the tag array to determine if the
+ * array contains dirty blocks.
+ */
+class CacheBlkIsDirtyVisitor : public CacheBlkVisitor
+{
+  public:
+    CacheBlkIsDirtyVisitor()
+        : _isDirty(false) {}
+
+    bool operator()(CacheBlk &blk) M5_ATTR_OVERRIDE {
+        if (blk.isDirty()) {
+            _isDirty = true;
+            return false;
+        } else {
+            return true;
+        }
+    }
 
     /**
-     * Snoop for the provided request in the cache and return the estimated
-     * time of completion.
-     * @todo Can a snoop probe not change state?
-     * @param pkt The memory request to satisfy
-     * @param update If true, update the hierarchy, otherwise just perform the
-     * request.
-     * @return The estimated completion time.
-     */
-    Tick snoopProbe(Packet * &pkt);
+     * Does the array contain a dirty line?
+     *
+     * \return true if yes, false otherwise.
+     */
+    bool isDirty() const { return _isDirty; };
+
+  private:
+    bool _isDirty;
 };
 
 #endif // __CACHE_HH__