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