CacheMemory.cc revision 9171
1/*
2 * Copyright (c) 1999-2012 Mark D. Hill and David A. Wood
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
29#include "base/intmath.hh"
30#include "debug/RubyCache.hh"
31#include "debug/RubyCacheTrace.hh"
32#include "debug/RubyResourceStalls.hh"
33#include "debug/RubyStats.hh"
34#include "mem/protocol/AccessPermission.hh"
35#include "mem/ruby/system/CacheMemory.hh"
36#include "mem/ruby/system/System.hh"
37
38using namespace std;
39
40ostream&
41operator<<(ostream& out, const CacheMemory& obj)
42{
43    obj.print(out);
44    out << flush;
45    return out;
46}
47
48CacheMemory *
49RubyCacheParams::create()
50{
51    return new CacheMemory(this);
52}
53
54CacheMemory::CacheMemory(const Params *p)
55    : SimObject(p),
56    dataArray(p->dataArrayBanks, p->dataAccessLatency, p->start_index_bit),
57    tagArray(p->tagArrayBanks, p->tagAccessLatency, p->start_index_bit)
58{
59    m_cache_size = p->size;
60    m_latency = p->latency;
61    m_cache_assoc = p->assoc;
62    m_policy = p->replacement_policy;
63    m_profiler_ptr = new CacheProfiler(name());
64    m_start_index_bit = p->start_index_bit;
65    m_is_instruction_only_cache = p->is_icache;
66    m_resource_stalls = p->resourceStalls;
67}
68
69void
70CacheMemory::init()
71{
72    m_cache_num_sets = (m_cache_size / m_cache_assoc) /
73        RubySystem::getBlockSizeBytes();
74    assert(m_cache_num_sets > 1);
75    m_cache_num_set_bits = floorLog2(m_cache_num_sets);
76    assert(m_cache_num_set_bits > 0);
77
78    if (m_policy == "PSEUDO_LRU")
79        m_replacementPolicy_ptr =
80            new PseudoLRUPolicy(m_cache_num_sets, m_cache_assoc);
81    else if (m_policy == "LRU")
82        m_replacementPolicy_ptr =
83            new LRUPolicy(m_cache_num_sets, m_cache_assoc);
84    else
85        assert(false);
86
87    m_cache.resize(m_cache_num_sets);
88    for (int i = 0; i < m_cache_num_sets; i++) {
89        m_cache[i].resize(m_cache_assoc);
90        for (int j = 0; j < m_cache_assoc; j++) {
91            m_cache[i][j] = NULL;
92        }
93    }
94}
95
96CacheMemory::~CacheMemory()
97{
98    if (m_replacementPolicy_ptr != NULL)
99        delete m_replacementPolicy_ptr;
100    delete m_profiler_ptr;
101    for (int i = 0; i < m_cache_num_sets; i++) {
102        for (int j = 0; j < m_cache_assoc; j++) {
103            delete m_cache[i][j];
104        }
105    }
106}
107
108// convert a Address to its location in the cache
109Index
110CacheMemory::addressToCacheSet(const Address& address) const
111{
112    assert(address == line_address(address));
113    return address.bitSelect(m_start_index_bit,
114                             m_start_index_bit + m_cache_num_set_bits - 1);
115}
116
117// Given a cache index: returns the index of the tag in a set.
118// returns -1 if the tag is not found.
119int
120CacheMemory::findTagInSet(Index cacheSet, const Address& tag) const
121{
122    assert(tag == line_address(tag));
123    // search the set for the tags
124    m5::hash_map<Address, int>::const_iterator it = m_tag_index.find(tag);
125    if (it != m_tag_index.end())
126        if (m_cache[cacheSet][it->second]->m_Permission !=
127            AccessPermission_NotPresent)
128            return it->second;
129    return -1; // Not found
130}
131
132// Given a cache index: returns the index of the tag in a set.
133// returns -1 if the tag is not found.
134int
135CacheMemory::findTagInSetIgnorePermissions(Index cacheSet,
136                                           const Address& tag) const
137{
138    assert(tag == line_address(tag));
139    // search the set for the tags
140    m5::hash_map<Address, int>::const_iterator it = m_tag_index.find(tag);
141    if (it != m_tag_index.end())
142        return it->second;
143    return -1; // Not found
144}
145
146bool
147CacheMemory::tryCacheAccess(const Address& address, RubyRequestType type,
148                            DataBlock*& data_ptr)
149{
150    assert(address == line_address(address));
151    DPRINTF(RubyCache, "address: %s\n", address);
152    Index cacheSet = addressToCacheSet(address);
153    int loc = findTagInSet(cacheSet, address);
154    if (loc != -1) {
155        // Do we even have a tag match?
156        AbstractCacheEntry* entry = m_cache[cacheSet][loc];
157        m_replacementPolicy_ptr->touch(cacheSet, loc, curTick());
158        data_ptr = &(entry->getDataBlk());
159
160        if (entry->m_Permission == AccessPermission_Read_Write) {
161            return true;
162        }
163        if ((entry->m_Permission == AccessPermission_Read_Only) &&
164            (type == RubyRequestType_LD || type == RubyRequestType_IFETCH)) {
165            return true;
166        }
167        // The line must not be accessible
168    }
169    data_ptr = NULL;
170    return false;
171}
172
173bool
174CacheMemory::testCacheAccess(const Address& address, RubyRequestType type,
175                             DataBlock*& data_ptr)
176{
177    assert(address == line_address(address));
178    DPRINTF(RubyCache, "address: %s\n", address);
179    Index cacheSet = addressToCacheSet(address);
180    int loc = findTagInSet(cacheSet, address);
181
182    if (loc != -1) {
183        // Do we even have a tag match?
184        AbstractCacheEntry* entry = m_cache[cacheSet][loc];
185        m_replacementPolicy_ptr->touch(cacheSet, loc, curTick());
186        data_ptr = &(entry->getDataBlk());
187
188        return m_cache[cacheSet][loc]->m_Permission !=
189            AccessPermission_NotPresent;
190    }
191
192    data_ptr = NULL;
193    return false;
194}
195
196// tests to see if an address is present in the cache
197bool
198CacheMemory::isTagPresent(const Address& address) const
199{
200    assert(address == line_address(address));
201    Index cacheSet = addressToCacheSet(address);
202    int loc = findTagInSet(cacheSet, address);
203
204    if (loc == -1) {
205        // We didn't find the tag
206        DPRINTF(RubyCache, "No tag match for address: %s\n", address);
207        return false;
208    }
209    DPRINTF(RubyCache, "address: %s found\n", address);
210    return true;
211}
212
213// Returns true if there is:
214//   a) a tag match on this address or there is
215//   b) an unused line in the same cache "way"
216bool
217CacheMemory::cacheAvail(const Address& address) const
218{
219    assert(address == line_address(address));
220
221    Index cacheSet = addressToCacheSet(address);
222
223    for (int i = 0; i < m_cache_assoc; i++) {
224        AbstractCacheEntry* entry = m_cache[cacheSet][i];
225        if (entry != NULL) {
226            if (entry->m_Address == address ||
227                entry->m_Permission == AccessPermission_NotPresent) {
228                // Already in the cache or we found an empty entry
229                return true;
230            }
231        } else {
232            return true;
233        }
234    }
235    return false;
236}
237
238AbstractCacheEntry*
239CacheMemory::allocate(const Address& address, AbstractCacheEntry* entry)
240{
241    assert(address == line_address(address));
242    assert(!isTagPresent(address));
243    assert(cacheAvail(address));
244    DPRINTF(RubyCache, "address: %s\n", address);
245
246    // Find the first open slot
247    Index cacheSet = addressToCacheSet(address);
248    std::vector<AbstractCacheEntry*> &set = m_cache[cacheSet];
249    for (int i = 0; i < m_cache_assoc; i++) {
250        if (!set[i] || set[i]->m_Permission == AccessPermission_NotPresent) {
251            set[i] = entry;  // Init entry
252            set[i]->m_Address = address;
253            set[i]->m_Permission = AccessPermission_Invalid;
254            DPRINTF(RubyCache, "Allocate clearing lock for addr: %x\n",
255                    address);
256            set[i]->m_locked = -1;
257            m_tag_index[address] = i;
258
259            m_replacementPolicy_ptr->touch(cacheSet, i, curTick());
260
261            return entry;
262        }
263    }
264    panic("Allocate didn't find an available entry");
265}
266
267void
268CacheMemory::deallocate(const Address& address)
269{
270    assert(address == line_address(address));
271    assert(isTagPresent(address));
272    DPRINTF(RubyCache, "address: %s\n", address);
273    Index cacheSet = addressToCacheSet(address);
274    int loc = findTagInSet(cacheSet, address);
275    if (loc != -1) {
276        delete m_cache[cacheSet][loc];
277        m_cache[cacheSet][loc] = NULL;
278        m_tag_index.erase(address);
279    }
280}
281
282// Returns with the physical address of the conflicting cache line
283Address
284CacheMemory::cacheProbe(const Address& address) const
285{
286    assert(address == line_address(address));
287    assert(!cacheAvail(address));
288
289    Index cacheSet = addressToCacheSet(address);
290    return m_cache[cacheSet][m_replacementPolicy_ptr->getVictim(cacheSet)]->
291        m_Address;
292}
293
294// looks an address up in the cache
295AbstractCacheEntry*
296CacheMemory::lookup(const Address& address)
297{
298    assert(address == line_address(address));
299    Index cacheSet = addressToCacheSet(address);
300    int loc = findTagInSet(cacheSet, address);
301    if(loc == -1) return NULL;
302    return m_cache[cacheSet][loc];
303}
304
305// looks an address up in the cache
306const AbstractCacheEntry*
307CacheMemory::lookup(const Address& address) const
308{
309    assert(address == line_address(address));
310    Index cacheSet = addressToCacheSet(address);
311    int loc = findTagInSet(cacheSet, address);
312    if(loc == -1) return NULL;
313    return m_cache[cacheSet][loc];
314}
315
316// Sets the most recently used bit for a cache block
317void
318CacheMemory::setMRU(const Address& address)
319{
320    Index cacheSet = addressToCacheSet(address);
321    int loc = findTagInSet(cacheSet, address);
322
323    if(loc != -1)
324        m_replacementPolicy_ptr->touch(cacheSet, loc, curTick());
325}
326
327void
328CacheMemory::profileMiss(const RubyRequest& msg)
329{
330    m_profiler_ptr->addCacheStatSample(msg.getType(),
331                                       msg.getAccessMode(),
332                                       msg.getPrefetch());
333}
334
335void
336CacheMemory::profileGenericRequest(GenericRequestType requestType,
337                                   RubyAccessMode accessType,
338                                   PrefetchBit pfBit)
339{
340    m_profiler_ptr->addGenericStatSample(requestType,
341                                         accessType,
342                                         pfBit);
343}
344
345void
346CacheMemory::recordCacheContents(int cntrl, CacheRecorder* tr) const
347{
348    uint64 warmedUpBlocks = 0;
349    uint64 totalBlocks M5_VAR_USED = (uint64)m_cache_num_sets
350                                                  * (uint64)m_cache_assoc;
351
352    for (int i = 0; i < m_cache_num_sets; i++) {
353        for (int j = 0; j < m_cache_assoc; j++) {
354            if (m_cache[i][j] != NULL) {
355                AccessPermission perm = m_cache[i][j]->m_Permission;
356                RubyRequestType request_type = RubyRequestType_NULL;
357                if (perm == AccessPermission_Read_Only) {
358                    if (m_is_instruction_only_cache) {
359                        request_type = RubyRequestType_IFETCH;
360                    } else {
361                        request_type = RubyRequestType_LD;
362                    }
363                } else if (perm == AccessPermission_Read_Write) {
364                    request_type = RubyRequestType_ST;
365                }
366
367                if (request_type != RubyRequestType_NULL) {
368                    tr->addRecord(cntrl, m_cache[i][j]->m_Address.getAddress(),
369                                  0, request_type,
370                                  m_replacementPolicy_ptr->getLastAccess(i, j),
371                                  m_cache[i][j]->getDataBlk());
372                    warmedUpBlocks++;
373                }
374            }
375        }
376    }
377
378    DPRINTF(RubyCacheTrace, "%s: %lli blocks of %lli total blocks"
379            "recorded %.2f%% \n", name().c_str(), warmedUpBlocks,
380            (uint64)m_cache_num_sets * (uint64)m_cache_assoc,
381            (float(warmedUpBlocks)/float(totalBlocks))*100.0);
382}
383
384void
385CacheMemory::print(ostream& out) const
386{
387    out << "Cache dump: " << m_cache_name << endl;
388    for (int i = 0; i < m_cache_num_sets; i++) {
389        for (int j = 0; j < m_cache_assoc; j++) {
390            if (m_cache[i][j] != NULL) {
391                out << "  Index: " << i
392                    << " way: " << j
393                    << " entry: " << *m_cache[i][j] << endl;
394            } else {
395                out << "  Index: " << i
396                    << " way: " << j
397                    << " entry: NULL" << endl;
398            }
399        }
400    }
401}
402
403void
404CacheMemory::printData(ostream& out) const
405{
406    out << "printData() not supported" << endl;
407}
408
409void
410CacheMemory::clearStats() const
411{
412    m_profiler_ptr->clearStats();
413}
414
415void
416CacheMemory::printStats(ostream& out) const
417{
418    m_profiler_ptr->printStats(out);
419}
420
421void
422CacheMemory::setLocked(const Address& address, int context)
423{
424    DPRINTF(RubyCache, "Setting Lock for addr: %x to %d\n", address, context);
425    assert(address == line_address(address));
426    Index cacheSet = addressToCacheSet(address);
427    int loc = findTagInSet(cacheSet, address);
428    assert(loc != -1);
429    m_cache[cacheSet][loc]->m_locked = context;
430}
431
432void
433CacheMemory::clearLocked(const Address& address)
434{
435    DPRINTF(RubyCache, "Clear Lock for addr: %x\n", address);
436    assert(address == line_address(address));
437    Index cacheSet = addressToCacheSet(address);
438    int loc = findTagInSet(cacheSet, address);
439    assert(loc != -1);
440    m_cache[cacheSet][loc]->m_locked = -1;
441}
442
443bool
444CacheMemory::isLocked(const Address& address, int context)
445{
446    assert(address == line_address(address));
447    Index cacheSet = addressToCacheSet(address);
448    int loc = findTagInSet(cacheSet, address);
449    assert(loc != -1);
450    DPRINTF(RubyCache, "Testing Lock for addr: %llx cur %d con %d\n",
451            address, m_cache[cacheSet][loc]->m_locked, context);
452    return m_cache[cacheSet][loc]->m_locked == context;
453}
454
455void
456CacheMemory::recordRequestType(CacheRequestType requestType) {
457    DPRINTF(RubyStats, "Recorded statistic: %s\n",
458            CacheRequestType_to_string(requestType));
459    switch(requestType) {
460    case CacheRequestType_DataArrayRead:
461        numDataArrayReads++;
462        return;
463    case CacheRequestType_DataArrayWrite:
464        numDataArrayWrites++;
465        return;
466    case CacheRequestType_TagArrayRead:
467        numTagArrayReads++;
468        return;
469    case CacheRequestType_TagArrayWrite:
470        numTagArrayWrites++;
471        return;
472    default:
473        warn("CacheMemory access_type not found: %s",
474             CacheRequestType_to_string(requestType));
475    }
476}
477
478void
479CacheMemory::regStats() {
480    using namespace Stats;
481
482    numDataArrayReads
483        .name(name() + ".num_data_array_reads")
484        .desc("number of data array reads")
485        ;
486
487    numDataArrayWrites
488        .name(name() + ".num_data_array_writes")
489        .desc("number of data array writes")
490        ;
491
492    numTagArrayReads
493        .name(name() + ".num_tag_array_reads")
494        .desc("number of tag array reads")
495        ;
496
497    numTagArrayWrites
498        .name(name() + ".num_tag_array_writes")
499        .desc("number of tag array writes")
500        ;
501
502    numTagArrayStalls
503        .name(name() + ".num_tag_array_stalls")
504        .desc("number of stalls caused by tag array")
505        ;
506
507    numDataArrayStalls
508        .name(name() + ".num_data_array_stalls")
509        .desc("number of stalls caused by data array")
510        ;
511}
512
513bool
514CacheMemory::checkResourceAvailable(CacheResourceType res, Address addr)
515{
516    if (!m_resource_stalls) {
517        return true;
518    }
519
520    if (res == CacheResourceType_TagArray) {
521        if (tagArray.tryAccess(addressToCacheSet(addr))) return true;
522        else {
523            DPRINTF(RubyResourceStalls, "Tag array stall on addr %s in set %d\n", addr, addressToCacheSet(addr));
524            numTagArrayStalls++;
525            return false;
526        }
527    } else if (res == CacheResourceType_DataArray) {
528        if (dataArray.tryAccess(addressToCacheSet(addr))) return true;
529        else {
530            DPRINTF(RubyResourceStalls, "Data array stall on addr %s in set %d\n", addr, addressToCacheSet(addr));
531            numDataArrayStalls++;
532            return false;
533        }
534    } else {
535        assert(false);
536        return true;
537    }
538}
539