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