cache_blk.hh revision 13445
1/*
2 * Copyright (c) 2012-2018 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 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 *          Andreas Sandberg
42 */
43
44/** @file
45 * Definitions of a simple cache block class.
46 */
47
48#ifndef __MEM_CACHE_CACHE_BLK_HH__
49#define __MEM_CACHE_CACHE_BLK_HH__
50
51#include <cassert>
52#include <cstdint>
53#include <iosfwd>
54#include <list>
55#include <string>
56
57#include "base/printable.hh"
58#include "base/types.hh"
59#include "mem/cache/replacement_policies/base.hh"
60#include "mem/packet.hh"
61#include "mem/request.hh"
62
63/**
64 * Cache block status bit assignments
65 */
66enum CacheBlkStatusBits : unsigned {
67    /** valid, readable */
68    BlkValid =          0x01,
69    /** write permission */
70    BlkWritable =       0x02,
71    /** read permission (yes, block can be valid but not readable) */
72    BlkReadable =       0x04,
73    /** dirty (modified) */
74    BlkDirty =          0x08,
75    /** block was a hardware prefetch yet unaccessed*/
76    BlkHWPrefetched =   0x20,
77    /** block holds data from the secure memory space */
78    BlkSecure =         0x40,
79};
80
81/**
82 * A Basic Cache block.
83 * Contains the tag, status, and a pointer to data.
84 */
85class CacheBlk : public ReplaceableEntry
86{
87  public:
88    /** Task Id associated with this block */
89    uint32_t task_id;
90
91    /** Data block tag value. */
92    Addr tag;
93    /**
94     * Contains a copy of the data in this block for easy access. This is used
95     * for efficient execution when the data could be actually stored in
96     * another format (COW, compressed, sub-blocked, etc). In all cases the
97     * data stored here should be kept consistant with the actual data
98     * referenced by this block.
99     */
100    uint8_t *data;
101
102    /** block state: OR of CacheBlkStatusBit */
103    typedef unsigned State;
104
105    /** The current status of this block. @sa CacheBlockStatusBits */
106    State status;
107
108    /** Which curTick() will this block be accessible */
109    Tick whenReady;
110
111    /** Number of references to this block since it was brought in. */
112    unsigned refCount;
113
114    /** holds the source requestor ID for this block. */
115    int srcMasterId;
116
117    /** Tick on which the block was inserted in the cache. */
118    Tick tickInserted;
119
120  protected:
121    /**
122     * Represents that the indicated thread context has a "lock" on
123     * the block, in the LL/SC sense.
124     */
125    class Lock {
126      public:
127        ContextID contextId;     // locking context
128        Addr lowAddr;      // low address of lock range
129        Addr highAddr;     // high address of lock range
130
131        // check for matching execution context, and an address that
132        // is within the lock
133        bool matches(const RequestPtr &req) const
134        {
135            Addr req_low = req->getPaddr();
136            Addr req_high = req_low + req->getSize() -1;
137            return (contextId == req->contextId()) &&
138                   (req_low >= lowAddr) && (req_high <= highAddr);
139        }
140
141        // check if a request is intersecting and thus invalidating the lock
142        bool intersects(const RequestPtr &req) const
143        {
144            Addr req_low = req->getPaddr();
145            Addr req_high = req_low + req->getSize() - 1;
146
147            return (req_low <= highAddr) && (req_high >= lowAddr);
148        }
149
150        Lock(const RequestPtr &req)
151            : contextId(req->contextId()),
152              lowAddr(req->getPaddr()),
153              highAddr(lowAddr + req->getSize() - 1)
154        {
155        }
156    };
157
158    /** List of thread contexts that have performed a load-locked (LL)
159     * on the block since the last store. */
160    std::list<Lock> lockList;
161
162  public:
163    CacheBlk() : data(nullptr)
164    {
165        invalidate();
166    }
167
168    CacheBlk(const CacheBlk&) = delete;
169    CacheBlk& operator=(const CacheBlk&) = delete;
170    virtual ~CacheBlk() {};
171
172    /**
173     * Checks the write permissions of this block.
174     * @return True if the block is writable.
175     */
176    bool isWritable() const
177    {
178        const State needed_bits = BlkWritable | BlkValid;
179        return (status & needed_bits) == needed_bits;
180    }
181
182    /**
183     * Checks the read permissions of this block.  Note that a block
184     * can be valid but not readable if there is an outstanding write
185     * upgrade miss.
186     * @return True if the block is readable.
187     */
188    bool isReadable() const
189    {
190        const State needed_bits = BlkReadable | BlkValid;
191        return (status & needed_bits) == needed_bits;
192    }
193
194    /**
195     * Checks that a block is valid.
196     * @return True if the block is valid.
197     */
198    bool isValid() const
199    {
200        return (status & BlkValid) != 0;
201    }
202
203    /**
204     * Invalidate the block and clear all state.
205     */
206    virtual void invalidate()
207    {
208        tag = MaxAddr;
209        task_id = ContextSwitchTaskId::Unknown;
210        status = 0;
211        whenReady = MaxTick;
212        refCount = 0;
213        srcMasterId = Request::invldMasterId;
214        tickInserted = MaxTick;
215        lockList.clear();
216    }
217
218    /**
219     * Check to see if a block has been written.
220     * @return True if the block is dirty.
221     */
222    bool isDirty() const
223    {
224        return (status & BlkDirty) != 0;
225    }
226
227    /**
228     * Check if this block was the result of a hardware prefetch, yet to
229     * be touched.
230     * @return True if the block was a hardware prefetch, unaccesed.
231     */
232    bool wasPrefetched() const
233    {
234        return (status & BlkHWPrefetched) != 0;
235    }
236
237    /**
238     * Check if this block holds data from the secure memory space.
239     * @return True if the block holds data from the secure memory space.
240     */
241    bool isSecure() const
242    {
243        return (status & BlkSecure) != 0;
244    }
245
246    /**
247     * Set valid bit.
248     */
249    virtual void setValid()
250    {
251        assert(!isValid());
252        status |= BlkValid;
253    }
254
255    /**
256     * Set secure bit.
257     */
258    virtual void setSecure()
259    {
260        status |= BlkSecure;
261    }
262
263    /**
264     * Set member variables when a block insertion occurs. Resets reference
265     * count to 1 (the insertion counts as a reference), and touch block if
266     * it hadn't been touched previously. Sets the insertion tick to the
267     * current tick. Marks the block valid.
268     *
269     * @param tag Block address tag.
270     * @param is_secure Whether the block is in secure space or not.
271     * @param src_master_ID The source requestor ID.
272     * @param task_ID The new task ID.
273     */
274    virtual void insert(const Addr tag, const bool is_secure,
275                        const int src_master_ID, const uint32_t task_ID);
276
277    /**
278     * Track the fact that a local locked was issued to the
279     * block. Invalidate any previous LL to the same address.
280     */
281    void trackLoadLocked(PacketPtr pkt)
282    {
283        assert(pkt->isLLSC());
284        auto l = lockList.begin();
285        while (l != lockList.end()) {
286            if (l->intersects(pkt->req))
287                l = lockList.erase(l);
288            else
289                ++l;
290        }
291
292        lockList.emplace_front(pkt->req);
293    }
294
295    /**
296     * Clear the any load lock that intersect the request, and is from
297     * a different context.
298     */
299    void clearLoadLocks(const RequestPtr &req)
300    {
301        auto l = lockList.begin();
302        while (l != lockList.end()) {
303            if (l->intersects(req) && l->contextId != req->contextId()) {
304                l = lockList.erase(l);
305            } else {
306                ++l;
307            }
308        }
309    }
310
311    /**
312     * Pretty-print tag, set and way, and interpret state bits to readable form
313     * including mapping to a MOESI state.
314     *
315     * @return string with basic state information
316     */
317    virtual std::string print() const
318    {
319        /**
320         *  state       M   O   E   S   I
321         *  writable    1   0   1   0   0
322         *  dirty       1   1   0   0   0
323         *  valid       1   1   1   1   0
324         *
325         *  state   writable    dirty   valid
326         *  M       1           1       1
327         *  O       0           1       1
328         *  E       1           0       1
329         *  S       0           0       1
330         *  I       0           0       0
331         *
332         * Note that only one cache ever has a block in Modified or
333         * Owned state, i.e., only one cache owns the block, or
334         * equivalently has the BlkDirty bit set. However, multiple
335         * caches on the same path to memory can have a block in the
336         * Exclusive state (despite the name). Exclusive means this
337         * cache has the only copy at this level of the hierarchy,
338         * i.e., there may be copies in caches above this cache (in
339         * various states), but there are no peers that have copies on
340         * this branch of the hierarchy, and no caches at or above
341         * this level on any other branch have copies either.
342         **/
343        unsigned state = isWritable() << 2 | isDirty() << 1 | isValid();
344        char s = '?';
345        switch (state) {
346          case 0b111: s = 'M'; break;
347          case 0b011: s = 'O'; break;
348          case 0b101: s = 'E'; break;
349          case 0b001: s = 'S'; break;
350          case 0b000: s = 'I'; break;
351          default:    s = 'T'; break; // @TODO add other types
352        }
353        return csprintf("state: %x (%c) valid: %d writable: %d readable: %d "
354                        "dirty: %d | tag: %#x set: %#x way: %#x", status, s,
355                        isValid(), isWritable(), isReadable(), isDirty(), tag,
356                        getSet(), getWay());
357    }
358
359    /**
360     * Handle interaction of load-locked operations and stores.
361     * @return True if write should proceed, false otherwise.  Returns
362     * false only in the case of a failed store conditional.
363     */
364    bool checkWrite(PacketPtr pkt)
365    {
366        assert(pkt->isWrite());
367
368        // common case
369        if (!pkt->isLLSC() && lockList.empty())
370            return true;
371
372        const RequestPtr &req = pkt->req;
373
374        if (pkt->isLLSC()) {
375            // it's a store conditional... have to check for matching
376            // load locked.
377            bool success = false;
378
379            auto l = lockList.begin();
380            while (!success && l != lockList.end()) {
381                if (l->matches(pkt->req)) {
382                    // it's a store conditional, and as far as the
383                    // memory system can tell, the requesting
384                    // context's lock is still valid.
385                    success = true;
386                    lockList.erase(l);
387                } else {
388                    ++l;
389                }
390            }
391
392            req->setExtraData(success ? 1 : 0);
393            // clear any intersected locks from other contexts (our LL
394            // should already have cleared them)
395            clearLoadLocks(req);
396            return success;
397        } else {
398            // a normal write, if there is any lock not from this
399            // context we clear the list, thus for a private cache we
400            // never clear locks on normal writes
401            clearLoadLocks(req);
402            return true;
403        }
404    }
405};
406
407/**
408 * Special instance of CacheBlk for use with tempBlk that deals with its
409 * block address regeneration.
410 * @sa Cache
411 */
412class TempCacheBlk final : public CacheBlk
413{
414  private:
415    /**
416     * Copy of the block's address, used to regenerate tempBlock's address.
417     */
418    Addr _addr;
419
420  public:
421    /**
422     * Creates a temporary cache block, with its own storage.
423     * @param size The size (in bytes) of this cache block.
424     */
425    TempCacheBlk(unsigned size) : CacheBlk()
426    {
427        data = new uint8_t[size];
428    }
429    TempCacheBlk(const TempCacheBlk&) = delete;
430    TempCacheBlk& operator=(const TempCacheBlk&) = delete;
431    ~TempCacheBlk() { delete [] data; };
432
433    /**
434     * Invalidate the block and clear all state.
435     */
436    void invalidate() override {
437        CacheBlk::invalidate();
438
439        _addr = MaxAddr;
440    }
441
442    void insert(const Addr addr, const bool is_secure,
443                const int src_master_ID=0, const uint32_t task_ID=0) override
444    {
445        // Make sure that the block has been properly invalidated
446        assert(status == 0);
447
448        // Set block address
449        _addr = addr;
450
451        // Set secure state
452        if (is_secure) {
453            setSecure();
454        }
455
456        // Validate block
457        setValid();
458    }
459
460    /**
461     * Get block's address.
462     *
463     * @return addr Address value.
464     */
465    Addr getAddr() const
466    {
467        return _addr;
468    }
469};
470
471/**
472 * Simple class to provide virtual print() method on cache blocks
473 * without allocating a vtable pointer for every single cache block.
474 * Just wrap the CacheBlk object in an instance of this before passing
475 * to a function that requires a Printable object.
476 */
477class CacheBlkPrintWrapper : public Printable
478{
479    CacheBlk *blk;
480  public:
481    CacheBlkPrintWrapper(CacheBlk *_blk) : blk(_blk) {}
482    virtual ~CacheBlkPrintWrapper() {}
483    void print(std::ostream &o, int verbosity = 0,
484               const std::string &prefix = "") const;
485};
486
487#endif //__MEM_CACHE_CACHE_BLK_HH__
488