base.cc revision 12794
1/* 2 * Copyright (c) 2012-2013, 2018 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 * Nikos Nikoleris 42 */ 43 44/** 45 * @file 46 * Definition of BaseCache functions. 47 */ 48 49#include "mem/cache/base.hh" 50 51#include "base/compiler.hh" 52#include "base/logging.hh" 53#include "debug/Cache.hh" 54#include "debug/CachePort.hh" 55#include "debug/CacheVerbose.hh" 56#include "mem/cache/mshr.hh" 57#include "mem/cache/prefetch/base.hh" 58#include "mem/cache/queue_entry.hh" 59#include "params/BaseCache.hh" 60#include "sim/core.hh" 61 62class BaseMasterPort; 63class BaseSlavePort; 64 65using namespace std; 66 67BaseCache::CacheSlavePort::CacheSlavePort(const std::string &_name, 68 BaseCache *_cache, 69 const std::string &_label) 70 : QueuedSlavePort(_name, _cache, queue), queue(*_cache, *this, _label), 71 blocked(false), mustSendRetry(false), 72 sendRetryEvent([this]{ processSendRetry(); }, _name) 73{ 74} 75 76BaseCache::BaseCache(const BaseCacheParams *p, unsigned blk_size) 77 : MemObject(p), 78 cpuSidePort (p->name + ".cpu_side", this, "CpuSidePort"), 79 memSidePort(p->name + ".mem_side", this, "MemSidePort"), 80 mshrQueue("MSHRs", p->mshrs, 0, p->demand_mshr_reserve), // see below 81 writeBuffer("write buffer", p->write_buffers, p->mshrs), // see below 82 tags(p->tags), 83 prefetcher(p->prefetcher), 84 prefetchOnAccess(p->prefetch_on_access), 85 writebackClean(p->writeback_clean), 86 tempBlockWriteback(nullptr), 87 writebackTempBlockAtomicEvent([this]{ writebackTempBlockAtomic(); }, 88 name(), false, 89 EventBase::Delayed_Writeback_Pri), 90 blkSize(blk_size), 91 lookupLatency(p->tag_latency), 92 dataLatency(p->data_latency), 93 forwardLatency(p->tag_latency), 94 fillLatency(p->data_latency), 95 responseLatency(p->response_latency), 96 numTarget(p->tgts_per_mshr), 97 forwardSnoops(true), 98 clusivity(p->clusivity), 99 isReadOnly(p->is_read_only), 100 blocked(0), 101 order(0), 102 noTargetMSHR(nullptr), 103 missCount(p->max_miss_count), 104 addrRanges(p->addr_ranges.begin(), p->addr_ranges.end()), 105 system(p->system) 106{ 107 // the MSHR queue has no reserve entries as we check the MSHR 108 // queue on every single allocation, whereas the write queue has 109 // as many reserve entries as we have MSHRs, since every MSHR may 110 // eventually require a writeback, and we do not check the write 111 // buffer before committing to an MSHR 112 113 // forward snoops is overridden in init() once we can query 114 // whether the connected master is actually snooping or not 115 116 tempBlock = new TempCacheBlk(); 117 tempBlock->data = new uint8_t[blkSize]; 118 119 tags->setCache(this); 120 if (prefetcher) 121 prefetcher->setCache(this); 122} 123 124BaseCache::~BaseCache() 125{ 126 delete [] tempBlock->data; 127 delete tempBlock; 128} 129 130void 131BaseCache::CacheSlavePort::setBlocked() 132{ 133 assert(!blocked); 134 DPRINTF(CachePort, "Port is blocking new requests\n"); 135 blocked = true; 136 // if we already scheduled a retry in this cycle, but it has not yet 137 // happened, cancel it 138 if (sendRetryEvent.scheduled()) { 139 owner.deschedule(sendRetryEvent); 140 DPRINTF(CachePort, "Port descheduled retry\n"); 141 mustSendRetry = true; 142 } 143} 144 145void 146BaseCache::CacheSlavePort::clearBlocked() 147{ 148 assert(blocked); 149 DPRINTF(CachePort, "Port is accepting new requests\n"); 150 blocked = false; 151 if (mustSendRetry) { 152 // @TODO: need to find a better time (next cycle?) 153 owner.schedule(sendRetryEvent, curTick() + 1); 154 } 155} 156 157void 158BaseCache::CacheSlavePort::processSendRetry() 159{ 160 DPRINTF(CachePort, "Port is sending retry\n"); 161 162 // reset the flag and call retry 163 mustSendRetry = false; 164 sendRetryReq(); 165} 166 167Addr 168BaseCache::regenerateBlkAddr(CacheBlk* blk) 169{ 170 if (blk != tempBlock) { 171 return tags->regenerateBlkAddr(blk); 172 } else { 173 return tempBlock->getAddr(); 174 } 175} 176 177void 178BaseCache::init() 179{ 180 if (!cpuSidePort.isConnected() || !memSidePort.isConnected()) 181 fatal("Cache ports on %s are not connected\n", name()); 182 cpuSidePort.sendRangeChange(); 183 forwardSnoops = cpuSidePort.isSnooping(); 184} 185 186BaseMasterPort & 187BaseCache::getMasterPort(const std::string &if_name, PortID idx) 188{ 189 if (if_name == "mem_side") { 190 return memSidePort; 191 } else { 192 return MemObject::getMasterPort(if_name, idx); 193 } 194} 195 196BaseSlavePort & 197BaseCache::getSlavePort(const std::string &if_name, PortID idx) 198{ 199 if (if_name == "cpu_side") { 200 return cpuSidePort; 201 } else { 202 return MemObject::getSlavePort(if_name, idx); 203 } 204} 205 206bool 207BaseCache::inRange(Addr addr) const 208{ 209 for (const auto& r : addrRanges) { 210 if (r.contains(addr)) { 211 return true; 212 } 213 } 214 return false; 215} 216 217void 218BaseCache::handleTimingReqHit(PacketPtr pkt, CacheBlk *blk, Tick request_time) 219{ 220 if (pkt->needsResponse()) { 221 pkt->makeTimingResponse(); 222 // @todo: Make someone pay for this 223 pkt->headerDelay = pkt->payloadDelay = 0; 224 225 // In this case we are considering request_time that takes 226 // into account the delay of the xbar, if any, and just 227 // lat, neglecting responseLatency, modelling hit latency 228 // just as lookupLatency or or the value of lat overriden 229 // by access(), that calls accessBlock() function. 230 cpuSidePort.schedTimingResp(pkt, request_time, true); 231 } else { 232 DPRINTF(Cache, "%s satisfied %s, no response needed\n", __func__, 233 pkt->print()); 234 235 // queue the packet for deletion, as the sending cache is 236 // still relying on it; if the block is found in access(), 237 // CleanEvict and Writeback messages will be deleted 238 // here as well 239 pendingDelete.reset(pkt); 240 } 241} 242 243void 244BaseCache::handleTimingReqMiss(PacketPtr pkt, MSHR *mshr, CacheBlk *blk, 245 Tick forward_time, Tick request_time) 246{ 247 if (mshr) { 248 /// MSHR hit 249 /// @note writebacks will be checked in getNextMSHR() 250 /// for any conflicting requests to the same block 251 252 //@todo remove hw_pf here 253 254 // Coalesce unless it was a software prefetch (see above). 255 if (pkt) { 256 assert(!pkt->isWriteback()); 257 // CleanEvicts corresponding to blocks which have 258 // outstanding requests in MSHRs are simply sunk here 259 if (pkt->cmd == MemCmd::CleanEvict) { 260 pendingDelete.reset(pkt); 261 } else if (pkt->cmd == MemCmd::WriteClean) { 262 // A WriteClean should never coalesce with any 263 // outstanding cache maintenance requests. 264 265 // We use forward_time here because there is an 266 // uncached memory write, forwarded to WriteBuffer. 267 allocateWriteBuffer(pkt, forward_time); 268 } else { 269 DPRINTF(Cache, "%s coalescing MSHR for %s\n", __func__, 270 pkt->print()); 271 272 assert(pkt->req->masterId() < system->maxMasters()); 273 mshr_hits[pkt->cmdToIndex()][pkt->req->masterId()]++; 274 275 // We use forward_time here because it is the same 276 // considering new targets. We have multiple 277 // requests for the same address here. It 278 // specifies the latency to allocate an internal 279 // buffer and to schedule an event to the queued 280 // port and also takes into account the additional 281 // delay of the xbar. 282 mshr->allocateTarget(pkt, forward_time, order++, 283 allocOnFill(pkt->cmd)); 284 if (mshr->getNumTargets() == numTarget) { 285 noTargetMSHR = mshr; 286 setBlocked(Blocked_NoTargets); 287 // need to be careful with this... if this mshr isn't 288 // ready yet (i.e. time > curTick()), we don't want to 289 // move it ahead of mshrs that are ready 290 // mshrQueue.moveToFront(mshr); 291 } 292 } 293 } 294 } else { 295 // no MSHR 296 assert(pkt->req->masterId() < system->maxMasters()); 297 mshr_misses[pkt->cmdToIndex()][pkt->req->masterId()]++; 298 299 if (pkt->isEviction() || pkt->cmd == MemCmd::WriteClean) { 300 // We use forward_time here because there is an 301 // writeback or writeclean, forwarded to WriteBuffer. 302 allocateWriteBuffer(pkt, forward_time); 303 } else { 304 if (blk && blk->isValid()) { 305 // If we have a write miss to a valid block, we 306 // need to mark the block non-readable. Otherwise 307 // if we allow reads while there's an outstanding 308 // write miss, the read could return stale data 309 // out of the cache block... a more aggressive 310 // system could detect the overlap (if any) and 311 // forward data out of the MSHRs, but we don't do 312 // that yet. Note that we do need to leave the 313 // block valid so that it stays in the cache, in 314 // case we get an upgrade response (and hence no 315 // new data) when the write miss completes. 316 // As long as CPUs do proper store/load forwarding 317 // internally, and have a sufficiently weak memory 318 // model, this is probably unnecessary, but at some 319 // point it must have seemed like we needed it... 320 assert((pkt->needsWritable() && !blk->isWritable()) || 321 pkt->req->isCacheMaintenance()); 322 blk->status &= ~BlkReadable; 323 } 324 // Here we are using forward_time, modelling the latency of 325 // a miss (outbound) just as forwardLatency, neglecting the 326 // lookupLatency component. 327 allocateMissBuffer(pkt, forward_time); 328 } 329 } 330} 331 332void 333BaseCache::recvTimingReq(PacketPtr pkt) 334{ 335 // anything that is merely forwarded pays for the forward latency and 336 // the delay provided by the crossbar 337 Tick forward_time = clockEdge(forwardLatency) + pkt->headerDelay; 338 339 // We use lookupLatency here because it is used to specify the latency 340 // to access. 341 Cycles lat = lookupLatency; 342 CacheBlk *blk = nullptr; 343 bool satisfied = false; 344 { 345 PacketList writebacks; 346 // Note that lat is passed by reference here. The function 347 // access() calls accessBlock() which can modify lat value. 348 satisfied = access(pkt, blk, lat, writebacks); 349 350 // copy writebacks to write buffer here to ensure they logically 351 // proceed anything happening below 352 doWritebacks(writebacks, forward_time); 353 } 354 355 // Here we charge the headerDelay that takes into account the latencies 356 // of the bus, if the packet comes from it. 357 // The latency charged it is just lat that is the value of lookupLatency 358 // modified by access() function, or if not just lookupLatency. 359 // In case of a hit we are neglecting response latency. 360 // In case of a miss we are neglecting forward latency. 361 Tick request_time = clockEdge(lat) + pkt->headerDelay; 362 // Here we reset the timing of the packet. 363 pkt->headerDelay = pkt->payloadDelay = 0; 364 // track time of availability of next prefetch, if any 365 Tick next_pf_time = MaxTick; 366 367 if (satisfied) { 368 // if need to notify the prefetcher we have to do it before 369 // anything else as later handleTimingReqHit might turn the 370 // packet in a response 371 if (prefetcher && 372 (prefetchOnAccess || (blk && blk->wasPrefetched()))) { 373 if (blk) 374 blk->status &= ~BlkHWPrefetched; 375 376 // Don't notify on SWPrefetch 377 if (!pkt->cmd.isSWPrefetch()) { 378 assert(!pkt->req->isCacheMaintenance()); 379 next_pf_time = prefetcher->notify(pkt); 380 } 381 } 382 383 handleTimingReqHit(pkt, blk, request_time); 384 } else { 385 handleTimingReqMiss(pkt, blk, forward_time, request_time); 386 387 // We should call the prefetcher reguardless if the request is 388 // satisfied or not, reguardless if the request is in the MSHR 389 // or not. The request could be a ReadReq hit, but still not 390 // satisfied (potentially because of a prior write to the same 391 // cache line. So, even when not satisfied, there is an MSHR 392 // already allocated for this, we need to let the prefetcher 393 // know about the request 394 395 // Don't notify prefetcher on SWPrefetch or cache maintenance 396 // operations 397 if (prefetcher && pkt && 398 !pkt->cmd.isSWPrefetch() && 399 !pkt->req->isCacheMaintenance()) { 400 next_pf_time = prefetcher->notify(pkt); 401 } 402 } 403 404 if (next_pf_time != MaxTick) { 405 schedMemSideSendEvent(next_pf_time); 406 } 407} 408 409void 410BaseCache::handleUncacheableWriteResp(PacketPtr pkt) 411{ 412 Tick completion_time = clockEdge(responseLatency) + 413 pkt->headerDelay + pkt->payloadDelay; 414 415 // Reset the bus additional time as it is now accounted for 416 pkt->headerDelay = pkt->payloadDelay = 0; 417 418 cpuSidePort.schedTimingResp(pkt, completion_time, true); 419} 420 421void 422BaseCache::recvTimingResp(PacketPtr pkt) 423{ 424 assert(pkt->isResponse()); 425 426 // all header delay should be paid for by the crossbar, unless 427 // this is a prefetch response from above 428 panic_if(pkt->headerDelay != 0 && pkt->cmd != MemCmd::HardPFResp, 429 "%s saw a non-zero packet delay\n", name()); 430 431 const bool is_error = pkt->isError(); 432 433 if (is_error) { 434 DPRINTF(Cache, "%s: Cache received %s with error\n", __func__, 435 pkt->print()); 436 } 437 438 DPRINTF(Cache, "%s: Handling response %s\n", __func__, 439 pkt->print()); 440 441 // if this is a write, we should be looking at an uncacheable 442 // write 443 if (pkt->isWrite()) { 444 assert(pkt->req->isUncacheable()); 445 handleUncacheableWriteResp(pkt); 446 return; 447 } 448 449 // we have dealt with any (uncacheable) writes above, from here on 450 // we know we are dealing with an MSHR due to a miss or a prefetch 451 MSHR *mshr = dynamic_cast<MSHR*>(pkt->popSenderState()); 452 assert(mshr); 453 454 if (mshr == noTargetMSHR) { 455 // we always clear at least one target 456 clearBlocked(Blocked_NoTargets); 457 noTargetMSHR = nullptr; 458 } 459 460 // Initial target is used just for stats 461 MSHR::Target *initial_tgt = mshr->getTarget(); 462 int stats_cmd_idx = initial_tgt->pkt->cmdToIndex(); 463 Tick miss_latency = curTick() - initial_tgt->recvTime; 464 465 if (pkt->req->isUncacheable()) { 466 assert(pkt->req->masterId() < system->maxMasters()); 467 mshr_uncacheable_lat[stats_cmd_idx][pkt->req->masterId()] += 468 miss_latency; 469 } else { 470 assert(pkt->req->masterId() < system->maxMasters()); 471 mshr_miss_latency[stats_cmd_idx][pkt->req->masterId()] += 472 miss_latency; 473 } 474 475 PacketList writebacks; 476 477 bool is_fill = !mshr->isForward && 478 (pkt->isRead() || pkt->cmd == MemCmd::UpgradeResp); 479 480 CacheBlk *blk = tags->findBlock(pkt->getAddr(), pkt->isSecure()); 481 482 if (is_fill && !is_error) { 483 DPRINTF(Cache, "Block for addr %#llx being updated in Cache\n", 484 pkt->getAddr()); 485 486 blk = handleFill(pkt, blk, writebacks, mshr->allocOnFill()); 487 assert(blk != nullptr); 488 } 489 490 if (blk && blk->isValid() && pkt->isClean() && !pkt->isInvalidate()) { 491 // The block was marked not readable while there was a pending 492 // cache maintenance operation, restore its flag. 493 blk->status |= BlkReadable; 494 495 // This was a cache clean operation (without invalidate) 496 // and we have a copy of the block already. Since there 497 // is no invalidation, we can promote targets that don't 498 // require a writable copy 499 mshr->promoteReadable(); 500 } 501 502 if (blk && blk->isWritable() && !pkt->req->isCacheInvalidate()) { 503 // If at this point the referenced block is writable and the 504 // response is not a cache invalidate, we promote targets that 505 // were deferred as we couldn't guarrantee a writable copy 506 mshr->promoteWritable(); 507 } 508 509 serviceMSHRTargets(mshr, pkt, blk, writebacks); 510 511 if (mshr->promoteDeferredTargets()) { 512 // avoid later read getting stale data while write miss is 513 // outstanding.. see comment in timingAccess() 514 if (blk) { 515 blk->status &= ~BlkReadable; 516 } 517 mshrQueue.markPending(mshr); 518 schedMemSideSendEvent(clockEdge() + pkt->payloadDelay); 519 } else { 520 // while we deallocate an mshr from the queue we still have to 521 // check the isFull condition before and after as we might 522 // have been using the reserved entries already 523 const bool was_full = mshrQueue.isFull(); 524 mshrQueue.deallocate(mshr); 525 if (was_full && !mshrQueue.isFull()) { 526 clearBlocked(Blocked_NoMSHRs); 527 } 528 529 // Request the bus for a prefetch if this deallocation freed enough 530 // MSHRs for a prefetch to take place 531 if (prefetcher && mshrQueue.canPrefetch()) { 532 Tick next_pf_time = std::max(prefetcher->nextPrefetchReadyTime(), 533 clockEdge()); 534 if (next_pf_time != MaxTick) 535 schedMemSideSendEvent(next_pf_time); 536 } 537 } 538 539 // if we used temp block, check to see if its valid and then clear it out 540 if (blk == tempBlock && tempBlock->isValid()) { 541 evictBlock(blk, writebacks); 542 } 543 544 const Tick forward_time = clockEdge(forwardLatency) + pkt->headerDelay; 545 // copy writebacks to write buffer 546 doWritebacks(writebacks, forward_time); 547 548 DPRINTF(CacheVerbose, "%s: Leaving with %s\n", __func__, pkt->print()); 549 delete pkt; 550} 551 552 553Tick 554BaseCache::recvAtomic(PacketPtr pkt) 555{ 556 // We are in atomic mode so we pay just for lookupLatency here. 557 Cycles lat = lookupLatency; 558 559 // follow the same flow as in recvTimingReq, and check if a cache 560 // above us is responding 561 if (pkt->cacheResponding() && !pkt->isClean()) { 562 assert(!pkt->req->isCacheInvalidate()); 563 DPRINTF(Cache, "Cache above responding to %s: not responding\n", 564 pkt->print()); 565 566 // if a cache is responding, and it had the line in Owned 567 // rather than Modified state, we need to invalidate any 568 // copies that are not on the same path to memory 569 assert(pkt->needsWritable() && !pkt->responderHadWritable()); 570 lat += ticksToCycles(memSidePort.sendAtomic(pkt)); 571 572 return lat * clockPeriod(); 573 } 574 575 // should assert here that there are no outstanding MSHRs or 576 // writebacks... that would mean that someone used an atomic 577 // access in timing mode 578 579 CacheBlk *blk = nullptr; 580 PacketList writebacks; 581 bool satisfied = access(pkt, blk, lat, writebacks); 582 583 if (pkt->isClean() && blk && blk->isDirty()) { 584 // A cache clean opearation is looking for a dirty 585 // block. If a dirty block is encountered a WriteClean 586 // will update any copies to the path to the memory 587 // until the point of reference. 588 DPRINTF(CacheVerbose, "%s: packet %s found block: %s\n", 589 __func__, pkt->print(), blk->print()); 590 PacketPtr wb_pkt = writecleanBlk(blk, pkt->req->getDest(), pkt->id); 591 writebacks.push_back(wb_pkt); 592 pkt->setSatisfied(); 593 } 594 595 // handle writebacks resulting from the access here to ensure they 596 // logically proceed anything happening below 597 doWritebacksAtomic(writebacks); 598 assert(writebacks.empty()); 599 600 if (!satisfied) { 601 lat += handleAtomicReqMiss(pkt, blk, writebacks); 602 } 603 604 // Note that we don't invoke the prefetcher at all in atomic mode. 605 // It's not clear how to do it properly, particularly for 606 // prefetchers that aggressively generate prefetch candidates and 607 // rely on bandwidth contention to throttle them; these will tend 608 // to pollute the cache in atomic mode since there is no bandwidth 609 // contention. If we ever do want to enable prefetching in atomic 610 // mode, though, this is the place to do it... see timingAccess() 611 // for an example (though we'd want to issue the prefetch(es) 612 // immediately rather than calling requestMemSideBus() as we do 613 // there). 614 615 // do any writebacks resulting from the response handling 616 doWritebacksAtomic(writebacks); 617 618 // if we used temp block, check to see if its valid and if so 619 // clear it out, but only do so after the call to recvAtomic is 620 // finished so that any downstream observers (such as a snoop 621 // filter), first see the fill, and only then see the eviction 622 if (blk == tempBlock && tempBlock->isValid()) { 623 // the atomic CPU calls recvAtomic for fetch and load/store 624 // sequentuially, and we may already have a tempBlock 625 // writeback from the fetch that we have not yet sent 626 if (tempBlockWriteback) { 627 // if that is the case, write the prevoius one back, and 628 // do not schedule any new event 629 writebackTempBlockAtomic(); 630 } else { 631 // the writeback/clean eviction happens after the call to 632 // recvAtomic has finished (but before any successive 633 // calls), so that the response handling from the fill is 634 // allowed to happen first 635 schedule(writebackTempBlockAtomicEvent, curTick()); 636 } 637 638 tempBlockWriteback = evictBlock(blk); 639 } 640 641 if (pkt->needsResponse()) { 642 pkt->makeAtomicResponse(); 643 } 644 645 return lat * clockPeriod(); 646} 647 648void 649BaseCache::functionalAccess(PacketPtr pkt, bool from_cpu_side) 650{ 651 Addr blk_addr = pkt->getBlockAddr(blkSize); 652 bool is_secure = pkt->isSecure(); 653 CacheBlk *blk = tags->findBlock(pkt->getAddr(), is_secure); 654 MSHR *mshr = mshrQueue.findMatch(blk_addr, is_secure); 655 656 pkt->pushLabel(name()); 657 658 CacheBlkPrintWrapper cbpw(blk); 659 660 // Note that just because an L2/L3 has valid data doesn't mean an 661 // L1 doesn't have a more up-to-date modified copy that still 662 // needs to be found. As a result we always update the request if 663 // we have it, but only declare it satisfied if we are the owner. 664 665 // see if we have data at all (owned or otherwise) 666 bool have_data = blk && blk->isValid() 667 && pkt->checkFunctional(&cbpw, blk_addr, is_secure, blkSize, 668 blk->data); 669 670 // data we have is dirty if marked as such or if we have an 671 // in-service MSHR that is pending a modified line 672 bool have_dirty = 673 have_data && (blk->isDirty() || 674 (mshr && mshr->inService && mshr->isPendingModified())); 675 676 bool done = have_dirty || 677 cpuSidePort.checkFunctional(pkt) || 678 mshrQueue.checkFunctional(pkt, blk_addr) || 679 writeBuffer.checkFunctional(pkt, blk_addr) || 680 memSidePort.checkFunctional(pkt); 681 682 DPRINTF(CacheVerbose, "%s: %s %s%s%s\n", __func__, pkt->print(), 683 (blk && blk->isValid()) ? "valid " : "", 684 have_data ? "data " : "", done ? "done " : ""); 685 686 // We're leaving the cache, so pop cache->name() label 687 pkt->popLabel(); 688 689 if (done) { 690 pkt->makeResponse(); 691 } else { 692 // if it came as a request from the CPU side then make sure it 693 // continues towards the memory side 694 if (from_cpu_side) { 695 memSidePort.sendFunctional(pkt); 696 } else if (cpuSidePort.isSnooping()) { 697 // if it came from the memory side, it must be a snoop request 698 // and we should only forward it if we are forwarding snoops 699 cpuSidePort.sendFunctionalSnoop(pkt); 700 } 701 } 702} 703 704 705void 706BaseCache::cmpAndSwap(CacheBlk *blk, PacketPtr pkt) 707{ 708 assert(pkt->isRequest()); 709 710 uint64_t overwrite_val; 711 bool overwrite_mem; 712 uint64_t condition_val64; 713 uint32_t condition_val32; 714 715 int offset = pkt->getOffset(blkSize); 716 uint8_t *blk_data = blk->data + offset; 717 718 assert(sizeof(uint64_t) >= pkt->getSize()); 719 720 overwrite_mem = true; 721 // keep a copy of our possible write value, and copy what is at the 722 // memory address into the packet 723 pkt->writeData((uint8_t *)&overwrite_val); 724 pkt->setData(blk_data); 725 726 if (pkt->req->isCondSwap()) { 727 if (pkt->getSize() == sizeof(uint64_t)) { 728 condition_val64 = pkt->req->getExtraData(); 729 overwrite_mem = !std::memcmp(&condition_val64, blk_data, 730 sizeof(uint64_t)); 731 } else if (pkt->getSize() == sizeof(uint32_t)) { 732 condition_val32 = (uint32_t)pkt->req->getExtraData(); 733 overwrite_mem = !std::memcmp(&condition_val32, blk_data, 734 sizeof(uint32_t)); 735 } else 736 panic("Invalid size for conditional read/write\n"); 737 } 738 739 if (overwrite_mem) { 740 std::memcpy(blk_data, &overwrite_val, pkt->getSize()); 741 blk->status |= BlkDirty; 742 } 743} 744 745QueueEntry* 746BaseCache::getNextQueueEntry() 747{ 748 // Check both MSHR queue and write buffer for potential requests, 749 // note that null does not mean there is no request, it could 750 // simply be that it is not ready 751 MSHR *miss_mshr = mshrQueue.getNext(); 752 WriteQueueEntry *wq_entry = writeBuffer.getNext(); 753 754 // If we got a write buffer request ready, first priority is a 755 // full write buffer, otherwise we favour the miss requests 756 if (wq_entry && (writeBuffer.isFull() || !miss_mshr)) { 757 // need to search MSHR queue for conflicting earlier miss. 758 MSHR *conflict_mshr = 759 mshrQueue.findPending(wq_entry->blkAddr, 760 wq_entry->isSecure); 761 762 if (conflict_mshr && conflict_mshr->order < wq_entry->order) { 763 // Service misses in order until conflict is cleared. 764 return conflict_mshr; 765 766 // @todo Note that we ignore the ready time of the conflict here 767 } 768 769 // No conflicts; issue write 770 return wq_entry; 771 } else if (miss_mshr) { 772 // need to check for conflicting earlier writeback 773 WriteQueueEntry *conflict_mshr = 774 writeBuffer.findPending(miss_mshr->blkAddr, 775 miss_mshr->isSecure); 776 if (conflict_mshr) { 777 // not sure why we don't check order here... it was in the 778 // original code but commented out. 779 780 // The only way this happens is if we are 781 // doing a write and we didn't have permissions 782 // then subsequently saw a writeback (owned got evicted) 783 // We need to make sure to perform the writeback first 784 // To preserve the dirty data, then we can issue the write 785 786 // should we return wq_entry here instead? I.e. do we 787 // have to flush writes in order? I don't think so... not 788 // for Alpha anyway. Maybe for x86? 789 return conflict_mshr; 790 791 // @todo Note that we ignore the ready time of the conflict here 792 } 793 794 // No conflicts; issue read 795 return miss_mshr; 796 } 797 798 // fall through... no pending requests. Try a prefetch. 799 assert(!miss_mshr && !wq_entry); 800 if (prefetcher && mshrQueue.canPrefetch()) { 801 // If we have a miss queue slot, we can try a prefetch 802 PacketPtr pkt = prefetcher->getPacket(); 803 if (pkt) { 804 Addr pf_addr = pkt->getBlockAddr(blkSize); 805 if (!tags->findBlock(pf_addr, pkt->isSecure()) && 806 !mshrQueue.findMatch(pf_addr, pkt->isSecure()) && 807 !writeBuffer.findMatch(pf_addr, pkt->isSecure())) { 808 // Update statistic on number of prefetches issued 809 // (hwpf_mshr_misses) 810 assert(pkt->req->masterId() < system->maxMasters()); 811 mshr_misses[pkt->cmdToIndex()][pkt->req->masterId()]++; 812 813 // allocate an MSHR and return it, note 814 // that we send the packet straight away, so do not 815 // schedule the send 816 return allocateMissBuffer(pkt, curTick(), false); 817 } else { 818 // free the request and packet 819 delete pkt; 820 } 821 } 822 } 823 824 return nullptr; 825} 826 827void 828BaseCache::satisfyRequest(PacketPtr pkt, CacheBlk *blk, bool, bool) 829{ 830 assert(pkt->isRequest()); 831 832 assert(blk && blk->isValid()); 833 // Occasionally this is not true... if we are a lower-level cache 834 // satisfying a string of Read and ReadEx requests from 835 // upper-level caches, a Read will mark the block as shared but we 836 // can satisfy a following ReadEx anyway since we can rely on the 837 // Read requester(s) to have buffered the ReadEx snoop and to 838 // invalidate their blocks after receiving them. 839 // assert(!pkt->needsWritable() || blk->isWritable()); 840 assert(pkt->getOffset(blkSize) + pkt->getSize() <= blkSize); 841 842 // Check RMW operations first since both isRead() and 843 // isWrite() will be true for them 844 if (pkt->cmd == MemCmd::SwapReq) { 845 if (pkt->isAtomicOp()) { 846 // extract data from cache and save it into the data field in 847 // the packet as a return value from this atomic op 848 849 int offset = tags->extractBlkOffset(pkt->getAddr()); 850 uint8_t *blk_data = blk->data + offset; 851 std::memcpy(pkt->getPtr<uint8_t>(), blk_data, pkt->getSize()); 852 853 // execute AMO operation 854 (*(pkt->getAtomicOp()))(blk_data); 855 856 // set block status to dirty 857 blk->status |= BlkDirty; 858 } else { 859 cmpAndSwap(blk, pkt); 860 } 861 } else if (pkt->isWrite()) { 862 // we have the block in a writable state and can go ahead, 863 // note that the line may be also be considered writable in 864 // downstream caches along the path to memory, but always 865 // Exclusive, and never Modified 866 assert(blk->isWritable()); 867 // Write or WriteLine at the first cache with block in writable state 868 if (blk->checkWrite(pkt)) { 869 pkt->writeDataToBlock(blk->data, blkSize); 870 } 871 // Always mark the line as dirty (and thus transition to the 872 // Modified state) even if we are a failed StoreCond so we 873 // supply data to any snoops that have appended themselves to 874 // this cache before knowing the store will fail. 875 blk->status |= BlkDirty; 876 DPRINTF(CacheVerbose, "%s for %s (write)\n", __func__, pkt->print()); 877 } else if (pkt->isRead()) { 878 if (pkt->isLLSC()) { 879 blk->trackLoadLocked(pkt); 880 } 881 882 // all read responses have a data payload 883 assert(pkt->hasRespData()); 884 pkt->setDataFromBlock(blk->data, blkSize); 885 } else if (pkt->isUpgrade()) { 886 // sanity check 887 assert(!pkt->hasSharers()); 888 889 if (blk->isDirty()) { 890 // we were in the Owned state, and a cache above us that 891 // has the line in Shared state needs to be made aware 892 // that the data it already has is in fact dirty 893 pkt->setCacheResponding(); 894 blk->status &= ~BlkDirty; 895 } 896 } else if (pkt->isClean()) { 897 blk->status &= ~BlkDirty; 898 } else { 899 assert(pkt->isInvalidate()); 900 invalidateBlock(blk); 901 DPRINTF(CacheVerbose, "%s for %s (invalidation)\n", __func__, 902 pkt->print()); 903 } 904} 905 906///////////////////////////////////////////////////// 907// 908// Access path: requests coming in from the CPU side 909// 910///////////////////////////////////////////////////// 911 912bool 913BaseCache::access(PacketPtr pkt, CacheBlk *&blk, Cycles &lat, 914 PacketList &writebacks) 915{ 916 // sanity check 917 assert(pkt->isRequest()); 918 919 chatty_assert(!(isReadOnly && pkt->isWrite()), 920 "Should never see a write in a read-only cache %s\n", 921 name()); 922 923 // Here lat is the value passed as parameter to accessBlock() function 924 // that can modify its value. 925 blk = tags->accessBlock(pkt->getAddr(), pkt->isSecure(), lat); 926 927 DPRINTF(Cache, "%s for %s %s\n", __func__, pkt->print(), 928 blk ? "hit " + blk->print() : "miss"); 929 930 if (pkt->req->isCacheMaintenance()) { 931 // A cache maintenance operation is always forwarded to the 932 // memory below even if the block is found in dirty state. 933 934 // We defer any changes to the state of the block until we 935 // create and mark as in service the mshr for the downstream 936 // packet. 937 return false; 938 } 939 940 if (pkt->isEviction()) { 941 // We check for presence of block in above caches before issuing 942 // Writeback or CleanEvict to write buffer. Therefore the only 943 // possible cases can be of a CleanEvict packet coming from above 944 // encountering a Writeback generated in this cache peer cache and 945 // waiting in the write buffer. Cases of upper level peer caches 946 // generating CleanEvict and Writeback or simply CleanEvict and 947 // CleanEvict almost simultaneously will be caught by snoops sent out 948 // by crossbar. 949 WriteQueueEntry *wb_entry = writeBuffer.findMatch(pkt->getAddr(), 950 pkt->isSecure()); 951 if (wb_entry) { 952 assert(wb_entry->getNumTargets() == 1); 953 PacketPtr wbPkt = wb_entry->getTarget()->pkt; 954 assert(wbPkt->isWriteback()); 955 956 if (pkt->isCleanEviction()) { 957 // The CleanEvict and WritebackClean snoops into other 958 // peer caches of the same level while traversing the 959 // crossbar. If a copy of the block is found, the 960 // packet is deleted in the crossbar. Hence, none of 961 // the other upper level caches connected to this 962 // cache have the block, so we can clear the 963 // BLOCK_CACHED flag in the Writeback if set and 964 // discard the CleanEvict by returning true. 965 wbPkt->clearBlockCached(); 966 return true; 967 } else { 968 assert(pkt->cmd == MemCmd::WritebackDirty); 969 // Dirty writeback from above trumps our clean 970 // writeback... discard here 971 // Note: markInService will remove entry from writeback buffer. 972 markInService(wb_entry); 973 delete wbPkt; 974 } 975 } 976 } 977 978 // Writeback handling is special case. We can write the block into 979 // the cache without having a writeable copy (or any copy at all). 980 if (pkt->isWriteback()) { 981 assert(blkSize == pkt->getSize()); 982 983 // we could get a clean writeback while we are having 984 // outstanding accesses to a block, do the simple thing for 985 // now and drop the clean writeback so that we do not upset 986 // any ordering/decisions about ownership already taken 987 if (pkt->cmd == MemCmd::WritebackClean && 988 mshrQueue.findMatch(pkt->getAddr(), pkt->isSecure())) { 989 DPRINTF(Cache, "Clean writeback %#llx to block with MSHR, " 990 "dropping\n", pkt->getAddr()); 991 return true; 992 } 993 994 if (!blk) { 995 // need to do a replacement 996 blk = allocateBlock(pkt, writebacks); 997 if (!blk) { 998 // no replaceable block available: give up, fwd to next level. 999 incMissCount(pkt); 1000 return false; 1001 } 1002 1003 blk->status |= (BlkValid | BlkReadable); 1004 } 1005 // only mark the block dirty if we got a writeback command, 1006 // and leave it as is for a clean writeback 1007 if (pkt->cmd == MemCmd::WritebackDirty) { 1008 // TODO: the coherent cache can assert(!blk->isDirty()); 1009 blk->status |= BlkDirty; 1010 } 1011 // if the packet does not have sharers, it is passing 1012 // writable, and we got the writeback in Modified or Exclusive 1013 // state, if not we are in the Owned or Shared state 1014 if (!pkt->hasSharers()) { 1015 blk->status |= BlkWritable; 1016 } 1017 // nothing else to do; writeback doesn't expect response 1018 assert(!pkt->needsResponse()); 1019 pkt->writeDataToBlock(blk->data, blkSize); 1020 DPRINTF(Cache, "%s new state is %s\n", __func__, blk->print()); 1021 incHitCount(pkt); 1022 // populate the time when the block will be ready to access. 1023 blk->whenReady = clockEdge(fillLatency) + pkt->headerDelay + 1024 pkt->payloadDelay; 1025 return true; 1026 } else if (pkt->cmd == MemCmd::CleanEvict) { 1027 if (blk) { 1028 // Found the block in the tags, need to stop CleanEvict from 1029 // propagating further down the hierarchy. Returning true will 1030 // treat the CleanEvict like a satisfied write request and delete 1031 // it. 1032 return true; 1033 } 1034 // We didn't find the block here, propagate the CleanEvict further 1035 // down the memory hierarchy. Returning false will treat the CleanEvict 1036 // like a Writeback which could not find a replaceable block so has to 1037 // go to next level. 1038 return false; 1039 } else if (pkt->cmd == MemCmd::WriteClean) { 1040 // WriteClean handling is a special case. We can allocate a 1041 // block directly if it doesn't exist and we can update the 1042 // block immediately. The WriteClean transfers the ownership 1043 // of the block as well. 1044 assert(blkSize == pkt->getSize()); 1045 1046 if (!blk) { 1047 if (pkt->writeThrough()) { 1048 // if this is a write through packet, we don't try to 1049 // allocate if the block is not present 1050 return false; 1051 } else { 1052 // a writeback that misses needs to allocate a new block 1053 blk = allocateBlock(pkt, writebacks); 1054 if (!blk) { 1055 // no replaceable block available: give up, fwd to 1056 // next level. 1057 incMissCount(pkt); 1058 return false; 1059 } 1060 1061 blk->status |= (BlkValid | BlkReadable); 1062 } 1063 } 1064 1065 // at this point either this is a writeback or a write-through 1066 // write clean operation and the block is already in this 1067 // cache, we need to update the data and the block flags 1068 assert(blk); 1069 // TODO: the coherent cache can assert(!blk->isDirty()); 1070 if (!pkt->writeThrough()) { 1071 blk->status |= BlkDirty; 1072 } 1073 // nothing else to do; writeback doesn't expect response 1074 assert(!pkt->needsResponse()); 1075 pkt->writeDataToBlock(blk->data, blkSize); 1076 DPRINTF(Cache, "%s new state is %s\n", __func__, blk->print()); 1077 1078 incHitCount(pkt); 1079 // populate the time when the block will be ready to access. 1080 blk->whenReady = clockEdge(fillLatency) + pkt->headerDelay + 1081 pkt->payloadDelay; 1082 // if this a write-through packet it will be sent to cache 1083 // below 1084 return !pkt->writeThrough(); 1085 } else if (blk && (pkt->needsWritable() ? blk->isWritable() : 1086 blk->isReadable())) { 1087 // OK to satisfy access 1088 incHitCount(pkt); 1089 satisfyRequest(pkt, blk); 1090 maintainClusivity(pkt->fromCache(), blk); 1091 1092 return true; 1093 } 1094 1095 // Can't satisfy access normally... either no block (blk == nullptr) 1096 // or have block but need writable 1097 1098 incMissCount(pkt); 1099 1100 if (!blk && pkt->isLLSC() && pkt->isWrite()) { 1101 // complete miss on store conditional... just give up now 1102 pkt->req->setExtraData(0); 1103 return true; 1104 } 1105 1106 return false; 1107} 1108 1109void 1110BaseCache::maintainClusivity(bool from_cache, CacheBlk *blk) 1111{ 1112 if (from_cache && blk && blk->isValid() && !blk->isDirty() && 1113 clusivity == Enums::mostly_excl) { 1114 // if we have responded to a cache, and our block is still 1115 // valid, but not dirty, and this cache is mostly exclusive 1116 // with respect to the cache above, drop the block 1117 invalidateBlock(blk); 1118 } 1119} 1120 1121CacheBlk* 1122BaseCache::handleFill(PacketPtr pkt, CacheBlk *blk, PacketList &writebacks, 1123 bool allocate) 1124{ 1125 assert(pkt->isResponse() || pkt->cmd == MemCmd::WriteLineReq); 1126 Addr addr = pkt->getAddr(); 1127 bool is_secure = pkt->isSecure(); 1128#if TRACING_ON 1129 CacheBlk::State old_state = blk ? blk->status : 0; 1130#endif 1131 1132 // When handling a fill, we should have no writes to this line. 1133 assert(addr == pkt->getBlockAddr(blkSize)); 1134 assert(!writeBuffer.findMatch(addr, is_secure)); 1135 1136 if (!blk) { 1137 // better have read new data... 1138 assert(pkt->hasData()); 1139 1140 // only read responses and write-line requests have data; 1141 // note that we don't write the data here for write-line - that 1142 // happens in the subsequent call to satisfyRequest 1143 assert(pkt->isRead() || pkt->cmd == MemCmd::WriteLineReq); 1144 1145 // need to do a replacement if allocating, otherwise we stick 1146 // with the temporary storage 1147 blk = allocate ? allocateBlock(pkt, writebacks) : nullptr; 1148 1149 if (!blk) { 1150 // No replaceable block or a mostly exclusive 1151 // cache... just use temporary storage to complete the 1152 // current request and then get rid of it 1153 assert(!tempBlock->isValid()); 1154 blk = tempBlock; 1155 tempBlock->insert(addr, is_secure); 1156 DPRINTF(Cache, "using temp block for %#llx (%s)\n", addr, 1157 is_secure ? "s" : "ns"); 1158 } 1159 1160 // we should never be overwriting a valid block 1161 assert(!blk->isValid()); 1162 } else { 1163 // existing block... probably an upgrade 1164 assert(regenerateBlkAddr(blk) == addr); 1165 assert(blk->isSecure() == is_secure); 1166 // either we're getting new data or the block should already be valid 1167 assert(pkt->hasData() || blk->isValid()); 1168 // don't clear block status... if block is already dirty we 1169 // don't want to lose that 1170 } 1171 1172 blk->status |= BlkValid | BlkReadable; 1173 1174 // sanity check for whole-line writes, which should always be 1175 // marked as writable as part of the fill, and then later marked 1176 // dirty as part of satisfyRequest 1177 if (pkt->cmd == MemCmd::WriteLineReq) { 1178 assert(!pkt->hasSharers()); 1179 } 1180 1181 // here we deal with setting the appropriate state of the line, 1182 // and we start by looking at the hasSharers flag, and ignore the 1183 // cacheResponding flag (normally signalling dirty data) if the 1184 // packet has sharers, thus the line is never allocated as Owned 1185 // (dirty but not writable), and always ends up being either 1186 // Shared, Exclusive or Modified, see Packet::setCacheResponding 1187 // for more details 1188 if (!pkt->hasSharers()) { 1189 // we could get a writable line from memory (rather than a 1190 // cache) even in a read-only cache, note that we set this bit 1191 // even for a read-only cache, possibly revisit this decision 1192 blk->status |= BlkWritable; 1193 1194 // check if we got this via cache-to-cache transfer (i.e., from a 1195 // cache that had the block in Modified or Owned state) 1196 if (pkt->cacheResponding()) { 1197 // we got the block in Modified state, and invalidated the 1198 // owners copy 1199 blk->status |= BlkDirty; 1200 1201 chatty_assert(!isReadOnly, "Should never see dirty snoop response " 1202 "in read-only cache %s\n", name()); 1203 } 1204 } 1205 1206 DPRINTF(Cache, "Block addr %#llx (%s) moving from state %x to %s\n", 1207 addr, is_secure ? "s" : "ns", old_state, blk->print()); 1208 1209 // if we got new data, copy it in (checking for a read response 1210 // and a response that has data is the same in the end) 1211 if (pkt->isRead()) { 1212 // sanity checks 1213 assert(pkt->hasData()); 1214 assert(pkt->getSize() == blkSize); 1215 1216 pkt->writeDataToBlock(blk->data, blkSize); 1217 } 1218 // We pay for fillLatency here. 1219 blk->whenReady = clockEdge() + fillLatency * clockPeriod() + 1220 pkt->payloadDelay; 1221 1222 return blk; 1223} 1224 1225CacheBlk* 1226BaseCache::allocateBlock(const PacketPtr pkt, PacketList &writebacks) 1227{ 1228 // Get address 1229 const Addr addr = pkt->getAddr(); 1230 1231 // Get secure bit 1232 const bool is_secure = pkt->isSecure(); 1233 1234 // Find replacement victim 1235 std::vector<CacheBlk*> evict_blks; 1236 CacheBlk *victim = tags->findVictim(addr, is_secure, evict_blks); 1237 1238 // It is valid to return nullptr if there is no victim 1239 if (!victim) 1240 return nullptr; 1241 1242 // Check for transient state allocations. If any of the entries listed 1243 // for eviction has a transient state, the allocation fails 1244 for (const auto& blk : evict_blks) { 1245 if (blk->isValid()) { 1246 Addr repl_addr = regenerateBlkAddr(blk); 1247 MSHR *repl_mshr = mshrQueue.findMatch(repl_addr, blk->isSecure()); 1248 if (repl_mshr) { 1249 // must be an outstanding upgrade or clean request 1250 // on a block we're about to replace... 1251 assert((!blk->isWritable() && repl_mshr->needsWritable()) || 1252 repl_mshr->isCleaning()); 1253 1254 // too hard to replace block with transient state 1255 // allocation failed, block not inserted 1256 return nullptr; 1257 } 1258 } 1259 } 1260 1261 // The victim will be replaced by a new entry, so increase the replacement 1262 // counter if a valid block is being replaced 1263 if (victim->isValid()) { 1264 DPRINTF(Cache, "replacement: replacing %#llx (%s) with %#llx " 1265 "(%s): %s\n", regenerateBlkAddr(victim), 1266 victim->isSecure() ? "s" : "ns", 1267 addr, is_secure ? "s" : "ns", 1268 victim->isDirty() ? "writeback" : "clean"); 1269 1270 replacements++; 1271 } 1272 1273 // Evict valid blocks associated to this victim block 1274 for (const auto& blk : evict_blks) { 1275 if (blk->isValid()) { 1276 if (blk->wasPrefetched()) { 1277 unusedPrefetches++; 1278 } 1279 1280 evictBlock(blk, writebacks); 1281 } 1282 } 1283 1284 // Insert new block at victimized entry 1285 tags->insertBlock(pkt, victim); 1286 1287 return victim; 1288} 1289 1290void 1291BaseCache::invalidateBlock(CacheBlk *blk) 1292{ 1293 if (blk != tempBlock) 1294 tags->invalidate(blk); 1295 blk->invalidate(); 1296} 1297 1298PacketPtr 1299BaseCache::writebackBlk(CacheBlk *blk) 1300{ 1301 chatty_assert(!isReadOnly || writebackClean, 1302 "Writeback from read-only cache"); 1303 assert(blk && blk->isValid() && (blk->isDirty() || writebackClean)); 1304 1305 writebacks[Request::wbMasterId]++; 1306 1307 RequestPtr req = std::make_shared<Request>( 1308 regenerateBlkAddr(blk), blkSize, 0, Request::wbMasterId); 1309 1310 if (blk->isSecure()) 1311 req->setFlags(Request::SECURE); 1312 1313 req->taskId(blk->task_id); 1314 1315 PacketPtr pkt = 1316 new Packet(req, blk->isDirty() ? 1317 MemCmd::WritebackDirty : MemCmd::WritebackClean); 1318 1319 DPRINTF(Cache, "Create Writeback %s writable: %d, dirty: %d\n", 1320 pkt->print(), blk->isWritable(), blk->isDirty()); 1321 1322 if (blk->isWritable()) { 1323 // not asserting shared means we pass the block in modified 1324 // state, mark our own block non-writeable 1325 blk->status &= ~BlkWritable; 1326 } else { 1327 // we are in the Owned state, tell the receiver 1328 pkt->setHasSharers(); 1329 } 1330 1331 // make sure the block is not marked dirty 1332 blk->status &= ~BlkDirty; 1333 1334 pkt->allocate(); 1335 pkt->setDataFromBlock(blk->data, blkSize); 1336 1337 return pkt; 1338} 1339 1340PacketPtr 1341BaseCache::writecleanBlk(CacheBlk *blk, Request::Flags dest, PacketId id) 1342{ 1343 RequestPtr req = std::make_shared<Request>( 1344 regenerateBlkAddr(blk), blkSize, 0, Request::wbMasterId); 1345 1346 if (blk->isSecure()) { 1347 req->setFlags(Request::SECURE); 1348 } 1349 req->taskId(blk->task_id); 1350 1351 PacketPtr pkt = new Packet(req, MemCmd::WriteClean, blkSize, id); 1352 1353 if (dest) { 1354 req->setFlags(dest); 1355 pkt->setWriteThrough(); 1356 } 1357 1358 DPRINTF(Cache, "Create %s writable: %d, dirty: %d\n", pkt->print(), 1359 blk->isWritable(), blk->isDirty()); 1360 1361 if (blk->isWritable()) { 1362 // not asserting shared means we pass the block in modified 1363 // state, mark our own block non-writeable 1364 blk->status &= ~BlkWritable; 1365 } else { 1366 // we are in the Owned state, tell the receiver 1367 pkt->setHasSharers(); 1368 } 1369 1370 // make sure the block is not marked dirty 1371 blk->status &= ~BlkDirty; 1372 1373 pkt->allocate(); 1374 pkt->setDataFromBlock(blk->data, blkSize); 1375 1376 return pkt; 1377} 1378 1379 1380void 1381BaseCache::memWriteback() 1382{ 1383 tags->forEachBlk([this](CacheBlk &blk) { writebackVisitor(blk); }); 1384} 1385 1386void 1387BaseCache::memInvalidate() 1388{ 1389 tags->forEachBlk([this](CacheBlk &blk) { invalidateVisitor(blk); }); 1390} 1391 1392bool 1393BaseCache::isDirty() const 1394{ 1395 return tags->anyBlk([](CacheBlk &blk) { return blk.isDirty(); }); 1396} 1397 1398void 1399BaseCache::writebackVisitor(CacheBlk &blk) 1400{ 1401 if (blk.isDirty()) { 1402 assert(blk.isValid()); 1403 1404 RequestPtr request = std::make_shared<Request>( 1405 regenerateBlkAddr(&blk), blkSize, 0, Request::funcMasterId); 1406 1407 request->taskId(blk.task_id); 1408 if (blk.isSecure()) { 1409 request->setFlags(Request::SECURE); 1410 } 1411 1412 Packet packet(request, MemCmd::WriteReq); 1413 packet.dataStatic(blk.data); 1414 1415 memSidePort.sendFunctional(&packet); 1416 1417 blk.status &= ~BlkDirty; 1418 } 1419} 1420 1421void 1422BaseCache::invalidateVisitor(CacheBlk &blk) 1423{ 1424 if (blk.isDirty()) 1425 warn_once("Invalidating dirty cache lines. " \ 1426 "Expect things to break.\n"); 1427 1428 if (blk.isValid()) { 1429 assert(!blk.isDirty()); 1430 invalidateBlock(&blk); 1431 } 1432} 1433 1434Tick 1435BaseCache::nextQueueReadyTime() const 1436{ 1437 Tick nextReady = std::min(mshrQueue.nextReadyTime(), 1438 writeBuffer.nextReadyTime()); 1439 1440 // Don't signal prefetch ready time if no MSHRs available 1441 // Will signal once enoguh MSHRs are deallocated 1442 if (prefetcher && mshrQueue.canPrefetch()) { 1443 nextReady = std::min(nextReady, 1444 prefetcher->nextPrefetchReadyTime()); 1445 } 1446 1447 return nextReady; 1448} 1449 1450 1451bool 1452BaseCache::sendMSHRQueuePacket(MSHR* mshr) 1453{ 1454 assert(mshr); 1455 1456 // use request from 1st target 1457 PacketPtr tgt_pkt = mshr->getTarget()->pkt; 1458 1459 DPRINTF(Cache, "%s: MSHR %s\n", __func__, tgt_pkt->print()); 1460 1461 CacheBlk *blk = tags->findBlock(mshr->blkAddr, mshr->isSecure); 1462 1463 // either a prefetch that is not present upstream, or a normal 1464 // MSHR request, proceed to get the packet to send downstream 1465 PacketPtr pkt = createMissPacket(tgt_pkt, blk, mshr->needsWritable()); 1466 1467 mshr->isForward = (pkt == nullptr); 1468 1469 if (mshr->isForward) { 1470 // not a cache block request, but a response is expected 1471 // make copy of current packet to forward, keep current 1472 // copy for response handling 1473 pkt = new Packet(tgt_pkt, false, true); 1474 assert(!pkt->isWrite()); 1475 } 1476 1477 // play it safe and append (rather than set) the sender state, 1478 // as forwarded packets may already have existing state 1479 pkt->pushSenderState(mshr); 1480 1481 if (pkt->isClean() && blk && blk->isDirty()) { 1482 // A cache clean opearation is looking for a dirty block. Mark 1483 // the packet so that the destination xbar can determine that 1484 // there will be a follow-up write packet as well. 1485 pkt->setSatisfied(); 1486 } 1487 1488 if (!memSidePort.sendTimingReq(pkt)) { 1489 // we are awaiting a retry, but we 1490 // delete the packet and will be creating a new packet 1491 // when we get the opportunity 1492 delete pkt; 1493 1494 // note that we have now masked any requestBus and 1495 // schedSendEvent (we will wait for a retry before 1496 // doing anything), and this is so even if we do not 1497 // care about this packet and might override it before 1498 // it gets retried 1499 return true; 1500 } else { 1501 // As part of the call to sendTimingReq the packet is 1502 // forwarded to all neighbouring caches (and any caches 1503 // above them) as a snoop. Thus at this point we know if 1504 // any of the neighbouring caches are responding, and if 1505 // so, we know it is dirty, and we can determine if it is 1506 // being passed as Modified, making our MSHR the ordering 1507 // point 1508 bool pending_modified_resp = !pkt->hasSharers() && 1509 pkt->cacheResponding(); 1510 markInService(mshr, pending_modified_resp); 1511 1512 if (pkt->isClean() && blk && blk->isDirty()) { 1513 // A cache clean opearation is looking for a dirty 1514 // block. If a dirty block is encountered a WriteClean 1515 // will update any copies to the path to the memory 1516 // until the point of reference. 1517 DPRINTF(CacheVerbose, "%s: packet %s found block: %s\n", 1518 __func__, pkt->print(), blk->print()); 1519 PacketPtr wb_pkt = writecleanBlk(blk, pkt->req->getDest(), 1520 pkt->id); 1521 PacketList writebacks; 1522 writebacks.push_back(wb_pkt); 1523 doWritebacks(writebacks, 0); 1524 } 1525 1526 return false; 1527 } 1528} 1529 1530bool 1531BaseCache::sendWriteQueuePacket(WriteQueueEntry* wq_entry) 1532{ 1533 assert(wq_entry); 1534 1535 // always a single target for write queue entries 1536 PacketPtr tgt_pkt = wq_entry->getTarget()->pkt; 1537 1538 DPRINTF(Cache, "%s: write %s\n", __func__, tgt_pkt->print()); 1539 1540 // forward as is, both for evictions and uncacheable writes 1541 if (!memSidePort.sendTimingReq(tgt_pkt)) { 1542 // note that we have now masked any requestBus and 1543 // schedSendEvent (we will wait for a retry before 1544 // doing anything), and this is so even if we do not 1545 // care about this packet and might override it before 1546 // it gets retried 1547 return true; 1548 } else { 1549 markInService(wq_entry); 1550 return false; 1551 } 1552} 1553 1554void 1555BaseCache::serialize(CheckpointOut &cp) const 1556{ 1557 bool dirty(isDirty()); 1558 1559 if (dirty) { 1560 warn("*** The cache still contains dirty data. ***\n"); 1561 warn(" Make sure to drain the system using the correct flags.\n"); 1562 warn(" This checkpoint will not restore correctly " \ 1563 "and dirty data in the cache will be lost!\n"); 1564 } 1565 1566 // Since we don't checkpoint the data in the cache, any dirty data 1567 // will be lost when restoring from a checkpoint of a system that 1568 // wasn't drained properly. Flag the checkpoint as invalid if the 1569 // cache contains dirty data. 1570 bool bad_checkpoint(dirty); 1571 SERIALIZE_SCALAR(bad_checkpoint); 1572} 1573 1574void 1575BaseCache::unserialize(CheckpointIn &cp) 1576{ 1577 bool bad_checkpoint; 1578 UNSERIALIZE_SCALAR(bad_checkpoint); 1579 if (bad_checkpoint) { 1580 fatal("Restoring from checkpoints with dirty caches is not " 1581 "supported in the classic memory system. Please remove any " 1582 "caches or drain them properly before taking checkpoints.\n"); 1583 } 1584} 1585 1586void 1587BaseCache::regStats() 1588{ 1589 MemObject::regStats(); 1590 1591 using namespace Stats; 1592 1593 // Hit statistics 1594 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1595 MemCmd cmd(access_idx); 1596 const string &cstr = cmd.toString(); 1597 1598 hits[access_idx] 1599 .init(system->maxMasters()) 1600 .name(name() + "." + cstr + "_hits") 1601 .desc("number of " + cstr + " hits") 1602 .flags(total | nozero | nonan) 1603 ; 1604 for (int i = 0; i < system->maxMasters(); i++) { 1605 hits[access_idx].subname(i, system->getMasterName(i)); 1606 } 1607 } 1608 1609// These macros make it easier to sum the right subset of commands and 1610// to change the subset of commands that are considered "demand" vs 1611// "non-demand" 1612#define SUM_DEMAND(s) \ 1613 (s[MemCmd::ReadReq] + s[MemCmd::WriteReq] + s[MemCmd::WriteLineReq] + \ 1614 s[MemCmd::ReadExReq] + s[MemCmd::ReadCleanReq] + s[MemCmd::ReadSharedReq]) 1615 1616// should writebacks be included here? prior code was inconsistent... 1617#define SUM_NON_DEMAND(s) \ 1618 (s[MemCmd::SoftPFReq] + s[MemCmd::HardPFReq]) 1619 1620 demandHits 1621 .name(name() + ".demand_hits") 1622 .desc("number of demand (read+write) hits") 1623 .flags(total | nozero | nonan) 1624 ; 1625 demandHits = SUM_DEMAND(hits); 1626 for (int i = 0; i < system->maxMasters(); i++) { 1627 demandHits.subname(i, system->getMasterName(i)); 1628 } 1629 1630 overallHits 1631 .name(name() + ".overall_hits") 1632 .desc("number of overall hits") 1633 .flags(total | nozero | nonan) 1634 ; 1635 overallHits = demandHits + SUM_NON_DEMAND(hits); 1636 for (int i = 0; i < system->maxMasters(); i++) { 1637 overallHits.subname(i, system->getMasterName(i)); 1638 } 1639 1640 // Miss statistics 1641 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1642 MemCmd cmd(access_idx); 1643 const string &cstr = cmd.toString(); 1644 1645 misses[access_idx] 1646 .init(system->maxMasters()) 1647 .name(name() + "." + cstr + "_misses") 1648 .desc("number of " + cstr + " misses") 1649 .flags(total | nozero | nonan) 1650 ; 1651 for (int i = 0; i < system->maxMasters(); i++) { 1652 misses[access_idx].subname(i, system->getMasterName(i)); 1653 } 1654 } 1655 1656 demandMisses 1657 .name(name() + ".demand_misses") 1658 .desc("number of demand (read+write) misses") 1659 .flags(total | nozero | nonan) 1660 ; 1661 demandMisses = SUM_DEMAND(misses); 1662 for (int i = 0; i < system->maxMasters(); i++) { 1663 demandMisses.subname(i, system->getMasterName(i)); 1664 } 1665 1666 overallMisses 1667 .name(name() + ".overall_misses") 1668 .desc("number of overall misses") 1669 .flags(total | nozero | nonan) 1670 ; 1671 overallMisses = demandMisses + SUM_NON_DEMAND(misses); 1672 for (int i = 0; i < system->maxMasters(); i++) { 1673 overallMisses.subname(i, system->getMasterName(i)); 1674 } 1675 1676 // Miss latency statistics 1677 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1678 MemCmd cmd(access_idx); 1679 const string &cstr = cmd.toString(); 1680 1681 missLatency[access_idx] 1682 .init(system->maxMasters()) 1683 .name(name() + "." + cstr + "_miss_latency") 1684 .desc("number of " + cstr + " miss cycles") 1685 .flags(total | nozero | nonan) 1686 ; 1687 for (int i = 0; i < system->maxMasters(); i++) { 1688 missLatency[access_idx].subname(i, system->getMasterName(i)); 1689 } 1690 } 1691 1692 demandMissLatency 1693 .name(name() + ".demand_miss_latency") 1694 .desc("number of demand (read+write) miss cycles") 1695 .flags(total | nozero | nonan) 1696 ; 1697 demandMissLatency = SUM_DEMAND(missLatency); 1698 for (int i = 0; i < system->maxMasters(); i++) { 1699 demandMissLatency.subname(i, system->getMasterName(i)); 1700 } 1701 1702 overallMissLatency 1703 .name(name() + ".overall_miss_latency") 1704 .desc("number of overall miss cycles") 1705 .flags(total | nozero | nonan) 1706 ; 1707 overallMissLatency = demandMissLatency + SUM_NON_DEMAND(missLatency); 1708 for (int i = 0; i < system->maxMasters(); i++) { 1709 overallMissLatency.subname(i, system->getMasterName(i)); 1710 } 1711 1712 // access formulas 1713 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1714 MemCmd cmd(access_idx); 1715 const string &cstr = cmd.toString(); 1716 1717 accesses[access_idx] 1718 .name(name() + "." + cstr + "_accesses") 1719 .desc("number of " + cstr + " accesses(hits+misses)") 1720 .flags(total | nozero | nonan) 1721 ; 1722 accesses[access_idx] = hits[access_idx] + misses[access_idx]; 1723 1724 for (int i = 0; i < system->maxMasters(); i++) { 1725 accesses[access_idx].subname(i, system->getMasterName(i)); 1726 } 1727 } 1728 1729 demandAccesses 1730 .name(name() + ".demand_accesses") 1731 .desc("number of demand (read+write) accesses") 1732 .flags(total | nozero | nonan) 1733 ; 1734 demandAccesses = demandHits + demandMisses; 1735 for (int i = 0; i < system->maxMasters(); i++) { 1736 demandAccesses.subname(i, system->getMasterName(i)); 1737 } 1738 1739 overallAccesses 1740 .name(name() + ".overall_accesses") 1741 .desc("number of overall (read+write) accesses") 1742 .flags(total | nozero | nonan) 1743 ; 1744 overallAccesses = overallHits + overallMisses; 1745 for (int i = 0; i < system->maxMasters(); i++) { 1746 overallAccesses.subname(i, system->getMasterName(i)); 1747 } 1748 1749 // miss rate formulas 1750 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1751 MemCmd cmd(access_idx); 1752 const string &cstr = cmd.toString(); 1753 1754 missRate[access_idx] 1755 .name(name() + "." + cstr + "_miss_rate") 1756 .desc("miss rate for " + cstr + " accesses") 1757 .flags(total | nozero | nonan) 1758 ; 1759 missRate[access_idx] = misses[access_idx] / accesses[access_idx]; 1760 1761 for (int i = 0; i < system->maxMasters(); i++) { 1762 missRate[access_idx].subname(i, system->getMasterName(i)); 1763 } 1764 } 1765 1766 demandMissRate 1767 .name(name() + ".demand_miss_rate") 1768 .desc("miss rate for demand accesses") 1769 .flags(total | nozero | nonan) 1770 ; 1771 demandMissRate = demandMisses / demandAccesses; 1772 for (int i = 0; i < system->maxMasters(); i++) { 1773 demandMissRate.subname(i, system->getMasterName(i)); 1774 } 1775 1776 overallMissRate 1777 .name(name() + ".overall_miss_rate") 1778 .desc("miss rate for overall accesses") 1779 .flags(total | nozero | nonan) 1780 ; 1781 overallMissRate = overallMisses / overallAccesses; 1782 for (int i = 0; i < system->maxMasters(); i++) { 1783 overallMissRate.subname(i, system->getMasterName(i)); 1784 } 1785 1786 // miss latency formulas 1787 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1788 MemCmd cmd(access_idx); 1789 const string &cstr = cmd.toString(); 1790 1791 avgMissLatency[access_idx] 1792 .name(name() + "." + cstr + "_avg_miss_latency") 1793 .desc("average " + cstr + " miss latency") 1794 .flags(total | nozero | nonan) 1795 ; 1796 avgMissLatency[access_idx] = 1797 missLatency[access_idx] / misses[access_idx]; 1798 1799 for (int i = 0; i < system->maxMasters(); i++) { 1800 avgMissLatency[access_idx].subname(i, system->getMasterName(i)); 1801 } 1802 } 1803 1804 demandAvgMissLatency 1805 .name(name() + ".demand_avg_miss_latency") 1806 .desc("average overall miss latency") 1807 .flags(total | nozero | nonan) 1808 ; 1809 demandAvgMissLatency = demandMissLatency / demandMisses; 1810 for (int i = 0; i < system->maxMasters(); i++) { 1811 demandAvgMissLatency.subname(i, system->getMasterName(i)); 1812 } 1813 1814 overallAvgMissLatency 1815 .name(name() + ".overall_avg_miss_latency") 1816 .desc("average overall miss latency") 1817 .flags(total | nozero | nonan) 1818 ; 1819 overallAvgMissLatency = overallMissLatency / overallMisses; 1820 for (int i = 0; i < system->maxMasters(); i++) { 1821 overallAvgMissLatency.subname(i, system->getMasterName(i)); 1822 } 1823 1824 blocked_cycles.init(NUM_BLOCKED_CAUSES); 1825 blocked_cycles 1826 .name(name() + ".blocked_cycles") 1827 .desc("number of cycles access was blocked") 1828 .subname(Blocked_NoMSHRs, "no_mshrs") 1829 .subname(Blocked_NoTargets, "no_targets") 1830 ; 1831 1832 1833 blocked_causes.init(NUM_BLOCKED_CAUSES); 1834 blocked_causes 1835 .name(name() + ".blocked") 1836 .desc("number of cycles access was blocked") 1837 .subname(Blocked_NoMSHRs, "no_mshrs") 1838 .subname(Blocked_NoTargets, "no_targets") 1839 ; 1840 1841 avg_blocked 1842 .name(name() + ".avg_blocked_cycles") 1843 .desc("average number of cycles each access was blocked") 1844 .subname(Blocked_NoMSHRs, "no_mshrs") 1845 .subname(Blocked_NoTargets, "no_targets") 1846 ; 1847 1848 avg_blocked = blocked_cycles / blocked_causes; 1849 1850 unusedPrefetches 1851 .name(name() + ".unused_prefetches") 1852 .desc("number of HardPF blocks evicted w/o reference") 1853 .flags(nozero) 1854 ; 1855 1856 writebacks 1857 .init(system->maxMasters()) 1858 .name(name() + ".writebacks") 1859 .desc("number of writebacks") 1860 .flags(total | nozero | nonan) 1861 ; 1862 for (int i = 0; i < system->maxMasters(); i++) { 1863 writebacks.subname(i, system->getMasterName(i)); 1864 } 1865 1866 // MSHR statistics 1867 // MSHR hit statistics 1868 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1869 MemCmd cmd(access_idx); 1870 const string &cstr = cmd.toString(); 1871 1872 mshr_hits[access_idx] 1873 .init(system->maxMasters()) 1874 .name(name() + "." + cstr + "_mshr_hits") 1875 .desc("number of " + cstr + " MSHR hits") 1876 .flags(total | nozero | nonan) 1877 ; 1878 for (int i = 0; i < system->maxMasters(); i++) { 1879 mshr_hits[access_idx].subname(i, system->getMasterName(i)); 1880 } 1881 } 1882 1883 demandMshrHits 1884 .name(name() + ".demand_mshr_hits") 1885 .desc("number of demand (read+write) MSHR hits") 1886 .flags(total | nozero | nonan) 1887 ; 1888 demandMshrHits = SUM_DEMAND(mshr_hits); 1889 for (int i = 0; i < system->maxMasters(); i++) { 1890 demandMshrHits.subname(i, system->getMasterName(i)); 1891 } 1892 1893 overallMshrHits 1894 .name(name() + ".overall_mshr_hits") 1895 .desc("number of overall MSHR hits") 1896 .flags(total | nozero | nonan) 1897 ; 1898 overallMshrHits = demandMshrHits + SUM_NON_DEMAND(mshr_hits); 1899 for (int i = 0; i < system->maxMasters(); i++) { 1900 overallMshrHits.subname(i, system->getMasterName(i)); 1901 } 1902 1903 // MSHR miss statistics 1904 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1905 MemCmd cmd(access_idx); 1906 const string &cstr = cmd.toString(); 1907 1908 mshr_misses[access_idx] 1909 .init(system->maxMasters()) 1910 .name(name() + "." + cstr + "_mshr_misses") 1911 .desc("number of " + cstr + " MSHR misses") 1912 .flags(total | nozero | nonan) 1913 ; 1914 for (int i = 0; i < system->maxMasters(); i++) { 1915 mshr_misses[access_idx].subname(i, system->getMasterName(i)); 1916 } 1917 } 1918 1919 demandMshrMisses 1920 .name(name() + ".demand_mshr_misses") 1921 .desc("number of demand (read+write) MSHR misses") 1922 .flags(total | nozero | nonan) 1923 ; 1924 demandMshrMisses = SUM_DEMAND(mshr_misses); 1925 for (int i = 0; i < system->maxMasters(); i++) { 1926 demandMshrMisses.subname(i, system->getMasterName(i)); 1927 } 1928 1929 overallMshrMisses 1930 .name(name() + ".overall_mshr_misses") 1931 .desc("number of overall MSHR misses") 1932 .flags(total | nozero | nonan) 1933 ; 1934 overallMshrMisses = demandMshrMisses + SUM_NON_DEMAND(mshr_misses); 1935 for (int i = 0; i < system->maxMasters(); i++) { 1936 overallMshrMisses.subname(i, system->getMasterName(i)); 1937 } 1938 1939 // MSHR miss latency statistics 1940 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1941 MemCmd cmd(access_idx); 1942 const string &cstr = cmd.toString(); 1943 1944 mshr_miss_latency[access_idx] 1945 .init(system->maxMasters()) 1946 .name(name() + "." + cstr + "_mshr_miss_latency") 1947 .desc("number of " + cstr + " MSHR miss cycles") 1948 .flags(total | nozero | nonan) 1949 ; 1950 for (int i = 0; i < system->maxMasters(); i++) { 1951 mshr_miss_latency[access_idx].subname(i, system->getMasterName(i)); 1952 } 1953 } 1954 1955 demandMshrMissLatency 1956 .name(name() + ".demand_mshr_miss_latency") 1957 .desc("number of demand (read+write) MSHR miss cycles") 1958 .flags(total | nozero | nonan) 1959 ; 1960 demandMshrMissLatency = SUM_DEMAND(mshr_miss_latency); 1961 for (int i = 0; i < system->maxMasters(); i++) { 1962 demandMshrMissLatency.subname(i, system->getMasterName(i)); 1963 } 1964 1965 overallMshrMissLatency 1966 .name(name() + ".overall_mshr_miss_latency") 1967 .desc("number of overall MSHR miss cycles") 1968 .flags(total | nozero | nonan) 1969 ; 1970 overallMshrMissLatency = 1971 demandMshrMissLatency + SUM_NON_DEMAND(mshr_miss_latency); 1972 for (int i = 0; i < system->maxMasters(); i++) { 1973 overallMshrMissLatency.subname(i, system->getMasterName(i)); 1974 } 1975 1976 // MSHR uncacheable statistics 1977 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1978 MemCmd cmd(access_idx); 1979 const string &cstr = cmd.toString(); 1980 1981 mshr_uncacheable[access_idx] 1982 .init(system->maxMasters()) 1983 .name(name() + "." + cstr + "_mshr_uncacheable") 1984 .desc("number of " + cstr + " MSHR uncacheable") 1985 .flags(total | nozero | nonan) 1986 ; 1987 for (int i = 0; i < system->maxMasters(); i++) { 1988 mshr_uncacheable[access_idx].subname(i, system->getMasterName(i)); 1989 } 1990 } 1991 1992 overallMshrUncacheable 1993 .name(name() + ".overall_mshr_uncacheable_misses") 1994 .desc("number of overall MSHR uncacheable misses") 1995 .flags(total | nozero | nonan) 1996 ; 1997 overallMshrUncacheable = 1998 SUM_DEMAND(mshr_uncacheable) + SUM_NON_DEMAND(mshr_uncacheable); 1999 for (int i = 0; i < system->maxMasters(); i++) { 2000 overallMshrUncacheable.subname(i, system->getMasterName(i)); 2001 } 2002 2003 // MSHR miss latency statistics 2004 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 2005 MemCmd cmd(access_idx); 2006 const string &cstr = cmd.toString(); 2007 2008 mshr_uncacheable_lat[access_idx] 2009 .init(system->maxMasters()) 2010 .name(name() + "." + cstr + "_mshr_uncacheable_latency") 2011 .desc("number of " + cstr + " MSHR uncacheable cycles") 2012 .flags(total | nozero | nonan) 2013 ; 2014 for (int i = 0; i < system->maxMasters(); i++) { 2015 mshr_uncacheable_lat[access_idx].subname( 2016 i, system->getMasterName(i)); 2017 } 2018 } 2019 2020 overallMshrUncacheableLatency 2021 .name(name() + ".overall_mshr_uncacheable_latency") 2022 .desc("number of overall MSHR uncacheable cycles") 2023 .flags(total | nozero | nonan) 2024 ; 2025 overallMshrUncacheableLatency = 2026 SUM_DEMAND(mshr_uncacheable_lat) + 2027 SUM_NON_DEMAND(mshr_uncacheable_lat); 2028 for (int i = 0; i < system->maxMasters(); i++) { 2029 overallMshrUncacheableLatency.subname(i, system->getMasterName(i)); 2030 } 2031 2032#if 0 2033 // MSHR access formulas 2034 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 2035 MemCmd cmd(access_idx); 2036 const string &cstr = cmd.toString(); 2037 2038 mshrAccesses[access_idx] 2039 .name(name() + "." + cstr + "_mshr_accesses") 2040 .desc("number of " + cstr + " mshr accesses(hits+misses)") 2041 .flags(total | nozero | nonan) 2042 ; 2043 mshrAccesses[access_idx] = 2044 mshr_hits[access_idx] + mshr_misses[access_idx] 2045 + mshr_uncacheable[access_idx]; 2046 } 2047 2048 demandMshrAccesses 2049 .name(name() + ".demand_mshr_accesses") 2050 .desc("number of demand (read+write) mshr accesses") 2051 .flags(total | nozero | nonan) 2052 ; 2053 demandMshrAccesses = demandMshrHits + demandMshrMisses; 2054 2055 overallMshrAccesses 2056 .name(name() + ".overall_mshr_accesses") 2057 .desc("number of overall (read+write) mshr accesses") 2058 .flags(total | nozero | nonan) 2059 ; 2060 overallMshrAccesses = overallMshrHits + overallMshrMisses 2061 + overallMshrUncacheable; 2062#endif 2063 2064 // MSHR miss rate formulas 2065 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 2066 MemCmd cmd(access_idx); 2067 const string &cstr = cmd.toString(); 2068 2069 mshrMissRate[access_idx] 2070 .name(name() + "." + cstr + "_mshr_miss_rate") 2071 .desc("mshr miss rate for " + cstr + " accesses") 2072 .flags(total | nozero | nonan) 2073 ; 2074 mshrMissRate[access_idx] = 2075 mshr_misses[access_idx] / accesses[access_idx]; 2076 2077 for (int i = 0; i < system->maxMasters(); i++) { 2078 mshrMissRate[access_idx].subname(i, system->getMasterName(i)); 2079 } 2080 } 2081 2082 demandMshrMissRate 2083 .name(name() + ".demand_mshr_miss_rate") 2084 .desc("mshr miss rate for demand accesses") 2085 .flags(total | nozero | nonan) 2086 ; 2087 demandMshrMissRate = demandMshrMisses / demandAccesses; 2088 for (int i = 0; i < system->maxMasters(); i++) { 2089 demandMshrMissRate.subname(i, system->getMasterName(i)); 2090 } 2091 2092 overallMshrMissRate 2093 .name(name() + ".overall_mshr_miss_rate") 2094 .desc("mshr miss rate for overall accesses") 2095 .flags(total | nozero | nonan) 2096 ; 2097 overallMshrMissRate = overallMshrMisses / overallAccesses; 2098 for (int i = 0; i < system->maxMasters(); i++) { 2099 overallMshrMissRate.subname(i, system->getMasterName(i)); 2100 } 2101 2102 // mshrMiss latency formulas 2103 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 2104 MemCmd cmd(access_idx); 2105 const string &cstr = cmd.toString(); 2106 2107 avgMshrMissLatency[access_idx] 2108 .name(name() + "." + cstr + "_avg_mshr_miss_latency") 2109 .desc("average " + cstr + " mshr miss latency") 2110 .flags(total | nozero | nonan) 2111 ; 2112 avgMshrMissLatency[access_idx] = 2113 mshr_miss_latency[access_idx] / mshr_misses[access_idx]; 2114 2115 for (int i = 0; i < system->maxMasters(); i++) { 2116 avgMshrMissLatency[access_idx].subname( 2117 i, system->getMasterName(i)); 2118 } 2119 } 2120 2121 demandAvgMshrMissLatency 2122 .name(name() + ".demand_avg_mshr_miss_latency") 2123 .desc("average overall mshr miss latency") 2124 .flags(total | nozero | nonan) 2125 ; 2126 demandAvgMshrMissLatency = demandMshrMissLatency / demandMshrMisses; 2127 for (int i = 0; i < system->maxMasters(); i++) { 2128 demandAvgMshrMissLatency.subname(i, system->getMasterName(i)); 2129 } 2130 2131 overallAvgMshrMissLatency 2132 .name(name() + ".overall_avg_mshr_miss_latency") 2133 .desc("average overall mshr miss latency") 2134 .flags(total | nozero | nonan) 2135 ; 2136 overallAvgMshrMissLatency = overallMshrMissLatency / overallMshrMisses; 2137 for (int i = 0; i < system->maxMasters(); i++) { 2138 overallAvgMshrMissLatency.subname(i, system->getMasterName(i)); 2139 } 2140 2141 // mshrUncacheable latency formulas 2142 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 2143 MemCmd cmd(access_idx); 2144 const string &cstr = cmd.toString(); 2145 2146 avgMshrUncacheableLatency[access_idx] 2147 .name(name() + "." + cstr + "_avg_mshr_uncacheable_latency") 2148 .desc("average " + cstr + " mshr uncacheable latency") 2149 .flags(total | nozero | nonan) 2150 ; 2151 avgMshrUncacheableLatency[access_idx] = 2152 mshr_uncacheable_lat[access_idx] / mshr_uncacheable[access_idx]; 2153 2154 for (int i = 0; i < system->maxMasters(); i++) { 2155 avgMshrUncacheableLatency[access_idx].subname( 2156 i, system->getMasterName(i)); 2157 } 2158 } 2159 2160 overallAvgMshrUncacheableLatency 2161 .name(name() + ".overall_avg_mshr_uncacheable_latency") 2162 .desc("average overall mshr uncacheable latency") 2163 .flags(total | nozero | nonan) 2164 ; 2165 overallAvgMshrUncacheableLatency = 2166 overallMshrUncacheableLatency / overallMshrUncacheable; 2167 for (int i = 0; i < system->maxMasters(); i++) { 2168 overallAvgMshrUncacheableLatency.subname(i, system->getMasterName(i)); 2169 } 2170 2171 replacements 2172 .name(name() + ".replacements") 2173 .desc("number of replacements") 2174 ; 2175} 2176 2177/////////////// 2178// 2179// CpuSidePort 2180// 2181/////////////// 2182bool 2183BaseCache::CpuSidePort::recvTimingSnoopResp(PacketPtr pkt) 2184{ 2185 // Snoops shouldn't happen when bypassing caches 2186 assert(!cache->system->bypassCaches()); 2187 2188 assert(pkt->isResponse()); 2189 2190 // Express snoop responses from master to slave, e.g., from L1 to L2 2191 cache->recvTimingSnoopResp(pkt); 2192 return true; 2193} 2194 2195 2196bool 2197BaseCache::CpuSidePort::tryTiming(PacketPtr pkt) 2198{ 2199 if (cache->system->bypassCaches() || pkt->isExpressSnoop()) { 2200 // always let express snoop packets through even if blocked 2201 return true; 2202 } else if (blocked || mustSendRetry) { 2203 // either already committed to send a retry, or blocked 2204 mustSendRetry = true; 2205 return false; 2206 } 2207 mustSendRetry = false; 2208 return true; 2209} 2210 2211bool 2212BaseCache::CpuSidePort::recvTimingReq(PacketPtr pkt) 2213{ 2214 assert(pkt->isRequest()); 2215 2216 if (cache->system->bypassCaches()) { 2217 // Just forward the packet if caches are disabled. 2218 // @todo This should really enqueue the packet rather 2219 bool M5_VAR_USED success = cache->memSidePort.sendTimingReq(pkt); 2220 assert(success); 2221 return true; 2222 } else if (tryTiming(pkt)) { 2223 cache->recvTimingReq(pkt); 2224 return true; 2225 } 2226 return false; 2227} 2228 2229Tick 2230BaseCache::CpuSidePort::recvAtomic(PacketPtr pkt) 2231{ 2232 if (cache->system->bypassCaches()) { 2233 // Forward the request if the system is in cache bypass mode. 2234 return cache->memSidePort.sendAtomic(pkt); 2235 } else { 2236 return cache->recvAtomic(pkt); 2237 } 2238} 2239 2240void 2241BaseCache::CpuSidePort::recvFunctional(PacketPtr pkt) 2242{ 2243 if (cache->system->bypassCaches()) { 2244 // The cache should be flushed if we are in cache bypass mode, 2245 // so we don't need to check if we need to update anything. 2246 cache->memSidePort.sendFunctional(pkt); 2247 return; 2248 } 2249 2250 // functional request 2251 cache->functionalAccess(pkt, true); 2252} 2253 2254AddrRangeList 2255BaseCache::CpuSidePort::getAddrRanges() const 2256{ 2257 return cache->getAddrRanges(); 2258} 2259 2260 2261BaseCache:: 2262CpuSidePort::CpuSidePort(const std::string &_name, BaseCache *_cache, 2263 const std::string &_label) 2264 : CacheSlavePort(_name, _cache, _label), cache(_cache) 2265{ 2266} 2267 2268/////////////// 2269// 2270// MemSidePort 2271// 2272/////////////// 2273bool 2274BaseCache::MemSidePort::recvTimingResp(PacketPtr pkt) 2275{ 2276 cache->recvTimingResp(pkt); 2277 return true; 2278} 2279 2280// Express snooping requests to memside port 2281void 2282BaseCache::MemSidePort::recvTimingSnoopReq(PacketPtr pkt) 2283{ 2284 // Snoops shouldn't happen when bypassing caches 2285 assert(!cache->system->bypassCaches()); 2286 2287 // handle snooping requests 2288 cache->recvTimingSnoopReq(pkt); 2289} 2290 2291Tick 2292BaseCache::MemSidePort::recvAtomicSnoop(PacketPtr pkt) 2293{ 2294 // Snoops shouldn't happen when bypassing caches 2295 assert(!cache->system->bypassCaches()); 2296 2297 return cache->recvAtomicSnoop(pkt); 2298} 2299 2300void 2301BaseCache::MemSidePort::recvFunctionalSnoop(PacketPtr pkt) 2302{ 2303 // Snoops shouldn't happen when bypassing caches 2304 assert(!cache->system->bypassCaches()); 2305 2306 // functional snoop (note that in contrast to atomic we don't have 2307 // a specific functionalSnoop method, as they have the same 2308 // behaviour regardless) 2309 cache->functionalAccess(pkt, false); 2310} 2311 2312void 2313BaseCache::CacheReqPacketQueue::sendDeferredPacket() 2314{ 2315 // sanity check 2316 assert(!waitingOnRetry); 2317 2318 // there should never be any deferred request packets in the 2319 // queue, instead we resly on the cache to provide the packets 2320 // from the MSHR queue or write queue 2321 assert(deferredPacketReadyTime() == MaxTick); 2322 2323 // check for request packets (requests & writebacks) 2324 QueueEntry* entry = cache.getNextQueueEntry(); 2325 2326 if (!entry) { 2327 // can happen if e.g. we attempt a writeback and fail, but 2328 // before the retry, the writeback is eliminated because 2329 // we snoop another cache's ReadEx. 2330 } else { 2331 // let our snoop responses go first if there are responses to 2332 // the same addresses 2333 if (checkConflictingSnoop(entry->blkAddr)) { 2334 return; 2335 } 2336 waitingOnRetry = entry->sendPacket(cache); 2337 } 2338 2339 // if we succeeded and are not waiting for a retry, schedule the 2340 // next send considering when the next queue is ready, note that 2341 // snoop responses have their own packet queue and thus schedule 2342 // their own events 2343 if (!waitingOnRetry) { 2344 schedSendEvent(cache.nextQueueReadyTime()); 2345 } 2346} 2347 2348BaseCache::MemSidePort::MemSidePort(const std::string &_name, 2349 BaseCache *_cache, 2350 const std::string &_label) 2351 : CacheMasterPort(_name, _cache, _reqQueue, _snoopRespQueue), 2352 _reqQueue(*_cache, *this, _snoopRespQueue, _label), 2353 _snoopRespQueue(*_cache, *this, _label), cache(_cache) 2354{ 2355} 2356