mem: per-thread cache occupancy and per-block ages
[gem5.git] / src / mem / cache / blk.hh
1 /*
2 * Copyright (c) 2012 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 __CACHE_BLK_HH__
49 #define __CACHE_BLK_HH__
50
51 #include <list>
52
53 #include "base/printable.hh"
54 #include "mem/packet.hh"
55 #include "mem/request.hh"
56 #include "sim/core.hh" // for Tick
57
58 /**
59 * Cache block status bit assignments
60 */
61 enum CacheBlkStatusBits {
62 /** valid, readable */
63 BlkValid = 0x01,
64 /** write permission */
65 BlkWritable = 0x02,
66 /** read permission (yes, block can be valid but not readable) */
67 BlkReadable = 0x04,
68 /** dirty (modified) */
69 BlkDirty = 0x08,
70 /** block was referenced */
71 BlkReferenced = 0x10,
72 /** block was a hardware prefetch yet unaccessed*/
73 BlkHWPrefetched = 0x20
74 };
75
76 /**
77 * A Basic Cache block.
78 * Contains the tag, status, and a pointer to data.
79 */
80 class CacheBlk
81 {
82 public:
83 /** Task Id associated with this block */
84 uint32_t task_id;
85
86 /** The address space ID of this block. */
87 int asid;
88 /** Data block tag value. */
89 Addr tag;
90 /**
91 * Contains a copy of the data in this block for easy access. This is used
92 * for efficient execution when the data could be actually stored in
93 * another format (COW, compressed, sub-blocked, etc). In all cases the
94 * data stored here should be kept consistant with the actual data
95 * referenced by this block.
96 */
97 uint8_t *data;
98 /** the number of bytes stored in this block. */
99 int size;
100
101 /** block state: OR of CacheBlkStatusBit */
102 typedef unsigned State;
103
104 /** The current status of this block. @sa CacheBlockStatusBits */
105 State status;
106
107 /** Which curTick() will this block be accessable */
108 Tick whenReady;
109
110 /**
111 * The set this block belongs to.
112 * @todo Move this into subclasses when we fix CacheTags to use them.
113 */
114 int set;
115
116 /** whether this block has been touched */
117 bool isTouched;
118
119 /** Number of references to this block since it was brought in. */
120 int refCount;
121
122 /** holds the source requestor ID for this block. */
123 int srcMasterId;
124
125 Tick tickInserted;
126
127 protected:
128 /**
129 * Represents that the indicated thread context has a "lock" on
130 * the block, in the LL/SC sense.
131 */
132 class Lock {
133 public:
134 int contextId; // locking context
135 Addr lowAddr; // low address of lock range
136 Addr highAddr; // high address of lock range
137
138 // check for matching execution context
139 bool matchesContext(Request *req)
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 bool overlapping(Request *req)
148 {
149 Addr req_low = req->getPaddr();
150 Addr req_high = req_low + req->getSize() - 1;
151
152 return (req_low <= highAddr) && (req_high >= lowAddr);
153 }
154
155 Lock(Request *req)
156 : contextId(req->contextId()),
157 lowAddr(req->getPaddr()),
158 highAddr(lowAddr + req->getSize() - 1)
159 {
160 }
161 };
162
163 /** List of thread contexts that have performed a load-locked (LL)
164 * on the block since the last store. */
165 std::list<Lock> lockList;
166
167 public:
168
169 CacheBlk()
170 : task_id(ContextSwitchTaskId::Unknown),
171 asid(-1), tag(0), data(0) ,size(0), status(0), whenReady(0),
172 set(-1), isTouched(false), refCount(0),
173 srcMasterId(Request::invldMasterId),
174 tickInserted(0)
175 {}
176
177 /**
178 * Copy the state of the given block into this one.
179 * @param rhs The block to copy.
180 * @return a const reference to this block.
181 */
182 const CacheBlk& operator=(const CacheBlk& rhs)
183 {
184 asid = rhs.asid;
185 tag = rhs.tag;
186 data = rhs.data;
187 size = rhs.size;
188 status = rhs.status;
189 whenReady = rhs.whenReady;
190 set = rhs.set;
191 refCount = rhs.refCount;
192 task_id = rhs.task_id;
193 return *this;
194 }
195
196 /**
197 * Checks the write permissions of this block.
198 * @return True if the block is writable.
199 */
200 bool isWritable() const
201 {
202 const State needed_bits = BlkWritable | BlkValid;
203 return (status & needed_bits) == needed_bits;
204 }
205
206 /**
207 * Checks the read permissions of this block. Note that a block
208 * can be valid but not readable if there is an outstanding write
209 * upgrade miss.
210 * @return True if the block is readable.
211 */
212 bool isReadable() const
213 {
214 const State needed_bits = BlkReadable | BlkValid;
215 return (status & needed_bits) == needed_bits;
216 }
217
218 /**
219 * Checks that a block is valid.
220 * @return True if the block is valid.
221 */
222 bool isValid() const
223 {
224 return (status & BlkValid) != 0;
225 }
226
227 /**
228 * Invalidate the block and clear all state.
229 */
230 void invalidate()
231 {
232 status = 0;
233 isTouched = false;
234 clearLoadLocks();
235 }
236
237 /**
238 * Check to see if a block has been written.
239 * @return True if the block is dirty.
240 */
241 bool isDirty() const
242 {
243 return (status & BlkDirty) != 0;
244 }
245
246 /**
247 * Check if this block has been referenced.
248 * @return True if the block has been referenced.
249 */
250 bool isReferenced() const
251 {
252 return (status & BlkReferenced) != 0;
253 }
254
255 /**
256 * Check if this block was the result of a hardware prefetch, yet to
257 * be touched.
258 * @return True if the block was a hardware prefetch, unaccesed.
259 */
260 bool wasPrefetched() const
261 {
262 return (status & BlkHWPrefetched) != 0;
263 }
264
265 /**
266 * Track the fact that a local locked was issued to the block. If
267 * multiple LLs get issued from the same context we could have
268 * redundant records on the list, but that's OK, as they'll all
269 * get blown away at the next store.
270 */
271 void trackLoadLocked(PacketPtr pkt)
272 {
273 assert(pkt->isLLSC());
274 lockList.push_front(Lock(pkt->req));
275 }
276
277 /**
278 * Clear the list of valid load locks. Should be called whenever
279 * block is written to or invalidated.
280 */
281 void clearLoadLocks(Request *req = NULL)
282 {
283 if (!req) {
284 // No request, invaldate all locks to this line
285 lockList.clear();
286 } else {
287 // Only invalidate locks that overlap with this request
288 std::list<Lock>::iterator lock_itr = lockList.begin();
289 while (lock_itr != lockList.end()) {
290 if (lock_itr->overlapping(req)) {
291 lock_itr = lockList.erase(lock_itr);
292 } else {
293 ++lock_itr;
294 }
295 }
296 }
297 }
298
299 /**
300 * Pretty-print a tag, and interpret state bits to readable form
301 * including mapping to a MOESI stat.
302 *
303 * @return string with basic state information
304 */
305 std::string print() const
306 {
307 /**
308 * state M O E S I
309 * writable 1 0 1 0 0
310 * dirty 1 1 0 0 0
311 * valid 1 1 1 1 0
312 *
313 * state writable dirty valid
314 * M 1 1 1
315 * O 0 1 1
316 * E 1 0 1
317 * S 0 0 1
318 * I 0 0 0
319 **/
320 unsigned state = isWritable() << 2 | isDirty() << 1 | isValid();
321 char s = '?';
322 switch (state) {
323 case 0b111: s = 'M'; break;
324 case 0b011: s = 'O'; break;
325 case 0b101: s = 'E'; break;
326 case 0b001: s = 'S'; break;
327 case 0b000: s = 'I'; break;
328 default: s = 'T'; break; // @TODO add other types
329 }
330 return csprintf("state: %x (%c) valid: %d writable: %d readable: %d "
331 "dirty: %d tag: %x data: %x", status, s, isValid(),
332 isWritable(), isReadable(), isDirty(), tag, *data);
333 }
334
335 /**
336 * Handle interaction of load-locked operations and stores.
337 * @return True if write should proceed, false otherwise. Returns
338 * false only in the case of a failed store conditional.
339 */
340 bool checkWrite(PacketPtr pkt)
341 {
342 Request *req = pkt->req;
343 if (pkt->isLLSC()) {
344 // it's a store conditional... have to check for matching
345 // load locked.
346 bool success = false;
347
348 for (std::list<Lock>::iterator i = lockList.begin();
349 i != lockList.end(); ++i)
350 {
351 if (i->matchesContext(req)) {
352 // it's a store conditional, and as far as the memory
353 // system can tell, the requesting context's lock is
354 // still valid.
355 success = true;
356 break;
357 }
358 }
359
360 req->setExtraData(success ? 1 : 0);
361 clearLoadLocks(req);
362 return success;
363 } else {
364 // for *all* stores (conditional or otherwise) we have to
365 // clear the list of load-locks as they're all invalid now.
366 clearLoadLocks(req);
367 return true;
368 }
369 }
370 };
371
372 /**
373 * Simple class to provide virtual print() method on cache blocks
374 * without allocating a vtable pointer for every single cache block.
375 * Just wrap the CacheBlk object in an instance of this before passing
376 * to a function that requires a Printable object.
377 */
378 class CacheBlkPrintWrapper : public Printable
379 {
380 CacheBlk *blk;
381 public:
382 CacheBlkPrintWrapper(CacheBlk *_blk) : blk(_blk) {}
383 virtual ~CacheBlkPrintWrapper() {}
384 void print(std::ostream &o, int verbosity = 0,
385 const std::string &prefix = "") const;
386 };
387
388 /**
389 * Wrap a method and present it as a cache block visitor.
390 *
391 * For example the forEachBlk method in the tag arrays expects a
392 * callable object/function as their parameter. This class wraps a
393 * method in an object and presents callable object that adheres to
394 * the cache block visitor protocol.
395 */
396 template <typename T, typename BlkType>
397 class CacheBlkVisitorWrapper
398 {
399 public:
400 typedef bool (T::*visitorPtr)(BlkType &blk);
401
402 CacheBlkVisitorWrapper(T &_obj, visitorPtr _visitor)
403 : obj(_obj), visitor(_visitor) {}
404
405 bool operator()(BlkType &blk) {
406 return (obj.*visitor)(blk);
407 }
408
409 private:
410 T &obj;
411 visitorPtr visitor;
412 };
413
414 /**
415 * Cache block visitor that determines if there are dirty blocks in a
416 * cache.
417 *
418 * Use with the forEachBlk method in the tag array to determine if the
419 * array contains dirty blocks.
420 */
421 template <typename BlkType>
422 class CacheBlkIsDirtyVisitor
423 {
424 public:
425 CacheBlkIsDirtyVisitor()
426 : _isDirty(false) {}
427
428 bool operator()(BlkType &blk) {
429 if (blk.isDirty()) {
430 _isDirty = true;
431 return false;
432 } else {
433 return true;
434 }
435 }
436
437 /**
438 * Does the array contain a dirty line?
439 *
440 * \return true if yes, false otherwise.
441 */
442 bool isDirty() const { return _isDirty; };
443
444 private:
445 bool _isDirty;
446 };
447
448 #endif //__CACHE_BLK_HH__