Mem: Use cycles to express cache-related latencies
[gem5.git] / src / mem / cache / tags / iic.cc
1 /*
2 * Copyright (c) 2002-2005 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Erik Hallnor
29 */
30
31 /**
32 * @file
33 * Definitions of the Indirect Index Cache tagstore.
34 */
35
36 #include <algorithm>
37 #include <cmath>
38 #include <string>
39 #include <vector>
40
41 #include "base/intmath.hh"
42 #include "base/trace.hh"
43 #include "debug/Cache.hh"
44 #include "debug/IIC.hh"
45 #include "debug/IICMore.hh"
46 #include "mem/cache/tags/iic.hh"
47 #include "mem/cache/base.hh"
48 #include "sim/core.hh"
49
50 using namespace std;
51
52 /** Track the number of accesses to each cache set. */
53 #define PROFILE_IIC 1
54
55 IIC::IIC(IIC::Params &params) :
56 hashSets(params.numSets), blkSize(params.blkSize), assoc(params.assoc),
57 hitLatency(params.hitLatency), subSize(params.subblockSize),
58 numSub(blkSize/subSize),
59 trivialSize((floorLog2(params.size/subSize)*numSub)/8),
60 tagShift(floorLog2(blkSize)), blkMask(blkSize - 1),
61 subShift(floorLog2(subSize)), subMask(numSub - 1),
62 hashDelay(params.hashDelay),
63 numTags(hashSets * assoc + params.size/blkSize -1),
64 numSecondary(params.size/blkSize),
65 tagNull(numTags),
66 primaryBound(hashSets * assoc)
67 {
68 // Check parameters
69 if (blkSize < 4 || !isPowerOf2(blkSize)) {
70 fatal("Block size must be at least 4 and a power of 2");
71 }
72 if (hashSets <= 0 || !isPowerOf2(hashSets)) {
73 fatal("# of hashsets must be non-zero and a power of 2");
74 }
75 if (assoc <= 0) {
76 fatal("associativity must be greater than zero");
77 }
78 if (hitLatency <= 0) {
79 fatal("access latency must be greater than zero");
80 }
81 if (numSub*subSize != blkSize) {
82 fatal("blocksize must be evenly divisible by subblock size");
83 }
84
85 // debug stuff
86 freeSecond = numSecondary;
87
88 warmedUp = false;
89 warmupBound = params.size/blkSize;
90 numBlocks = params.size/subSize;
91
92 // Replacement Policy Initialization
93 repl = params.rp;
94 repl->setIIC(this);
95
96 //last_miss_time = 0
97
98 // allocate data reference counters
99 dataReferenceCount = new int[numBlocks];
100 memset(dataReferenceCount, 0, numBlocks*sizeof(int));
101
102 // Allocate storage for both internal data and block fast access data.
103 // We allocate it as one large chunk to reduce overhead and to make
104 // deletion easier.
105 unsigned data_index = 0;
106 dataStore = new uint8_t[(numBlocks + numTags) * blkSize];
107 dataBlks = new uint8_t*[numBlocks];
108 for (unsigned i = 0; i < numBlocks; ++i) {
109 dataBlks[i] = &dataStore[data_index];
110 freeDataBlock(i);
111 data_index += subSize;
112 }
113
114 assert(data_index == numBlocks * subSize);
115
116 // allocate and init tag store
117 tagStore = new IICTag[numTags];
118
119 unsigned blkIndex = 0;
120 // allocate and init sets
121 sets = new IICSet[hashSets];
122 for (unsigned i = 0; i < hashSets; ++i) {
123 sets[i].assoc = assoc;
124 sets[i].tags = new IICTag*[assoc];
125 sets[i].chain_ptr = tagNull;
126
127 for (unsigned j = 0; j < assoc; ++j) {
128 IICTag *tag = &tagStore[blkIndex++];
129 tag->chain_ptr = tagNull;
130 tag->data_ptr.resize(numSub);
131 tag->size = blkSize;
132 tag->trivialData = new uint8_t[trivialSize];
133 tag->numData = 0;
134 sets[i].tags[j] = tag;
135 tag->set = i;
136 tag->data = &dataStore[data_index];
137 data_index += blkSize;
138 }
139 }
140
141 assert(blkIndex == primaryBound);
142
143 for (unsigned i = primaryBound; i < tagNull; i++) {
144 tagStore[i].chain_ptr = i+1;
145 //setup data ptrs to subblocks
146 tagStore[i].data_ptr.resize(numSub);
147 tagStore[i].size = blkSize;
148 tagStore[i].trivialData = new uint8_t[trivialSize];
149 tagStore[i].numData = 0;
150 tagStore[i].set = 0;
151 tagStore[i].data = &dataStore[data_index];
152 data_index += blkSize;
153 }
154 freelist = primaryBound;
155 }
156
157 IIC::~IIC()
158 {
159 delete [] dataReferenceCount;
160 delete [] dataStore;
161 delete [] tagStore;
162 delete [] sets;
163 delete [] dataBlks;
164 }
165
166 /* register cache stats */
167 void
168 IIC::regStats(const string &name)
169 {
170 using namespace Stats;
171
172 BaseTags::regStats(name);
173
174 hitHashDepth.init(0, 20, 1);
175 missHashDepth.init(0, 20, 1);
176 setAccess.init(0, hashSets, 1);
177
178 /** IIC Statistics */
179 hitHashDepth
180 .name(name + ".hit_hash_depth_dist")
181 .desc("Dist. of Hash lookup depths")
182 .flags(pdf)
183 ;
184
185 missHashDepth
186 .name(name + ".miss_hash_depth_dist")
187 .desc("Dist. of Hash lookup depths")
188 .flags(pdf)
189 ;
190
191 repl->regStatsWithSuffix(name);
192
193 if (PROFILE_IIC)
194 setAccess
195 .name(name + ".set_access_dist")
196 .desc("Dist. of Accesses across sets")
197 .flags(pdf)
198 ;
199
200 missDepthTotal
201 .name(name + ".miss_depth_total")
202 .desc("Total of miss depths")
203 ;
204
205 hashMiss
206 .name(name + ".hash_miss")
207 .desc("Total of misses in hash table")
208 ;
209
210 hitDepthTotal
211 .name(name + ".hit_depth_total")
212 .desc("Total of hit depths")
213 ;
214
215 hashHit
216 .name(name + ".hash_hit")
217 .desc("Total of hites in hash table")
218 ;
219 }
220
221
222 IICTag*
223 IIC::accessBlock(Addr addr, Cycles &lat, int context_src)
224 {
225 Addr tag = extractTag(addr);
226 unsigned set = hash(addr);
227 Cycles set_lat;
228
229 unsigned long chain_ptr = tagNull;
230
231 if (PROFILE_IIC)
232 setAccess.sample(set);
233
234 IICTag *tag_ptr = sets[set].findTag(tag, chain_ptr);
235 set_lat = Cycles(1);
236 if (tag_ptr == NULL && chain_ptr != tagNull) {
237 int secondary_depth;
238 tag_ptr = secondaryChain(tag, chain_ptr, &secondary_depth);
239 set_lat += Cycles(secondary_depth);
240 // set depth for statistics fix this later!!! egh
241 sets[set].depth = set_lat;
242
243 if (tag_ptr != NULL) {
244 /* need to move tag into primary table */
245 // need to preserve chain: fix this egh
246 sets[set].tags[assoc-1]->chain_ptr = tag_ptr->chain_ptr;
247 tagSwap(tag_ptr - tagStore, sets[set].tags[assoc-1] - tagStore);
248 tag_ptr = sets[set].findTag(tag, chain_ptr);
249 assert(tag_ptr!=NULL);
250 }
251
252 }
253 set_lat = Cycles(set_lat * hashDelay + hitLatency);
254 if (tag_ptr != NULL) {
255 // IIC replacement: if this is not the first element of
256 // list, reorder
257 sets[set].moveToHead(tag_ptr);
258
259 hitHashDepth.sample(sets[set].depth);
260 hashHit++;
261 hitDepthTotal += sets[set].depth;
262 tag_ptr->status |= BlkReferenced;
263 lat = set_lat;
264 if (tag_ptr->whenReady > curTick() &&
265 cache->ticksToCycles(tag_ptr->whenReady - curTick()) > set_lat) {
266 lat = cache->ticksToCycles(tag_ptr->whenReady - curTick());
267 }
268
269 tag_ptr->refCount += 1;
270 }
271 else {
272 // fall through: cache block not found, not a hit...
273 missHashDepth.sample(sets[set].depth);
274 hashMiss++;
275 missDepthTotal += sets[set].depth;
276 lat = set_lat;
277 }
278 return tag_ptr;
279 }
280
281
282 IICTag*
283 IIC::findBlock(Addr addr) const
284 {
285 Addr tag = extractTag(addr);
286 unsigned set = hash(addr);
287
288 unsigned long chain_ptr = tagNull;
289
290 IICTag *tag_ptr = sets[set].findTag(tag, chain_ptr);
291 if (tag_ptr == NULL && chain_ptr != tagNull) {
292 int secondary_depth;
293 tag_ptr = secondaryChain(tag, chain_ptr, &secondary_depth);
294 }
295 return tag_ptr;
296 }
297
298
299 IICTag*
300 IIC::findVictim(Addr addr, PacketList &writebacks)
301 {
302 DPRINTF(IIC, "Finding Replacement for %x\n", addr);
303 unsigned set = hash(addr);
304 IICTag *tag_ptr;
305 unsigned long *tmp_data = new unsigned long[numSub];
306
307 // Get a enough subblocks for a full cache line
308 for (unsigned i = 0; i < numSub; ++i){
309 tmp_data[i] = getFreeDataBlock(writebacks);
310 assert(dataReferenceCount[tmp_data[i]]==0);
311 }
312
313 tag_ptr = getFreeTag(set, writebacks);
314
315 tag_ptr->set = set;
316 for (unsigned i = 0; i < numSub; ++i) {
317 tag_ptr->data_ptr[i] = tmp_data[i];
318 dataReferenceCount[tag_ptr->data_ptr[i]]++;
319 }
320 tag_ptr->numData = numSub;
321 assert(tag_ptr - tagStore < primaryBound); // make sure it is in primary
322 tag_ptr->chain_ptr = tagNull;
323 sets[set].moveToHead(tag_ptr);
324 delete [] tmp_data;
325
326 list<unsigned long> tag_indexes;
327 repl->doAdvance(tag_indexes);
328 /*
329 while (!tag_indexes.empty()) {
330 if (!tagStore[tag_indexes.front()].isCompressed()) {
331 compress_blocks.push_back(&tagStore[tag_indexes.front()]);
332 }
333 tag_indexes.pop_front();
334 }
335 */
336
337 tag_ptr->re = (void*)repl->add(tag_ptr-tagStore);
338
339 return tag_ptr;
340 }
341
342 void
343 IIC::insertBlock(Addr addr, BlkType* blk, int context_src)
344 {
345 }
346
347 void
348 IIC::freeReplacementBlock(PacketList & writebacks)
349 {
350 IICTag *tag_ptr;
351 unsigned long data_ptr;
352 /* consult replacement policy */
353 tag_ptr = &tagStore[repl->getRepl()];
354 assert(tag_ptr != NULL);
355 assert(tag_ptr->isValid());
356
357 DPRINTF(Cache, "Replacing %x in IIC: %s\n",
358 regenerateBlkAddr(tag_ptr->tag,0),
359 tag_ptr->isDirty() ? "writeback" : "clean");
360 /* write back replaced block data */
361 replacements[0]++;
362 totalRefs += tag_ptr->refCount;
363 ++sampledRefs;
364 tag_ptr->refCount = 0;
365
366 if (tag_ptr->isDirty()) {
367 /* PacketPtr writeback =
368 buildWritebackReq(regenerateBlkAddr(tag_ptr->tag, 0),
369 tag_ptr->req->asid, tag_ptr->xc, blkSize,
370 tag_ptr->data,
371 tag_ptr->size);
372 */
373 Request *writebackReq = new Request(regenerateBlkAddr(tag_ptr->tag, 0),
374 blkSize, 0, Request::wbMasterId);
375 PacketPtr writeback = new Packet(writebackReq, MemCmd::Writeback);
376 writeback->allocate();
377 memcpy(writeback->getPtr<uint8_t>(), tag_ptr->data, blkSize);
378
379 writebacks.push_back(writeback);
380 }
381
382 // free the data blocks
383 for (int i = 0; i < tag_ptr->numData; ++i) {
384 data_ptr = tag_ptr->data_ptr[i];
385 assert(dataReferenceCount[data_ptr]>0);
386 if (--dataReferenceCount[data_ptr] == 0) {
387 freeDataBlock(data_ptr);
388 }
389 }
390 freeTag(tag_ptr);
391 }
392
393 unsigned long
394 IIC::getFreeDataBlock(PacketList & writebacks)
395 {
396 unsigned long data_ptr;
397
398 /* find data block */
399 while (blkFreelist.empty()) {
400 freeReplacementBlock(writebacks);
401 }
402
403 data_ptr = blkFreelist.front();
404 blkFreelist.pop_front();
405 DPRINTF(IICMore,"Found free data at %d\n",data_ptr);
406 return data_ptr;
407 }
408
409
410
411 IICTag*
412 IIC::getFreeTag(int set, PacketList & writebacks)
413 {
414 unsigned long tag_index;
415 IICTag *tag_ptr;
416 // Add new tag
417 tag_ptr = sets[set].findFree();
418 // if no free in primary, and secondary exists
419 if (!tag_ptr && numSecondary) {
420 // need to spill a tag into secondary storage
421 while (freelist == tagNull) {
422 // get replacements until one is in secondary
423 freeReplacementBlock(writebacks);
424 }
425
426 tag_index = freelist;
427 freelist = tagStore[freelist].chain_ptr;
428 freeSecond--;
429
430 assert(tag_index != tagNull);
431 tagSwap(tag_index, sets[set].tags[assoc-1] - tagStore);
432 tagStore[tag_index].chain_ptr = sets[set].chain_ptr;
433 sets[set].chain_ptr = tag_index;
434
435 tag_ptr = sets[set].tags[assoc-1];
436 }
437 DPRINTF(IICMore,"Found free tag at %d\n",tag_ptr - tagStore);
438 tagsInUse++;
439 if (!warmedUp && tagsInUse.value() >= warmupBound) {
440 warmedUp = true;
441 warmupCycle = curTick();
442 }
443
444 return tag_ptr;
445 }
446
447 void
448 IIC::freeTag(IICTag *tag_ptr)
449 {
450 unsigned long tag_index, tmp_index;
451 // Fix tag_ptr
452 if (tag_ptr) {
453 // we have a tag to clear
454 DPRINTF(IICMore,"Freeing Tag for %x\n",
455 regenerateBlkAddr(tag_ptr->tag,0));
456 tagsInUse--;
457 tag_ptr->status = 0;
458 tag_ptr->numData = 0;
459 tag_ptr->re = NULL;
460 tag_index = tag_ptr - tagStore;
461 if (tag_index >= primaryBound) {
462 // tag_ptr points to secondary store
463 assert(tag_index < tagNull); // remove this?? egh
464 if (tag_ptr->chain_ptr == tagNull) {
465 // need to fix chain list
466 unsigned tmp_set = hash(tag_ptr->tag << tagShift);
467 if (sets[tmp_set].chain_ptr == tag_index) {
468 sets[tmp_set].chain_ptr = tagNull;
469 } else {
470 tmp_index = sets[tmp_set].chain_ptr;
471 while (tmp_index != tagNull
472 && tagStore[tmp_index].chain_ptr != tag_index) {
473 tmp_index = tagStore[tmp_index].chain_ptr;
474 }
475 assert(tmp_index != tagNull);
476 tagStore[tmp_index].chain_ptr = tagNull;
477 }
478 tag_ptr->chain_ptr = freelist;
479 freelist = tag_index;
480 freeSecond++;
481 } else {
482 // copy next chained entry to this tag location
483 tmp_index = tag_ptr->chain_ptr;
484 tagSwap(tmp_index, tag_index);
485 tagStore[tmp_index].chain_ptr = freelist;
486 freelist = tmp_index;
487 freeSecond++;
488 }
489 } else {
490 // tag_ptr in primary hash table
491 assert(tag_index < primaryBound);
492 tag_ptr->status = 0;
493 unsigned tmp_set = hash(tag_ptr->tag << tagShift);
494 if (sets[tmp_set].chain_ptr != tagNull) { // collapse chain
495 tmp_index = sets[tmp_set].chain_ptr;
496 tagSwap(tag_index, tmp_index);
497 tagStore[tmp_index].chain_ptr = freelist;
498 freelist = tmp_index;
499 freeSecond++;
500 sets[tmp_set].chain_ptr = tag_ptr->chain_ptr;
501 sets[tmp_set].moveToTail(tag_ptr);
502 }
503 }
504 }
505 }
506
507 void
508 IIC::freeDataBlock(unsigned long data_ptr)
509 {
510 assert(dataReferenceCount[data_ptr] == 0);
511 DPRINTF(IICMore, "Freeing data at %d\n", data_ptr);
512 blkFreelist.push_front(data_ptr);
513 }
514
515 /** Use a simple modulo hash. */
516 #define SIMPLE_HASH 0
517
518 unsigned
519 IIC::hash(Addr addr) const {
520 #if SIMPLE_HASH
521 return extractTag(addr) % iic_hash_size;
522 #else
523 Addr tag, mask, x, y;
524 tag = extractTag(addr);
525 mask = hashSets-1; /* assumes iic_hash_size is a power of 2 */
526 x = tag & mask;
527 y = (tag >> (int)(::log((double)hashSets)/::log((double)2))) & mask;
528 assert (x < hashSets && y < hashSets);
529 return x ^ y;
530 #endif
531 }
532
533
534 void
535 IICSet::moveToHead(IICTag *tag)
536 {
537 if (tags[0] == tag)
538 return;
539
540 // write 'next' block into blks[i], moving up from MRU toward LRU
541 // until we overwrite the block we moved to head.
542
543 // start by setting up to write 'blk' into blks[0]
544 int i = 0;
545 IICTag *next = tag;
546
547 do {
548 assert(i < assoc);
549 // swap blks[i] and next
550 IICTag *tmp = tags[i];
551 tags[i] = next;
552 next = tmp;
553 ++i;
554 } while (next != tag);
555 }
556
557 void
558 IICSet::moveToTail(IICTag *tag)
559 {
560 if (tags[assoc-1] == tag)
561 return;
562
563 // write 'next' block into blks[i], moving up from MRU toward LRU
564 // until we overwrite the block we moved to head.
565
566 // start by setting up to write 'blk' into blks[0]
567 int i = assoc - 1;
568 IICTag *next = tag;
569
570 do {
571 assert(i >= 0);
572 // swap blks[i] and next
573 IICTag *tmp = tags[i];
574 tags[i] = next;
575 next = tmp;
576 --i;
577 } while (next != tag);
578 }
579
580 void
581 IIC::tagSwap(unsigned long index1, unsigned long index2)
582 {
583 DPRINTF(IIC,"Swapping tag[%d]=%x for tag[%d]=%x\n",index1,
584 tagStore[index1].tag<<tagShift, index2,
585 tagStore[index2].tag<<tagShift);
586 IICTag tmp_tag;
587 tmp_tag = tagStore[index1];
588 tagStore[index1] = tagStore[index2];
589 tagStore[index2] = tmp_tag;
590 if (tagStore[index1].isValid())
591 repl->fixTag(tagStore[index1].re, index2, index1);
592 if (tagStore[index2].isValid())
593 repl->fixTag(tagStore[index2].re, index1, index2);
594 }
595
596
597 IICTag *
598 IIC::secondaryChain(Addr tag, unsigned long chain_ptr,
599 int *_depth) const
600 {
601 int depth = 0;
602 while (chain_ptr != tagNull) {
603 DPRINTF(IIC,"Searching secondary at %d for %x\n", chain_ptr,
604 tag<<tagShift);
605 if (tagStore[chain_ptr].tag == tag &&
606 (tagStore[chain_ptr].isValid())) {
607 *_depth = depth;
608 return &tagStore[chain_ptr];
609 }
610 depth++;
611 chain_ptr = tagStore[chain_ptr].chain_ptr;
612 }
613 *_depth = depth;
614 return NULL;
615 }
616
617 void
618 IIC::invalidate(IIC::BlkType *tag_ptr)
619 {
620 if (tag_ptr) {
621 for (int i = 0; i < tag_ptr->numData; ++i) {
622 dataReferenceCount[tag_ptr->data_ptr[i]]--;
623 if (dataReferenceCount[tag_ptr->data_ptr[i]] == 0) {
624 freeDataBlock(tag_ptr->data_ptr[i]);
625 }
626 }
627 repl->removeEntry(tag_ptr->re);
628 freeTag(tag_ptr);
629 }
630 }
631
632 void
633 IIC::clearLocks()
634 {
635 for (int i = 0; i < numTags; i++){
636 tagStore[i].clearLoadLocks();
637 }
638 }
639
640 void
641 IIC::cleanupRefs()
642 {
643 for (unsigned i = 0; i < numTags; ++i) {
644 if (tagStore[i].isValid()) {
645 totalRefs += tagStore[i].refCount;
646 ++sampledRefs;
647 }
648 }
649 }