mem-cache: Fix non-bijective function in Skewed caches
[gem5.git] / src / mem / cache / blk.hh
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_BLK_HH__
49 #define __MEM_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 */
66 enum 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 */
85 class 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 /**
112 * The set and way this block belongs to.
113 * @todo Move this into subclasses when we fix CacheTags to use them.
114 */
115 int set, way;
116
117 /** Number of references to this block since it was brought in. */
118 unsigned refCount;
119
120 /** holds the source requestor ID for this block. */
121 int srcMasterId;
122
123 /** Tick on which the block was inserted in the cache. */
124 Tick tickInserted;
125
126 protected:
127 /**
128 * Represents that the indicated thread context has a "lock" on
129 * the block, in the LL/SC sense.
130 */
131 class Lock {
132 public:
133 ContextID contextId; // locking context
134 Addr lowAddr; // low address of lock range
135 Addr highAddr; // high address of lock range
136
137 // check for matching execution context, and an address that
138 // is within the lock
139 bool matches(const RequestPtr &req) const
140 {
141 Addr req_low = req->getPaddr();
142 Addr req_high = req_low + req->getSize() -1;
143 return (contextId == req->contextId()) &&
144 (req_low >= lowAddr) && (req_high <= highAddr);
145 }
146
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)
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 tickInserted = MaxTick;
221 lockList.clear();
222 }
223
224 /**
225 * Check to see if a block has been written.
226 * @return True if the block is dirty.
227 */
228 bool isDirty() const
229 {
230 return (status & BlkDirty) != 0;
231 }
232
233 /**
234 * Check if this block was the result of a hardware prefetch, yet to
235 * be touched.
236 * @return True if the block was a hardware prefetch, unaccesed.
237 */
238 bool wasPrefetched() const
239 {
240 return (status & BlkHWPrefetched) != 0;
241 }
242
243 /**
244 * Check if this block holds data from the secure memory space.
245 * @return True if the block holds data from the secure memory space.
246 */
247 bool isSecure() const
248 {
249 return (status & BlkSecure) != 0;
250 }
251
252 /**
253 * Set member variables when a block insertion occurs. Resets reference
254 * count to 1 (the insertion counts as a reference), and touch block if
255 * it hadn't been touched previously. Sets the insertion tick to the
256 * current tick. Does not make block valid.
257 *
258 * @param tag Block address tag.
259 * @param is_secure Whether the block is in secure space or not.
260 * @param src_master_ID The source requestor ID.
261 * @param task_ID The new task ID.
262 */
263 virtual void insert(const Addr tag, const bool is_secure,
264 const int src_master_ID, const uint32_t task_ID);
265
266 /**
267 * Track the fact that a local locked was issued to the
268 * block. Invalidate any previous LL to the same address.
269 */
270 void trackLoadLocked(PacketPtr pkt)
271 {
272 assert(pkt->isLLSC());
273 auto l = lockList.begin();
274 while (l != lockList.end()) {
275 if (l->intersects(pkt->req))
276 l = lockList.erase(l);
277 else
278 ++l;
279 }
280
281 lockList.emplace_front(pkt->req);
282 }
283
284 /**
285 * Clear the any load lock that intersect the request, and is from
286 * a different context.
287 */
288 void clearLoadLocks(const RequestPtr &req)
289 {
290 auto l = lockList.begin();
291 while (l != lockList.end()) {
292 if (l->intersects(req) && l->contextId != req->contextId()) {
293 l = lockList.erase(l);
294 } else {
295 ++l;
296 }
297 }
298 }
299
300 /**
301 * Pretty-print a tag, and interpret state bits to readable form
302 * including mapping to a MOESI state.
303 *
304 * @return string with basic state information
305 */
306 std::string print() const
307 {
308 /**
309 * state M O E S I
310 * writable 1 0 1 0 0
311 * dirty 1 1 0 0 0
312 * valid 1 1 1 1 0
313 *
314 * state writable dirty valid
315 * M 1 1 1
316 * O 0 1 1
317 * E 1 0 1
318 * S 0 0 1
319 * I 0 0 0
320 *
321 * Note that only one cache ever has a block in Modified or
322 * Owned state, i.e., only one cache owns the block, or
323 * equivalently has the BlkDirty bit set. However, multiple
324 * caches on the same path to memory can have a block in the
325 * Exclusive state (despite the name). Exclusive means this
326 * cache has the only copy at this level of the hierarchy,
327 * i.e., there may be copies in caches above this cache (in
328 * various states), but there are no peers that have copies on
329 * this branch of the hierarchy, and no caches at or above
330 * this level on any other branch have copies either.
331 **/
332 unsigned state = isWritable() << 2 | isDirty() << 1 | isValid();
333 char s = '?';
334 switch (state) {
335 case 0b111: s = 'M'; break;
336 case 0b011: s = 'O'; break;
337 case 0b101: s = 'E'; break;
338 case 0b001: s = 'S'; break;
339 case 0b000: s = 'I'; break;
340 default: s = 'T'; break; // @TODO add other types
341 }
342 return csprintf("state: %x (%c) valid: %d writable: %d readable: %d "
343 "dirty: %d tag: %x", status, s, isValid(),
344 isWritable(), isReadable(), isDirty(), tag);
345 }
346
347 /**
348 * Handle interaction of load-locked operations and stores.
349 * @return True if write should proceed, false otherwise. Returns
350 * false only in the case of a failed store conditional.
351 */
352 bool checkWrite(PacketPtr pkt)
353 {
354 assert(pkt->isWrite());
355
356 // common case
357 if (!pkt->isLLSC() && lockList.empty())
358 return true;
359
360 const RequestPtr &req = pkt->req;
361
362 if (pkt->isLLSC()) {
363 // it's a store conditional... have to check for matching
364 // load locked.
365 bool success = false;
366
367 auto l = lockList.begin();
368 while (!success && l != lockList.end()) {
369 if (l->matches(pkt->req)) {
370 // it's a store conditional, and as far as the
371 // memory system can tell, the requesting
372 // context's lock is still valid.
373 success = true;
374 lockList.erase(l);
375 } else {
376 ++l;
377 }
378 }
379
380 req->setExtraData(success ? 1 : 0);
381 // clear any intersected locks from other contexts (our LL
382 // should already have cleared them)
383 clearLoadLocks(req);
384 return success;
385 } else {
386 // a normal write, if there is any lock not from this
387 // context we clear the list, thus for a private cache we
388 // never clear locks on normal writes
389 clearLoadLocks(req);
390 return true;
391 }
392 }
393 };
394
395 /**
396 * Special instance of CacheBlk for use with tempBlk that deals with its
397 * block address regeneration.
398 * @sa Cache
399 */
400 class TempCacheBlk final : public CacheBlk
401 {
402 private:
403 /**
404 * Copy of the block's address, used to regenerate tempBlock's address.
405 */
406 Addr _addr;
407
408 public:
409 /**
410 * Creates a temporary cache block, with its own storage.
411 * @param size The size (in bytes) of this cache block.
412 */
413 TempCacheBlk(unsigned size) : CacheBlk()
414 {
415 data = new uint8_t[size];
416 }
417 TempCacheBlk(const TempCacheBlk&) = delete;
418 TempCacheBlk& operator=(const TempCacheBlk&) = delete;
419 ~TempCacheBlk() { delete [] data; };
420
421 /**
422 * Invalidate the block and clear all state.
423 */
424 void invalidate() override {
425 CacheBlk::invalidate();
426
427 _addr = MaxAddr;
428 }
429
430 void insert(const Addr addr, const bool is_secure,
431 const int src_master_ID=0, const uint32_t task_ID=0) override
432 {
433 // Set block address
434 _addr = addr;
435
436 // Set secure state
437 if (is_secure) {
438 status = BlkSecure;
439 } else {
440 status = 0;
441 }
442 }
443
444 /**
445 * Get block's address.
446 *
447 * @return addr Address value.
448 */
449 Addr getAddr() const
450 {
451 return _addr;
452 }
453 };
454
455 /**
456 * Simple class to provide virtual print() method on cache blocks
457 * without allocating a vtable pointer for every single cache block.
458 * Just wrap the CacheBlk object in an instance of this before passing
459 * to a function that requires a Printable object.
460 */
461 class CacheBlkPrintWrapper : public Printable
462 {
463 CacheBlk *blk;
464 public:
465 CacheBlkPrintWrapper(CacheBlk *_blk) : blk(_blk) {}
466 virtual ~CacheBlkPrintWrapper() {}
467 void print(std::ostream &o, int verbosity = 0,
468 const std::string &prefix = "") const;
469 };
470
471 #endif //__MEM_CACHE_BLK_HH__