base_set_assoc.hh revision 10263
1/*
2 * Copyright (c) 2012-2013 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) 2003-2005,2014 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 */
42
43/**
44 * @file
45 * Declaration of a base set associative tag store.
46 */
47
48#ifndef __MEM_CACHE_TAGS_BASESETASSOC_HH__
49#define __MEM_CACHE_TAGS_BASESETASSOC_HH__
50
51#include <cassert>
52#include <cstring>
53#include <list>
54
55#include "mem/cache/tags/base.hh"
56#include "mem/cache/tags/cacheset.hh"
57#include "mem/cache/base.hh"
58#include "mem/cache/blk.hh"
59#include "mem/packet.hh"
60#include "params/BaseSetAssoc.hh"
61
62/**
63 * A BaseSetAssoc cache tag store.
64 * @sa  \ref gem5MemorySystem "gem5 Memory System"
65 *
66 * The BaseSetAssoc tags provide a base, as well as the functionality
67 * common to any set associative tags. Any derived class must implement
68 * the methods related to the specifics of the actual replacment policy.
69 * These are:
70 *
71 * BlkType* accessBlock();
72 * BlkType* findVictim();
73 * void insertBlock();
74 * void invalidate();
75 */
76class BaseSetAssoc : public BaseTags
77{
78  public:
79    /** Typedef the block type used in this tag store. */
80    typedef CacheBlk BlkType;
81    /** Typedef for a list of pointers to the local block class. */
82    typedef std::list<BlkType*> BlkList;
83    /** Typedef the set type used in this tag store. */
84    typedef CacheSet<CacheBlk> SetType;
85
86
87  protected:
88    /** The associativity of the cache. */
89    const unsigned assoc;
90    /** The number of sets in the cache. */
91    const unsigned numSets;
92    /** Whether tags and data are accessed sequentially. */
93    const bool sequentialAccess;
94
95    /** The cache sets. */
96    SetType *sets;
97
98    /** The cache blocks. */
99    BlkType *blks;
100    /** The data blocks, 1 per cache block. */
101    uint8_t *dataBlks;
102
103    /** The amount to shift the address to get the set. */
104    int setShift;
105    /** The amount to shift the address to get the tag. */
106    int tagShift;
107    /** Mask out all bits that aren't part of the set index. */
108    unsigned setMask;
109    /** Mask out all bits that aren't part of the block offset. */
110    unsigned blkMask;
111
112public:
113
114    /** Convenience typedef. */
115     typedef BaseSetAssocParams Params;
116
117    /**
118     * Construct and initialize this tag store.
119     */
120    BaseSetAssoc(const Params *p);
121
122    /**
123     * Destructor
124     */
125    virtual ~BaseSetAssoc();
126
127    /**
128     * Return the block size.
129     * @return the block size.
130     */
131    unsigned
132    getBlockSize() const
133    {
134        return blkSize;
135    }
136
137    /**
138     * Return the subblock size. In the case of BaseSetAssoc it is always
139     * the block size.
140     * @return The block size.
141     */
142    unsigned
143    getSubBlockSize() const
144    {
145        return blkSize;
146    }
147
148    /**
149     * Invalidate the given block.
150     * @param blk The block to invalidate.
151     */
152    void invalidate(BlkType *blk)
153    {
154        assert(blk);
155        assert(blk->isValid());
156        tagsInUse--;
157        assert(blk->srcMasterId < cache->system->maxMasters());
158        occupancies[blk->srcMasterId]--;
159        blk->srcMasterId = Request::invldMasterId;
160        blk->task_id = ContextSwitchTaskId::Unknown;
161        blk->tickInserted = curTick();
162    }
163
164    /**
165     * Access block and update replacement data. May not succeed, in which case
166     * NULL pointer is returned. This has all the implications of a cache
167     * access and should only be used as such. Returns the access latency as a
168     * side effect.
169     * @param addr The address to find.
170     * @param is_secure True if the target memory space is secure.
171     * @param asid The address space ID.
172     * @param lat The access latency.
173     * @return Pointer to the cache block if found.
174     */
175    BlkType* accessBlock(Addr addr, bool is_secure, Cycles &lat,
176                                 int context_src)
177    {
178        Addr tag = extractTag(addr);
179        int set = extractSet(addr);
180        BlkType *blk = sets[set].findBlk(tag, is_secure);
181        lat = hitLatency;
182
183        // Access all tags in parallel, hence one in each way.  The data side
184        // either accesses all blocks in parallel, or one block sequentially on
185        // a hit.  Sequential access with a miss doesn't access data.
186        tagAccesses += assoc;
187        if (sequentialAccess) {
188            if (blk != NULL) {
189                dataAccesses += 1;
190            }
191        } else {
192            dataAccesses += assoc;
193        }
194
195        if (blk != NULL) {
196            if (blk->whenReady > curTick()
197                && cache->ticksToCycles(blk->whenReady - curTick())
198                > hitLatency) {
199                lat = cache->ticksToCycles(blk->whenReady - curTick());
200            }
201            blk->refCount += 1;
202        }
203
204        return blk;
205    }
206
207    /**
208     * Finds the given address in the cache, do not update replacement data.
209     * i.e. This is a no-side-effect find of a block.
210     * @param addr The address to find.
211     * @param is_secure True if the target memory space is secure.
212     * @param asid The address space ID.
213     * @return Pointer to the cache block if found.
214     */
215    BlkType* findBlock(Addr addr, bool is_secure) const;
216
217    /**
218     * Find an invalid block to evict for the address provided.
219     * If there are no invalid blocks, this will return the block
220     * in the least-recently-used position.
221     * @param addr The addr to a find a replacement candidate for.
222     * @return The candidate block.
223     */
224    BlkType* findVictim(Addr addr) const
225    {
226        BlkType *blk = NULL;
227        int set = extractSet(addr);
228
229        // prefer to evict an invalid block
230        for (int i = 0; i < assoc; ++i) {
231            blk = sets[set].blks[i];
232            if (!blk->isValid()) {
233                break;
234            }
235        }
236
237        return blk;
238    }
239
240    /**
241     * Insert the new block into the cache.
242     * @param pkt Packet holding the address to update
243     * @param blk The block to update.
244     */
245     void insertBlock(PacketPtr pkt, BlkType *blk)
246     {
247         Addr addr = pkt->getAddr();
248         MasterID master_id = pkt->req->masterId();
249         uint32_t task_id = pkt->req->taskId();
250         bool is_secure = pkt->isSecure();
251         if (!blk->isTouched) {
252             tagsInUse++;
253             blk->isTouched = true;
254             if (!warmedUp && tagsInUse.value() >= warmupBound) {
255                 warmedUp = true;
256                 warmupCycle = curTick();
257             }
258         }
259
260         // If we're replacing a block that was previously valid update
261         // stats for it. This can't be done in findBlock() because a
262         // found block might not actually be replaced there if the
263         // coherence protocol says it can't be.
264         if (blk->isValid()) {
265             replacements[0]++;
266             totalRefs += blk->refCount;
267             ++sampledRefs;
268             blk->refCount = 0;
269
270             // deal with evicted block
271             assert(blk->srcMasterId < cache->system->maxMasters());
272             occupancies[blk->srcMasterId]--;
273
274             blk->invalidate();
275         }
276
277         blk->isTouched = true;
278         // Set tag for new block.  Caller is responsible for setting status.
279         blk->tag = extractTag(addr);
280         if (is_secure)
281             blk->status |= BlkSecure;
282
283         // deal with what we are bringing in
284         assert(master_id < cache->system->maxMasters());
285         occupancies[master_id]++;
286         blk->srcMasterId = master_id;
287         blk->task_id = task_id;
288         blk->tickInserted = curTick();
289
290         // We only need to write into one tag and one data block.
291         tagAccesses += 1;
292         dataAccesses += 1;
293     }
294
295    /**
296     * Generate the tag from the given address.
297     * @param addr The address to get the tag from.
298     * @return The tag of the address.
299     */
300    Addr extractTag(Addr addr) const
301    {
302        return (addr >> tagShift);
303    }
304
305    /**
306     * Calculate the set index from the address.
307     * @param addr The address to get the set from.
308     * @return The set index of the address.
309     */
310    int extractSet(Addr addr) const
311    {
312        return ((addr >> setShift) & setMask);
313    }
314
315    /**
316     * Get the block offset from an address.
317     * @param addr The address to get the offset of.
318     * @return The block offset.
319     */
320    int extractBlkOffset(Addr addr) const
321    {
322        return (addr & blkMask);
323    }
324
325    /**
326     * Align an address to the block size.
327     * @param addr the address to align.
328     * @return The block address.
329     */
330    Addr blkAlign(Addr addr) const
331    {
332        return (addr & ~(Addr)blkMask);
333    }
334
335    /**
336     * Regenerate the block address from the tag.
337     * @param tag The tag of the block.
338     * @param set The set of the block.
339     * @return The block address.
340     */
341    Addr regenerateBlkAddr(Addr tag, unsigned set) const
342    {
343        return ((tag << tagShift) | ((Addr)set << setShift));
344    }
345
346    /**
347     * Return the hit latency.
348     * @return the hit latency.
349     */
350    Cycles getHitLatency() const
351    {
352        return hitLatency;
353    }
354    /**
355     *iterated through all blocks and clear all locks
356     *Needed to clear all lock tracking at once
357     */
358    virtual void clearLocks();
359
360    /**
361     * Called at end of simulation to complete average block reference stats.
362     */
363    virtual void cleanupRefs();
364
365    /**
366     * Print all tags used
367     */
368    virtual std::string print() const;
369
370    /**
371     * Called prior to dumping stats to compute task occupancy
372     */
373    virtual void computeStats();
374
375    /**
376     * Visit each block in the tag store and apply a visitor to the
377     * block.
378     *
379     * The visitor should be a function (or object that behaves like a
380     * function) that takes a cache block reference as its parameter
381     * and returns a bool. A visitor can request the traversal to be
382     * stopped by returning false, returning true causes it to be
383     * called for the next block in the tag store.
384     *
385     * \param visitor Visitor to call on each block.
386     */
387    template <typename V>
388    void forEachBlk(V &visitor) {
389        for (unsigned i = 0; i < numSets * assoc; ++i) {
390            if (!visitor(blks[i]))
391                return;
392        }
393    }
394};
395
396#endif // __MEM_CACHE_TAGS_BASESETASSOC_HH__
397