cache.hh revision 11168:f98eb2da15a4
1/*
2 * Copyright (c) 2012-2014 ARM Limited
3 * All rights reserved.
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder.  You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Copyright (c) 2002-2005 The Regents of The University of Michigan
15 * All rights reserved.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions are
19 * met: redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer;
21 * redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution;
24 * neither the name of the copyright holders nor the names of its
25 * contributors may be used to endorse or promote products derived from
26 * this software without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 *
40 * Authors: Erik Hallnor
41 *          Dave Greene
42 *          Steve Reinhardt
43 *          Ron Dreslinski
44 *          Andreas Hansson
45 */
46
47/**
48 * @file
49 * Describes a cache based on template policies.
50 */
51
52#ifndef __MEM_CACHE_CACHE_HH__
53#define __MEM_CACHE_CACHE_HH__
54
55#include "base/misc.hh" // fatal, panic, and warn
56#include "mem/cache/base.hh"
57#include "mem/cache/blk.hh"
58#include "mem/cache/mshr.hh"
59#include "mem/cache/tags/base.hh"
60#include "params/Cache.hh"
61#include "sim/eventq.hh"
62
63//Forward decleration
64class BasePrefetcher;
65
66/**
67 * A template-policy based cache. The behavior of the cache can be altered by
68 * supplying different template policies. TagStore handles all tag and data
69 * storage @sa TagStore, \ref gem5MemorySystem "gem5 Memory System"
70 */
71class Cache : public BaseCache
72{
73  public:
74
75    /** A typedef for a list of CacheBlk pointers. */
76    typedef std::list<CacheBlk*> BlkList;
77
78  protected:
79
80    /**
81     * The CPU-side port extends the base cache slave port with access
82     * functions for functional, atomic and timing requests.
83     */
84    class CpuSidePort : public CacheSlavePort
85    {
86      private:
87
88        // a pointer to our specific cache implementation
89        Cache *cache;
90
91      protected:
92
93        virtual bool recvTimingSnoopResp(PacketPtr pkt);
94
95        virtual bool recvTimingReq(PacketPtr pkt);
96
97        virtual Tick recvAtomic(PacketPtr pkt);
98
99        virtual void recvFunctional(PacketPtr pkt);
100
101        virtual AddrRangeList getAddrRanges() const;
102
103      public:
104
105        CpuSidePort(const std::string &_name, Cache *_cache,
106                    const std::string &_label);
107
108    };
109
110    /**
111     * Override the default behaviour of sendDeferredPacket to enable
112     * the memory-side cache port to also send requests based on the
113     * current MSHR status. This queue has a pointer to our specific
114     * cache implementation and is used by the MemSidePort.
115     */
116    class CacheReqPacketQueue : public ReqPacketQueue
117    {
118
119      protected:
120
121        Cache &cache;
122        SnoopRespPacketQueue &snoopRespQueue;
123
124      public:
125
126        CacheReqPacketQueue(Cache &cache, MasterPort &port,
127                            SnoopRespPacketQueue &snoop_resp_queue,
128                            const std::string &label) :
129            ReqPacketQueue(cache, port, label), cache(cache),
130            snoopRespQueue(snoop_resp_queue) { }
131
132        /**
133         * Override the normal sendDeferredPacket and do not only
134         * consider the transmit list (used for responses), but also
135         * requests.
136         */
137        virtual void sendDeferredPacket();
138
139    };
140
141    /**
142     * The memory-side port extends the base cache master port with
143     * access functions for functional, atomic and timing snoops.
144     */
145    class MemSidePort : public CacheMasterPort
146    {
147      private:
148
149        /** The cache-specific queue. */
150        CacheReqPacketQueue _reqQueue;
151
152        SnoopRespPacketQueue _snoopRespQueue;
153
154        // a pointer to our specific cache implementation
155        Cache *cache;
156
157      protected:
158
159        virtual void recvTimingSnoopReq(PacketPtr pkt);
160
161        virtual bool recvTimingResp(PacketPtr pkt);
162
163        virtual Tick recvAtomicSnoop(PacketPtr pkt);
164
165        virtual void recvFunctionalSnoop(PacketPtr pkt);
166
167      public:
168
169        MemSidePort(const std::string &_name, Cache *_cache,
170                    const std::string &_label);
171    };
172
173    /** Tag and data Storage */
174    BaseTags *tags;
175
176    /** Prefetcher */
177    BasePrefetcher *prefetcher;
178
179    /** Temporary cache block for occasional transitory use */
180    CacheBlk *tempBlock;
181
182    /**
183     * This cache should allocate a block on a line-sized write miss.
184     */
185    const bool doFastWrites;
186
187    /**
188     * Turn line-sized writes into WriteInvalidate transactions.
189     */
190    void promoteWholeLineWrites(PacketPtr pkt);
191
192    /**
193     * Notify the prefetcher on every access, not just misses.
194     */
195    const bool prefetchOnAccess;
196
197    /**
198     * @todo this is a temporary workaround until the 4-phase code is committed.
199     * upstream caches need this packet until true is returned, so hold it for
200     * deletion until a subsequent call
201     */
202    std::vector<PacketPtr> pendingDelete;
203
204    /**
205     * Does all the processing necessary to perform the provided request.
206     * @param pkt The memory request to perform.
207     * @param blk The cache block to be updated.
208     * @param lat The latency of the access.
209     * @param writebacks List for any writebacks that need to be performed.
210     * @return Boolean indicating whether the request was satisfied.
211     */
212    bool access(PacketPtr pkt, CacheBlk *&blk,
213                Cycles &lat, PacketList &writebacks);
214
215    /**
216     *Handle doing the Compare and Swap function for SPARC.
217     */
218    void cmpAndSwap(CacheBlk *blk, PacketPtr pkt);
219
220    /**
221     * Find a block frame for new block at address addr targeting the
222     * given security space, assuming that the block is not currently
223     * in the cache.  Append writebacks if any to provided packet
224     * list.  Return free block frame.  May return NULL if there are
225     * no replaceable blocks at the moment.
226     */
227    CacheBlk *allocateBlock(Addr addr, bool is_secure, PacketList &writebacks);
228
229    /**
230     * Populates a cache block and handles all outstanding requests for the
231     * satisfied fill request. This version takes two memory requests. One
232     * contains the fill data, the other is an optional target to satisfy.
233     * @param pkt The memory request with the fill data.
234     * @param blk The cache block if it already exists.
235     * @param writebacks List for any writebacks that need to be performed.
236     * @return Pointer to the new cache block.
237     */
238    CacheBlk *handleFill(PacketPtr pkt, CacheBlk *blk,
239                        PacketList &writebacks);
240
241
242    /**
243     * Performs the access specified by the request.
244     * @param pkt The request to perform.
245     * @return The result of the access.
246     */
247    bool recvTimingReq(PacketPtr pkt);
248
249    /**
250     * Insert writebacks into the write buffer
251     */
252    void doWritebacks(PacketList& writebacks, Tick forward_time);
253
254    /**
255     * Send writebacks down the memory hierarchy in atomic mode
256     */
257    void doWritebacksAtomic(PacketList& writebacks);
258
259    /**
260     * Handles a response (cache line fill/write ack) from the bus.
261     * @param pkt The response packet
262     */
263    void recvTimingResp(PacketPtr pkt);
264
265    /**
266     * Snoops bus transactions to maintain coherence.
267     * @param pkt The current bus transaction.
268     */
269    void recvTimingSnoopReq(PacketPtr pkt);
270
271    /**
272     * Handle a snoop response.
273     * @param pkt Snoop response packet
274     */
275    void recvTimingSnoopResp(PacketPtr pkt);
276
277    /**
278     * Performs the access specified by the request.
279     * @param pkt The request to perform.
280     * @return The number of ticks required for the access.
281     */
282    Tick recvAtomic(PacketPtr pkt);
283
284    /**
285     * Snoop for the provided request in the cache and return the estimated
286     * time taken.
287     * @param pkt The memory request to snoop
288     * @return The number of ticks required for the snoop.
289     */
290    Tick recvAtomicSnoop(PacketPtr pkt);
291
292    /**
293     * Performs the access specified by the request.
294     * @param pkt The request to perform.
295     * @param fromCpuSide from the CPU side port or the memory side port
296     */
297    void functionalAccess(PacketPtr pkt, bool fromCpuSide);
298
299    void satisfyCpuSideRequest(PacketPtr pkt, CacheBlk *blk,
300                               bool deferred_response = false,
301                               bool pending_downgrade = false);
302    bool satisfyMSHR(MSHR *mshr, PacketPtr pkt, CacheBlk *blk);
303
304    void doTimingSupplyResponse(PacketPtr req_pkt, const uint8_t *blk_data,
305                                bool already_copied, bool pending_inval);
306
307    /**
308     * Perform an upward snoop if needed, and update the block state
309     * (possibly invalidating the block). Also create a response if required.
310     *
311     * @param pkt Snoop packet
312     * @param blk Cache block being snooped
313     * @param is_timing Timing or atomic for the response
314     * @param is_deferred Is this a deferred snoop or not?
315     * @param pending_inval Do we have a pending invalidation?
316     *
317     * @return The snoop delay incurred by the upwards snoop
318     */
319    uint32_t handleSnoop(PacketPtr pkt, CacheBlk *blk,
320                         bool is_timing, bool is_deferred, bool pending_inval);
321
322    /**
323     * Create a writeback request for the given block.
324     * @param blk The block to writeback.
325     * @return The writeback request for the block.
326     */
327    PacketPtr writebackBlk(CacheBlk *blk);
328
329    /**
330     * Create a CleanEvict request for the given block.
331     * @param blk The block to evict.
332     * @return The CleanEvict request for the block.
333     */
334    PacketPtr cleanEvictBlk(CacheBlk *blk);
335
336
337    void memWriteback();
338    void memInvalidate();
339    bool isDirty() const;
340
341    /**
342     * Cache block visitor that writes back dirty cache blocks using
343     * functional writes.
344     *
345     * \return Always returns true.
346     */
347    bool writebackVisitor(CacheBlk &blk);
348    /**
349     * Cache block visitor that invalidates all blocks in the cache.
350     *
351     * @warn Dirty cache lines will not be written back to memory.
352     *
353     * \return Always returns true.
354     */
355    bool invalidateVisitor(CacheBlk &blk);
356
357    /**
358     * Generate an appropriate downstream bus request packet for the
359     * given parameters.
360     * @param cpu_pkt  The upstream request that needs to be satisfied.
361     * @param blk The block currently in the cache corresponding to
362     * cpu_pkt (NULL if none).
363     * @param needsExclusive  Indicates that an exclusive copy is required
364     * even if the request in cpu_pkt doesn't indicate that.
365     * @return A new Packet containing the request, or NULL if the
366     * current request in cpu_pkt should just be forwarded on.
367     */
368    PacketPtr getBusPacket(PacketPtr cpu_pkt, CacheBlk *blk,
369                           bool needsExclusive) const;
370
371    /**
372     * Return the next MSHR to service, either a pending miss from the
373     * mshrQueue, a buffered write from the write buffer, or something
374     * from the prefetcher.  This function is responsible for
375     * prioritizing among those sources on the fly.
376     */
377    MSHR *getNextMSHR();
378
379    /**
380     * Send up a snoop request and find cached copies. If cached copies are
381     * found, set the BLOCK_CACHED flag in pkt.
382     */
383    bool isCachedAbove(PacketPtr pkt, bool is_timing = true) const;
384
385    /**
386     * Selects an outstanding request to service.  Called when the
387     * cache gets granted the downstream bus in timing mode.
388     * @return The request to service, NULL if none found.
389     */
390    PacketPtr getTimingPacket();
391
392    /**
393     * Marks a request as in service (sent on the bus). This can have
394     * side effect since storage for no response commands is
395     * deallocated once they are successfully sent. Also remember if
396     * we are expecting a dirty response from another cache,
397     * effectively making this MSHR the ordering point.
398     */
399    void markInService(MSHR *mshr, bool pending_dirty_resp);
400
401    /**
402     * Return whether there are any outstanding misses.
403     */
404    bool outstandingMisses() const
405    {
406        return mshrQueue.allocated != 0;
407    }
408
409    CacheBlk *findBlock(Addr addr, bool is_secure) const {
410        return tags->findBlock(addr, is_secure);
411    }
412
413    bool inCache(Addr addr, bool is_secure) const {
414        return (tags->findBlock(addr, is_secure) != 0);
415    }
416
417    bool inMissQueue(Addr addr, bool is_secure) const {
418        return (mshrQueue.findMatch(addr, is_secure) != 0);
419    }
420
421    /**
422     * Find next request ready time from among possible sources.
423     */
424    Tick nextMSHRReadyTime() const;
425
426  public:
427    /** Instantiates a basic cache object. */
428    Cache(const CacheParams *p);
429
430    /** Non-default destructor is needed to deallocate memory. */
431    virtual ~Cache();
432
433    void regStats();
434
435    /** serialize the state of the caches
436     * We currently don't support checkpointing cache state, so this panics.
437     */
438    void serialize(CheckpointOut &cp) const override;
439    void unserialize(CheckpointIn &cp) override;
440};
441
442/**
443 * Wrap a method and present it as a cache block visitor.
444 *
445 * For example the forEachBlk method in the tag arrays expects a
446 * callable object/function as their parameter. This class wraps a
447 * method in an object and presents  callable object that adheres to
448 * the cache block visitor protocol.
449 */
450class CacheBlkVisitorWrapper : public CacheBlkVisitor
451{
452  public:
453    typedef bool (Cache::*VisitorPtr)(CacheBlk &blk);
454
455    CacheBlkVisitorWrapper(Cache &_cache, VisitorPtr _visitor)
456        : cache(_cache), visitor(_visitor) {}
457
458    bool operator()(CacheBlk &blk) override {
459        return (cache.*visitor)(blk);
460    }
461
462  private:
463    Cache &cache;
464    VisitorPtr visitor;
465};
466
467/**
468 * Cache block visitor that determines if there are dirty blocks in a
469 * cache.
470 *
471 * Use with the forEachBlk method in the tag array to determine if the
472 * array contains dirty blocks.
473 */
474class CacheBlkIsDirtyVisitor : public CacheBlkVisitor
475{
476  public:
477    CacheBlkIsDirtyVisitor()
478        : _isDirty(false) {}
479
480    bool operator()(CacheBlk &blk) override {
481        if (blk.isDirty()) {
482            _isDirty = true;
483            return false;
484        } else {
485            return true;
486        }
487    }
488
489    /**
490     * Does the array contain a dirty line?
491     *
492     * \return true if yes, false otherwise.
493     */
494    bool isDirty() const { return _isDirty; };
495
496  private:
497    bool _isDirty;
498};
499
500#endif // __MEM_CACHE_CACHE_HH__
501