cache.hh revision 3861:3b35b0f0b6a9
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    BlkType* findBlock(Addr addr)
283    {
284        return tags->findBlock(addr);
285    }
286
287    BlkType* findBlock(PacketPtr &pkt)
288    {
289        return tags->findBlock(pkt->getAddr());
290    }
291
292    void invalidateBlk(CacheBlk *blk)
293    {
294        tags->invalidateBlk(tags->regenerateBlkAddr(blk->tag, blk->set));
295    }
296
297  public:
298
299    class Params
300    {
301      public:
302        TagStore *tags;
303        MissBuffer *missQueue;
304        Coherence *coherence;
305        BaseCache::Params baseParams;
306        BasePrefetcher*prefetcher;
307        bool prefetchAccess;
308        int hitLatency;
309        CompressionAlgorithm *compressionAlg;
310        const int16_t blkSize;
311        const bool doFastWrites;
312        const bool prefetchMiss;
313        const bool storeCompressed;
314        const bool compressOnWriteback;
315        const int16_t compLatency;
316        const bool adaptiveCompression;
317        const bool writebackCompressed;
318
319        Params(TagStore *_tags, MissBuffer *mq, Coherence *coh,
320               BaseCache::Params params,
321               BasePrefetcher *_prefetcher,
322               bool prefetch_access, int hit_latency,
323               bool do_fast_writes,
324               bool store_compressed, bool adaptive_compression,
325               bool writeback_compressed,
326               CompressionAlgorithm *_compressionAlg, int comp_latency,
327               bool prefetch_miss)
328            : tags(_tags), missQueue(mq), coherence(coh),
329              baseParams(params),
330              prefetcher(_prefetcher), prefetchAccess(prefetch_access),
331              hitLatency(hit_latency),
332              compressionAlg(_compressionAlg),
333              blkSize(_tags->getBlockSize()),
334              doFastWrites(do_fast_writes),
335              prefetchMiss(prefetch_miss),
336              storeCompressed(store_compressed),
337              compressOnWriteback(!store_compressed && writeback_compressed),
338              compLatency(comp_latency),
339              adaptiveCompression(adaptive_compression),
340              writebackCompressed(writeback_compressed)
341        {
342        }
343    };
344
345    /** Instantiates a basic cache object. */
346    Cache(const std::string &_name, Params &params);
347
348    virtual Port *getPort(const std::string &if_name, int idx = -1);
349
350    virtual void recvStatusChange(Port::Status status, bool isCpuSide);
351
352    void regStats();
353
354    /**
355     * Performs the access specified by the request.
356     * @param pkt The request to perform.
357     * @return The result of the access.
358     */
359    bool access(PacketPtr &pkt);
360
361    /**
362     * Selects a request to send on the bus.
363     * @return The memory request to service.
364     */
365    virtual PacketPtr getPacket();
366
367    /**
368     * Was the request was sent successfully?
369     * @param pkt The request.
370     * @param success True if the request was sent successfully.
371     */
372    virtual void sendResult(PacketPtr &pkt, MSHR* mshr, bool success);
373
374    /**
375     * Was the CSHR request was sent successfully?
376     * @param pkt The request.
377     * @param success True if the request was sent successfully.
378     */
379    virtual void sendCoherenceResult(PacketPtr &pkt, MSHR* cshr, bool success);
380
381    /**
382     * Handles a response (cache line fill/write ack) from the bus.
383     * @param pkt The request being responded to.
384     */
385    void handleResponse(PacketPtr &pkt);
386
387    /**
388     * Selects a coherence message to forward to lower levels of the hierarchy.
389     * @return The coherence message to forward.
390     */
391    virtual PacketPtr getCoherencePacket();
392
393    /**
394     * Snoops bus transactions to maintain coherence.
395     * @param pkt The current bus transaction.
396     */
397    void snoop(PacketPtr &pkt);
398
399    void snoopResponse(PacketPtr &pkt);
400
401    /**
402     * Invalidates the block containing address if found.
403     * @param addr The address to look for.
404     * @param asid The address space ID of the address.
405     * @todo Is this function necessary?
406     */
407    void invalidateBlk(Addr addr);
408
409    /**
410     * Squash all requests associated with specified thread.
411     * intended for use by I-cache.
412     * @param threadNum The thread to squash.
413     */
414    void squash(int threadNum)
415    {
416        missQueue->squash(threadNum);
417    }
418
419    /**
420     * Return the number of outstanding misses in a Cache.
421     * Default returns 0.
422     *
423     * @retval unsigned The number of missing still outstanding.
424     */
425    unsigned outstandingMisses() const
426    {
427        return missQueue->getMisses();
428    }
429
430    /**
431     * Perform the access specified in the request and return the estimated
432     * time of completion. This function can either update the hierarchy state
433     * or just perform the access wherever the data is found depending on the
434     * state of the update flag.
435     * @param pkt The memory request to satisfy
436     * @param update If true, update the hierarchy, otherwise just perform the
437     * request.
438     * @return The estimated completion time.
439     */
440    Tick probe(PacketPtr &pkt, bool update, CachePort * otherSidePort);
441
442    /**
443     * Snoop for the provided request in the cache and return the estimated
444     * time of completion.
445     * @todo Can a snoop probe not change state?
446     * @param pkt The memory request to satisfy
447     * @param update If true, update the hierarchy, otherwise just perform the
448     * request.
449     * @return The estimated completion time.
450     */
451    Tick snoopProbe(PacketPtr &pkt);
452
453    bool inCache(Addr addr) {
454        return (tags->findBlock(addr) != 0);
455    }
456
457    bool inMissQueue(Addr addr) {
458        return (missQueue->findMSHR(addr) != 0);
459    }
460};
461
462#endif // __CACHE_HH__
463