mem-cache: Use Packet functions to write data blocks
[gem5.git] / src / mem / cache / blk.hh
1 /*
2 * Copyright (c) 2012-2017 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 <list>
52
53 #include "base/printable.hh"
54 #include "mem/packet.hh"
55 #include "mem/request.hh"
56
57 /**
58 * Cache block status bit assignments
59 */
60 enum CacheBlkStatusBits : unsigned {
61 /** valid, readable */
62 BlkValid = 0x01,
63 /** write permission */
64 BlkWritable = 0x02,
65 /** read permission (yes, block can be valid but not readable) */
66 BlkReadable = 0x04,
67 /** dirty (modified) */
68 BlkDirty = 0x08,
69 /** block was a hardware prefetch yet unaccessed*/
70 BlkHWPrefetched = 0x20,
71 /** block holds data from the secure memory space */
72 BlkSecure = 0x40,
73 };
74
75 /**
76 * A Basic Cache block.
77 * Contains the tag, status, and a pointer to data.
78 */
79 class CacheBlk
80 {
81 public:
82 /** Task Id associated with this block */
83 uint32_t task_id;
84
85 /** Data block tag value. */
86 Addr tag;
87 /**
88 * Contains a copy of the data in this block for easy access. This is used
89 * for efficient execution when the data could be actually stored in
90 * another format (COW, compressed, sub-blocked, etc). In all cases the
91 * data stored here should be kept consistant with the actual data
92 * referenced by this block.
93 */
94 uint8_t *data;
95
96 /** block state: OR of CacheBlkStatusBit */
97 typedef unsigned State;
98
99 /** The current status of this block. @sa CacheBlockStatusBits */
100 State status;
101
102 /** Which curTick() will this block be accessible */
103 Tick whenReady;
104
105 /**
106 * The set and way this block belongs to.
107 * @todo Move this into subclasses when we fix CacheTags to use them.
108 */
109 int set, way;
110
111 /**
112 * Whether this block has been touched since simulation started.
113 * Used to calculate number of used tags.
114 */
115 bool isTouched;
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 /**
127 * Replacement policy data. As of now it is only an update timestamp.
128 * Tick on which the block was last touched.
129 */
130 Tick lastTouchTick;
131
132 /**
133 * Re-Reference Interval Prediction Value. Used with RRIP repl policy.
134 */
135 unsigned rrpv;
136
137 protected:
138 /**
139 * Represents that the indicated thread context has a "lock" on
140 * the block, in the LL/SC sense.
141 */
142 class Lock {
143 public:
144 ContextID contextId; // locking context
145 Addr lowAddr; // low address of lock range
146 Addr highAddr; // high address of lock range
147
148 // check for matching execution context, and an address that
149 // is within the lock
150 bool matches(const RequestPtr req) const
151 {
152 Addr req_low = req->getPaddr();
153 Addr req_high = req_low + req->getSize() -1;
154 return (contextId == req->contextId()) &&
155 (req_low >= lowAddr) && (req_high <= highAddr);
156 }
157
158 // check if a request is intersecting and thus invalidating the lock
159 bool intersects(const RequestPtr req) const
160 {
161 Addr req_low = req->getPaddr();
162 Addr req_high = req_low + req->getSize() - 1;
163
164 return (req_low <= highAddr) && (req_high >= lowAddr);
165 }
166
167 Lock(const RequestPtr req)
168 : contextId(req->contextId()),
169 lowAddr(req->getPaddr()),
170 highAddr(lowAddr + req->getSize() - 1)
171 {
172 }
173 };
174
175 /** List of thread contexts that have performed a load-locked (LL)
176 * on the block since the last store. */
177 std::list<Lock> lockList;
178
179 public:
180
181 CacheBlk()
182 {
183 invalidate();
184 }
185
186 CacheBlk(const CacheBlk&) = delete;
187 CacheBlk& operator=(const CacheBlk&) = delete;
188 virtual ~CacheBlk() {};
189
190 /**
191 * Checks the write permissions of this block.
192 * @return True if the block is writable.
193 */
194 bool isWritable() const
195 {
196 const State needed_bits = BlkWritable | BlkValid;
197 return (status & needed_bits) == needed_bits;
198 }
199
200 /**
201 * Checks the read permissions of this block. Note that a block
202 * can be valid but not readable if there is an outstanding write
203 * upgrade miss.
204 * @return True if the block is readable.
205 */
206 bool isReadable() const
207 {
208 const State needed_bits = BlkReadable | BlkValid;
209 return (status & needed_bits) == needed_bits;
210 }
211
212 /**
213 * Checks that a block is valid.
214 * @return True if the block is valid.
215 */
216 bool isValid() const
217 {
218 return (status & BlkValid) != 0;
219 }
220
221 /**
222 * Invalidate the block and clear all state.
223 */
224 virtual void invalidate()
225 {
226 tag = MaxAddr;
227 task_id = ContextSwitchTaskId::Unknown;
228 status = 0;
229 whenReady = MaxTick;
230 isTouched = false;
231 refCount = 0;
232 srcMasterId = Request::invldMasterId;
233 tickInserted = MaxTick;
234 lockList.clear();
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 was the result of a hardware prefetch, yet to
248 * be touched.
249 * @return True if the block was a hardware prefetch, unaccesed.
250 */
251 bool wasPrefetched() const
252 {
253 return (status & BlkHWPrefetched) != 0;
254 }
255
256 /**
257 * Check if this block holds data from the secure memory space.
258 * @return True if the block holds data from the secure memory space.
259 */
260 bool isSecure() const
261 {
262 return (status & BlkSecure) != 0;
263 }
264
265 /**
266 * Track the fact that a local locked was issued to the
267 * block. Invalidate any previous LL to the same address.
268 */
269 void trackLoadLocked(PacketPtr pkt)
270 {
271 assert(pkt->isLLSC());
272 auto l = lockList.begin();
273 while (l != lockList.end()) {
274 if (l->intersects(pkt->req))
275 l = lockList.erase(l);
276 else
277 ++l;
278 }
279
280 lockList.emplace_front(pkt->req);
281 }
282
283 /**
284 * Clear the any load lock that intersect the request, and is from
285 * a different context.
286 */
287 void clearLoadLocks(RequestPtr req)
288 {
289 auto l = lockList.begin();
290 while (l != lockList.end()) {
291 if (l->intersects(req) && l->contextId != req->contextId()) {
292 l = lockList.erase(l);
293 } else {
294 ++l;
295 }
296 }
297 }
298
299 /**
300 * Pretty-print a tag, and interpret state bits to readable form
301 * including mapping to a MOESI state.
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 * Note that only one cache ever has a block in Modified or
321 * Owned state, i.e., only one cache owns the block, or
322 * equivalently has the BlkDirty bit set. However, multiple
323 * caches on the same path to memory can have a block in the
324 * Exclusive state (despite the name). Exclusive means this
325 * cache has the only copy at this level of the hierarchy,
326 * i.e., there may be copies in caches above this cache (in
327 * various states), but there are no peers that have copies on
328 * this branch of the hierarchy, and no caches at or above
329 * this level on any other branch have copies either.
330 **/
331 unsigned state = isWritable() << 2 | isDirty() << 1 | isValid();
332 char s = '?';
333 switch (state) {
334 case 0b111: s = 'M'; break;
335 case 0b011: s = 'O'; break;
336 case 0b101: s = 'E'; break;
337 case 0b001: s = 'S'; break;
338 case 0b000: s = 'I'; break;
339 default: s = 'T'; break; // @TODO add other types
340 }
341 return csprintf("state: %x (%c) valid: %d writable: %d readable: %d "
342 "dirty: %d tag: %x", status, s, isValid(),
343 isWritable(), isReadable(), isDirty(), tag);
344 }
345
346 /**
347 * Handle interaction of load-locked operations and stores.
348 * @return True if write should proceed, false otherwise. Returns
349 * false only in the case of a failed store conditional.
350 */
351 bool checkWrite(PacketPtr pkt)
352 {
353 assert(pkt->isWrite());
354
355 // common case
356 if (!pkt->isLLSC() && lockList.empty())
357 return true;
358
359 RequestPtr req = pkt->req;
360
361 if (pkt->isLLSC()) {
362 // it's a store conditional... have to check for matching
363 // load locked.
364 bool success = false;
365
366 auto l = lockList.begin();
367 while (!success && l != lockList.end()) {
368 if (l->matches(pkt->req)) {
369 // it's a store conditional, and as far as the
370 // memory system can tell, the requesting
371 // context's lock is still valid.
372 success = true;
373 lockList.erase(l);
374 } else {
375 ++l;
376 }
377 }
378
379 req->setExtraData(success ? 1 : 0);
380 // clear any intersected locks from other contexts (our LL
381 // should already have cleared them)
382 clearLoadLocks(req);
383 return success;
384 } else {
385 // a normal write, if there is any lock not from this
386 // context we clear the list, thus for a private cache we
387 // never clear locks on normal writes
388 clearLoadLocks(req);
389 return true;
390 }
391 }
392 };
393
394 /**
395 * Simple class to provide virtual print() method on cache blocks
396 * without allocating a vtable pointer for every single cache block.
397 * Just wrap the CacheBlk object in an instance of this before passing
398 * to a function that requires a Printable object.
399 */
400 class CacheBlkPrintWrapper : public Printable
401 {
402 CacheBlk *blk;
403 public:
404 CacheBlkPrintWrapper(CacheBlk *_blk) : blk(_blk) {}
405 virtual ~CacheBlkPrintWrapper() {}
406 void print(std::ostream &o, int verbosity = 0,
407 const std::string &prefix = "") const;
408 };
409
410 /**
411 * Base class for cache block visitor, operating on the cache block
412 * base class (later subclassed for the various tag classes). This
413 * visitor class is used as part of the forEachBlk interface in the
414 * tag classes.
415 */
416 class CacheBlkVisitor
417 {
418 public:
419
420 CacheBlkVisitor() {}
421 virtual ~CacheBlkVisitor() {}
422
423 virtual bool operator()(CacheBlk &blk) = 0;
424 };
425
426 #endif //__MEM_CACHE_BLK_HH__