cache_blk.hh revision 13477:044307c0d0b8
12SN/A/*
21762SN/A * Copyright (c) 2012-2018 ARM Limited
32SN/A * All rights reserved.
42SN/A *
52SN/A * The license below extends only to copyright in the software and shall
62SN/A * not be construed as granting a license to any other intellectual
72SN/A * property including but not limited to intellectual property relating
82SN/A * to a hardware implementation of the functionality of the software
92SN/A * licensed hereunder.  You may use the software subject to the license
102SN/A * terms below provided that you ensure that this notice is replicated
112SN/A * unmodified and in its entirety in all distributions of the software,
122SN/A * modified or unmodified, in source code or in binary form.
132SN/A *
142SN/A * Copyright (c) 2003-2005 The Regents of The University of Michigan
152SN/A * All rights reserved.
162SN/A *
172SN/A * Redistribution and use in source and binary forms, with or without
182SN/A * modification, are permitted provided that the following conditions are
192SN/A * met: redistributions of source code must retain the above copyright
202SN/A * notice, this list of conditions and the following disclaimer;
212SN/A * redistributions in binary form must reproduce the above copyright
222SN/A * notice, this list of conditions and the following disclaimer in the
232SN/A * documentation and/or other materials provided with the distribution;
242SN/A * neither the name of the copyright holders nor the names of its
252SN/A * contributors may be used to endorse or promote products derived from
262SN/A * this software without specific prior written permission.
272665Ssaidi@eecs.umich.edu *
282665Ssaidi@eecs.umich.edu * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
292665Ssaidi@eecs.umich.edu * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
302SN/A * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
312SN/A * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
322SN/A * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
332SN/A * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
342SN/A * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
352SN/A * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
362SN/A * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
372432SN/A * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
381147SN/A * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
393453Sgblack@eecs.umich.edu *
402984Sgblack@eecs.umich.edu * Authors: Erik Hallnor
412984Sgblack@eecs.umich.edu *          Andreas Sandberg
421147SN/A */
432517SN/A
442984Sgblack@eecs.umich.edu/** @file
4556SN/A * Definitions of a simple cache block class.
462SN/A */
472680Sktlim@umich.edu
482SN/A#ifndef __MEM_CACHE_CACHE_BLK_HH__
493453Sgblack@eecs.umich.edu#define __MEM_CACHE_CACHE_BLK_HH__
502SN/A
515004Sgblack@eecs.umich.edu#include <cassert>
522SN/A#include <cstdint>
533453Sgblack@eecs.umich.edu#include <iosfwd>
543453Sgblack@eecs.umich.edu#include <list>
553453Sgblack@eecs.umich.edu#include <string>
563453Sgblack@eecs.umich.edu
575004Sgblack@eecs.umich.edu#include "base/printable.hh"
582SN/A#include "base/types.hh"
595004Sgblack@eecs.umich.edu#include "mem/cache/replacement_policies/base.hh"
605004Sgblack@eecs.umich.edu#include "mem/packet.hh"
615004Sgblack@eecs.umich.edu#include "mem/request.hh"
622SN/A
633453Sgblack@eecs.umich.edu/**
645004Sgblack@eecs.umich.edu * Cache block status bit assignments
652SN/A */
663453Sgblack@eecs.umich.eduenum CacheBlkStatusBits : unsigned {
673453Sgblack@eecs.umich.edu    /** valid, readable */
683453Sgblack@eecs.umich.edu    BlkValid =          0x01,
692SN/A    /** write permission */
703453Sgblack@eecs.umich.edu    BlkWritable =       0x02,
712SN/A    /** read permission (yes, block can be valid but not readable) */
725004Sgblack@eecs.umich.edu    BlkReadable =       0x04,
735004Sgblack@eecs.umich.edu    /** dirty (modified) */
742SN/A    BlkDirty =          0x08,
753453Sgblack@eecs.umich.edu    /** block was a hardware prefetch yet unaccessed*/
763453Sgblack@eecs.umich.edu    BlkHWPrefetched =   0x20,
773453Sgblack@eecs.umich.edu    /** block holds data from the secure memory space */
782SN/A    BlkSecure =         0x40,
793453Sgblack@eecs.umich.edu};
803453Sgblack@eecs.umich.edu
813453Sgblack@eecs.umich.edu/**
823453Sgblack@eecs.umich.edu * A Basic Cache block.
833453Sgblack@eecs.umich.edu * Contains the tag, status, and a pointer to data.
843453Sgblack@eecs.umich.edu */
852SN/Aclass CacheBlk : public ReplaceableEntry
863453Sgblack@eecs.umich.edu{
872SN/A  public:
883453Sgblack@eecs.umich.edu    /** Task Id associated with this block */
893453Sgblack@eecs.umich.edu    uint32_t task_id;
903453Sgblack@eecs.umich.edu
914957Sacolyte@umich.edu    /** Data block tag value. */
924957Sacolyte@umich.edu    Addr tag;
935004Sgblack@eecs.umich.edu    /**
945004Sgblack@eecs.umich.edu     * Contains a copy of the data in this block for easy access. This is used
955004Sgblack@eecs.umich.edu     * for efficient execution when the data could be actually stored in
965004Sgblack@eecs.umich.edu     * another format (COW, compressed, sub-blocked, etc). In all cases the
975004Sgblack@eecs.umich.edu     * data stored here should be kept consistant with the actual data
985004Sgblack@eecs.umich.edu     * referenced by this block.
995004Sgblack@eecs.umich.edu     */
1005004Sgblack@eecs.umich.edu    uint8_t *data;
1015004Sgblack@eecs.umich.edu
1025004Sgblack@eecs.umich.edu    /** block state: OR of CacheBlkStatusBit */
1035004Sgblack@eecs.umich.edu    typedef unsigned State;
1044967Sacolyte@umich.edu
1053453Sgblack@eecs.umich.edu    /** The current status of this block. @sa CacheBlockStatusBits */
1062SN/A    State status;
1073453Sgblack@eecs.umich.edu
1083453Sgblack@eecs.umich.edu    /**
1093453Sgblack@eecs.umich.edu     * Which curTick() will this block be accessible. Its value is only
1103453Sgblack@eecs.umich.edu     * meaningful if the block is valid.
1113453Sgblack@eecs.umich.edu     */
1123453Sgblack@eecs.umich.edu    Tick whenReady;
1133453Sgblack@eecs.umich.edu
1142SN/A    /** Number of references to this block since it was brought in. */
1153453Sgblack@eecs.umich.edu    unsigned refCount;
1163453Sgblack@eecs.umich.edu
1173453Sgblack@eecs.umich.edu    /** holds the source requestor ID for this block. */
1182SN/A    int srcMasterId;
1194967Sacolyte@umich.edu
1203453Sgblack@eecs.umich.edu    /**
1212SN/A     * Tick on which the block was inserted in the cache. Its value is only
1223453Sgblack@eecs.umich.edu     * meaningful if the block is valid.
1233453Sgblack@eecs.umich.edu     */
1243453Sgblack@eecs.umich.edu    Tick tickInserted;
1253453Sgblack@eecs.umich.edu
1263453Sgblack@eecs.umich.edu  protected:
1273453Sgblack@eecs.umich.edu    /**
1283453Sgblack@eecs.umich.edu     * Represents that the indicated thread context has a "lock" on
1293453Sgblack@eecs.umich.edu     * the block, in the LL/SC sense.
1303453Sgblack@eecs.umich.edu     */
1313453Sgblack@eecs.umich.edu    class Lock {
1323453Sgblack@eecs.umich.edu      public:
1333453Sgblack@eecs.umich.edu        ContextID contextId;     // locking context
1343453Sgblack@eecs.umich.edu        Addr lowAddr;      // low address of lock range
1353453Sgblack@eecs.umich.edu        Addr highAddr;     // high address of lock range
1363453Sgblack@eecs.umich.edu
1372SN/A        // check for matching execution context, and an address that
1383453Sgblack@eecs.umich.edu        // is within the lock
1393453Sgblack@eecs.umich.edu        bool matches(const RequestPtr &req) const
1403453Sgblack@eecs.umich.edu        {
1413453Sgblack@eecs.umich.edu            Addr req_low = req->getPaddr();
1424967Sacolyte@umich.edu            Addr req_high = req_low + req->getSize() -1;
1433453Sgblack@eecs.umich.edu            return (contextId == req->contextId()) &&
1443453Sgblack@eecs.umich.edu                   (req_low >= lowAddr) && (req_high <= highAddr);
1452SN/A        }
1462SN/A
147        // check if a request is intersecting and thus invalidating the lock
148        bool intersects(const RequestPtr &req) const
149        {
150            Addr req_low = req->getPaddr();
151            Addr req_high = req_low + req->getSize() - 1;
152
153            return (req_low <= highAddr) && (req_high >= lowAddr);
154        }
155
156        Lock(const RequestPtr &req)
157            : contextId(req->contextId()),
158              lowAddr(req->getPaddr()),
159              highAddr(lowAddr + req->getSize() - 1)
160        {
161        }
162    };
163
164    /** List of thread contexts that have performed a load-locked (LL)
165     * on the block since the last store. */
166    std::list<Lock> lockList;
167
168  public:
169    CacheBlk() : data(nullptr), tickInserted(0)
170    {
171        invalidate();
172    }
173
174    CacheBlk(const CacheBlk&) = delete;
175    CacheBlk& operator=(const CacheBlk&) = delete;
176    virtual ~CacheBlk() {};
177
178    /**
179     * Checks the write permissions of this block.
180     * @return True if the block is writable.
181     */
182    bool isWritable() const
183    {
184        const State needed_bits = BlkWritable | BlkValid;
185        return (status & needed_bits) == needed_bits;
186    }
187
188    /**
189     * Checks the read permissions of this block.  Note that a block
190     * can be valid but not readable if there is an outstanding write
191     * upgrade miss.
192     * @return True if the block is readable.
193     */
194    bool isReadable() const
195    {
196        const State needed_bits = BlkReadable | BlkValid;
197        return (status & needed_bits) == needed_bits;
198    }
199
200    /**
201     * Checks that a block is valid.
202     * @return True if the block is valid.
203     */
204    bool isValid() const
205    {
206        return (status & BlkValid) != 0;
207    }
208
209    /**
210     * Invalidate the block and clear all state.
211     */
212    virtual void invalidate()
213    {
214        tag = MaxAddr;
215        task_id = ContextSwitchTaskId::Unknown;
216        status = 0;
217        whenReady = MaxTick;
218        refCount = 0;
219        srcMasterId = Request::invldMasterId;
220        lockList.clear();
221    }
222
223    /**
224     * Check to see if a block has been written.
225     * @return True if the block is dirty.
226     */
227    bool isDirty() const
228    {
229        return (status & BlkDirty) != 0;
230    }
231
232    /**
233     * Check if this block was the result of a hardware prefetch, yet to
234     * be touched.
235     * @return True if the block was a hardware prefetch, unaccesed.
236     */
237    bool wasPrefetched() const
238    {
239        return (status & BlkHWPrefetched) != 0;
240    }
241
242    /**
243     * Check if this block holds data from the secure memory space.
244     * @return True if the block holds data from the secure memory space.
245     */
246    bool isSecure() const
247    {
248        return (status & BlkSecure) != 0;
249    }
250
251    /**
252     * Set valid bit.
253     */
254    virtual void setValid()
255    {
256        assert(!isValid());
257        status |= BlkValid;
258    }
259
260    /**
261     * Set secure bit.
262     */
263    virtual void setSecure()
264    {
265        status |= BlkSecure;
266    }
267
268    /**
269     * Get tick at which block's data will be available for access.
270     *
271     * @return Data ready tick.
272     */
273    Tick getWhenReady() const
274    {
275        return whenReady;
276    }
277
278    /**
279     * Set tick at which block's data will be available for access. The new
280     * tick must be chronologically sequential with respect to previous
281     * accesses.
282     *
283     * @param tick New data ready tick.
284     */
285    void setWhenReady(const Tick tick)
286    {
287        assert((whenReady == MaxTick) || (tick >= whenReady));
288        assert(tick >= tickInserted);
289        whenReady = tick;
290    }
291
292    /**
293     * Set member variables when a block insertion occurs. Resets reference
294     * count to 1 (the insertion counts as a reference), and touch block if
295     * it hadn't been touched previously. Sets the insertion tick to the
296     * current tick. Marks the block valid.
297     *
298     * @param tag Block address tag.
299     * @param is_secure Whether the block is in secure space or not.
300     * @param src_master_ID The source requestor ID.
301     * @param task_ID The new task ID.
302     */
303    virtual void insert(const Addr tag, const bool is_secure,
304                        const int src_master_ID, const uint32_t task_ID);
305
306    /**
307     * Track the fact that a local locked was issued to the
308     * block. Invalidate any previous LL to the same address.
309     */
310    void trackLoadLocked(PacketPtr pkt)
311    {
312        assert(pkt->isLLSC());
313        auto l = lockList.begin();
314        while (l != lockList.end()) {
315            if (l->intersects(pkt->req))
316                l = lockList.erase(l);
317            else
318                ++l;
319        }
320
321        lockList.emplace_front(pkt->req);
322    }
323
324    /**
325     * Clear the any load lock that intersect the request, and is from
326     * a different context.
327     */
328    void clearLoadLocks(const RequestPtr &req)
329    {
330        auto l = lockList.begin();
331        while (l != lockList.end()) {
332            if (l->intersects(req) && l->contextId != req->contextId()) {
333                l = lockList.erase(l);
334            } else {
335                ++l;
336            }
337        }
338    }
339
340    /**
341     * Pretty-print tag, set and way, and interpret state bits to readable form
342     * including mapping to a MOESI state.
343     *
344     * @return string with basic state information
345     */
346    virtual std::string print() const
347    {
348        /**
349         *  state       M   O   E   S   I
350         *  writable    1   0   1   0   0
351         *  dirty       1   1   0   0   0
352         *  valid       1   1   1   1   0
353         *
354         *  state   writable    dirty   valid
355         *  M       1           1       1
356         *  O       0           1       1
357         *  E       1           0       1
358         *  S       0           0       1
359         *  I       0           0       0
360         *
361         * Note that only one cache ever has a block in Modified or
362         * Owned state, i.e., only one cache owns the block, or
363         * equivalently has the BlkDirty bit set. However, multiple
364         * caches on the same path to memory can have a block in the
365         * Exclusive state (despite the name). Exclusive means this
366         * cache has the only copy at this level of the hierarchy,
367         * i.e., there may be copies in caches above this cache (in
368         * various states), but there are no peers that have copies on
369         * this branch of the hierarchy, and no caches at or above
370         * this level on any other branch have copies either.
371         **/
372        unsigned state = isWritable() << 2 | isDirty() << 1 | isValid();
373        char s = '?';
374        switch (state) {
375          case 0b111: s = 'M'; break;
376          case 0b011: s = 'O'; break;
377          case 0b101: s = 'E'; break;
378          case 0b001: s = 'S'; break;
379          case 0b000: s = 'I'; break;
380          default:    s = 'T'; break; // @TODO add other types
381        }
382        return csprintf("state: %x (%c) valid: %d writable: %d readable: %d "
383                        "dirty: %d | tag: %#x set: %#x way: %#x", status, s,
384                        isValid(), isWritable(), isReadable(), isDirty(), tag,
385                        getSet(), getWay());
386    }
387
388    /**
389     * Handle interaction of load-locked operations and stores.
390     * @return True if write should proceed, false otherwise.  Returns
391     * false only in the case of a failed store conditional.
392     */
393    bool checkWrite(PacketPtr pkt)
394    {
395        assert(pkt->isWrite());
396
397        // common case
398        if (!pkt->isLLSC() && lockList.empty())
399            return true;
400
401        const RequestPtr &req = pkt->req;
402
403        if (pkt->isLLSC()) {
404            // it's a store conditional... have to check for matching
405            // load locked.
406            bool success = false;
407
408            auto l = lockList.begin();
409            while (!success && l != lockList.end()) {
410                if (l->matches(pkt->req)) {
411                    // it's a store conditional, and as far as the
412                    // memory system can tell, the requesting
413                    // context's lock is still valid.
414                    success = true;
415                    lockList.erase(l);
416                } else {
417                    ++l;
418                }
419            }
420
421            req->setExtraData(success ? 1 : 0);
422            // clear any intersected locks from other contexts (our LL
423            // should already have cleared them)
424            clearLoadLocks(req);
425            return success;
426        } else {
427            // a normal write, if there is any lock not from this
428            // context we clear the list, thus for a private cache we
429            // never clear locks on normal writes
430            clearLoadLocks(req);
431            return true;
432        }
433    }
434};
435
436/**
437 * Special instance of CacheBlk for use with tempBlk that deals with its
438 * block address regeneration.
439 * @sa Cache
440 */
441class TempCacheBlk final : public CacheBlk
442{
443  private:
444    /**
445     * Copy of the block's address, used to regenerate tempBlock's address.
446     */
447    Addr _addr;
448
449  public:
450    /**
451     * Creates a temporary cache block, with its own storage.
452     * @param size The size (in bytes) of this cache block.
453     */
454    TempCacheBlk(unsigned size) : CacheBlk()
455    {
456        data = new uint8_t[size];
457    }
458    TempCacheBlk(const TempCacheBlk&) = delete;
459    TempCacheBlk& operator=(const TempCacheBlk&) = delete;
460    ~TempCacheBlk() { delete [] data; };
461
462    /**
463     * Invalidate the block and clear all state.
464     */
465    void invalidate() override {
466        CacheBlk::invalidate();
467
468        _addr = MaxAddr;
469    }
470
471    void insert(const Addr addr, const bool is_secure,
472                const int src_master_ID=0, const uint32_t task_ID=0) override
473    {
474        // Make sure that the block has been properly invalidated
475        assert(status == 0);
476
477        // Set block address
478        _addr = addr;
479
480        // Set secure state
481        if (is_secure) {
482            setSecure();
483        }
484
485        // Validate block
486        setValid();
487    }
488
489    /**
490     * Get block's address.
491     *
492     * @return addr Address value.
493     */
494    Addr getAddr() const
495    {
496        return _addr;
497    }
498};
499
500/**
501 * Simple class to provide virtual print() method on cache blocks
502 * without allocating a vtable pointer for every single cache block.
503 * Just wrap the CacheBlk object in an instance of this before passing
504 * to a function that requires a Printable object.
505 */
506class CacheBlkPrintWrapper : public Printable
507{
508    CacheBlk *blk;
509  public:
510    CacheBlkPrintWrapper(CacheBlk *_blk) : blk(_blk) {}
511    virtual ~CacheBlkPrintWrapper() {}
512    void print(std::ostream &o, int verbosity = 0,
513               const std::string &prefix = "") const;
514};
515
516#endif //__MEM_CACHE_CACHE_BLK_HH__
517