base.cc revision 13747
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 // populate the time when the block will be ready to access. 1041 blk->setWhenReady(clockEdge(fillLatency) + pkt->headerDelay + 1042 pkt->payloadDelay); 1043 return true; 1044 } else if (pkt->cmd == MemCmd::CleanEvict) { 1045 if (blk) { 1046 // Found the block in the tags, need to stop CleanEvict from 1047 // propagating further down the hierarchy. Returning true will 1048 // treat the CleanEvict like a satisfied write request and delete 1049 // it. 1050 return true; 1051 } 1052 // We didn't find the block here, propagate the CleanEvict further 1053 // down the memory hierarchy. Returning false will treat the CleanEvict 1054 // like a Writeback which could not find a replaceable block so has to 1055 // go to next level. 1056 return false; 1057 } else if (pkt->cmd == MemCmd::WriteClean) { 1058 // WriteClean handling is a special case. We can allocate a 1059 // block directly if it doesn't exist and we can update the 1060 // block immediately. The WriteClean transfers the ownership 1061 // of the block as well. 1062 assert(blkSize == pkt->getSize()); 1063 1064 if (!blk) { 1065 if (pkt->writeThrough()) { 1066 // if this is a write through packet, we don't try to 1067 // allocate if the block is not present 1068 return false; 1069 } else { 1070 // a writeback that misses needs to allocate a new block 1071 blk = allocateBlock(pkt, writebacks); 1072 if (!blk) { 1073 // no replaceable block available: give up, fwd to 1074 // next level. 1075 incMissCount(pkt); 1076 return false; 1077 } 1078 1079 blk->status |= BlkReadable; 1080 } 1081 } 1082 1083 // at this point either this is a writeback or a write-through 1084 // write clean operation and the block is already in this 1085 // cache, we need to update the data and the block flags 1086 assert(blk); 1087 // TODO: the coherent cache can assert(!blk->isDirty()); 1088 if (!pkt->writeThrough()) { 1089 blk->status |= BlkDirty; 1090 } 1091 // nothing else to do; writeback doesn't expect response 1092 assert(!pkt->needsResponse()); 1093 pkt->writeDataToBlock(blk->data, blkSize); 1094 DPRINTF(Cache, "%s new state is %s\n", __func__, blk->print()); 1095 1096 incHitCount(pkt); 1097 // populate the time when the block will be ready to access. 1098 blk->setWhenReady(clockEdge(fillLatency) + pkt->headerDelay + 1099 pkt->payloadDelay); 1100 // if this a write-through packet it will be sent to cache 1101 // below 1102 return !pkt->writeThrough(); 1103 } else if (blk && (pkt->needsWritable() ? blk->isWritable() : 1104 blk->isReadable())) { 1105 // OK to satisfy access 1106 incHitCount(pkt); 1107 satisfyRequest(pkt, blk); 1108 maintainClusivity(pkt->fromCache(), blk); 1109 1110 return true; 1111 } 1112 1113 // Can't satisfy access normally... either no block (blk == nullptr) 1114 // or have block but need writable 1115 1116 incMissCount(pkt); 1117 1118 if (!blk && pkt->isLLSC() && pkt->isWrite()) { 1119 // complete miss on store conditional... just give up now 1120 pkt->req->setExtraData(0); 1121 return true; 1122 } 1123 1124 return false; 1125} 1126 1127void 1128BaseCache::maintainClusivity(bool from_cache, CacheBlk *blk) 1129{ 1130 if (from_cache && blk && blk->isValid() && !blk->isDirty() && 1131 clusivity == Enums::mostly_excl) { 1132 // if we have responded to a cache, and our block is still 1133 // valid, but not dirty, and this cache is mostly exclusive 1134 // with respect to the cache above, drop the block 1135 invalidateBlock(blk); 1136 } 1137} 1138 1139CacheBlk* 1140BaseCache::handleFill(PacketPtr pkt, CacheBlk *blk, PacketList &writebacks, 1141 bool allocate) 1142{ 1143 assert(pkt->isResponse()); 1144 Addr addr = pkt->getAddr(); 1145 bool is_secure = pkt->isSecure(); 1146#if TRACING_ON 1147 CacheBlk::State old_state = blk ? blk->status : 0; 1148#endif 1149 1150 // When handling a fill, we should have no writes to this line. 1151 assert(addr == pkt->getBlockAddr(blkSize)); 1152 assert(!writeBuffer.findMatch(addr, is_secure)); 1153 1154 if (!blk) { 1155 // better have read new data... 1156 assert(pkt->hasData() || pkt->cmd == MemCmd::InvalidateResp); 1157 1158 // need to do a replacement if allocating, otherwise we stick 1159 // with the temporary storage 1160 blk = allocate ? allocateBlock(pkt, writebacks) : nullptr; 1161 1162 if (!blk) { 1163 // No replaceable block or a mostly exclusive 1164 // cache... just use temporary storage to complete the 1165 // current request and then get rid of it 1166 blk = tempBlock; 1167 tempBlock->insert(addr, is_secure); 1168 DPRINTF(Cache, "using temp block for %#llx (%s)\n", addr, 1169 is_secure ? "s" : "ns"); 1170 } 1171 } else { 1172 // existing block... probably an upgrade 1173 // don't clear block status... if block is already dirty we 1174 // don't want to lose that 1175 } 1176 1177 // Block is guaranteed to be valid at this point 1178 assert(blk->isValid()); 1179 assert(blk->isSecure() == is_secure); 1180 assert(regenerateBlkAddr(blk) == addr); 1181 1182 blk->status |= BlkReadable; 1183 1184 // sanity check for whole-line writes, which should always be 1185 // marked as writable as part of the fill, and then later marked 1186 // dirty as part of satisfyRequest 1187 if (pkt->cmd == MemCmd::InvalidateResp) { 1188 assert(!pkt->hasSharers()); 1189 } 1190 1191 // here we deal with setting the appropriate state of the line, 1192 // and we start by looking at the hasSharers flag, and ignore the 1193 // cacheResponding flag (normally signalling dirty data) if the 1194 // packet has sharers, thus the line is never allocated as Owned 1195 // (dirty but not writable), and always ends up being either 1196 // Shared, Exclusive or Modified, see Packet::setCacheResponding 1197 // for more details 1198 if (!pkt->hasSharers()) { 1199 // we could get a writable line from memory (rather than a 1200 // cache) even in a read-only cache, note that we set this bit 1201 // even for a read-only cache, possibly revisit this decision 1202 blk->status |= BlkWritable; 1203 1204 // check if we got this via cache-to-cache transfer (i.e., from a 1205 // cache that had the block in Modified or Owned state) 1206 if (pkt->cacheResponding()) { 1207 // we got the block in Modified state, and invalidated the 1208 // owners copy 1209 blk->status |= BlkDirty; 1210 1211 chatty_assert(!isReadOnly, "Should never see dirty snoop response " 1212 "in read-only cache %s\n", name()); 1213 } 1214 } 1215 1216 DPRINTF(Cache, "Block addr %#llx (%s) moving from state %x to %s\n", 1217 addr, is_secure ? "s" : "ns", old_state, blk->print()); 1218 1219 // if we got new data, copy it in (checking for a read response 1220 // and a response that has data is the same in the end) 1221 if (pkt->isRead()) { 1222 // sanity checks 1223 assert(pkt->hasData()); 1224 assert(pkt->getSize() == blkSize); 1225 1226 pkt->writeDataToBlock(blk->data, blkSize); 1227 } 1228 // We pay for fillLatency here. 1229 blk->setWhenReady(clockEdge(fillLatency) + pkt->payloadDelay); 1230 1231 return blk; 1232} 1233 1234CacheBlk* 1235BaseCache::allocateBlock(const PacketPtr pkt, PacketList &writebacks) 1236{ 1237 // Get address 1238 const Addr addr = pkt->getAddr(); 1239 1240 // Get secure bit 1241 const bool is_secure = pkt->isSecure(); 1242 1243 // Find replacement victim 1244 std::vector<CacheBlk*> evict_blks; 1245 CacheBlk *victim = tags->findVictim(addr, is_secure, evict_blks); 1246 1247 // It is valid to return nullptr if there is no victim 1248 if (!victim) 1249 return nullptr; 1250 1251 // Print victim block's information 1252 DPRINTF(CacheRepl, "Replacement victim: %s\n", victim->print()); 1253 1254 // Check for transient state allocations. If any of the entries listed 1255 // for eviction has a transient state, the allocation fails 1256 for (const auto& blk : evict_blks) { 1257 if (blk->isValid()) { 1258 Addr repl_addr = regenerateBlkAddr(blk); 1259 MSHR *repl_mshr = mshrQueue.findMatch(repl_addr, blk->isSecure()); 1260 if (repl_mshr) { 1261 // must be an outstanding upgrade or clean request 1262 // on a block we're about to replace... 1263 assert((!blk->isWritable() && repl_mshr->needsWritable()) || 1264 repl_mshr->isCleaning()); 1265 1266 // too hard to replace block with transient state 1267 // allocation failed, block not inserted 1268 return nullptr; 1269 } 1270 } 1271 } 1272 1273 // The victim will be replaced by a new entry, so increase the replacement 1274 // counter if a valid block is being replaced 1275 if (victim->isValid()) { 1276 DPRINTF(Cache, "replacement: replacing %#llx (%s) with %#llx " 1277 "(%s): %s\n", regenerateBlkAddr(victim), 1278 victim->isSecure() ? "s" : "ns", 1279 addr, is_secure ? "s" : "ns", 1280 victim->isDirty() ? "writeback" : "clean"); 1281 1282 replacements++; 1283 } 1284 1285 // Evict valid blocks associated to this victim block 1286 for (const auto& blk : evict_blks) { 1287 if (blk->isValid()) { 1288 if (blk->wasPrefetched()) { 1289 unusedPrefetches++; 1290 } 1291 1292 evictBlock(blk, writebacks); 1293 } 1294 } 1295 1296 // Insert new block at victimized entry 1297 tags->insertBlock(addr, is_secure, pkt->req->masterId(), 1298 pkt->req->taskId(), victim); 1299 1300 return victim; 1301} 1302 1303void 1304BaseCache::invalidateBlock(CacheBlk *blk) 1305{ 1306 // If handling a block present in the Tags, let it do its invalidation 1307 // process, which will update stats and invalidate the block itself 1308 if (blk != tempBlock) { 1309 tags->invalidate(blk); 1310 } else { 1311 tempBlock->invalidate(); 1312 } 1313} 1314 1315void 1316BaseCache::evictBlock(CacheBlk *blk, PacketList &writebacks) 1317{ 1318 PacketPtr pkt = evictBlock(blk); 1319 if (pkt) { 1320 writebacks.push_back(pkt); 1321 } 1322} 1323 1324PacketPtr 1325BaseCache::writebackBlk(CacheBlk *blk) 1326{ 1327 chatty_assert(!isReadOnly || writebackClean, 1328 "Writeback from read-only cache"); 1329 assert(blk && blk->isValid() && (blk->isDirty() || writebackClean)); 1330 1331 writebacks[Request::wbMasterId]++; 1332 1333 RequestPtr req = std::make_shared<Request>( 1334 regenerateBlkAddr(blk), blkSize, 0, Request::wbMasterId); 1335 1336 if (blk->isSecure()) 1337 req->setFlags(Request::SECURE); 1338 1339 req->taskId(blk->task_id); 1340 1341 PacketPtr pkt = 1342 new Packet(req, blk->isDirty() ? 1343 MemCmd::WritebackDirty : MemCmd::WritebackClean); 1344 1345 DPRINTF(Cache, "Create Writeback %s writable: %d, dirty: %d\n", 1346 pkt->print(), blk->isWritable(), blk->isDirty()); 1347 1348 if (blk->isWritable()) { 1349 // not asserting shared means we pass the block in modified 1350 // state, mark our own block non-writeable 1351 blk->status &= ~BlkWritable; 1352 } else { 1353 // we are in the Owned state, tell the receiver 1354 pkt->setHasSharers(); 1355 } 1356 1357 // make sure the block is not marked dirty 1358 blk->status &= ~BlkDirty; 1359 1360 pkt->allocate(); 1361 pkt->setDataFromBlock(blk->data, blkSize); 1362 1363 return pkt; 1364} 1365 1366PacketPtr 1367BaseCache::writecleanBlk(CacheBlk *blk, Request::Flags dest, PacketId id) 1368{ 1369 RequestPtr req = std::make_shared<Request>( 1370 regenerateBlkAddr(blk), blkSize, 0, Request::wbMasterId); 1371 1372 if (blk->isSecure()) { 1373 req->setFlags(Request::SECURE); 1374 } 1375 req->taskId(blk->task_id); 1376 1377 PacketPtr pkt = new Packet(req, MemCmd::WriteClean, blkSize, id); 1378 1379 if (dest) { 1380 req->setFlags(dest); 1381 pkt->setWriteThrough(); 1382 } 1383 1384 DPRINTF(Cache, "Create %s writable: %d, dirty: %d\n", pkt->print(), 1385 blk->isWritable(), blk->isDirty()); 1386 1387 if (blk->isWritable()) { 1388 // not asserting shared means we pass the block in modified 1389 // state, mark our own block non-writeable 1390 blk->status &= ~BlkWritable; 1391 } else { 1392 // we are in the Owned state, tell the receiver 1393 pkt->setHasSharers(); 1394 } 1395 1396 // make sure the block is not marked dirty 1397 blk->status &= ~BlkDirty; 1398 1399 pkt->allocate(); 1400 pkt->setDataFromBlock(blk->data, blkSize); 1401 1402 return pkt; 1403} 1404 1405 1406void 1407BaseCache::memWriteback() 1408{ 1409 tags->forEachBlk([this](CacheBlk &blk) { writebackVisitor(blk); }); 1410} 1411 1412void 1413BaseCache::memInvalidate() 1414{ 1415 tags->forEachBlk([this](CacheBlk &blk) { invalidateVisitor(blk); }); 1416} 1417 1418bool 1419BaseCache::isDirty() const 1420{ 1421 return tags->anyBlk([](CacheBlk &blk) { return blk.isDirty(); }); 1422} 1423 1424bool 1425BaseCache::coalesce() const 1426{ 1427 return writeAllocator && writeAllocator->coalesce(); 1428} 1429 1430void 1431BaseCache::writebackVisitor(CacheBlk &blk) 1432{ 1433 if (blk.isDirty()) { 1434 assert(blk.isValid()); 1435 1436 RequestPtr request = std::make_shared<Request>( 1437 regenerateBlkAddr(&blk), blkSize, 0, Request::funcMasterId); 1438 1439 request->taskId(blk.task_id); 1440 if (blk.isSecure()) { 1441 request->setFlags(Request::SECURE); 1442 } 1443 1444 Packet packet(request, MemCmd::WriteReq); 1445 packet.dataStatic(blk.data); 1446 1447 memSidePort.sendFunctional(&packet); 1448 1449 blk.status &= ~BlkDirty; 1450 } 1451} 1452 1453void 1454BaseCache::invalidateVisitor(CacheBlk &blk) 1455{ 1456 if (blk.isDirty()) 1457 warn_once("Invalidating dirty cache lines. " \ 1458 "Expect things to break.\n"); 1459 1460 if (blk.isValid()) { 1461 assert(!blk.isDirty()); 1462 invalidateBlock(&blk); 1463 } 1464} 1465 1466Tick 1467BaseCache::nextQueueReadyTime() const 1468{ 1469 Tick nextReady = std::min(mshrQueue.nextReadyTime(), 1470 writeBuffer.nextReadyTime()); 1471 1472 // Don't signal prefetch ready time if no MSHRs available 1473 // Will signal once enoguh MSHRs are deallocated 1474 if (prefetcher && mshrQueue.canPrefetch()) { 1475 nextReady = std::min(nextReady, 1476 prefetcher->nextPrefetchReadyTime()); 1477 } 1478 1479 return nextReady; 1480} 1481 1482 1483bool 1484BaseCache::sendMSHRQueuePacket(MSHR* mshr) 1485{ 1486 assert(mshr); 1487 1488 // use request from 1st target 1489 PacketPtr tgt_pkt = mshr->getTarget()->pkt; 1490 1491 DPRINTF(Cache, "%s: MSHR %s\n", __func__, tgt_pkt->print()); 1492 1493 // if the cache is in write coalescing mode or (additionally) in 1494 // no allocation mode, and we have a write packet with an MSHR 1495 // that is not a whole-line write (due to incompatible flags etc), 1496 // then reset the write mode 1497 if (writeAllocator && writeAllocator->coalesce() && tgt_pkt->isWrite()) { 1498 if (!mshr->isWholeLineWrite()) { 1499 // if we are currently write coalescing, hold on the 1500 // MSHR as many cycles extra as we need to completely 1501 // write a cache line 1502 if (writeAllocator->delay(mshr->blkAddr)) { 1503 Tick delay = blkSize / tgt_pkt->getSize() * clockPeriod(); 1504 DPRINTF(CacheVerbose, "Delaying pkt %s %llu ticks to allow " 1505 "for write coalescing\n", tgt_pkt->print(), delay); 1506 mshrQueue.delay(mshr, delay); 1507 return false; 1508 } else { 1509 writeAllocator->reset(); 1510 } 1511 } else { 1512 writeAllocator->resetDelay(mshr->blkAddr); 1513 } 1514 } 1515 1516 CacheBlk *blk = tags->findBlock(mshr->blkAddr, mshr->isSecure); 1517 1518 // either a prefetch that is not present upstream, or a normal 1519 // MSHR request, proceed to get the packet to send downstream 1520 PacketPtr pkt = createMissPacket(tgt_pkt, blk, mshr->needsWritable(), 1521 mshr->isWholeLineWrite()); 1522 1523 mshr->isForward = (pkt == nullptr); 1524 1525 if (mshr->isForward) { 1526 // not a cache block request, but a response is expected 1527 // make copy of current packet to forward, keep current 1528 // copy for response handling 1529 pkt = new Packet(tgt_pkt, false, true); 1530 assert(!pkt->isWrite()); 1531 } 1532 1533 // play it safe and append (rather than set) the sender state, 1534 // as forwarded packets may already have existing state 1535 pkt->pushSenderState(mshr); 1536 1537 if (pkt->isClean() && blk && blk->isDirty()) { 1538 // A cache clean opearation is looking for a dirty block. Mark 1539 // the packet so that the destination xbar can determine that 1540 // there will be a follow-up write packet as well. 1541 pkt->setSatisfied(); 1542 } 1543 1544 if (!memSidePort.sendTimingReq(pkt)) { 1545 // we are awaiting a retry, but we 1546 // delete the packet and will be creating a new packet 1547 // when we get the opportunity 1548 delete pkt; 1549 1550 // note that we have now masked any requestBus and 1551 // schedSendEvent (we will wait for a retry before 1552 // doing anything), and this is so even if we do not 1553 // care about this packet and might override it before 1554 // it gets retried 1555 return true; 1556 } else { 1557 // As part of the call to sendTimingReq the packet is 1558 // forwarded to all neighbouring caches (and any caches 1559 // above them) as a snoop. Thus at this point we know if 1560 // any of the neighbouring caches are responding, and if 1561 // so, we know it is dirty, and we can determine if it is 1562 // being passed as Modified, making our MSHR the ordering 1563 // point 1564 bool pending_modified_resp = !pkt->hasSharers() && 1565 pkt->cacheResponding(); 1566 markInService(mshr, pending_modified_resp); 1567 1568 if (pkt->isClean() && blk && blk->isDirty()) { 1569 // A cache clean opearation is looking for a dirty 1570 // block. If a dirty block is encountered a WriteClean 1571 // will update any copies to the path to the memory 1572 // until the point of reference. 1573 DPRINTF(CacheVerbose, "%s: packet %s found block: %s\n", 1574 __func__, pkt->print(), blk->print()); 1575 PacketPtr wb_pkt = writecleanBlk(blk, pkt->req->getDest(), 1576 pkt->id); 1577 PacketList writebacks; 1578 writebacks.push_back(wb_pkt); 1579 doWritebacks(writebacks, 0); 1580 } 1581 1582 return false; 1583 } 1584} 1585 1586bool 1587BaseCache::sendWriteQueuePacket(WriteQueueEntry* wq_entry) 1588{ 1589 assert(wq_entry); 1590 1591 // always a single target for write queue entries 1592 PacketPtr tgt_pkt = wq_entry->getTarget()->pkt; 1593 1594 DPRINTF(Cache, "%s: write %s\n", __func__, tgt_pkt->print()); 1595 1596 // forward as is, both for evictions and uncacheable writes 1597 if (!memSidePort.sendTimingReq(tgt_pkt)) { 1598 // note that we have now masked any requestBus and 1599 // schedSendEvent (we will wait for a retry before 1600 // doing anything), and this is so even if we do not 1601 // care about this packet and might override it before 1602 // it gets retried 1603 return true; 1604 } else { 1605 markInService(wq_entry); 1606 return false; 1607 } 1608} 1609 1610void 1611BaseCache::serialize(CheckpointOut &cp) const 1612{ 1613 bool dirty(isDirty()); 1614 1615 if (dirty) { 1616 warn("*** The cache still contains dirty data. ***\n"); 1617 warn(" Make sure to drain the system using the correct flags.\n"); 1618 warn(" This checkpoint will not restore correctly " \ 1619 "and dirty data in the cache will be lost!\n"); 1620 } 1621 1622 // Since we don't checkpoint the data in the cache, any dirty data 1623 // will be lost when restoring from a checkpoint of a system that 1624 // wasn't drained properly. Flag the checkpoint as invalid if the 1625 // cache contains dirty data. 1626 bool bad_checkpoint(dirty); 1627 SERIALIZE_SCALAR(bad_checkpoint); 1628} 1629 1630void 1631BaseCache::unserialize(CheckpointIn &cp) 1632{ 1633 bool bad_checkpoint; 1634 UNSERIALIZE_SCALAR(bad_checkpoint); 1635 if (bad_checkpoint) { 1636 fatal("Restoring from checkpoints with dirty caches is not " 1637 "supported in the classic memory system. Please remove any " 1638 "caches or drain them properly before taking checkpoints.\n"); 1639 } 1640} 1641 1642void 1643BaseCache::regStats() 1644{ 1645 MemObject::regStats(); 1646 1647 using namespace Stats; 1648 1649 // Hit statistics 1650 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1651 MemCmd cmd(access_idx); 1652 const string &cstr = cmd.toString(); 1653 1654 hits[access_idx] 1655 .init(system->maxMasters()) 1656 .name(name() + "." + cstr + "_hits") 1657 .desc("number of " + cstr + " hits") 1658 .flags(total | nozero | nonan) 1659 ; 1660 for (int i = 0; i < system->maxMasters(); i++) { 1661 hits[access_idx].subname(i, system->getMasterName(i)); 1662 } 1663 } 1664 1665// These macros make it easier to sum the right subset of commands and 1666// to change the subset of commands that are considered "demand" vs 1667// "non-demand" 1668#define SUM_DEMAND(s) \ 1669 (s[MemCmd::ReadReq] + s[MemCmd::WriteReq] + s[MemCmd::WriteLineReq] + \ 1670 s[MemCmd::ReadExReq] + s[MemCmd::ReadCleanReq] + s[MemCmd::ReadSharedReq]) 1671 1672// should writebacks be included here? prior code was inconsistent... 1673#define SUM_NON_DEMAND(s) \ 1674 (s[MemCmd::SoftPFReq] + s[MemCmd::HardPFReq] + s[MemCmd::SoftPFExReq]) 1675 1676 demandHits 1677 .name(name() + ".demand_hits") 1678 .desc("number of demand (read+write) hits") 1679 .flags(total | nozero | nonan) 1680 ; 1681 demandHits = SUM_DEMAND(hits); 1682 for (int i = 0; i < system->maxMasters(); i++) { 1683 demandHits.subname(i, system->getMasterName(i)); 1684 } 1685 1686 overallHits 1687 .name(name() + ".overall_hits") 1688 .desc("number of overall hits") 1689 .flags(total | nozero | nonan) 1690 ; 1691 overallHits = demandHits + SUM_NON_DEMAND(hits); 1692 for (int i = 0; i < system->maxMasters(); i++) { 1693 overallHits.subname(i, system->getMasterName(i)); 1694 } 1695 1696 // Miss statistics 1697 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1698 MemCmd cmd(access_idx); 1699 const string &cstr = cmd.toString(); 1700 1701 misses[access_idx] 1702 .init(system->maxMasters()) 1703 .name(name() + "." + cstr + "_misses") 1704 .desc("number of " + cstr + " misses") 1705 .flags(total | nozero | nonan) 1706 ; 1707 for (int i = 0; i < system->maxMasters(); i++) { 1708 misses[access_idx].subname(i, system->getMasterName(i)); 1709 } 1710 } 1711 1712 demandMisses 1713 .name(name() + ".demand_misses") 1714 .desc("number of demand (read+write) misses") 1715 .flags(total | nozero | nonan) 1716 ; 1717 demandMisses = SUM_DEMAND(misses); 1718 for (int i = 0; i < system->maxMasters(); i++) { 1719 demandMisses.subname(i, system->getMasterName(i)); 1720 } 1721 1722 overallMisses 1723 .name(name() + ".overall_misses") 1724 .desc("number of overall misses") 1725 .flags(total | nozero | nonan) 1726 ; 1727 overallMisses = demandMisses + SUM_NON_DEMAND(misses); 1728 for (int i = 0; i < system->maxMasters(); i++) { 1729 overallMisses.subname(i, system->getMasterName(i)); 1730 } 1731 1732 // Miss latency statistics 1733 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1734 MemCmd cmd(access_idx); 1735 const string &cstr = cmd.toString(); 1736 1737 missLatency[access_idx] 1738 .init(system->maxMasters()) 1739 .name(name() + "." + cstr + "_miss_latency") 1740 .desc("number of " + cstr + " miss cycles") 1741 .flags(total | nozero | nonan) 1742 ; 1743 for (int i = 0; i < system->maxMasters(); i++) { 1744 missLatency[access_idx].subname(i, system->getMasterName(i)); 1745 } 1746 } 1747 1748 demandMissLatency 1749 .name(name() + ".demand_miss_latency") 1750 .desc("number of demand (read+write) miss cycles") 1751 .flags(total | nozero | nonan) 1752 ; 1753 demandMissLatency = SUM_DEMAND(missLatency); 1754 for (int i = 0; i < system->maxMasters(); i++) { 1755 demandMissLatency.subname(i, system->getMasterName(i)); 1756 } 1757 1758 overallMissLatency 1759 .name(name() + ".overall_miss_latency") 1760 .desc("number of overall miss cycles") 1761 .flags(total | nozero | nonan) 1762 ; 1763 overallMissLatency = demandMissLatency + SUM_NON_DEMAND(missLatency); 1764 for (int i = 0; i < system->maxMasters(); i++) { 1765 overallMissLatency.subname(i, system->getMasterName(i)); 1766 } 1767 1768 // access formulas 1769 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1770 MemCmd cmd(access_idx); 1771 const string &cstr = cmd.toString(); 1772 1773 accesses[access_idx] 1774 .name(name() + "." + cstr + "_accesses") 1775 .desc("number of " + cstr + " accesses(hits+misses)") 1776 .flags(total | nozero | nonan) 1777 ; 1778 accesses[access_idx] = hits[access_idx] + misses[access_idx]; 1779 1780 for (int i = 0; i < system->maxMasters(); i++) { 1781 accesses[access_idx].subname(i, system->getMasterName(i)); 1782 } 1783 } 1784 1785 demandAccesses 1786 .name(name() + ".demand_accesses") 1787 .desc("number of demand (read+write) accesses") 1788 .flags(total | nozero | nonan) 1789 ; 1790 demandAccesses = demandHits + demandMisses; 1791 for (int i = 0; i < system->maxMasters(); i++) { 1792 demandAccesses.subname(i, system->getMasterName(i)); 1793 } 1794 1795 overallAccesses 1796 .name(name() + ".overall_accesses") 1797 .desc("number of overall (read+write) accesses") 1798 .flags(total | nozero | nonan) 1799 ; 1800 overallAccesses = overallHits + overallMisses; 1801 for (int i = 0; i < system->maxMasters(); i++) { 1802 overallAccesses.subname(i, system->getMasterName(i)); 1803 } 1804 1805 // miss rate formulas 1806 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1807 MemCmd cmd(access_idx); 1808 const string &cstr = cmd.toString(); 1809 1810 missRate[access_idx] 1811 .name(name() + "." + cstr + "_miss_rate") 1812 .desc("miss rate for " + cstr + " accesses") 1813 .flags(total | nozero | nonan) 1814 ; 1815 missRate[access_idx] = misses[access_idx] / accesses[access_idx]; 1816 1817 for (int i = 0; i < system->maxMasters(); i++) { 1818 missRate[access_idx].subname(i, system->getMasterName(i)); 1819 } 1820 } 1821 1822 demandMissRate 1823 .name(name() + ".demand_miss_rate") 1824 .desc("miss rate for demand accesses") 1825 .flags(total | nozero | nonan) 1826 ; 1827 demandMissRate = demandMisses / demandAccesses; 1828 for (int i = 0; i < system->maxMasters(); i++) { 1829 demandMissRate.subname(i, system->getMasterName(i)); 1830 } 1831 1832 overallMissRate 1833 .name(name() + ".overall_miss_rate") 1834 .desc("miss rate for overall accesses") 1835 .flags(total | nozero | nonan) 1836 ; 1837 overallMissRate = overallMisses / overallAccesses; 1838 for (int i = 0; i < system->maxMasters(); i++) { 1839 overallMissRate.subname(i, system->getMasterName(i)); 1840 } 1841 1842 // miss latency formulas 1843 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1844 MemCmd cmd(access_idx); 1845 const string &cstr = cmd.toString(); 1846 1847 avgMissLatency[access_idx] 1848 .name(name() + "." + cstr + "_avg_miss_latency") 1849 .desc("average " + cstr + " miss latency") 1850 .flags(total | nozero | nonan) 1851 ; 1852 avgMissLatency[access_idx] = 1853 missLatency[access_idx] / misses[access_idx]; 1854 1855 for (int i = 0; i < system->maxMasters(); i++) { 1856 avgMissLatency[access_idx].subname(i, system->getMasterName(i)); 1857 } 1858 } 1859 1860 demandAvgMissLatency 1861 .name(name() + ".demand_avg_miss_latency") 1862 .desc("average overall miss latency") 1863 .flags(total | nozero | nonan) 1864 ; 1865 demandAvgMissLatency = demandMissLatency / demandMisses; 1866 for (int i = 0; i < system->maxMasters(); i++) { 1867 demandAvgMissLatency.subname(i, system->getMasterName(i)); 1868 } 1869 1870 overallAvgMissLatency 1871 .name(name() + ".overall_avg_miss_latency") 1872 .desc("average overall miss latency") 1873 .flags(total | nozero | nonan) 1874 ; 1875 overallAvgMissLatency = overallMissLatency / overallMisses; 1876 for (int i = 0; i < system->maxMasters(); i++) { 1877 overallAvgMissLatency.subname(i, system->getMasterName(i)); 1878 } 1879 1880 blocked_cycles.init(NUM_BLOCKED_CAUSES); 1881 blocked_cycles 1882 .name(name() + ".blocked_cycles") 1883 .desc("number of cycles access was blocked") 1884 .subname(Blocked_NoMSHRs, "no_mshrs") 1885 .subname(Blocked_NoTargets, "no_targets") 1886 ; 1887 1888 1889 blocked_causes.init(NUM_BLOCKED_CAUSES); 1890 blocked_causes 1891 .name(name() + ".blocked") 1892 .desc("number of cycles access was blocked") 1893 .subname(Blocked_NoMSHRs, "no_mshrs") 1894 .subname(Blocked_NoTargets, "no_targets") 1895 ; 1896 1897 avg_blocked 1898 .name(name() + ".avg_blocked_cycles") 1899 .desc("average number of cycles each access was blocked") 1900 .subname(Blocked_NoMSHRs, "no_mshrs") 1901 .subname(Blocked_NoTargets, "no_targets") 1902 ; 1903 1904 avg_blocked = blocked_cycles / blocked_causes; 1905 1906 unusedPrefetches 1907 .name(name() + ".unused_prefetches") 1908 .desc("number of HardPF blocks evicted w/o reference") 1909 .flags(nozero) 1910 ; 1911 1912 writebacks 1913 .init(system->maxMasters()) 1914 .name(name() + ".writebacks") 1915 .desc("number of writebacks") 1916 .flags(total | nozero | nonan) 1917 ; 1918 for (int i = 0; i < system->maxMasters(); i++) { 1919 writebacks.subname(i, system->getMasterName(i)); 1920 } 1921 1922 // MSHR statistics 1923 // MSHR hit statistics 1924 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1925 MemCmd cmd(access_idx); 1926 const string &cstr = cmd.toString(); 1927 1928 mshr_hits[access_idx] 1929 .init(system->maxMasters()) 1930 .name(name() + "." + cstr + "_mshr_hits") 1931 .desc("number of " + cstr + " MSHR hits") 1932 .flags(total | nozero | nonan) 1933 ; 1934 for (int i = 0; i < system->maxMasters(); i++) { 1935 mshr_hits[access_idx].subname(i, system->getMasterName(i)); 1936 } 1937 } 1938 1939 demandMshrHits 1940 .name(name() + ".demand_mshr_hits") 1941 .desc("number of demand (read+write) MSHR hits") 1942 .flags(total | nozero | nonan) 1943 ; 1944 demandMshrHits = SUM_DEMAND(mshr_hits); 1945 for (int i = 0; i < system->maxMasters(); i++) { 1946 demandMshrHits.subname(i, system->getMasterName(i)); 1947 } 1948 1949 overallMshrHits 1950 .name(name() + ".overall_mshr_hits") 1951 .desc("number of overall MSHR hits") 1952 .flags(total | nozero | nonan) 1953 ; 1954 overallMshrHits = demandMshrHits + SUM_NON_DEMAND(mshr_hits); 1955 for (int i = 0; i < system->maxMasters(); i++) { 1956 overallMshrHits.subname(i, system->getMasterName(i)); 1957 } 1958 1959 // MSHR miss statistics 1960 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1961 MemCmd cmd(access_idx); 1962 const string &cstr = cmd.toString(); 1963 1964 mshr_misses[access_idx] 1965 .init(system->maxMasters()) 1966 .name(name() + "." + cstr + "_mshr_misses") 1967 .desc("number of " + cstr + " MSHR misses") 1968 .flags(total | nozero | nonan) 1969 ; 1970 for (int i = 0; i < system->maxMasters(); i++) { 1971 mshr_misses[access_idx].subname(i, system->getMasterName(i)); 1972 } 1973 } 1974 1975 demandMshrMisses 1976 .name(name() + ".demand_mshr_misses") 1977 .desc("number of demand (read+write) MSHR misses") 1978 .flags(total | nozero | nonan) 1979 ; 1980 demandMshrMisses = SUM_DEMAND(mshr_misses); 1981 for (int i = 0; i < system->maxMasters(); i++) { 1982 demandMshrMisses.subname(i, system->getMasterName(i)); 1983 } 1984 1985 overallMshrMisses 1986 .name(name() + ".overall_mshr_misses") 1987 .desc("number of overall MSHR misses") 1988 .flags(total | nozero | nonan) 1989 ; 1990 overallMshrMisses = demandMshrMisses + SUM_NON_DEMAND(mshr_misses); 1991 for (int i = 0; i < system->maxMasters(); i++) { 1992 overallMshrMisses.subname(i, system->getMasterName(i)); 1993 } 1994 1995 // MSHR miss latency statistics 1996 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 1997 MemCmd cmd(access_idx); 1998 const string &cstr = cmd.toString(); 1999 2000 mshr_miss_latency[access_idx] 2001 .init(system->maxMasters()) 2002 .name(name() + "." + cstr + "_mshr_miss_latency") 2003 .desc("number of " + cstr + " MSHR miss cycles") 2004 .flags(total | nozero | nonan) 2005 ; 2006 for (int i = 0; i < system->maxMasters(); i++) { 2007 mshr_miss_latency[access_idx].subname(i, system->getMasterName(i)); 2008 } 2009 } 2010 2011 demandMshrMissLatency 2012 .name(name() + ".demand_mshr_miss_latency") 2013 .desc("number of demand (read+write) MSHR miss cycles") 2014 .flags(total | nozero | nonan) 2015 ; 2016 demandMshrMissLatency = SUM_DEMAND(mshr_miss_latency); 2017 for (int i = 0; i < system->maxMasters(); i++) { 2018 demandMshrMissLatency.subname(i, system->getMasterName(i)); 2019 } 2020 2021 overallMshrMissLatency 2022 .name(name() + ".overall_mshr_miss_latency") 2023 .desc("number of overall MSHR miss cycles") 2024 .flags(total | nozero | nonan) 2025 ; 2026 overallMshrMissLatency = 2027 demandMshrMissLatency + SUM_NON_DEMAND(mshr_miss_latency); 2028 for (int i = 0; i < system->maxMasters(); i++) { 2029 overallMshrMissLatency.subname(i, system->getMasterName(i)); 2030 } 2031 2032 // MSHR uncacheable statistics 2033 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 2034 MemCmd cmd(access_idx); 2035 const string &cstr = cmd.toString(); 2036 2037 mshr_uncacheable[access_idx] 2038 .init(system->maxMasters()) 2039 .name(name() + "." + cstr + "_mshr_uncacheable") 2040 .desc("number of " + cstr + " MSHR uncacheable") 2041 .flags(total | nozero | nonan) 2042 ; 2043 for (int i = 0; i < system->maxMasters(); i++) { 2044 mshr_uncacheable[access_idx].subname(i, system->getMasterName(i)); 2045 } 2046 } 2047 2048 overallMshrUncacheable 2049 .name(name() + ".overall_mshr_uncacheable_misses") 2050 .desc("number of overall MSHR uncacheable misses") 2051 .flags(total | nozero | nonan) 2052 ; 2053 overallMshrUncacheable = 2054 SUM_DEMAND(mshr_uncacheable) + SUM_NON_DEMAND(mshr_uncacheable); 2055 for (int i = 0; i < system->maxMasters(); i++) { 2056 overallMshrUncacheable.subname(i, system->getMasterName(i)); 2057 } 2058 2059 // MSHR miss latency statistics 2060 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 2061 MemCmd cmd(access_idx); 2062 const string &cstr = cmd.toString(); 2063 2064 mshr_uncacheable_lat[access_idx] 2065 .init(system->maxMasters()) 2066 .name(name() + "." + cstr + "_mshr_uncacheable_latency") 2067 .desc("number of " + cstr + " MSHR uncacheable cycles") 2068 .flags(total | nozero | nonan) 2069 ; 2070 for (int i = 0; i < system->maxMasters(); i++) { 2071 mshr_uncacheable_lat[access_idx].subname( 2072 i, system->getMasterName(i)); 2073 } 2074 } 2075 2076 overallMshrUncacheableLatency 2077 .name(name() + ".overall_mshr_uncacheable_latency") 2078 .desc("number of overall MSHR uncacheable cycles") 2079 .flags(total | nozero | nonan) 2080 ; 2081 overallMshrUncacheableLatency = 2082 SUM_DEMAND(mshr_uncacheable_lat) + 2083 SUM_NON_DEMAND(mshr_uncacheable_lat); 2084 for (int i = 0; i < system->maxMasters(); i++) { 2085 overallMshrUncacheableLatency.subname(i, system->getMasterName(i)); 2086 } 2087 2088#if 0 2089 // MSHR access formulas 2090 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 2091 MemCmd cmd(access_idx); 2092 const string &cstr = cmd.toString(); 2093 2094 mshrAccesses[access_idx] 2095 .name(name() + "." + cstr + "_mshr_accesses") 2096 .desc("number of " + cstr + " mshr accesses(hits+misses)") 2097 .flags(total | nozero | nonan) 2098 ; 2099 mshrAccesses[access_idx] = 2100 mshr_hits[access_idx] + mshr_misses[access_idx] 2101 + mshr_uncacheable[access_idx]; 2102 } 2103 2104 demandMshrAccesses 2105 .name(name() + ".demand_mshr_accesses") 2106 .desc("number of demand (read+write) mshr accesses") 2107 .flags(total | nozero | nonan) 2108 ; 2109 demandMshrAccesses = demandMshrHits + demandMshrMisses; 2110 2111 overallMshrAccesses 2112 .name(name() + ".overall_mshr_accesses") 2113 .desc("number of overall (read+write) mshr accesses") 2114 .flags(total | nozero | nonan) 2115 ; 2116 overallMshrAccesses = overallMshrHits + overallMshrMisses 2117 + overallMshrUncacheable; 2118#endif 2119 2120 // MSHR miss rate formulas 2121 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 2122 MemCmd cmd(access_idx); 2123 const string &cstr = cmd.toString(); 2124 2125 mshrMissRate[access_idx] 2126 .name(name() + "." + cstr + "_mshr_miss_rate") 2127 .desc("mshr miss rate for " + cstr + " accesses") 2128 .flags(total | nozero | nonan) 2129 ; 2130 mshrMissRate[access_idx] = 2131 mshr_misses[access_idx] / accesses[access_idx]; 2132 2133 for (int i = 0; i < system->maxMasters(); i++) { 2134 mshrMissRate[access_idx].subname(i, system->getMasterName(i)); 2135 } 2136 } 2137 2138 demandMshrMissRate 2139 .name(name() + ".demand_mshr_miss_rate") 2140 .desc("mshr miss rate for demand accesses") 2141 .flags(total | nozero | nonan) 2142 ; 2143 demandMshrMissRate = demandMshrMisses / demandAccesses; 2144 for (int i = 0; i < system->maxMasters(); i++) { 2145 demandMshrMissRate.subname(i, system->getMasterName(i)); 2146 } 2147 2148 overallMshrMissRate 2149 .name(name() + ".overall_mshr_miss_rate") 2150 .desc("mshr miss rate for overall accesses") 2151 .flags(total | nozero | nonan) 2152 ; 2153 overallMshrMissRate = overallMshrMisses / overallAccesses; 2154 for (int i = 0; i < system->maxMasters(); i++) { 2155 overallMshrMissRate.subname(i, system->getMasterName(i)); 2156 } 2157 2158 // mshrMiss latency formulas 2159 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 2160 MemCmd cmd(access_idx); 2161 const string &cstr = cmd.toString(); 2162 2163 avgMshrMissLatency[access_idx] 2164 .name(name() + "." + cstr + "_avg_mshr_miss_latency") 2165 .desc("average " + cstr + " mshr miss latency") 2166 .flags(total | nozero | nonan) 2167 ; 2168 avgMshrMissLatency[access_idx] = 2169 mshr_miss_latency[access_idx] / mshr_misses[access_idx]; 2170 2171 for (int i = 0; i < system->maxMasters(); i++) { 2172 avgMshrMissLatency[access_idx].subname( 2173 i, system->getMasterName(i)); 2174 } 2175 } 2176 2177 demandAvgMshrMissLatency 2178 .name(name() + ".demand_avg_mshr_miss_latency") 2179 .desc("average overall mshr miss latency") 2180 .flags(total | nozero | nonan) 2181 ; 2182 demandAvgMshrMissLatency = demandMshrMissLatency / demandMshrMisses; 2183 for (int i = 0; i < system->maxMasters(); i++) { 2184 demandAvgMshrMissLatency.subname(i, system->getMasterName(i)); 2185 } 2186 2187 overallAvgMshrMissLatency 2188 .name(name() + ".overall_avg_mshr_miss_latency") 2189 .desc("average overall mshr miss latency") 2190 .flags(total | nozero | nonan) 2191 ; 2192 overallAvgMshrMissLatency = overallMshrMissLatency / overallMshrMisses; 2193 for (int i = 0; i < system->maxMasters(); i++) { 2194 overallAvgMshrMissLatency.subname(i, system->getMasterName(i)); 2195 } 2196 2197 // mshrUncacheable latency formulas 2198 for (int access_idx = 0; access_idx < MemCmd::NUM_MEM_CMDS; ++access_idx) { 2199 MemCmd cmd(access_idx); 2200 const string &cstr = cmd.toString(); 2201 2202 avgMshrUncacheableLatency[access_idx] 2203 .name(name() + "." + cstr + "_avg_mshr_uncacheable_latency") 2204 .desc("average " + cstr + " mshr uncacheable latency") 2205 .flags(total | nozero | nonan) 2206 ; 2207 avgMshrUncacheableLatency[access_idx] = 2208 mshr_uncacheable_lat[access_idx] / mshr_uncacheable[access_idx]; 2209 2210 for (int i = 0; i < system->maxMasters(); i++) { 2211 avgMshrUncacheableLatency[access_idx].subname( 2212 i, system->getMasterName(i)); 2213 } 2214 } 2215 2216 overallAvgMshrUncacheableLatency 2217 .name(name() + ".overall_avg_mshr_uncacheable_latency") 2218 .desc("average overall mshr uncacheable latency") 2219 .flags(total | nozero | nonan) 2220 ; 2221 overallAvgMshrUncacheableLatency = 2222 overallMshrUncacheableLatency / overallMshrUncacheable; 2223 for (int i = 0; i < system->maxMasters(); i++) { 2224 overallAvgMshrUncacheableLatency.subname(i, system->getMasterName(i)); 2225 } 2226 2227 replacements 2228 .name(name() + ".replacements") 2229 .desc("number of replacements") 2230 ; 2231} 2232 2233void 2234BaseCache::regProbePoints() 2235{ 2236 ppHit = new ProbePointArg<PacketPtr>(this->getProbeManager(), "Hit"); 2237 ppMiss = new ProbePointArg<PacketPtr>(this->getProbeManager(), "Miss"); 2238 ppFill = new ProbePointArg<PacketPtr>(this->getProbeManager(), "Fill"); 2239} 2240 2241/////////////// 2242// 2243// CpuSidePort 2244// 2245/////////////// 2246bool 2247BaseCache::CpuSidePort::recvTimingSnoopResp(PacketPtr pkt) 2248{ 2249 // Snoops shouldn't happen when bypassing caches 2250 assert(!cache->system->bypassCaches()); 2251 2252 assert(pkt->isResponse()); 2253 2254 // Express snoop responses from master to slave, e.g., from L1 to L2 2255 cache->recvTimingSnoopResp(pkt); 2256 return true; 2257} 2258 2259 2260bool 2261BaseCache::CpuSidePort::tryTiming(PacketPtr pkt) 2262{ 2263 if (cache->system->bypassCaches() || pkt->isExpressSnoop()) { 2264 // always let express snoop packets through even if blocked 2265 return true; 2266 } else if (blocked || mustSendRetry) { 2267 // either already committed to send a retry, or blocked 2268 mustSendRetry = true; 2269 return false; 2270 } 2271 mustSendRetry = false; 2272 return true; 2273} 2274 2275bool 2276BaseCache::CpuSidePort::recvTimingReq(PacketPtr pkt) 2277{ 2278 assert(pkt->isRequest()); 2279 2280 if (cache->system->bypassCaches()) { 2281 // Just forward the packet if caches are disabled. 2282 // @todo This should really enqueue the packet rather 2283 bool M5_VAR_USED success = cache->memSidePort.sendTimingReq(pkt); 2284 assert(success); 2285 return true; 2286 } else if (tryTiming(pkt)) { 2287 cache->recvTimingReq(pkt); 2288 return true; 2289 } 2290 return false; 2291} 2292 2293Tick 2294BaseCache::CpuSidePort::recvAtomic(PacketPtr pkt) 2295{ 2296 if (cache->system->bypassCaches()) { 2297 // Forward the request if the system is in cache bypass mode. 2298 return cache->memSidePort.sendAtomic(pkt); 2299 } else { 2300 return cache->recvAtomic(pkt); 2301 } 2302} 2303 2304void 2305BaseCache::CpuSidePort::recvFunctional(PacketPtr pkt) 2306{ 2307 if (cache->system->bypassCaches()) { 2308 // The cache should be flushed if we are in cache bypass mode, 2309 // so we don't need to check if we need to update anything. 2310 cache->memSidePort.sendFunctional(pkt); 2311 return; 2312 } 2313 2314 // functional request 2315 cache->functionalAccess(pkt, true); 2316} 2317 2318AddrRangeList 2319BaseCache::CpuSidePort::getAddrRanges() const 2320{ 2321 return cache->getAddrRanges(); 2322} 2323 2324 2325BaseCache:: 2326CpuSidePort::CpuSidePort(const std::string &_name, BaseCache *_cache, 2327 const std::string &_label) 2328 : CacheSlavePort(_name, _cache, _label), cache(_cache) 2329{ 2330} 2331 2332/////////////// 2333// 2334// MemSidePort 2335// 2336/////////////// 2337bool 2338BaseCache::MemSidePort::recvTimingResp(PacketPtr pkt) 2339{ 2340 cache->recvTimingResp(pkt); 2341 return true; 2342} 2343 2344// Express snooping requests to memside port 2345void 2346BaseCache::MemSidePort::recvTimingSnoopReq(PacketPtr pkt) 2347{ 2348 // Snoops shouldn't happen when bypassing caches 2349 assert(!cache->system->bypassCaches()); 2350 2351 // handle snooping requests 2352 cache->recvTimingSnoopReq(pkt); 2353} 2354 2355Tick 2356BaseCache::MemSidePort::recvAtomicSnoop(PacketPtr pkt) 2357{ 2358 // Snoops shouldn't happen when bypassing caches 2359 assert(!cache->system->bypassCaches()); 2360 2361 return cache->recvAtomicSnoop(pkt); 2362} 2363 2364void 2365BaseCache::MemSidePort::recvFunctionalSnoop(PacketPtr pkt) 2366{ 2367 // Snoops shouldn't happen when bypassing caches 2368 assert(!cache->system->bypassCaches()); 2369 2370 // functional snoop (note that in contrast to atomic we don't have 2371 // a specific functionalSnoop method, as they have the same 2372 // behaviour regardless) 2373 cache->functionalAccess(pkt, false); 2374} 2375 2376void 2377BaseCache::CacheReqPacketQueue::sendDeferredPacket() 2378{ 2379 // sanity check 2380 assert(!waitingOnRetry); 2381 2382 // there should never be any deferred request packets in the 2383 // queue, instead we resly on the cache to provide the packets 2384 // from the MSHR queue or write queue 2385 assert(deferredPacketReadyTime() == MaxTick); 2386 2387 // check for request packets (requests & writebacks) 2388 QueueEntry* entry = cache.getNextQueueEntry(); 2389 2390 if (!entry) { 2391 // can happen if e.g. we attempt a writeback and fail, but 2392 // before the retry, the writeback is eliminated because 2393 // we snoop another cache's ReadEx. 2394 } else { 2395 // let our snoop responses go first if there are responses to 2396 // the same addresses 2397 if (checkConflictingSnoop(entry->blkAddr)) { 2398 return; 2399 } 2400 waitingOnRetry = entry->sendPacket(cache); 2401 } 2402 2403 // if we succeeded and are not waiting for a retry, schedule the 2404 // next send considering when the next queue is ready, note that 2405 // snoop responses have their own packet queue and thus schedule 2406 // their own events 2407 if (!waitingOnRetry) { 2408 schedSendEvent(cache.nextQueueReadyTime()); 2409 } 2410} 2411 2412BaseCache::MemSidePort::MemSidePort(const std::string &_name, 2413 BaseCache *_cache, 2414 const std::string &_label) 2415 : CacheMasterPort(_name, _cache, _reqQueue, _snoopRespQueue), 2416 _reqQueue(*_cache, *this, _snoopRespQueue, _label), 2417 _snoopRespQueue(*_cache, *this, true, _label), cache(_cache) 2418{ 2419} 2420 2421void 2422WriteAllocator::updateMode(Addr write_addr, unsigned write_size, 2423 Addr blk_addr) 2424{ 2425 // check if we are continuing where the last write ended 2426 if (nextAddr == write_addr) { 2427 delayCtr[blk_addr] = delayThreshold; 2428 // stop if we have already saturated 2429 if (mode != WriteMode::NO_ALLOCATE) { 2430 byteCount += write_size; 2431 // switch to streaming mode if we have passed the lower 2432 // threshold 2433 if (mode == WriteMode::ALLOCATE && 2434 byteCount > coalesceLimit) { 2435 mode = WriteMode::COALESCE; 2436 DPRINTF(Cache, "Switched to write coalescing\n"); 2437 } else if (mode == WriteMode::COALESCE && 2438 byteCount > noAllocateLimit) { 2439 // and continue and switch to non-allocating mode if we 2440 // pass the upper threshold 2441 mode = WriteMode::NO_ALLOCATE; 2442 DPRINTF(Cache, "Switched to write-no-allocate\n"); 2443 } 2444 } 2445 } else { 2446 // we did not see a write matching the previous one, start 2447 // over again 2448 byteCount = write_size; 2449 mode = WriteMode::ALLOCATE; 2450 resetDelay(blk_addr); 2451 } 2452 nextAddr = write_addr + write_size; 2453} 2454 2455WriteAllocator* 2456WriteAllocatorParams::create() 2457{ 2458 return new WriteAllocator(this); 2459} 2460