cache.hh revision 4190:5069dfa3d62e
1/*
2 * Copyright (c) 2002-2005 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Erik Hallnor
29 *          Dave Greene
30 *          Steve Reinhardt
31 */
32
33/**
34 * @file
35 * Describes a cache based on template policies.
36 */
37
38#ifndef __CACHE_HH__
39#define __CACHE_HH__
40
41#include "base/compression/base.hh"
42#include "base/misc.hh" // fatal, panic, and warn
43#include "cpu/smt.hh" // SMT_MAX_THREADS
44
45#include "mem/cache/base_cache.hh"
46#include "mem/cache/cache_blk.hh"
47#include "mem/cache/miss/miss_buffer.hh"
48
49//Forward decleration
50class MSHR;
51class BasePrefetcher;
52
53/**
54 * A template-policy based cache. The behavior of the cache can be altered by
55 * supplying different template policies. TagStore handles all tag and data
56 * storage @sa TagStore. Buffering handles all misses and writes/writebacks
57 * @sa MissQueue. Coherence handles all coherence policy details @sa
58 * UniCoherence, SimpleMultiCoherence.
59 */
60template <class TagStore, class Coherence>
61class Cache : public BaseCache
62{
63  public:
64    /** Define the type of cache block to use. */
65    typedef typename TagStore::BlkType BlkType;
66    /** A typedef for a list of BlkType pointers. */
67    typedef typename TagStore::BlkList BlkList;
68
69    bool prefetchAccess;
70
71  protected:
72
73    class CpuSidePort : public CachePort
74    {
75      public:
76        CpuSidePort(const std::string &_name,
77                    Cache<TagStore,Coherence> *_cache);
78
79        // BaseCache::CachePort just has a BaseCache *; this function
80        // lets us get back the type info we lost when we stored the
81        // cache pointer there.
82        Cache<TagStore,Coherence> *myCache() {
83            return static_cast<Cache<TagStore,Coherence> *>(cache);
84        }
85
86        virtual bool recvTiming(PacketPtr pkt);
87
88        virtual Tick recvAtomic(PacketPtr pkt);
89
90        virtual void recvFunctional(PacketPtr pkt);
91    };
92
93    class MemSidePort : public CachePort
94    {
95      public:
96        MemSidePort(const std::string &_name,
97                    Cache<TagStore,Coherence> *_cache);
98
99        // BaseCache::CachePort just has a BaseCache *; this function
100        // lets us get back the type info we lost when we stored the
101        // cache pointer there.
102        Cache<TagStore,Coherence> *myCache() {
103            return static_cast<Cache<TagStore,Coherence> *>(cache);
104        }
105
106        virtual bool recvTiming(PacketPtr pkt);
107
108        virtual Tick recvAtomic(PacketPtr pkt);
109
110        virtual void recvFunctional(PacketPtr pkt);
111    };
112
113    /** Tag and data Storage */
114    TagStore *tags;
115    /** Miss and Writeback handler */
116    MissBuffer *missQueue;
117    /** Coherence protocol. */
118    Coherence *coherence;
119
120    /** Prefetcher */
121    BasePrefetcher *prefetcher;
122
123    /**
124     * The clock ratio of the outgoing bus.
125     * Used for calculating critical word first.
126     */
127    int busRatio;
128
129     /**
130      * The bus width in bytes of the outgoing bus.
131      * Used for calculating critical word first.
132      */
133    int busWidth;
134
135    /**
136     * The latency of a hit in this device.
137     */
138    int hitLatency;
139
140     /**
141      * A permanent mem req to always be used to cause invalidations.
142      * Used to append to target list, to cause an invalidation.
143      */
144    PacketPtr invalidatePkt;
145    Request *invalidateReq;
146
147    /**
148     * Policy class for performing compression.
149     */
150    CompressionAlgorithm *compressionAlg;
151
152    /**
153     * The block size of this cache. Set to value in the Tags object.
154     */
155    const int16_t blkSize;
156
157    /**
158     * Can this cache should allocate a block on a line-sized write miss.
159     */
160    const bool doFastWrites;
161
162    const bool prefetchMiss;
163
164    /**
165     * Can the data can be stored in a compressed form.
166     */
167    const bool storeCompressed;
168
169    /**
170     * Do we need to compress blocks on writebacks (i.e. because
171     * writeback bus is compressed but storage is not)?
172     */
173    const bool compressOnWriteback;
174
175    /**
176     * The latency of a compression operation.
177     */
178    const int16_t compLatency;
179
180    /**
181     * Should we use an adaptive compression scheme.
182     */
183    const bool adaptiveCompression;
184
185    /**
186     * Do writebacks need to be compressed (i.e. because writeback bus
187     * is compressed), whether or not they're already compressed for
188     * storage.
189     */
190    const bool writebackCompressed;
191
192    /**
193     * Compare the internal block data to the fast access block data.
194     * @param blk The cache block to check.
195     * @return True if the data is the same.
196     */
197    bool verifyData(BlkType *blk);
198
199    /**
200     * Update the internal data of the block. The data to write is assumed to
201     * be in the fast access data.
202     * @param blk The block with the data to update.
203     * @param writebacks A list to store any generated writebacks.
204     * @param compress_block True if we should compress this block
205     */
206    void updateData(BlkType *blk, PacketList &writebacks, bool compress_block);
207
208    /**
209     * Handle a replacement for the given request.
210     * @param blk A pointer to the block, usually NULL
211     * @param pkt The memory request to satisfy.
212     * @param new_state The new state of the block.
213     * @param writebacks A list to store any generated writebacks.
214     */
215    BlkType* doReplacement(BlkType *blk, PacketPtr &pkt,
216                           CacheBlk::State new_state, PacketList &writebacks);
217
218    /**
219     * Does all the processing necessary to perform the provided request.
220     * @param pkt The memory request to perform.
221     * @param lat The latency of the access.
222     * @param writebacks List for any writebacks that need to be performed.
223     * @param update True if the replacement data should be updated.
224     * @return Pointer to the cache block touched by the request. NULL if it
225     * was a miss.
226     */
227    BlkType* handleAccess(PacketPtr &pkt, int & lat,
228                          PacketList & writebacks, bool update = true);
229
230    /**
231     * Populates a cache block and handles all outstanding requests for the
232     * satisfied fill request. This version takes an MSHR pointer and uses its
233     * request to fill the cache block, while repsonding to its targets.
234     * @param blk The cache block if it already exists.
235     * @param mshr The MSHR that contains the fill data and targets to satisfy.
236     * @param new_state The state of the new cache block.
237     * @param writebacks List for any writebacks that need to be performed.
238     * @return Pointer to the new cache block.
239     */
240    BlkType* handleFill(BlkType *blk, MSHR * mshr, CacheBlk::State new_state,
241                        PacketList & writebacks, PacketPtr pkt);
242
243    /**
244     * Populates a cache block and handles all outstanding requests for the
245     * satisfied fill request. This version takes two memory requests. One
246     * contains the fill data, the other is an optional target to satisfy.
247     * Used for Cache::probe.
248     * @param blk The cache block if it already exists.
249     * @param pkt The memory request with the fill data.
250     * @param new_state The state of the new cache block.
251     * @param writebacks List for any writebacks that need to be performed.
252     * @param target The memory request to perform after the fill.
253     * @return Pointer to the new cache block.
254     */
255    BlkType* handleFill(BlkType *blk, PacketPtr &pkt,
256                        CacheBlk::State new_state,
257                        PacketList & writebacks, PacketPtr target = NULL);
258
259    /**
260     * Sets the blk to the new state and handles the given request.
261     * @param blk The cache block being snooped.
262     * @param new_state The new coherence state for the block.
263     * @param pkt The request to satisfy
264     */
265    void handleSnoop(BlkType *blk, CacheBlk::State new_state,
266                     PacketPtr &pkt);
267
268    /**
269     * Sets the blk to the new state.
270     * @param blk The cache block being snooped.
271     * @param new_state The new coherence state for the block.
272     */
273    void handleSnoop(BlkType *blk, CacheBlk::State new_state);
274
275    /**
276     * Create a writeback request for the given block.
277     * @param blk The block to writeback.
278     * @return The writeback request for the block.
279     */
280    PacketPtr writebackBlk(BlkType *blk);
281
282  public:
283
284    class Params
285    {
286      public:
287        TagStore *tags;
288        MissBuffer *missQueue;
289        Coherence *coherence;
290        BaseCache::Params baseParams;
291        BasePrefetcher*prefetcher;
292        bool prefetchAccess;
293        int hitLatency;
294        CompressionAlgorithm *compressionAlg;
295        const int16_t blkSize;
296        const bool doFastWrites;
297        const bool prefetchMiss;
298        const bool storeCompressed;
299        const bool compressOnWriteback;
300        const int16_t compLatency;
301        const bool adaptiveCompression;
302        const bool writebackCompressed;
303
304        Params(TagStore *_tags, MissBuffer *mq, Coherence *coh,
305               BaseCache::Params params,
306               BasePrefetcher *_prefetcher,
307               bool prefetch_access, int hit_latency,
308               bool do_fast_writes,
309               bool store_compressed, bool adaptive_compression,
310               bool writeback_compressed,
311               CompressionAlgorithm *_compressionAlg, int comp_latency,
312               bool prefetch_miss)
313            : tags(_tags), missQueue(mq), coherence(coh),
314              baseParams(params),
315              prefetcher(_prefetcher), prefetchAccess(prefetch_access),
316              hitLatency(hit_latency),
317              compressionAlg(_compressionAlg),
318              blkSize(_tags->getBlockSize()),
319              doFastWrites(do_fast_writes),
320              prefetchMiss(prefetch_miss),
321              storeCompressed(store_compressed),
322              compressOnWriteback(!store_compressed && writeback_compressed),
323              compLatency(comp_latency),
324              adaptiveCompression(adaptive_compression),
325              writebackCompressed(writeback_compressed)
326        {
327        }
328    };
329
330    /** Instantiates a basic cache object. */
331    Cache(const std::string &_name, Params &params);
332
333    virtual Port *getPort(const std::string &if_name, int idx = -1);
334    virtual void deletePortRefs(Port *p);
335
336    virtual void recvStatusChange(Port::Status status, bool isCpuSide);
337
338    void regStats();
339
340    /**
341     * Performs the access specified by the request.
342     * @param pkt The request to perform.
343     * @return The result of the access.
344     */
345    bool access(PacketPtr &pkt);
346
347    /**
348     * Selects a request to send on the bus.
349     * @return The memory request to service.
350     */
351    virtual PacketPtr getPacket();
352
353    /**
354     * Was the request was sent successfully?
355     * @param pkt The request.
356     * @param success True if the request was sent successfully.
357     */
358    virtual void sendResult(PacketPtr &pkt, MSHR* mshr, bool success);
359
360    /**
361     * Was the CSHR request was sent successfully?
362     * @param pkt The request.
363     * @param success True if the request was sent successfully.
364     */
365    virtual void sendCoherenceResult(PacketPtr &pkt, MSHR* cshr, bool success);
366
367    /**
368     * Handles a response (cache line fill/write ack) from the bus.
369     * @param pkt The request being responded to.
370     */
371    void handleResponse(PacketPtr &pkt);
372
373    /**
374     * Selects a coherence message to forward to lower levels of the hierarchy.
375     * @return The coherence message to forward.
376     */
377    virtual PacketPtr getCoherencePacket();
378
379    /**
380     * Snoops bus transactions to maintain coherence.
381     * @param pkt The current bus transaction.
382     */
383    void snoop(PacketPtr &pkt);
384
385    void snoopResponse(PacketPtr &pkt);
386
387    /**
388     * Squash all requests associated with specified thread.
389     * intended for use by I-cache.
390     * @param threadNum The thread to squash.
391     */
392    void squash(int threadNum)
393    {
394        missQueue->squash(threadNum);
395    }
396
397    /**
398     * Return the number of outstanding misses in a Cache.
399     * Default returns 0.
400     *
401     * @retval unsigned The number of missing still outstanding.
402     */
403    unsigned outstandingMisses() const
404    {
405        return missQueue->getMisses();
406    }
407
408    /**
409     * Perform the access specified in the request and return the estimated
410     * time of completion. This function can either update the hierarchy state
411     * or just perform the access wherever the data is found depending on the
412     * state of the update flag.
413     * @param pkt The memory request to satisfy
414     * @param update If true, update the hierarchy, otherwise just perform the
415     * request.
416     * @return The estimated completion time.
417     */
418    Tick probe(PacketPtr &pkt, bool update, CachePort * otherSidePort);
419
420    /**
421     * Snoop for the provided request in the cache and return the estimated
422     * time of completion.
423     * @todo Can a snoop probe not change state?
424     * @param pkt The memory request to satisfy
425     * @param update If true, update the hierarchy, otherwise just perform the
426     * request.
427     * @return The estimated completion time.
428     */
429    Tick snoopProbe(PacketPtr &pkt);
430
431    bool inCache(Addr addr) {
432        return (tags->findBlock(addr) != 0);
433    }
434
435    bool inMissQueue(Addr addr) {
436        return (missQueue->findMSHR(addr) != 0);
437    }
438};
439
440#endif // __CACHE_HH__
441